主脚本会话通信

ScriptSession 是全局 API,也可从 "scripting" 导入。它向同一 App 进程、同一脚本已运行的 index/home_screen 主会话发送请求并取得应答,适用于主 App 的 App Intent 复用路径。它不跨真正的扩展进程传输、不唤醒 App、不再启动一份脚本;找不到接收者会明确拒绝。

// index.tsx: keep your normal main UI/session alive.
import { ScriptSession, Storage } from "scripting"
const id = ScriptSession.register(async message => {
  // Validate your application command and perform the operation here.
  // Return acknowledgement before exiting/unregistering this main script.
  return { accepted: true, message }
})
Storage.set("mainSessionID", id)
// On normal shutdown: ScriptSession.unregister(id)
// app_intents.tsx
import { AppIntentManager, AppIntentProtocol, ScriptSession, Storage } from "scripting"
export const StopMainIntent = AppIntentManager.register({
  name: "StopMainIntent",
  protocol: AppIntentProtocol.LiveActivityIntent,
  perform: async () => {
    const id = Storage.get<string>("mainSessionID")
    if (!id) throw new Error("Start the main script first")
    console.log(await ScriptSession.request(id, { command: "stop" }, { timeout: 5000 }))
  },
})

每次注册生成新 ID,旧 ID 不投递给替代会话。同一脚本仅一个接收者,每个进程最多 32 会话、32 个待应答请求。输入/应答为 JSON 数据,各最多 64 KiB;handler 返回 undefined 时应答为 null。函数、symbol、BigInt、非有限数、undefined 字段和循环引用会拒绝。

应答超时默认 10000 毫秒,可设 100...30000。恢复运行后不再执行过期排队命令;超时不撤销已接收操作、不抢占同步 JS,也不能证明主会话已死。停止命令应答不代表真实位置恢复。退出/注销会拒绝待完成请求并释放 handler,迟到应答忽略;请先返回应答再 Script.exit。

Error codes: SCRIPT_SESSION_UNAVAILABLE, SCRIPT_SESSION_NOT_FOUND, SCRIPT_SESSION_BUSY, SCRIPT_SESSION_CLOSED, SCRIPT_SESSION_TIMEOUT, SCRIPT_SESSION_INVALID_DATA, SCRIPT_SESSION_INVALID_HANDLER, SCRIPT_SESSION_HANDLER_FAILED, ERR_PRO_REQUIRED.