AgentSession
多轮会话句柄(纯 headless,无 UI;由 createSession 创建)。send() 提交输入(空闲起新轮,运行中经注入
屏障并入下一轮),events 为可多消费者的会话事件流,messages() / history() 读历史快照;另提供
手动压缩 / 快照 / 恢复 / fork、setModel / setThinking / setCwd 空闲期热切换、interrupt() 与幂等
close()。
new AgentSession(init): AgentSession;AgentSessionInit
AgentSession
applicationPrompt
Section titled “applicationPrompt”Getter 签名
Section titled “Getter 签名”get applicationPrompt(): ApplicationPromptInfo;events
Section titled “events”Getter 签名
Section titled “Getter 签名”get events(): AsyncIterable<KernelEvent>;会话事件流(async iterable;多消费者广播,2026-09-02 起)。每次 for-await 即一个 独立订阅者:SessionView 泵、Narrator、宿主自建循环可同时挂,各得全量事件、互不争抢; 首订阅者收到会话创建以来的积压,晚订阅者自订阅点起。跨轮连续,close() 后以 session.ended 收尾并正常终结(各订阅者排空后 for-await 自然退出)。
AsyncIterable<KernelEvent>
platform
Section titled “platform”Getter 签名
Section titled “Getter 签名”get platform(): PlatformAudioClient;平台直连面(令牌档):platform.transcribe({ audio, model?, language? }) /
platform.speak({ input, voice?, model?, format? })——纯 HTTP 客户端直打
/t1/asr、/t1/tts,不进会话历史、不进事件流(App 自决是否把转写作为下一条
输入、是否播放合成音频);失败 throw PlatformRequestError(携网关错误码)。托管/
注入档无平台连接:调用即 invalid_options 指引令牌档(fail-fast,恒不静默)。
sessionId
Section titled “sessionId”Getter 签名
Section titled “Getter 签名”get sessionId(): string;string
checkpoint()
Section titled “checkpoint()”checkpoint(options?): Promise<ContextCheckpointMeta>;手动快照(trigger=‘manual’):把当前完整历史写成自包含只读拷贝,返回头部 meta; 落盘后推 session.checkpointed 事件。运行中 throw turn_running(历史归内核所有, 空闲期快照才是完整上下文);未接线 throw checkpoints_not_wired。
options?
Section titled “options?”Promise<ContextCheckpointMeta>
close()
Section titled “close()”close(): void;关闭会话(幂等):空闲立即收口(session.ended + 流终结);运行中先 abort,收口推迟到泵终态——中止轮的尾部事件(turn.aborted 等)不丢失。
void
closeAsync()
Section titled “closeAsync()”closeAsync(options?): Promise<SessionDrainResult>;信号/超时仅约束观察,逻辑 close 仍即时生效;非法选项在 close 前拒绝。
options?
Section titled “options?”Promise<SessionDrainResult>
compact()
Section titled “compact()”compact(options?): Promise<CompactResult>;手动压缩:对当前历史执行一次 manual 压缩,成功即就地替换历史、 推 session.compacted / cost.usage.updated 事件、以 { rewritten:true, reason: ‘compaction’ } 提交落盘。压缩前缺省先落 pre_compaction 快照(可关;快照 id 随 结果与事件体交付);压缩失败快照保留。
- 运行中 → rejected:‘turn_running’(不排队;await idle() 后重试——显式优于隐式);
- 历史为空 → rejected:‘empty_history’;compaction:false 或窗口未知 → ‘not_configured’;
- 并发 compact()/restore()/checkpoint() 按到达序串行;期间 send() 缓冲到操作链排空。 close 后调用 throw session_closed(编程错误,与 send 同律)。
options?
Section titled “options?”Promise<CompactResult>
currentModel()
Section titled “currentModel()”currentModel(): ResolvedModel;当前模型档快照
cwd(): string;会话当前工作目录(session.created.cwd 起,随 setCwd 改写)
string
deleteCheckpoint()
Section titled “deleteCheckpoint()”deleteCheckpoint(checkpointId): Promise<void>;删除本会话的一份快照(幂等);运行中 throw turn_running;未接线 throw checkpoints_not_wired
checkpointId
Section titled “checkpointId”string
Promise<void>
drain()
Section titled “drain()”drain(options?): Promise<SessionDrainResult>;等查询生成器实际收尾与提交;不得从本会话 history callback 内调用并等待。
options?
Section titled “options?”Promise<SessionDrainResult>
exportCheckpoint()
Section titled “exportCheckpoint()”exportCheckpoint(checkpointId): Promise<Uint8Array<ArrayBufferLike>>;导出本会话的一份快照为自包含字节(UTF-8 JSON { format:'tansr-checkpoint/1', checkpoint, attachments: { [sha256]: base64 } };image 字节内联进 attachments,快照体以 $ref 引用)。
只读,运行中 / close 后皆可(与 listCheckpoints 同律)。快照不存在 throw checkpoint_not_found。
checkpointId
Section titled “checkpointId”string
Promise<Uint8Array<ArrayBufferLike>>
fork()
Section titled “fork()”fork(checkpointId, options?): Promise<ForkResult>;自本会话的一份快照 fork 出新会话(源会话零改动;不隐式打开新会话——显式优于隐式):
读快照 → store.fork(createFileSessionStore:kernel 原语,新卷首记录 kind=‘fork’ +
meta.forkedFrom + 附件按 sha 复制;自建 store 缺该法回落 create + commit 全量历史)→ 返回
{ sessionId },开发者随后 createSession({ resume: { sessionId, store } }) 打开(或一步到位
用 createSession({ fork: { sessionId, checkpointId }, store }))。label = 新会话标题、cwd =
新会话工作目录(缺省沿本会话)。不签发事件(session.forked 在新会话首次打开时由快捷形签发)。
失败面(结构化 throw):未接线快照 checkpoints_not_wired / 未给会话 store
session_store_not_wired / 快照不存在 checkpoint_not_found / close 后 session_closed。
checkpointId
Section titled “checkpointId”string
options?
Section titled “options?”Promise<ForkResult>
getInputStatus()
Section titled “getInputStatus()”getInputStatus(inputId, target): SessionInputReceipt | null;inputId
Section titled “inputId”string
target
Section titled “target”SessionInputReceipt | null
getInputTarget()
Section titled “getInputTarget()”getInputTarget(): SessionInputTarget | null;SessionInputTarget | null
history()
Section titled “history()”history(options?): Promise<HistoryPage>;历史分页读:消息索引口径的 [offset, offset+limit) 切片,
与 messages() 同一投影口径(同一份历史快照、同为深拷贝;运行中亦可读,返回轮起
时的历史)。切片恒配对完整:起点向前对齐到干净边界并回填 offset,终点向后
对齐(limit 是下限,为凑齐工具轮可多返回几条)。缺省全量 = 与 messages() 字节等价;
limit: 0 只取 total;offset 越界 → 空页且 offset 回填 total。休眠会话(未起
AgentSession)请用 readHistoryPage(store, sessionId, page)。
options?
Section titled “options?”Promise<HistoryPage>
idle()
Section titled “idle()”idle(): Promise<void>;排空当前轮(含结转连锁起的新轮)与空闲期操作链:close/断言前等待终态收口
Promise<void>
importCheckpoint()
Section titled “importCheckpoint()”importCheckpoint(bytes, options?): Promise<ContextCheckpointMeta>;把 exportCheckpoint() 产物(本会话或他会话 / 他机导出)导入为本会话的一份新快照:
校验 format / schema / 每附件 sha256 / 每 $ref 皆有附件 / 消息形(任一不过 throw
checkpoint_import_invalid,不落半成品;校验先于入队,零副作用)→ 身份改写(sessionId = 本会话;
checkpointId 重铸;trigger ‘manual’;createdAt 现时;label 覆写或沿用;cwd / model / tokens 沿用;
compactionId 剥除)→ store.put → 推 session.checkpointed(每次快照落盘皆签发)。
不触本会话历史(导入的是快照,之后可 restore()/fork());close 后 throw session_closed。
put 入空闲期串行链——与 checkpoint / restore / deleteCheckpoint 同链按到达序执行(避免与删除的附件 GC
并发造成共享附件误删);运行中的轮不受影响(本方法不触历史,链内不校验 turn_running)。
Uint8Array
options?
Section titled “options?”Promise<ContextCheckpointMeta>
inputCapabilities()
Section titled “inputCapabilities()”inputCapabilities(): SessionInputCapabilities;interrupt()
Section titled “interrupt()”interrupt(): void;中断当前轮(优雅:事件流走到 turn.aborted);空闲/已关闭为无害空操作
void
listCheckpoints()
Section titled “listCheckpoints()”listCheckpoints(): Promise<ContextCheckpointMeta[]>;列举本会话全部快照头部(checkpointId 升序 = 时间线;只读,运行中亦可)
Promise<ContextCheckpointMeta[]>
messages()
Section titled “messages()”messages(): IRMessage[];会话历史快照(深拷贝;可直接作恢复/续跑的 initialMessages)
pushBody()
Section titled “pushBody()”pushBody(body, source): void;装配层合成事件入流(hooks emit / provider 切换 / todo 台账):包络本地 补齐,seq 与内核事件共用同一会话计数器。内部使用;不属公开 API 面。
source
Section titled “source”string
void
restore()
Section titled “restore()”restore(checkpointId, options?): Promise<RestoreResult>;自快照恢复(同会话就地换史):空闲校验 → 读快照 → sessionId 对账 → (可选)pre_restore 快照 → 以快照 messages 替换历史(与 resume 预载同径: 配对治理 + 深拷贝)→ 推 session.restored → { rewritten:true, reason:‘restore’ } 提交 落盘(整卷轮换)。同一快照连续恢复两次,第二次历史字节等价、仍换卷(不做无变化 短路,可解释优先)。快照 cwd ≠ 会话 cwd 时不改 cwd,推 turn.error(scope= ‘sdk.notice’,recoverable)提示 cwd_mismatch_on_restore。
checkpointId
Section titled “checkpointId”string
options?
Section titled “options?”Promise<RestoreResult>
running()
Section titled “running()”running(): boolean;boolean
send()
Section titled “send()”send(prompt): void;提交输入:空闲起新轮;运行中经内核注入屏障(下一 assembling 前消费, 自然终态未消费的旧注入结转为下一轮开场输入;中断/硬限制不结转)。close 后调用属编程错误, 结构化 throw(不静默吞输入)。
prompt
Section titled “prompt”string
void
setCwd()
Section titled “setCwd()”setCwd(dir): Promise<SetCwdResult>;切换会话工作目录(空闲期;运行中 → rejected:‘turn_running’,不排队)。校验经 kernel
resolveSessionCwd(绝对 / 存在 / 目录;SDK 面由本机开发者亲手给出,恒等 resolve 策略——与
CLI --cwd 同律,不设白名单闸);通过即:按新 cwd 重建执行器 + 权限门 + PreToolUse hooks
(装配层 rebindCwd;registry / 已读文件表 / grep 聚合共享;权限引擎实例复用)→ 改写会话
cwd(快照 meta.cwd、恢复对账锚、Task 子代理 ToolContext.cwd 随之)→ 推 session.cwd_changed
{from,to} → 落盘 store.recordCwdChange(meta.cwd 改写 + cwdHistory 追加;缺席不落)。
与 compact()/restore() 同一空闲期串行链(期间 send() 缓冲)。目标与当前相同:零副作用回
changed(不推事件、不落盘)。不重跑 loadConfig(项目层配置不随 cwd 变;已知限界,详见 SDK 技术手册)。
string
Promise<SetCwdResult>
setModel()
Section titled “setModel()”setModel(next): void;模型切换(对后续轮生效;运行中轮不受影响):
- 字符串(别名/ref):仅托管模式可用,经装配期 registry 重新解析构造 (解析失败抛 TansrSdkError(‘assembly_failed’),会话状态不变);
- SetModelBinding:client 与 model 成对更换(跨 provider 时旧 client 不可复用);contextWindowTokens 不传则清空(宁缺毋错)。
string | SetModelBinding
void
setThinking()
Section titled “setThinking()”setThinking(thinking): void;动态切换思考生成(生成面旋钮,setModel 同形制):下一轮生效,运行中轮 不受影响。undefined = 回到不注入(模型缺省);呈现面(思考显示与否) 走 SessionView delivery,两旋钮正交互不推导。
thinking
Section titled “thinking”| {
budget?: number;
}
| undefined
void
submitInput()
Section titled “submitInput()”submitInput(input): Promise<SessionInputResult>;Promise<SessionInputResult>
本文是否有帮助?
感谢反馈,我们会持续改进这篇文章。