@tbox.cn/dsh-acp-bridge-core 0.1.0-rc.4 → 0.1.0-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -59,37 +59,36 @@ declare function isIgnorable(event: {
59
59
  }): boolean;
60
60
  //#endregion
61
61
  //#region src/kinds.d.ts
62
- /**
63
- * 工具呈现映射——kind 静态表 · locations 门控列 · title 构造器。
64
- *
65
- * kind 判定 = bridge-core 自建名字→kind 静态映射(移植基线 TOOL_KIND_MAP,
66
- * 键面适配 dsh 原生工具名;dsh 呈现层 GenericCallView.kind 是呈现层字段而非
67
- * 事件流字段,WS 载体不可依赖——决策 [acp-projection-contract] tool_call 行)。
68
- * 前缀规则:`subagent_` 族 → other(多实例委派工具);`scratch_` 家族镜像
69
- * bash / write / edit 原型(形态签名呈现的 kind 对位,决策
70
- * [plan-mode-sandbox-composition] 工具呈现映射节)。
71
- *
72
- * locations 规则照抄基线 0.9.20 `toLocations` 门控(input 派生 + [edit, write]
73
- * 白名单;决策 [dependency-baseline-refresh]——真源 = LOCATIONS_ALLOWED 列,
74
- * scratch 两件显式 true;dsh meta locations 通道不消费)。
75
- *
76
- * title 构造器逐字移植基线(agent/tool/title.ts),键面适配 dsh 名
77
- * (todo_write / web_fetch / web_search),行为基线 = "verb + object"。
78
- */
79
62
  /** ACP ToolCallKind 词面(对齐 @agentclientprotocol/sdk v1 稳定面)。 */
80
63
  type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'think' | 'fetch' | 'other';
81
64
  /** locations 白名单列(投影基准表真源;基线 0.9.20 `[edit, write]` + scratch 两件显式 true)。 */
82
65
  declare const LOCATIONS_ALLOWED: Set<string>;
83
66
  declare function toolKind(name: string): ToolCallKind;
67
+ declare const pickPath: (i: Record<string, unknown>) => string | undefined;
68
+ declare const pickOld: (i: Record<string, unknown>) => string | undefined;
69
+ declare const pickNew: (i: Record<string, unknown>) => string | undefined;
70
+ /** 相对路径绝对化(已绝对原样;cwd 缺席原样;解析失败不抛)。 */
71
+ declare function absolutize(p: string | undefined, cwd: string | undefined): string | undefined;
84
72
  /**
85
73
  * Build ACP tool-call locations from a tool's input.
86
74
  *
87
75
  * 照抄基线 0.9.20 `toLocations`(projector.ts:155-182):input 派生 +
88
76
  * 白名单门控——read/glob/grep 接受目录路径,客户端(zed < fix)对每个
89
77
  * location 做 eager 解析会以目录为根建隐藏 worktree 无界扫描(25GB+ 实测);
90
- * 目录能力工具的 location 是放大器,2026-10-12 起移除。
78
+ * 目录能力工具的 location 是放大器,2026-10-12 起移除。路径按 cwd 绝对化
79
+ * (ACP ToolCallLocation.path 契约)。
80
+ */
81
+ declare function toLocations(name: string, input: unknown, cwd?: string): Array<{
82
+ path: string;
83
+ line: number | null;
84
+ }>;
85
+ /**
86
+ * 结果期 locations:meta.path(dsh 呈现层 canonical 绝对路径)优先,否则 input
87
+ * 派生。**白名单门控优先于 meta.path**——read / read_image 等目录与图像能力
88
+ * 工具在 dsh 呈现层同样携带 `{path}` meta,不得因此绕过 eager 解析门控
89
+ * (LOCATIONS_ALLOWED 是唯一真源,[dependency-baseline-refresh])。
91
90
  */
92
- declare function toLocations(name: string, input: unknown): Array<{
91
+ declare function locationsForResult(name: string, input: unknown, meta: unknown, cwd?: string): Array<{
93
92
  path: string;
94
93
  line: number | null;
95
94
  }>;
@@ -101,6 +100,11 @@ declare const TOOL_TITLE_BUILDERS: Record<string, (i: Record<string, unknown>) =
101
100
  * 返回裸动词)。
102
101
  */
103
102
  declare function buildToolTitle(name: string, input: unknown): string;
103
+ /**
104
+ * 结果期 title:pending title + dsh presentationMeta 后缀(write 家族
105
+ * created/updated;edit 家族 N changes)。meta 缺席零后缀(旧日志降级)。
106
+ */
107
+ declare function buildToolResultTitle(name: string, input: unknown, meta: unknown): string;
104
108
  /**
105
109
  * 子透传工具 title 前缀(基线 withSubagentPrefix 对位——subagent-native-adoption
106
110
  * 收官补齐):`[label|sid后8位] title`。label 缺席(catalog 未到达 / 无 label)
@@ -204,6 +208,42 @@ declare function agentCapabilities(negotiatedVersion: number): {
204
208
  meta: AgentCapabilitiesMeta;
205
209
  };
206
210
  //#endregion
211
+ //#region src/attempts.d.ts
212
+ /**
213
+ * 流式 attempt 登记——dsh `agent/assistant-stream` 与 durable `assistant/message`
214
+ * 的配对状态(per-channel 注入 ProjectOptions,stateless 投影纪律)。
215
+ *
216
+ * 配对键 = `(turn, step)`:dsh agent loop 把同一 phase 的 turn/step 同时传给流式
217
+ * start 帧与 durable append(两端同源),同一 step 的重试 attempt 由后到者覆盖
218
+ * (旧 attempt 内容已随流式发出、无法撤回——retry 语义固有,归已知限制)。
219
+ *
220
+ * `resolve` 语义 = 查找 → 调用方 `fits` 校验 → **无论成败消费**:同一
221
+ * `(turn, step)` 只有一个 durable `assistant/message`,消费避免残留污染后续配对;
222
+ * 未命中返回 undefined(投影层走全量回退,即修复前行为)。
223
+ */
224
+ /** 一个流式 attempt 的投影快照(文本 = 已经由流式通道发出的累计内容)。 */
225
+ interface AttemptSnapshot {
226
+ attemptId: string;
227
+ turn: number;
228
+ step: number;
229
+ text: string;
230
+ reasoning: string;
231
+ }
232
+ declare class StreamAttemptState {
233
+ #private;
234
+ /** start 帧登记;同一 `(turn, step)` 的新 attempt 覆盖旧记录(重试 = 新 attempt)。 */
235
+ begin(attemptId: string, turn: number, step: number): void;
236
+ /** chunk 帧累计(记录缺席 = start 未到达,忽略累计——chunk 仍由投影层原样发出)。 */
237
+ record(attemptId: string, kind: 'text' | 'reasoning', text: string): void;
238
+ /**
239
+ * durable `assistant/message` 配对:精确 `(turn, step)` 查找 → `fits` 校验 →
240
+ * 消费。`fits` 失败同样消费(该 step 的 durable 已落定,记录不应再参与后续配对)。
241
+ */
242
+ resolve(turn: number, step: number, fits: (snapshot: AttemptSnapshot) => boolean): AttemptSnapshot | undefined;
243
+ /** 通道关闭清空。 */
244
+ clear(): void;
245
+ }
246
+ //#endregion
207
247
  //#region src/project.d.ts
208
248
  /** 工具调用登记——tool/call → { name, input },tool/result 查询(dsh 事件无冗余的对位)。 */
209
249
  declare class ToolJournal {
@@ -272,6 +312,12 @@ interface ProjectOptions {
272
312
  text: number;
273
313
  reasoning: number;
274
314
  }>;
315
+ /**
316
+ * 流式 attempt 配对表(per-channel 注入):durable `assistant/message` 到达时
317
+ * 按 `(turn, step)` 找到同源流式累计,只补发未发出的后缀并复用 attemptId。
318
+ * live 投影必须注入;回放(live:false)不注入。
319
+ */
320
+ attempts?: StreamAttemptState;
275
321
  /** 工具调用登记(载体层持有,随会话生命周期)。 */
276
322
  journal?: ToolJournal;
277
323
  /** subagent/catalog 编排消费钩子(零标准 update 发射)。 */
@@ -280,6 +326,8 @@ interface ProjectOptions {
280
326
  subagents?: SubagentCatalogState;
281
327
  /** 终端协议门控(客户端 `_meta.terminal_output` 声明——基线 supportsTerminalOutput)。 */
282
328
  supportsTerminalOutput?: boolean;
329
+ /** 会话 cwd(locations / diff 绝对化基准——载体注入;缺席时相对路径原样降级)。 */
330
+ cwd?: string;
283
331
  }
284
332
  /**
285
333
  * 子会话事件透传投影(live 专用——基线 ephemeral 语义,回放不透传):子 tool
@@ -290,6 +338,7 @@ interface ProjectOptions {
290
338
  declare function projectSubagentChildEvent(childId: string, ev: SessionEvent, state: SubagentCatalogState, opts: {
291
339
  journal: ToolJournal;
292
340
  supportsTerminalOutput?: boolean;
341
+ cwd?: string;
293
342
  }): SessionUpdate[];
294
343
  /**
295
344
  * 事件投影入口(分类查表 → 分支投影)。
@@ -308,11 +357,15 @@ interface AssistantStreamFrameLike {
308
357
  type: string;
309
358
  text?: string;
310
359
  };
360
+ /** start 帧携带的 durable turn/step(与 assistant/message 配对用;其余帧缺席)。 */
361
+ turn?: number;
362
+ step?: number;
311
363
  }
312
364
  /**
313
365
  * 流式帧投影:text-delta → agent_message_chunk、reasoning-delta → agent_thought_chunk
314
- * (messageId = attemptId——流 start / durable 记录 id 的边界对位,基准表流式 chunk
315
- * 边界行);start / end / 其他 chunk 类型零发射。live 专用(回放走 durable)。
366
+ * (messageId = attemptId——同一条消息的 chunk 共享 messageId,durable 落定后只补
367
+ * 后缀并沿用该 id);start 帧登记 attempt 的 `(turn, step)`,end / 其他 chunk 零发射。
368
+ * live 专用(回放走 durable)。
316
369
  */
317
370
  declare function projectStreamFrame(frame: AssistantStreamFrameLike, opts: ProjectOptions): SessionUpdate[];
318
371
  /**
@@ -339,6 +392,10 @@ declare class TurnFoldTracker {
339
392
  * surfaceOp / ignorable);来源分类:dsh 0.2.1-rc.2 类型推导(类型面字段——0.2.1 实测 wire 面字段零漂移,快照免重录)与
340
393
  * echo driver 实测形状(流式帧),文件头登记。断言面 = update 判别联合的
341
394
  * 逐字段形状(表格驱动,[acp-projection-contract] 场景驱动表行一一对应)。
395
+ *
396
+ * 2026-11-03([acp-tool-presentation-fidelity]):工具帧统一携带 ACP `name`
397
+ * 字段;diff 断言覆盖三源优先级(meta.diffs / meta.path / 输入回退——真机
398
+ * 参数为 snake_case,键归一在 kinds.ts);locations 按 fixture.cwd 绝对化。
342
399
  */
343
400
  interface WireFixture {
344
401
  /** 场景名(与契约场景驱动表行对应)。 */
@@ -355,6 +412,8 @@ interface WireFixture {
355
412
  expectedDerived?: Array<Record<string, unknown>>;
356
413
  /** unknown 事件分级记档期望:[type, level] 序列。 */
357
414
  expectedUnknown?: Array<[string, 'debug' | 'warn']>;
415
+ /** 会话 cwd(locations / diff 绝对化基准——runner 注入 ProjectOptions.cwd)。 */
416
+ cwd?: string;
358
417
  }
359
418
  declare const WIRE_FIXTURES: WireFixture[];
360
419
  //#endregion
@@ -516,9 +575,15 @@ declare function isAcpSessionMode(value: string): value is AcpSessionMode;
516
575
  * mode → 双 knob 语义映射;未知 mode 返回 undefined(调用方转 invalidParams)。
517
576
  */
518
577
  declare function translateMode(mode: string): ModeKnobs | undefined;
578
+ /**
579
+ * effective sandbox → 初始 ACP mode(create / resume 推导源——决策
580
+ * [acp-mode-initialization]):read-only → plan;其余(含 undefined:服务缺席
581
+ * 形态)→ build。
582
+ */
583
+ declare function modeFromSandbox(mode: string | undefined): AcpSessionMode;
519
584
  /** mode 选项构造(category 'mode'——UX 语义分类;currentValue 由载体状态供给)。 */
520
585
  declare function modeConfigOption(currentMode: AcpSessionMode): SessionConfigOption;
521
586
  /** opaque 选项 value 编码:携带完整 route 身份(in-tree modelValue 对位,无 JSON.parse)。 */
522
587
  declare function resolveModelValue(provider: string, model: string): string;
523
588
  //#endregion
524
- export { type AcpSessionMode, type AgentCapabilitiesMeta, type AskUserQuestionAnswerLike, type AskUserQuestionItemLike, type AssistantStreamFrameLike, COMMAND_GATE_PATTERN, type Classification, type ClassifiedEventType, type CommandDescriptorLike, type CommandGateResult, type CommandOutcome, type ElicitationContentValue, type ElicitationSchema, LATEST_PROTOCOL_VERSION, LOCATIONS_ALLOWED, MODEL_CONFIG_ID, MODE_CONFIG_ID, MODE_TABLE, type ModeKnobs, PROTOCOL_VERSIONS, PROVIDER_DEFAULT_REASONING_VALUE, type ProjectOptions, REASONING_CONFIG_ID, RpcErrorCode, type RpcErrorData, type RpcErrorInput, SHADOW_COMMANDS, SHADOW_COMMANDS_RATIONALE, type SkillSummaryLike, type SubagentCatalogPayload, SubagentCatalogState, TOOL_TITLE_BUILDERS, type ToolCallKind, ToolJournal, TurnFoldTracker, WIRE_FIXTURES, type WireFixture, agentCapabilities, buildElicitationSchema, buildToolTitle, classify, commandGate, commandsProjection, isAcpSessionMode, isIgnorable, mapRpcError, modeConfigOption, negotiateProtocolVersion, parseElicitationContent, parseToolArguments, projectEvent, projectRecord, projectStreamFrame, projectSubagentChildEvent, resolveModelValue, settleToResponse, slugifyQuestion, stopReasonFromTurnEnd, toLocations, toolKind, translateMode, withSubagentPrefix };
589
+ export { type AcpSessionMode, type AgentCapabilitiesMeta, type AskUserQuestionAnswerLike, type AskUserQuestionItemLike, type AssistantStreamFrameLike, type AttemptSnapshot, COMMAND_GATE_PATTERN, type Classification, type ClassifiedEventType, type CommandDescriptorLike, type CommandGateResult, type CommandOutcome, type ElicitationContentValue, type ElicitationSchema, LATEST_PROTOCOL_VERSION, LOCATIONS_ALLOWED, MODEL_CONFIG_ID, MODE_CONFIG_ID, MODE_TABLE, type ModeKnobs, PROTOCOL_VERSIONS, PROVIDER_DEFAULT_REASONING_VALUE, type ProjectOptions, REASONING_CONFIG_ID, RpcErrorCode, type RpcErrorData, type RpcErrorInput, SHADOW_COMMANDS, SHADOW_COMMANDS_RATIONALE, type SkillSummaryLike, StreamAttemptState, type SubagentCatalogPayload, SubagentCatalogState, TOOL_TITLE_BUILDERS, type ToolCallKind, ToolJournal, TurnFoldTracker, WIRE_FIXTURES, type WireFixture, absolutize, agentCapabilities, buildElicitationSchema, buildToolResultTitle, buildToolTitle, classify, commandGate, commandsProjection, isAcpSessionMode, isIgnorable, locationsForResult, mapRpcError, modeConfigOption, modeFromSandbox, negotiateProtocolVersion, parseElicitationContent, parseToolArguments, pickNew, pickOld, pickPath, projectEvent, projectRecord, projectStreamFrame, projectSubagentChildEvent, resolveModelValue, settleToResponse, slugifyQuestion, stopReasonFromTurnEnd, toLocations, toolKind, translateMode, withSubagentPrefix };
package/lib/index.js CHANGED
@@ -1,2 +1,11 @@
1
- const e={"user/message":`project`,"assistant/message":`project`,"tool/call":`project`,"tool/result":`project`,"todo/write":`project`,"session/title":`project`,"command/run":`project`,"command/done":`project`,"subagent/catalog":`project`,"turn/start":`project`,"turn/end":`project`,"step/start":`skip`,"step/end":`skip`,"developer/message":`skip`,"system/message":`skip`,"assistant/attempt":`skip`,"request/header":`skip`,"request/context":`skip`,"session/end-seed":`skip`,"agent/inbox/spliced":`skip`,"tool/ptc-dispatch-start":`skip`,"tool/ptc-dispatch":`skip`,"subagent/descriptor":`skip`,"approval/asked":`skip`,"approval/decided":`skip`,"approval/policy":`skip`,"permission/preset":`skip`,"sandbox/mode":`skip`,"model/selection":`skip`,"goal/change":`skip`};function t(t){return e[t]??`unknown`}function n(e){return e.ignorable===!0}const r={read:`read`,read_image:`read`,write:`edit`,edit:`edit`,bash:`execute`,pwsh:`execute`,glob:`search`,grep:`search`,web_search:`search`,web_fetch:`fetch`,webfetch:`fetch`,todo_write:`think`,plan:`think`,skill:`other`},i=new Set([`edit`,`write`,`scratch_write`,`scratch_edit`]);function a(e){return r[e]||(e.startsWith(`scratch_`)?r[e.slice(8)]??`other`:(e.startsWith(`subagent_`),`other`))}const o=e=>typeof e==`string`?e:void 0;function s(e,t){if(!i.has(e))return[];let n=t??{},r=o(n.filePath??n.path);return r?[{path:r,line:typeof n.line==`number`?n.line:typeof n.lineNumber==`number`?n.lineNumber:null}]:[]}const c={bash:e=>{let t=o(e.command),n=o(e.description);return n?`${n} (${t?.slice(0,60)??``})`:t?`Execute ${t.slice(0,120)}${t.length>120?`…`:``}`:`Execute`},pwsh:e=>{let t=o(e.command);return t?`Execute ${t.slice(0,120)}${t.length>120?`…`:``}`:`Execute`},read:e=>`Read ${o(e.filePath??e.path)??`file`}`,read_image:e=>`Read image ${o(e.filePath??e.path)??`file`}`,write:e=>`Write ${o(e.filePath??e.path)??`file`}`,edit:e=>`Edit ${o(e.filePath??e.path)??`file`}`,grep:e=>{let t=o(e.pattern),n=o(e.path);return`Grep${t?` "${t}"`:``}${n?` in ${n}`:``}`},glob:e=>`Glob ${o(e.pattern)??``}`,web_fetch:e=>`Fetch ${o(e.url)??`URL`}`,web_search:e=>{let t=o(e.query);return`Search${t?` "${t}"`:``}`},webfetch:e=>{let t=o(e.url),n=o(e.format);return`Fetch ${t??`URL`}${n&&n!==`markdown`?` (${n})`:``}`},todo_write:e=>{let t=e.todos,n=Array.isArray(t)?t:[],r=n.filter(e=>e.status===`completed`).length;return`Update TODOs${n.length?` (${r}/${n.length})`:``}`},ask_user_question:()=>`Ask the user`,skill:e=>`Load skill: ${o(e.name)??``}`};function l(e,t){return(c[e]??(()=>e))(t??{})}function u(e,t,n){return`[${t??`subagent:${n.slice(-8)}`}] ${e}`}function d(e){if(e!==void 0)try{let t=JSON.parse(e);return typeof t==`object`&&t?t:void 0}catch{return}}const f={methodNotFound:-32601,invalidParams:-32602,conflict:-32600,internal:-32603,sessionNotFound:-32002},p=e=>typeof e==`string`?e:void 0;function m(e){let t=e.message,n=e.data&&typeof e.data==`object`?e.data:{};switch(e.code){case`session-not-found`:{let e=p(n.sessionId);return{code:f.sessionNotFound,message:t??`session not found`,data:e===void 0?void 0:{uri:`session:${e}`}}}case`session/writer-held`:return{code:f.conflict,message:t??`session is owned by another writer`,data:{reason:p(n.reason)??`writer-held`,retryable:!0}};case`turn-error`:return{code:f.internal,message:t??`turn failed`,data:{sessionId:p(n.sessionId),kind:p(n.kind)??`turn-error`,retryable:n.retryable===!0,code:p(n.code),partialOutput:n.partialOutput===!0}};case`llm-auth`:return{code:f.internal,message:t??`llm credential missing`,data:{kind:`auth`,retryable:!1}};case`retry-after-turn`:return{code:f.internal,message:t??`reload in progress`,data:{retryable:!0,reason:`skill_reload_in_progress`}};case`method-not-found`:return{code:f.methodNotFound,message:t??`method not found`};case`invalid-params`:return{code:f.invalidParams,message:t??`invalid params`,data:n.errors===void 0?void 0:{errors:n.errors}};default:return{code:f.internal,message:t??`dsh error`,data:{kind:`unknown-dsh-error`,...e.code===void 0?{}:{code:e.code},...Object.keys(n).length>0?{detail:n}:{}}}}}function h(e){let t=e?.kind;switch(t){case`completed`:case`aborted`:case`blocked`:return{stopReason:`end_turn`};case`interrupted`:return{stopReason:`cancelled`};case`max-tokens`:return{stopReason:`max_tokens`};case`error`:return{error:!0};case`forked`:default:return{stopReason:`end_turn`,warn:`unknown turn end reason: ${String(t)}`}}}const g=[1],_=g[g.length-1]??1;function v(e){return e===void 0?{version:_}:g.includes(e)?{version:e}:{version:_,warn:`client protocol version ${e} not in supported set`}}function ee(e){return{capabilities:{loadSession:!0,promptCapabilities:{}},meta:{openacpagent:{usage:{},image:{}},tboxcode:{protocolVersion:e}}}}var y=class{#e=new Map;record(e,t,n){this.#e.set(e,{name:t,input:d(n)})}lookup(e){return this.#e.get(e)}},b=class{byChild=new Map;#e=new Map;#t=new Map;#n=new Map;accept(e){this.byChild.set(e.childId,{mode:e.mode,...e.label===void 0?{}:{label:e.label}});let t=this.#e.size>1;for(let[n,r]of this.#e)this.#t.set(n,{childId:e.childId,toolName:r,...e.label===void 0?{}:{label:e.label},ambiguous:t});this.#e.size===1&&this.#n.set(e.childId,[...this.#e.keys()][0]),this.#e.clear()}trackDelegation(e,t){this.#e.set(e,t)}tracks(e){return this.byChild.has(e)}parentCallIdOf(e){return this.#n.get(e)}labelOfChild(e){return this.byChild.get(e)?.label}metaFor(e,t){let n=this.#t.get(e),r=n?.toolName??t,i=r===`subagent`?`general`:r.startsWith(`subagent_`)?r.slice(9):r;return n===void 0||n.ambiguous?{runId:e,agentType:i}:{runId:n.childId,agentType:i,...n.label===void 0?{}:{name:n.label}}}};const x=e=>typeof e==`string`?e:void 0,S=e=>e.data??{};function C(e,t){return{sessionUpdate:`user_message_chunk`,content:{type:`text`,text:e},...t?{messageId:t}:{}}}function w(e,t){return{sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:e},...t?{messageId:t}:{}}}function T(e,t){return{sessionUpdate:`agent_thought_chunk`,content:{type:`text`,text:e},...t?{messageId:t}:{}}}function E(e,t,n,r){return{sessionUpdate:`usage_update`,used:e,size:t,_meta:{openacpagent:{usage:{cacheReadTokens:n,cacheWriteTokens:r}}}}}function D(e,t){if(e.source?.kind!==`user`)return[];let n=e,r=typeof n.id==`string`?n.id:null,i=n.content??[];if(i.length===0)return[C(``,r)];let a=[];for(let e of i)e.type===`text`?a.push(C(x(e.text)??``,r)):a.push(C(`[${String(e.type)}]`,r));return a}function O(e,t){let n=e.message,r=[],i=typeof n?.id==`string`?n.id:null,a=t.seen,o=n?.content??[];for(let e of o){let t=e.type;if(t!==`text`&&t!==`reasoning`)continue;let n=x(e.text)??``;if(a){let e=i??``,o=a.get(e)??{text:0,reasoning:0},s=t===`reasoning`?`reasoning`:`text`,c=n.slice(o[s]);if(!c)continue;o[s]=n.length,a.set(e,o),r.push(t===`reasoning`?T(c,i):w(c,i))}else r.push(t===`reasoning`?T(n,i):w(n,i))}let s=e.usage;if(s){let e=(typeof s.totalTokens==`number`?s.totalTokens:void 0)??(typeof s.inputTokens==`number`?s.inputTokens:0)+(typeof s.outputTokens==`number`?s.outputTokens:0);r.push(E(e,2e5,typeof s.cacheReadTokens==`number`?s.cacheReadTokens:0,typeof s.cacheWriteTokens==`number`?s.cacheWriteTokens:0))}return r}function te(e,t){let n=x(e.callId)??``,r=x(e.name)??`unknown`,i=x(e.arguments);t.journal?.record(n,r,i);let o=d(i);t.subagents!==void 0&&(r===`subagent`||r.startsWith(`subagent_`))&&t.subagents.trackDelegation(n,r);let c=r===`bash`&&t.supportsTerminalOutput===!0;return[{sessionUpdate:`tool_call`,toolCallId:n,title:l(r,o),kind:a(r),status:`pending`,locations:s(r,o),rawInput:o??{},...c?{content:[{type:`terminal`,terminalId:n}]}:{}}]}function ne(e,t){let n=e.message,r=x(n?.toolCallId)??``,i=t.journal?.lookup(r),o=i?.name??`unknown`,c=i?.input,u=n?.isError===!0||e.error!==void 0?`failed`:`completed`,d=l(o,c),f=(n?.content??[]).filter(e=>e.type===`text`).map(e=>x(e.text)??``).join(``),p=[];if((o===`edit`||o===`write`)&&c!==void 0){let e=c;x(e.filePath)!==void 0&&p.push({type:`diff`,path:String(e.filePath),oldText:x(e.oldString)??null,newText:x(e.newString)??x(e.content)??``})}let m=o===`bash`;m&&t.supportsTerminalOutput===!0?p.push({type:`terminal`,terminalId:r}):f.trimEnd()&&p.push({type:`content`,content:{type:`text`,text:f}});let h={},g=e.meta;return g!=null&&(h.openacpagent={toolMeta:g}),t.subagents!==void 0&&(o===`subagent`||o.startsWith(`subagent_`))&&(h.openacpagent={...h.openacpagent,subagent:t.subagents.metaFor(r,o)}),m&&t.supportsTerminalOutput===!0?[{sessionUpdate:`tool_call_update`,toolCallId:r,_meta:{terminal_output:{terminal_id:r,data:f}}},{sessionUpdate:`tool_call_update`,toolCallId:r,status:u,title:d,kind:a(o),locations:s(o,c),rawInput:c??{},rawOutput:{content:n?.content??[],meta:g,error:e.error},...p.length>0?{content:p}:{},_meta:{...h,terminal_exit:{terminal_id:r,exit_code:u===`completed`?0:1,signal:null}}}]:[{sessionUpdate:`tool_call_update`,toolCallId:r,status:u,title:d,kind:a(o),locations:s(o,c),rawInput:c??{},rawOutput:{content:n?.content??[],meta:g,error:e.error},...p.length>0?{content:p}:{},...Object.keys(h).length>0?{_meta:h}:{}}]}function re(e,t,n,r){let i=t.type,o=S(t),c=n.parentCallIdOf(e)??e;if(i===`tool/call`){let t=x(o.callId)??``,i=x(o.name)??`unknown`,f=x(o.arguments);r.journal.record(t,i,f);let p=d(f),m=i===`bash`&&r.supportsTerminalOutput===!0;return[{sessionUpdate:`tool_call`,toolCallId:`${c}:${t}`,title:u(l(i,p),n.labelOfChild(e),e),kind:a(i),status:`pending`,locations:s(i,p),rawInput:p??{},...m?{content:[{type:`terminal`,terminalId:`${c}:${t}`}]}:{}}]}if(i===`tool/result`){let t=o.message,i=x(t?.toolCallId)??``,d=r.journal.lookup(i),f=d?.name??`unknown`,p=d?.input,m=t?.isError===!0||o.error!==void 0?`failed`:`completed`,h=(t?.content??[]).filter(e=>e.type===`text`).map(e=>x(e.text)??``).join(``);return[{sessionUpdate:`tool_call_update`,toolCallId:`${c}:${i}`,status:m,title:u(l(f,p),n.labelOfChild(e),e),kind:a(f),locations:s(f,p),rawInput:p??{},rawOutput:{content:t?.content??[],error:o.error},...h.trimEnd()?{content:[{type:`content`,content:{type:`text`,text:h}}]}:{},_meta:{openacpagent:{subagent:n.metaFor(c,f)}}}]}return[]}function ie(e){return[{sessionUpdate:`plan`,entries:(e.todos??[]).map(e=>({content:x(e.content)??``,status:e.status===`in_progress`?`in_progress`:e.status===`completed`?`completed`:`pending`}))}]}function ae(e,t){let n=t.source;return[{sessionUpdate:`session_info_update`,title:x(t.title)??null,updatedAt:new Date(e.time).toISOString(),_meta:n?.kind===void 0?{}:{openacpagent:{titleSource:n.kind}}}]}function oe(e){let t=x(e.name)??``,n=x(e.args);return[C(`/${t}${n?` ${n}`:``}`,x(e.commandId))]}function se(e){let t=e.kind===`success`?`success`:`error`,n=w(x(e.text)??(t===`success`?`Command completed`:`Command failed`),x(e.commandId));return typeof e.sourceEventSeq==`number`&&(n._meta={openacpagent:{sourceEventSeq:e.sourceEventSeq}}),[n]}function k(e,r,i){let a=t(e.type);if(a===`skip`)return[];if(a===`unknown`)return i?.(e.type,n(e)?`debug`:`warn`),[];let o=S(e);switch(e.type){case`user/message`:return D(o,r);case`assistant/message`:return O(o,r);case`tool/call`:return te(o,r);case`tool/result`:return ne(o,r);case`todo/write`:return ie(o);case`session/title`:return ae(e,o);case`command/run`:return oe(o);case`command/done`:return se(o);case`subagent/catalog`:{let t=x(o.childId);if(t!==void 0){let n=o;r.subagents?.accept({childId:t,childCreatedAt:typeof n.childCreatedAt==`number`?n.childCreatedAt:e.time,mode:x(n.mode)??`unknown`,label:x(n.label)}),r.onSubagentCatalog?.({childId:t,childCreatedAt:typeof n.childCreatedAt==`number`?n.childCreatedAt:e.time,mode:x(n.mode)??`unknown`,label:x(n.label)})}return[]}case`turn/start`:case`turn/end`:return[];default:return[]}}function ce(e,t,n){return k(e,{...t,live:!1},n)}function le(e,t){if(!t.live||e.type!==`chunk`)return[];let n=e.chunk?.type;return n===`text-delta`?[w(x(e.chunk?.text)??``,e.attemptId)]:n===`reasoning-delta`?[T(x(e.chunk?.text)??``,e.attemptId)]:[]}var ue=class{#e=[];constructor(e){this.onDerived=e}accept(e){let t=e.data??{};if(e.type===`turn/start`&&typeof t.turn==`number`)this.#e.push({turn:t.turn,tools:new Map});else if(e.type===`tool/call`&&typeof t.callId==`string`)this.#e[this.#e.length-1]?.tools.set(t.callId,{resolved:!1});else if(e.type===`tool/result`){let e=t.message,n=x(e?.toolCallId),r=this.#e[this.#e.length-1];if(n!==void 0&&r!==void 0){let e=r.tools.get(n);e&&(e.resolved=!0)}}else if(e.type===`turn/end`){let e=this.#e[this.#e.length-1];if(e){for(let[t,n]of e.tools)n.resolved||this.onDerived({sessionUpdate:`tool_call_update`,toolCallId:t,status:`failed`,_meta:{derived:!0}});this.#e.pop()}}}};let A=0;const j=(e,t,n={})=>({type:e,seq:++A,time:17e11,data:t,...n}),M={id:`msg-u1`,role:`user`,content:[{type:`text`,text:`hello`}],source:{kind:`user`}},N={id:`msg-cat1`,role:`user`,content:[{type:`text`,text:`<skill catalog>`}],source:{kind:`skill-catalog`,form:`catalog`,entries:[]}},P={id:`msg-rc1`,role:`user`,content:[{type:`text`,text:`<runtime context>`}],source:{kind:`runtime-context`}},F={id:`msg-a1`,role:`assistant`,content:[{type:`text`,text:`world`}],source:{kind:`model`,provider:`echo`,model:`echo`}},I={id:`msg-a2`,role:`assistant`,content:[{type:`reasoning`,text:`thinking…`},{type:`text`,text:`answer`}],source:{kind:`model`,provider:`echo`,model:`echo`}},L=[{name:`echo-whitelist`,events:[j(`user/message`,N),j(`user/message`,P),j(`user/message`,M)],expectedLive:[R(`hello`,`msg-u1`)]},{name:`user-last-subagent-task`,events:[j(`user/message`,{...M,id:`msg-task`,content:[{type:`text`,text:`delegate task`}]})],expectedLive:[R(`delegate task`,`msg-task`)]},{name:`assistant-durable-mixed`,events:[j(`assistant/message`,{turn:1,step:1,message:I,stream:[],usage:{inputTokens:10,outputTokens:5,totalTokens:15,cacheReadTokens:3,cacheWriteTokens:2}})],expectedLive:[B(`thinking…`,`msg-a2`),z(`answer`,`msg-a2`),V(15,3,2)]},{name:`assistant-durable-no-usage`,events:[j(`assistant/message`,{turn:1,step:2,message:F,stream:[]})],expectedLive:[z(`world`,`msg-a1`)]},{name:`tool-lifecycle-bash`,events:[j(`turn/start`,{turn:1}),j(`tool/call`,{turn:1,step:1,callId:`c1`,name:`bash`,arguments:`{"command":"ls -la"}`}),j(`tool/result`,{turn:1,step:1,message:{toolCallId:`c1`,role:`tool`,content:[{type:`text`,text:`file.txt`}]}}),j(`turn/end`,{turn:1,reason:{kind:`completed`}})],expectedLive:[U(`c1`,`Execute ls -la`,`execute`,{command:`ls -la`}),W(`c1`,`completed`,`Execute ls -la`,`execute`,[],{command:`ls -la`},{content:[{type:`text`,text:`file.txt`}],contentFrames:[{type:`content`,content:{type:`text`,text:`file.txt`}}]})],expectedDerived:[]},{name:`tool-derived-failed`,events:[j(`turn/start`,{turn:1}),j(`tool/call`,{turn:1,step:1,callId:`c2`,name:`read`,arguments:`{"filePath":"a.ts"}`}),j(`turn/end`,{turn:1,reason:{kind:`error`}})],expectedLive:[U(`c2`,`Read a.ts`,`read`,{filePath:`a.ts`})],expectedDerived:[{sessionUpdate:`tool_call_update`,toolCallId:`c2`,status:`failed`,_meta:{derived:!0}}]},{name:`edit-diff-locations`,events:[j(`tool/call`,{turn:1,step:1,callId:`c3`,name:`edit`,arguments:`{"filePath":"src/a.ts","oldString":"a","newString":"b"}`}),j(`tool/result`,{turn:1,step:1,message:{toolCallId:`c3`,role:`tool`,content:[{type:`text`,text:`ok`}]}})],expectedLive:[U(`c3`,`Edit src/a.ts`,`edit`,{filePath:`src/a.ts`,oldString:`a`,newString:`b`},[{path:`src/a.ts`,line:null}]),W(`c3`,`completed`,`Edit src/a.ts`,`edit`,[{path:`src/a.ts`,line:null}],{filePath:`src/a.ts`,oldString:`a`,newString:`b`},{content:[{type:`text`,text:`ok`}],contentFrames:[{type:`diff`,path:`src/a.ts`,oldText:`a`,newText:`b`},{type:`content`,content:{type:`text`,text:`ok`}}]})]},{name:`locations-gated-read`,events:[j(`tool/call`,{turn:1,step:1,callId:`c4`,name:`read`,arguments:`{"filePath":"a.ts"}`}),j(`tool/result`,{turn:1,step:1,message:{toolCallId:`c4`,role:`tool`,content:[{type:`text`,text:`x`}]}})],expectedLive:[U(`c4`,`Read a.ts`,`read`,{filePath:`a.ts`}),W(`c4`,`completed`,`Read a.ts`,`read`,[],{filePath:`a.ts`},{content:[{type:`text`,text:`x`}],contentFrames:[{type:`content`,content:{type:`text`,text:`x`}}]})]},{name:`journal-missing-degraded`,events:[j(`tool/result`,{turn:1,step:1,message:{toolCallId:`ghost`,role:`tool`,content:[{type:`text`,text:`late`}]}})],expectedLive:[W(`ghost`,`completed`,`unknown`,`other`,[],{},{content:[{type:`text`,text:`late`}],contentFrames:[{type:`content`,content:{type:`text`,text:`late`}}]})]},{name:`plan-todo-write`,events:[j(`todo/write`,{todos:[{content:`a`,status:`completed`},{content:`b`,status:`in_progress`},{content:`c`,status:`pending`}]})],expectedLive:[{sessionUpdate:`plan`,entries:[{content:`a`,status:`completed`},{content:`b`,status:`in_progress`},{content:`c`,status:`pending`}]}]},{name:`session-info-title`,events:[j(`session/title`,{title:`Fix bug`,messageSeqs:[1],source:{kind:`provider`,provider:`p`}})],expectedLive:[{sessionUpdate:`session_info_update`,title:`Fix bug`,updatedAt:new Date(17e11).toISOString(),_meta:{openacpagent:{titleSource:`provider`}}}]},{name:`command-projection`,events:[j(`command/run`,{commandId:`cmd1`,name:`compact`,source:{kind:`user`}}),j(`command/done`,{commandId:`cmd1`,kind:`success`,text:`compacted`,sourceEventSeq:9})],expectedLive:[R(`/compact`,`cmd1`),H(z(`compacted`,`cmd1`),{openacpagent:{sourceEventSeq:9}})]},{name:`command-echo-record-input-false`,events:[j(`command/run`,{commandId:`cmd2`,name:`feedback`,source:{kind:`user`}})],expectedLive:[R(`/feedback`,`cmd2`)]},{name:`stream-frame-boundaries`,events:[],streamFrames:[{type:`start`,attemptId:`att1`},{type:`chunk`,attemptId:`att1`,chunk:{type:`text-delta`,text:`he`}},{type:`chunk`,attemptId:`att1`,chunk:{type:`reasoning-delta`,text:`think`}},{type:`chunk`,attemptId:`att1`,chunk:{type:`tool-call-delta`}},{type:`end`,attemptId:`att1`,index:2,outcome:{kind:`committed`,eventType:`assistant/message`,seq:5}}],expectedLive:[z(`he`,`att1`),B(`think`,`att1`)],expectedReplay:[]},{name:`surface-replace-folded`,events:[j(`user/message`,{...M,id:`msg-ck`,content:[{type:`text`,text:`compacted summary`}]},{surfaceOp:{op:`replace`,startSeq:1,endSeq:3}})],expectedLive:[R(`compacted summary`,`msg-ck`)]},{name:`unknown-fallback-graded`,events:[j(`llm/retry`,{attempt:1},{ignorable:!0}),j(`brand-new-event`,{x:1})],expectedLive:[],expectedUnknown:[[`llm/retry`,`debug`],[`brand-new-event`,`warn`]]},{name:`skip-classified-silent`,events:[j(`sandbox/mode`,{mode:`read-only`}),j(`permission/preset`,{preset:`auto`}),j(`model/selection`,{provider:`p`,model:`m`}),j(`subagent/descriptor`,{childId:`c`}),j(`goal/change`,{kind:`goal/change`,version:1,operation:`create`})],expectedLive:[],expectedUnknown:[]}];function R(e,t){return{sessionUpdate:`user_message_chunk`,content:{type:`text`,text:e},messageId:t}}function z(e,t){return{sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:e},messageId:t}}function B(e,t){return{sessionUpdate:`agent_thought_chunk`,content:{type:`text`,text:e},messageId:t}}function V(e,t,n){return{sessionUpdate:`usage_update`,used:e,size:2e5,_meta:{openacpagent:{usage:{cacheReadTokens:t,cacheWriteTokens:n}}}}}function H(e,t){return{...e,_meta:t}}function U(e,t,n,r,i=[]){return{sessionUpdate:`tool_call`,toolCallId:e,title:t,kind:n,status:`pending`,locations:i,rawInput:r}}function W(e,t,n,r,i,a,o){return{sessionUpdate:`tool_call_update`,toolCallId:e,status:t,title:n,kind:r,...i.length>0?{locations:i}:{locations:[]},rawInput:a,rawOutput:{content:o.content??[],meta:void 0,error:void 0},...o.contentFrames&&o.contentFrames.length>0?{content:o.contentFrames}:{}}}const G=/^\/([a-z][a-z0-9_-]*)(?=$|[\s])/u,K=new Set([`plan`,`permission`,`export`]),de={plan:`mode 单一真源 = configOption 通道(死防御——组合挂回 plan-mode 插件时已正确)`,permission:`权限档单一真源 = configOption 通道(dsh /permission 是会话中切档唯一写路径,投影制造第二写入口)`,export:`产物走 web 认证 GET 路由,ACP 客户端不可达`};function fe(e){let t=e?.trim()??``,n=G.exec(t);if(n===null)return{hit:!1,name:``,shadow:!1};let r=n[1]??``;return{hit:!0,name:r,shadow:K.has(r)}}function pe(e){return e.kind===`aborted`?{stopReason:`cancelled`}:{stopReason:`end_turn`,usage:{totalTokens:0,inputTokens:0,outputTokens:0}}}function me(e,t){let n=new Map;for(let t of e){if(K.has(t.name))continue;let e=t.input?.hint;n.set(t.name,{name:t.name,description:t.description,...e===void 0?{}:{input:{hint:e}}})}for(let e of t)!e.invocation.userInvocable||n.has(e.name)||n.set(e.name,{name:e.name,description:e.description});return[...n.values()].sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}function q(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t===``?`question`:t}function J(e){let t=new Set;return e.map(e=>{let n=q(e.header??e.question),r=n,i=2;for(;t.has(r);)r=`${n}-${i}`,i+=1;return t.add(r),r})}function he(e){let t=e.options??[],n=e=>({const:e.label,title:e.description===void 0?e.label:`${e.label} — ${e.description}`}),r=e.intent===void 0?void 0:t.find(t=>t.label===e.intent?.approve),i=r===void 0?t:t.filter(e=>e!==r);return[...r===void 0?[]:[n(r)],...i.map(n),{const:`__custom__`,title:`Other — type your own answer below`}]}function ge(e){let t=J(e),n={},r=[];return e.forEach((e,i)=>{let a=t[i]??`question-${i}`,o=e.detail===void 0?e.question:`${e.question}\n\n${e.detail}`;if(e.options!==void 0&&e.options.length>0){let t=he(e);n[a]=e.multiSelect===!0?{type:`array`,title:e.header??e.question,description:o,minItems:1,items:{anyOf:t}}:{type:`string`,title:e.header??e.question,description:o,oneOf:t}}else n[a]={type:`string`,title:e.header??e.question,description:o};n[`${a}_customText`]={type:`string`,title:`Custom answer`},r.push(a)}),{type:`object`,properties:n,required:r}}function Y(e,t){return t.has(e)}function _e(e,t){let n=J(e);return{answers:e.map((e,r)=>{let i=n[r]??`question-${r}`,a=t[i];if(a===void 0)throw Error(`elicitation content missing property: ${i}`);let o=new Set((e.options??[]).map(e=>e.label));if(e.options!==void 0&&e.options.length>0&&e.multiSelect===!0){if(!Array.isArray(a)||a.some(e=>typeof e!=`string`))throw Error(`elicitation content property is not a string array: ${i}`);let t=a.filter(e=>Y(e,o)),n=a.filter(e=>!Y(e,o));return{id:e.id,selected:t,...n.length===0?{}:{custom:n.join(`
2
- `)}}}if(typeof a!=`string`)throw Error(`elicitation content property is not a string: ${i}`);return e.options===void 0||e.options.length===0?{id:e.id,selected:[],...a===``?{}:{custom:a}}:Y(a,o)?{id:e.id,selected:[a]}:{id:e.id,selected:[],custom:a}})}}const X=`mode`,ve=`model`,Z=`reasoning_effort`,ye=``,Q={build:{sandbox:`danger-full-access`,approval:`never`},plan:{sandbox:`read-only`,approval:`ask`}},be={build:`Build`,plan:`Plan`},xe=[`build`,`plan`];function $(e){return e in Q}function Se(e){return $(e)?Q[e]:void 0}function Ce(e){return{id:X,name:`Mode`,category:`mode`,type:`select`,currentValue:e,options:xe.map(e=>({value:e,name:be[e]}))}}function we(e,t){return JSON.stringify([e,t])}export{G as COMMAND_GATE_PATTERN,_ as LATEST_PROTOCOL_VERSION,i as LOCATIONS_ALLOWED,ve as MODEL_CONFIG_ID,X as MODE_CONFIG_ID,Q as MODE_TABLE,g as PROTOCOL_VERSIONS,ye as PROVIDER_DEFAULT_REASONING_VALUE,Z as REASONING_CONFIG_ID,f as RpcErrorCode,K as SHADOW_COMMANDS,de as SHADOW_COMMANDS_RATIONALE,b as SubagentCatalogState,c as TOOL_TITLE_BUILDERS,y as ToolJournal,ue as TurnFoldTracker,L as WIRE_FIXTURES,ee as agentCapabilities,ge as buildElicitationSchema,l as buildToolTitle,t as classify,fe as commandGate,me as commandsProjection,$ as isAcpSessionMode,n as isIgnorable,m as mapRpcError,Ce as modeConfigOption,v as negotiateProtocolVersion,_e as parseElicitationContent,d as parseToolArguments,k as projectEvent,ce as projectRecord,le as projectStreamFrame,re as projectSubagentChildEvent,we as resolveModelValue,pe as settleToResponse,q as slugifyQuestion,h as stopReasonFromTurnEnd,s as toLocations,a as toolKind,Se as translateMode,u as withSubagentPrefix};
1
+ import{isAbsolute as e,resolve as t}from"node:path";const n={"user/message":`project`,"assistant/message":`project`,"tool/call":`project`,"tool/result":`project`,"todo/write":`project`,"session/title":`project`,"command/run":`project`,"command/done":`project`,"subagent/catalog":`project`,"turn/start":`project`,"turn/end":`project`,"step/start":`skip`,"step/end":`skip`,"developer/message":`skip`,"system/message":`skip`,"assistant/attempt":`skip`,"request/header":`skip`,"request/context":`skip`,"session/end-seed":`skip`,"agent/inbox/spliced":`skip`,"tool/ptc-dispatch-start":`skip`,"tool/ptc-dispatch":`skip`,"subagent/descriptor":`skip`,"approval/asked":`skip`,"approval/decided":`skip`,"approval/policy":`skip`,"permission/preset":`skip`,"sandbox/mode":`skip`,"model/selection":`skip`,"goal/change":`skip`};function r(e){return n[e]??`unknown`}function i(e){return e.ignorable===!0}const a={read:`read`,read_image:`read`,write:`edit`,edit:`edit`,str_replace_editor:`edit`,bash:`execute`,pwsh:`execute`,glob:`search`,grep:`search`,web_search:`search`,web_fetch:`fetch`,webfetch:`fetch`,todo_write:`think`,plan:`think`,skill:`other`},o=new Set([`edit`,`write`,`scratch_write`,`scratch_edit`,`str_replace_editor`]);function s(e){return a[e]||(e.startsWith(`scratch_`)?a[e.slice(8)]??`other`:(e.startsWith(`subagent_`),`other`))}const c=e=>typeof e==`string`?e:void 0,l=e=>c(e.file_path)??c(e.filePath)??c(e.path),u=e=>c(e.old_string)??c(e.oldString)??c(e.old_str),d=e=>c(e.new_string)??c(e.newString)??c(e.new_str);function f(n,r){if(n!==void 0){if(e(n)||r===void 0)return n;try{return t(r,n)}catch{return n}}}const p=new Set([`scratch_write`,`scratch_edit`]);function m(t,n,r){if(!o.has(t))return[];let i=n??{},a=l(i);if(!a||p.has(t)&&!e(a))return[];let s=typeof i.line==`number`?i.line:typeof i.lineNumber==`number`?i.lineNumber:typeof i.offset==`number`?i.offset:null;return[{path:f(a,r)??a,line:s}]}function h(e,t,n,r){if(!o.has(e))return[];let i=c(n?.path);if(i!==void 0){let e=t??{};return[{path:i,line:typeof e.line==`number`?e.line:typeof e.lineNumber==`number`?e.lineNumber:typeof e.offset==`number`?e.offset:null}]}return m(e,t,r)}const ee=e=>{let t=typeof e.offset==`number`?e.offset:void 0,n=typeof e.limit==`number`?e.limit:void 0;return n!==void 0&&n>0?` (${t??1} - ${(t??1)+n-1})`:t===void 0?``:` (from line ${t})`},te={create:`Create`,str_replace:`Replace`,insert:`Insert`,view:`View`},g={bash:e=>{let t=c(e.command),n=c(e.description);return n?`${n} (${t?.slice(0,60)??``})`:t?`Execute ${t.slice(0,120)}${t.length>120?`…`:``}`:`Execute`},pwsh:e=>{let t=c(e.command);return t?`Execute ${t.slice(0,120)}${t.length>120?`…`:``}`:`Execute`},read:e=>`Read ${l(e)??`file`}${ee(e)}`,read_image:e=>`Read image ${l(e)??`file`}`,write:e=>`Write ${l(e)??`file`}`,edit:e=>`Edit ${l(e)??`file`}`,scratch_bash:e=>{let t=c(e.description);if(t)return`Scratch: ${t}`;let n=c(e.command);return n?`Execute ${n.slice(0,120)}${n.length>120?`…`:``}`:`Execute`},scratch_write:e=>`Write scratch file ${l(e)??`file`}`,scratch_edit:e=>`Edit scratch file ${l(e)??`file`}`,subagent:e=>{let t=c(e.description)??c(e.prompt);return t?`Delegate: ${t}`:`Delegate`},str_replace_editor:e=>{let t=te[c(e.command)??``]??`str_replace_editor`,n=l(e);return n?`${t} ${n}`:t},grep:e=>{let t=c(e.pattern),n=c(e.path);return`Grep${t?` "${t}"`:``}${n?` in ${n}`:``}`},glob:e=>`Glob ${c(e.pattern)??``}`,web_fetch:e=>`Fetch ${c(e.url)??`URL`}`,web_search:e=>{let t=c(e.query);return`Search${t?` "${t}"`:``}`},webfetch:e=>{let t=c(e.url),n=c(e.format);return`Fetch ${t??`URL`}${n&&n!==`markdown`?` (${n})`:``}`},todo_write:e=>{let t=e.todos,n=Array.isArray(t)?t:[],r=n.filter(e=>e.status===`completed`).length;return`Update TODOs${n.length?` (${r}/${n.length})`:``}`},ask_user_question:()=>`Ask the user`,skill:e=>`Load skill: ${c(e.name)??``}`};function _(e,t){return(g[e]??(()=>e))(t??{})}function v(e,t,n){let r=_(e,t),i=n??{};if(e===`write`||e===`scratch_write`)return i.operation===`create`?`${r} (created)`:i.operation===`update`?`${r} (updated)`:r;if(e===`edit`||e===`scratch_edit`){let e=i.diffs;return Array.isArray(e)&&e.length>0?`${r} (${e.length} changes)`:r}return r}function y(e,t,n){return`[${t??`subagent:${n.slice(-8)}`}] ${e}`}function b(e){if(e!==void 0)try{let t=JSON.parse(e);return typeof t==`object`&&t?t:void 0}catch{return}}const x={methodNotFound:-32601,invalidParams:-32602,conflict:-32600,internal:-32603,sessionNotFound:-32002},S=e=>typeof e==`string`?e:void 0;function ne(e){let t=e.message,n=e.data&&typeof e.data==`object`?e.data:{};switch(e.code){case`session-not-found`:{let e=S(n.sessionId);return{code:x.sessionNotFound,message:t??`session not found`,data:e===void 0?void 0:{uri:`session:${e}`}}}case`session/writer-held`:return{code:x.conflict,message:t??`session is owned by another writer`,data:{reason:S(n.reason)??`writer-held`,retryable:!0}};case`turn-error`:return{code:x.internal,message:t??`turn failed`,data:{sessionId:S(n.sessionId),kind:S(n.kind)??`turn-error`,retryable:n.retryable===!0,code:S(n.code),partialOutput:n.partialOutput===!0}};case`llm-auth`:return{code:x.internal,message:t??`llm credential missing`,data:{kind:`auth`,retryable:!1}};case`retry-after-turn`:return{code:x.internal,message:t??`reload in progress`,data:{retryable:!0,reason:`skill_reload_in_progress`}};case`method-not-found`:return{code:x.methodNotFound,message:t??`method not found`};case`invalid-params`:return{code:x.invalidParams,message:t??`invalid params`,data:n.errors===void 0?void 0:{errors:n.errors}};default:return{code:x.internal,message:t??`dsh error`,data:{kind:`unknown-dsh-error`,...e.code===void 0?{}:{code:e.code},...Object.keys(n).length>0?{detail:n}:{}}}}}function C(e){let t=e?.kind;switch(t){case`completed`:case`aborted`:case`blocked`:return{stopReason:`end_turn`};case`interrupted`:return{stopReason:`cancelled`};case`max-tokens`:return{stopReason:`max_tokens`};case`error`:return{error:!0};case`forked`:default:return{stopReason:`end_turn`,warn:`unknown turn end reason: ${String(t)}`}}}const w=[1],T=w[w.length-1]??1;function re(e){return e===void 0?{version:T}:w.includes(e)?{version:e}:{version:T,warn:`client protocol version ${e} not in supported set`}}function ie(e){return{capabilities:{loadSession:!0,promptCapabilities:{}},meta:{openacpagent:{usage:{},image:{}},tboxcode:{protocolVersion:e}}}}var ae=class{#e=new Map;record(e,t,n){this.#e.set(e,{name:t,input:b(n)})}lookup(e){return this.#e.get(e)}},oe=class{byChild=new Map;#e=new Map;#t=new Map;#n=new Map;accept(e){this.byChild.set(e.childId,{mode:e.mode,...e.label===void 0?{}:{label:e.label}});let t=this.#e.size>1;for(let[n,r]of this.#e)this.#t.set(n,{childId:e.childId,toolName:r,...e.label===void 0?{}:{label:e.label},ambiguous:t});this.#e.size===1&&this.#n.set(e.childId,[...this.#e.keys()][0]),this.#e.clear()}trackDelegation(e,t){this.#e.set(e,t)}tracks(e){return this.byChild.has(e)}parentCallIdOf(e){return this.#n.get(e)}labelOfChild(e){return this.byChild.get(e)?.label}metaFor(e,t){let n=this.#t.get(e),r=n?.toolName??t,i=r===`subagent`?`general`:r.startsWith(`subagent_`)?r.slice(9):r;return n===void 0||n.ambiguous?{runId:e,agentType:i}:{runId:n.childId,agentType:i,...n.label===void 0?{}:{name:n.label}}}};const E=e=>typeof e==`string`?e:void 0,D=e=>e.data??{},O=new Set([`write`,`scratch_write`]),k=new Set([`edit`,`scratch_edit`]),se=e=>typeof e==`object`&&!!e&&typeof e.path==`string`&&(e.oldText===null||typeof e.oldText==`string`)&&typeof e.newText==`string`;function A(e,t,n,r){let i=n??{},a=i.diffs;if(Array.isArray(a)&&a.length>0)return a.every(se)?a:[];let o=E(i.path),s=t??{};if(o!==void 0)return O.has(e)?[{path:o,oldText:i.operation===`create`?null:E(i.before)??null,newText:E(i.after)??E(s.content)??``}]:k.has(e)?[{path:o,oldText:E(i.before)??u(s)??null,newText:E(i.after)??d(s)??``}]:[];let c=f(l(s),r);return c===void 0?[]:O.has(e)?[{path:c,oldText:null,newText:E(s.content)??``}]:k.has(e)?[{path:c,oldText:u(s)??null,newText:d(s)??``}]:e===`str_replace_editor`?s.command===`create`?[{path:c,oldText:null,newText:E(s.file_text)??``}]:s.command===`str_replace`?[{path:c,oldText:E(s.old_str)??null,newText:E(s.new_str)??``}]:[]:[]}function j(e,t){return{sessionUpdate:`user_message_chunk`,content:{type:`text`,text:e},...t?{messageId:t}:{}}}function M(e,t){return{sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:e},...t?{messageId:t}:{}}}function N(e,t){return{sessionUpdate:`agent_thought_chunk`,content:{type:`text`,text:e},...t?{messageId:t}:{}}}function ce(e,t,n,r){return{sessionUpdate:`usage_update`,used:e,size:t,_meta:{openacpagent:{usage:{cacheReadTokens:n,cacheWriteTokens:r}}}}}function le(e,t){if(e.source?.kind!==`user`)return[];let n=e,r=typeof n.id==`string`?n.id:null,i=n.content??[];if(i.length===0)return[j(``,r)];let a=[];for(let e of i)e.type===`text`?a.push(j(E(e.text)??``,r)):a.push(j(`[${String(e.type)}]`,r));return a}function ue(e,t){let n=e.message,r=[],i=typeof n?.id==`string`?n.id:null,a=t.seen,o=n?.content??[],s=typeof e.turn==`number`?e.turn:void 0,c=typeof e.step==`number`?e.step:void 0,l=t.live&&a!==void 0&&t.attempts!==void 0&&s!==void 0&&c!==void 0?t.attempts.resolve(s,c,e=>de(e,o)):void 0,u=l?.attemptId??i;if(a&&l!==void 0){let e=a.get(l.attemptId);a.set(l.attemptId,{text:Math.max(e?.text??0,l.text.length),reasoning:Math.max(e?.reasoning??0,l.reasoning.length)})}let d=0,f=0;for(let e of o){let t=e.type;if(t!==`text`&&t!==`reasoning`)continue;let n=E(e.text)??``,i=t===`reasoning`?`reasoning`:`text`,o=i===`reasoning`?f:d;if(a){let e=u??``,t=a.get(e)??{text:0,reasoning:0},s=Math.min(n.length,Math.max(0,t[i]-o)),c=n.slice(s);c&&r.push(i===`reasoning`?N(c,u):M(c,u)),t[i]=Math.max(t[i],o+n.length),a.set(e,t)}else r.push(i===`reasoning`?N(n,u):M(n,u));i===`reasoning`?f+=n.length:d+=n.length}if(a&&l!==void 0&&i!==null&&i!==l.attemptId){let e=a.get(l.attemptId);e!==void 0&&a.set(i,{...e})}let p=e.usage;if(p){let e=(typeof p.totalTokens==`number`?p.totalTokens:void 0)??(typeof p.inputTokens==`number`?p.inputTokens:0)+(typeof p.outputTokens==`number`?p.outputTokens:0);r.push(ce(e,2e5,typeof p.cacheReadTokens==`number`?p.cacheReadTokens:0,typeof p.cacheWriteTokens==`number`?p.cacheWriteTokens:0))}return r}function de(e,t){let n=``,r=``;for(let e of t)e.type===`text`?n+=E(e.text)??``:e.type===`reasoning`&&(r+=E(e.text)??``);return P(e.text,n)&&P(e.reasoning,r)}function P(e,t){return t.startsWith(e)||e.startsWith(t)}function fe(e,t){let n=E(e.callId)??``,r=E(e.name)??`unknown`,i=E(e.arguments);t.journal?.record(n,r,i);let a=b(i);t.subagents!==void 0&&(r===`subagent`||r.startsWith(`subagent_`))&&t.subagents.trackDelegation(n,r);let o=r===`bash`&&t.supportsTerminalOutput===!0;return[{sessionUpdate:`tool_call`,toolCallId:n,name:r,title:_(r,a),kind:s(r),status:`pending`,locations:m(r,a,t.cwd),rawInput:a??{},...o?{content:[{type:`terminal`,terminalId:n}]}:{}}]}function pe(e,t){let n=e.message,r=E(n?.toolCallId)??``,i=t.journal?.lookup(r),a=i?.name??`unknown`,o=i?.input,c=n?.isError===!0||e.error!==void 0?`failed`:`completed`,l=e.meta,u=v(a,o,l),d=(n?.content??[]).filter(e=>e.type===`text`).map(e=>E(e.text)??``).join(``),f=[];if(c===`completed`)for(let e of A(a,o,l,t.cwd))f.push({type:`diff`,...e});let p=a===`bash`;p&&t.supportsTerminalOutput===!0?f.push({type:`terminal`,terminalId:r}):d.trimEnd()&&f.push({type:`content`,content:{type:`text`,text:d}});let m={};return l!=null&&(m.openacpagent={toolMeta:l}),t.subagents!==void 0&&(a===`subagent`||a.startsWith(`subagent_`))&&(m.openacpagent={...m.openacpagent,subagent:t.subagents.metaFor(r,a)}),p&&t.supportsTerminalOutput===!0?[{sessionUpdate:`tool_call_update`,toolCallId:r,_meta:{terminal_output:{terminal_id:r,data:d}}},{sessionUpdate:`tool_call_update`,toolCallId:r,name:a,status:c,title:u,kind:s(a),locations:h(a,o,l,t.cwd),rawInput:o??{},rawOutput:{content:n?.content??[],meta:l,error:e.error},...f.length>0?{content:f}:{},_meta:{...m,terminal_exit:{terminal_id:r,exit_code:c===`completed`?0:1,signal:null}}}]:[{sessionUpdate:`tool_call_update`,toolCallId:r,name:a,status:c,title:u,kind:s(a),locations:h(a,o,l,t.cwd),rawInput:o??{},rawOutput:{content:n?.content??[],meta:l,error:e.error},...f.length>0?{content:f}:{},...Object.keys(m).length>0?{_meta:m}:{}}]}function me(e,t,n,r){let i=t.type,a=D(t),o=n.parentCallIdOf(e)??e;if(i===`tool/call`){let t=E(a.callId)??``,i=E(a.name)??`unknown`,c=E(a.arguments);r.journal.record(t,i,c);let l=b(c),u=i===`bash`&&r.supportsTerminalOutput===!0;return[{sessionUpdate:`tool_call`,toolCallId:`${o}:${t}`,name:i,title:y(_(i,l),n.labelOfChild(e),e),kind:s(i),status:`pending`,locations:m(i,l,r.cwd),rawInput:l??{},...u?{content:[{type:`terminal`,terminalId:`${o}:${t}`}]}:{}}]}if(i===`tool/result`){let t=a.message,i=E(t?.toolCallId)??``,c=r.journal.lookup(i),l=c?.name??`unknown`,u=c?.input,d=t?.isError===!0||a.error!==void 0?`failed`:`completed`,f=a.meta,p=(t?.content??[]).filter(e=>e.type===`text`).map(e=>E(e.text)??``).join(``),m=[];if(d===`completed`)for(let e of A(l,u,f,r.cwd))m.push({type:`diff`,...e});return[{sessionUpdate:`tool_call_update`,toolCallId:`${o}:${i}`,name:l,status:d,title:y(v(l,u,f),n.labelOfChild(e),e),kind:s(l),locations:h(l,u,f,r.cwd),rawInput:u??{},rawOutput:{content:t?.content??[],...f==null?{}:{meta:f},error:a.error},...p.trimEnd()?{content:[...m,{type:`content`,content:{type:`text`,text:p}}]}:m.length>0?{content:m}:{},_meta:{openacpagent:{...f==null?{}:{toolMeta:f},subagent:n.metaFor(o,l)}}}]}return[]}function he(e){return[{sessionUpdate:`plan`,entries:(e.todos??[]).map(e=>({content:E(e.content)??``,status:e.status===`in_progress`?`in_progress`:e.status===`completed`?`completed`:`pending`}))}]}function ge(e,t){let n=t.source;return[{sessionUpdate:`session_info_update`,title:E(t.title)??null,updatedAt:new Date(e.time).toISOString(),_meta:n?.kind===void 0?{}:{openacpagent:{titleSource:n.kind}}}]}function _e(e){let t=E(e.name)??``,n=E(e.args);return[j(`/${t}${n?` ${n}`:``}`,E(e.commandId))]}function F(e){let t=e.kind===`success`?`success`:`error`,n=M(E(e.text)??(t===`success`?`Command completed`:`Command failed`),E(e.commandId));return typeof e.sourceEventSeq==`number`&&(n._meta={openacpagent:{sourceEventSeq:e.sourceEventSeq}}),[n]}function I(e,t,n){let a=r(e.type);if(a===`skip`)return[];if(a===`unknown`)return n?.(e.type,i(e)?`debug`:`warn`),[];let o=D(e);switch(e.type){case`user/message`:return le(o,t);case`assistant/message`:return ue(o,t);case`tool/call`:return fe(o,t);case`tool/result`:return pe(o,t);case`todo/write`:return he(o);case`session/title`:return ge(e,o);case`command/run`:return _e(o);case`command/done`:return F(o);case`subagent/catalog`:{let n=E(o.childId);if(n!==void 0){let r=o;t.subagents?.accept({childId:n,childCreatedAt:typeof r.childCreatedAt==`number`?r.childCreatedAt:e.time,mode:E(r.mode)??`unknown`,label:E(r.label)}),t.onSubagentCatalog?.({childId:n,childCreatedAt:typeof r.childCreatedAt==`number`?r.childCreatedAt:e.time,mode:E(r.mode)??`unknown`,label:E(r.label)})}return[]}case`turn/start`:case`turn/end`:return[];default:return[]}}function ve(e,t,n){return I(e,{...t,live:!1},n)}function ye(e,t){if(!t.live)return[];if(e.type===`start`)return typeof e.turn==`number`&&typeof e.step==`number`&&t.attempts?.begin(e.attemptId,e.turn,e.step),[];if(e.type!==`chunk`)return[];let n=e.chunk?.type,r=E(e.chunk?.text)??``;return n===`text-delta`?(t.attempts?.record(e.attemptId,`text`,r),[M(r,e.attemptId)]):n===`reasoning-delta`?(t.attempts?.record(e.attemptId,`reasoning`,r),[N(r,e.attemptId)]):[]}var be=class{#e=[];constructor(e){this.onDerived=e}accept(e){let t=e.data??{};if(e.type===`turn/start`&&typeof t.turn==`number`)this.#e.push({turn:t.turn,tools:new Map});else if(e.type===`tool/call`&&typeof t.callId==`string`)this.#e[this.#e.length-1]?.tools.set(t.callId,{resolved:!1});else if(e.type===`tool/result`){let e=t.message,n=E(e?.toolCallId),r=this.#e[this.#e.length-1];if(n!==void 0&&r!==void 0){let e=r.tools.get(n);e&&(e.resolved=!0)}}else if(e.type===`turn/end`){let e=this.#e[this.#e.length-1];if(e){for(let[t,n]of e.tools)n.resolved||this.onDerived({sessionUpdate:`tool_call_update`,toolCallId:t,status:`failed`,_meta:{derived:!0}});this.#e.pop()}}}},xe=class{#e=new Map;begin(e,t,n){if(!(e===``||!Number.isInteger(t)||!Number.isInteger(n))){for(let[e,r]of this.#e)r.turn===t&&r.step===n&&this.#e.delete(e);for(;this.#e.size>=8;){let e=this.#e.keys().next().value;if(e===void 0)break;this.#e.delete(e)}this.#e.set(e,{attemptId:e,turn:t,step:n,text:``,reasoning:``})}}record(e,t,n){let r=this.#e.get(e);r!==void 0&&(r[t]+=n)}resolve(e,t,n){let r=this.#t(e,t);if(r!==void 0)return this.#e.delete(r.attemptId),n(r)?r:void 0}clear(){this.#e.clear()}#t(e,t){for(let n of this.#e.values())if(n.turn===e&&n.step===t)return n}};let Se=0;const L=(e,t,n={})=>({type:e,seq:++Se,time:17e11,data:t,...n}),R={id:`msg-u1`,role:`user`,content:[{type:`text`,text:`hello`}],source:{kind:`user`}},Ce={id:`msg-cat1`,role:`user`,content:[{type:`text`,text:`<skill catalog>`}],source:{kind:`skill-catalog`,form:`catalog`,entries:[]}},we={id:`msg-rc1`,role:`user`,content:[{type:`text`,text:`<runtime context>`}],source:{kind:`runtime-context`}},Te={id:`msg-a1`,role:`assistant`,content:[{type:`text`,text:`world`}],source:{kind:`model`,provider:`echo`,model:`echo`}},Ee={id:`msg-a2`,role:`assistant`,content:[{type:`reasoning`,text:`thinking…`},{type:`text`,text:`answer`}],source:{kind:`model`,provider:`echo`,model:`echo`}},De=[{name:`echo-whitelist`,events:[L(`user/message`,Ce),L(`user/message`,we),L(`user/message`,R)],expectedLive:[z(`hello`,`msg-u1`)]},{name:`user-last-subagent-task`,events:[L(`user/message`,{...R,id:`msg-task`,content:[{type:`text`,text:`delegate task`}]})],expectedLive:[z(`delegate task`,`msg-task`)]},{name:`assistant-durable-mixed`,events:[L(`assistant/message`,{turn:1,step:1,message:Ee,stream:[],usage:{inputTokens:10,outputTokens:5,totalTokens:15,cacheReadTokens:3,cacheWriteTokens:2}})],expectedLive:[V(`thinking…`,`msg-a2`),B(`answer`,`msg-a2`),H(15,3,2)]},{name:`assistant-durable-no-usage`,events:[L(`assistant/message`,{turn:1,step:2,message:Te,stream:[]})],expectedLive:[B(`world`,`msg-a1`)]},{name:`tool-lifecycle-bash`,events:[L(`turn/start`,{turn:1}),L(`tool/call`,{turn:1,step:1,callId:`c1`,name:`bash`,arguments:`{"command":"ls -la"}`}),L(`tool/result`,{turn:1,step:1,message:{toolCallId:`c1`,role:`tool`,content:[{type:`text`,text:`file.txt`}]}}),L(`turn/end`,{turn:1,reason:{kind:`completed`}})],expectedLive:[U(`c1`,`Execute ls -la`,`execute`,{command:`ls -la`},[],`bash`),W(`c1`,`completed`,`Execute ls -la`,`execute`,[],{command:`ls -la`},{name:`bash`,content:[{type:`text`,text:`file.txt`}],contentFrames:[{type:`content`,content:{type:`text`,text:`file.txt`}}]})],expectedDerived:[]},{name:`tool-derived-failed`,events:[L(`turn/start`,{turn:1}),L(`tool/call`,{turn:1,step:1,callId:`c2`,name:`read`,arguments:`{"file_path":"a.ts"}`}),L(`turn/end`,{turn:1,reason:{kind:`error`}})],expectedLive:[U(`c2`,`Read a.ts`,`read`,{file_path:`a.ts`},[],`read`)],expectedDerived:[{sessionUpdate:`tool_call_update`,toolCallId:`c2`,status:`failed`,_meta:{derived:!0}}]},{name:`edit-diff-locations`,cwd:`/w`,events:[L(`tool/call`,{turn:1,step:1,callId:`c3`,name:`edit`,arguments:`{"file_path":"src/a.ts","old_string":"a","new_string":"b"}`}),L(`tool/result`,{turn:1,step:1,message:{toolCallId:`c3`,role:`tool`,content:[{type:`text`,text:`ok`}]}})],expectedLive:[U(`c3`,`Edit src/a.ts`,`edit`,{file_path:`src/a.ts`,old_string:`a`,new_string:`b`},[{path:`/w/src/a.ts`,line:null}],`edit`),W(`c3`,`completed`,`Edit src/a.ts`,`edit`,[{path:`/w/src/a.ts`,line:null}],{file_path:`src/a.ts`,old_string:`a`,new_string:`b`},{name:`edit`,content:[{type:`text`,text:`ok`}],contentFrames:[{type:`diff`,path:`/w/src/a.ts`,oldText:`a`,newText:`b`},{type:`content`,content:{type:`text`,text:`ok`}}]})]},{name:`write-create-diff`,cwd:`/w`,events:[L(`tool/call`,{turn:1,step:1,callId:`w1`,name:`write`,arguments:`{"file_path":"src/new.ts","content":"line1\\nline2\\n"}`}),L(`tool/result`,{turn:1,step:1,message:{toolCallId:`w1`,role:`tool`,content:[{type:`text`,text:`<path>/w/src/new.ts</path>
2
+ Created file`}]},meta:{operation:`create`,path:`/w/src/new.ts`,diffs:[]}})],expectedLive:[U(`w1`,`Write src/new.ts`,`edit`,{file_path:`src/new.ts`,content:`line1
3
+ line2
4
+ `},[{path:`/w/src/new.ts`,line:null}],`write`),W(`w1`,`completed`,`Write src/new.ts (created)`,`edit`,[{path:`/w/src/new.ts`,line:null}],{file_path:`src/new.ts`,content:`line1
5
+ line2
6
+ `},{name:`write`,meta:{operation:`create`,path:`/w/src/new.ts`,diffs:[]},content:[{type:`text`,text:`<path>/w/src/new.ts</path>
7
+ Created file`}],contentFrames:[{type:`diff`,path:`/w/src/new.ts`,oldText:null,newText:`line1
8
+ line2
9
+ `},{type:`content`,content:{type:`text`,text:`<path>/w/src/new.ts</path>
10
+ Created file`}}]})]},{name:`write-update-diff`,cwd:`/w`,events:[L(`tool/call`,{turn:1,step:1,callId:`w2`,name:`write`,arguments:`{"file_path":"src/a.ts","content":"new"}`}),L(`tool/result`,{turn:1,step:1,message:{toolCallId:`w2`,role:`tool`,content:[{type:`text`,text:`Updated file`}]},meta:{operation:`update`,path:`/w/src/a.ts`,diffs:[{path:`/w/src/a.ts`,oldText:`old`,newText:`new`}]}})],expectedLive:[U(`w2`,`Write src/a.ts`,`edit`,{file_path:`src/a.ts`,content:`new`},[{path:`/w/src/a.ts`,line:null}],`write`),W(`w2`,`completed`,`Write src/a.ts (updated)`,`edit`,[{path:`/w/src/a.ts`,line:null}],{file_path:`src/a.ts`,content:`new`},{name:`write`,meta:{operation:`update`,path:`/w/src/a.ts`,diffs:[{path:`/w/src/a.ts`,oldText:`old`,newText:`new`}]},content:[{type:`text`,text:`Updated file`}],contentFrames:[{type:`diff`,path:`/w/src/a.ts`,oldText:`old`,newText:`new`},{type:`content`,content:{type:`text`,text:`Updated file`}}]})]},{name:`edit-snake-diff`,cwd:`/w`,events:[L(`tool/call`,{turn:1,step:1,callId:`e1`,name:`edit`,arguments:`{"file_path":"src/a.ts","old_string":"a","new_string":"b"}`}),L(`tool/result`,{turn:1,step:1,message:{toolCallId:`e1`,role:`tool`,content:[{type:`text`,text:`ok`}]},meta:{path:`/w/src/a.ts`,diffs:[{path:`/w/src/a.ts`,oldText:`a`,newText:`b`}]}})],expectedLive:[U(`e1`,`Edit src/a.ts`,`edit`,{file_path:`src/a.ts`,old_string:`a`,new_string:`b`},[{path:`/w/src/a.ts`,line:null}],`edit`),W(`e1`,`completed`,`Edit src/a.ts (1 changes)`,`edit`,[{path:`/w/src/a.ts`,line:null}],{file_path:`src/a.ts`,old_string:`a`,new_string:`b`},{name:`edit`,meta:{path:`/w/src/a.ts`,diffs:[{path:`/w/src/a.ts`,oldText:`a`,newText:`b`}]},content:[{type:`text`,text:`ok`}],contentFrames:[{type:`diff`,path:`/w/src/a.ts`,oldText:`a`,newText:`b`},{type:`content`,content:{type:`text`,text:`ok`}}]})]},{name:`scratch-write-diff`,cwd:`/w`,events:[L(`tool/call`,{turn:1,step:1,callId:`sw1`,name:`scratch_write`,arguments:`{"filePath":"x.py","content":"print(1)"}`}),L(`tool/result`,{turn:1,step:1,message:{toolCallId:`sw1`,role:`tool`,content:[{type:`text`,text:`written: /tmp/tboxcode-scratch/s1/x.py`}]},meta:{path:`/tmp/tboxcode-scratch/s1/x.py`,operation:`create`,diffs:[{path:`/tmp/tboxcode-scratch/s1/x.py`,oldText:null,newText:`print(1)`}]}})],expectedLive:[U(`sw1`,`Write scratch file x.py`,`edit`,{filePath:`x.py`,content:`print(1)`},[],`scratch_write`),W(`sw1`,`completed`,`Write scratch file x.py (created)`,`edit`,[{path:`/tmp/tboxcode-scratch/s1/x.py`,line:null}],{filePath:`x.py`,content:`print(1)`},{name:`scratch_write`,meta:{path:`/tmp/tboxcode-scratch/s1/x.py`,operation:`create`,diffs:[{path:`/tmp/tboxcode-scratch/s1/x.py`,oldText:null,newText:`print(1)`}]},content:[{type:`text`,text:`written: /tmp/tboxcode-scratch/s1/x.py`}],contentFrames:[{type:`diff`,path:`/tmp/tboxcode-scratch/s1/x.py`,oldText:null,newText:`print(1)`},{type:`content`,content:{type:`text`,text:`written: /tmp/tboxcode-scratch/s1/x.py`}}]})]},{name:`write-failed-no-diff`,cwd:`/w`,events:[L(`tool/call`,{turn:1,step:1,callId:`wf1`,name:`write`,arguments:`{"file_path":"src/a.ts","content":"x"}`}),L(`tool/result`,{turn:1,step:1,message:{toolCallId:`wf1`,role:`tool`,isError:!0,content:[{type:`text`,text:`denied`}]},meta:{path:`/w/src/a.ts`,diffs:[{path:`/w/src/a.ts`,oldText:`old`,newText:`x`}]},error:{name:`FsError`,message:`denied`}})],expectedLive:[U(`wf1`,`Write src/a.ts`,`edit`,{file_path:`src/a.ts`,content:`x`},[{path:`/w/src/a.ts`,line:null}],`write`),W(`wf1`,`failed`,`Write src/a.ts`,`edit`,[{path:`/w/src/a.ts`,line:null}],{file_path:`src/a.ts`,content:`x`},{name:`write`,meta:{path:`/w/src/a.ts`,diffs:[{path:`/w/src/a.ts`,oldText:`old`,newText:`x`}]},content:[{type:`text`,text:`denied`}],contentFrames:[{type:`content`,content:{type:`text`,text:`denied`}}],error:{name:`FsError`,message:`denied`}})]},{name:`str-replace-editor-create`,cwd:`/w`,events:[L(`tool/call`,{turn:1,step:1,callId:`sre1`,name:`str_replace_editor`,arguments:`{"command":"create","path":"src/b.ts","file_text":"x"}`}),L(`tool/result`,{turn:1,step:1,message:{toolCallId:`sre1`,role:`tool`,content:[{type:`text`,text:`created`}]}})],expectedLive:[U(`sre1`,`Create src/b.ts`,`edit`,{command:`create`,path:`src/b.ts`,file_text:`x`},[{path:`/w/src/b.ts`,line:null}],`str_replace_editor`),W(`sre1`,`completed`,`Create src/b.ts`,`edit`,[{path:`/w/src/b.ts`,line:null}],{command:`create`,path:`src/b.ts`,file_text:`x`},{name:`str_replace_editor`,content:[{type:`text`,text:`created`}],contentFrames:[{type:`diff`,path:`/w/src/b.ts`,oldText:null,newText:`x`},{type:`content`,content:{type:`text`,text:`created`}}]})]},{name:`locations-gated-read`,events:[L(`tool/call`,{turn:1,step:1,callId:`c4`,name:`read`,arguments:`{"file_path":"a.ts"}`}),L(`tool/result`,{turn:1,step:1,message:{toolCallId:`c4`,role:`tool`,content:[{type:`text`,text:`x`}]}})],expectedLive:[U(`c4`,`Read a.ts`,`read`,{file_path:`a.ts`},[],`read`),W(`c4`,`completed`,`Read a.ts`,`read`,[],{file_path:`a.ts`},{name:`read`,content:[{type:`text`,text:`x`}],contentFrames:[{type:`content`,content:{type:`text`,text:`x`}}]})]},{name:`journal-missing-degraded`,events:[L(`tool/result`,{turn:1,step:1,message:{toolCallId:`ghost`,role:`tool`,content:[{type:`text`,text:`late`}]}})],expectedLive:[W(`ghost`,`completed`,`unknown`,`other`,[],{},{name:`unknown`,content:[{type:`text`,text:`late`}],contentFrames:[{type:`content`,content:{type:`text`,text:`late`}}]})]},{name:`plan-todo-write`,events:[L(`todo/write`,{todos:[{content:`a`,status:`completed`},{content:`b`,status:`in_progress`},{content:`c`,status:`pending`}]})],expectedLive:[{sessionUpdate:`plan`,entries:[{content:`a`,status:`completed`},{content:`b`,status:`in_progress`},{content:`c`,status:`pending`}]}]},{name:`session-info-title`,events:[L(`session/title`,{title:`Fix bug`,messageSeqs:[1],source:{kind:`provider`,provider:`p`}})],expectedLive:[{sessionUpdate:`session_info_update`,title:`Fix bug`,updatedAt:new Date(17e11).toISOString(),_meta:{openacpagent:{titleSource:`provider`}}}]},{name:`command-projection`,events:[L(`command/run`,{commandId:`cmd1`,name:`compact`,source:{kind:`user`}}),L(`command/done`,{commandId:`cmd1`,kind:`success`,text:`compacted`,sourceEventSeq:9})],expectedLive:[z(`/compact`,`cmd1`),Oe(B(`compacted`,`cmd1`),{openacpagent:{sourceEventSeq:9}})]},{name:`command-echo-record-input-false`,events:[L(`command/run`,{commandId:`cmd2`,name:`feedback`,source:{kind:`user`}})],expectedLive:[z(`/feedback`,`cmd2`)]},{name:`stream-frame-boundaries`,events:[],streamFrames:[{type:`start`,attemptId:`att1`},{type:`chunk`,attemptId:`att1`,chunk:{type:`text-delta`,text:`he`}},{type:`chunk`,attemptId:`att1`,chunk:{type:`reasoning-delta`,text:`think`}},{type:`chunk`,attemptId:`att1`,chunk:{type:`tool-call-delta`}},{type:`end`,attemptId:`att1`,index:2,outcome:{kind:`committed`,eventType:`assistant/message`,seq:5}}],expectedLive:[B(`he`,`att1`),V(`think`,`att1`)],expectedReplay:[]},{name:`stream-durable-merged`,events:[L(`assistant/message`,{turn:1,step:1,message:{id:`msg-merged`,role:`assistant`,content:[{type:`reasoning`,text:`think`},{type:`text`,text:`Hello`}],source:{kind:`model`,provider:`echo`,model:`echo`}},stream:[],usage:{inputTokens:1,outputTokens:1}})],streamFrames:[{type:`start`,attemptId:`att-merged`,revision:1,turn:1,step:1},{type:`chunk`,attemptId:`att-merged`,revision:2,index:0,time:0,chunk:{type:`reasoning-delta`,text:`thi`}},{type:`chunk`,attemptId:`att-merged`,revision:3,index:1,time:1,chunk:{type:`text-delta`,text:`Hel`}}],expectedLive:[V(`thi`,`att-merged`),B(`Hel`,`att-merged`),V(`nk`,`att-merged`),B(`lo`,`att-merged`),H(2,0,0)],expectedReplay:[V(`think`,`msg-merged`),B(`Hello`,`msg-merged`),H(2,0,0)]},{name:`surface-replace-folded`,events:[L(`user/message`,{...R,id:`msg-ck`,content:[{type:`text`,text:`compacted summary`}]},{surfaceOp:{op:`replace`,startSeq:1,endSeq:3}})],expectedLive:[z(`compacted summary`,`msg-ck`)]},{name:`unknown-fallback-graded`,events:[L(`llm/retry`,{attempt:1},{ignorable:!0}),L(`brand-new-event`,{x:1})],expectedLive:[],expectedUnknown:[[`llm/retry`,`debug`],[`brand-new-event`,`warn`]]},{name:`skip-classified-silent`,events:[L(`sandbox/mode`,{mode:`read-only`}),L(`permission/preset`,{preset:`auto`}),L(`model/selection`,{provider:`p`,model:`m`}),L(`subagent/descriptor`,{childId:`c`}),L(`goal/change`,{kind:`goal/change`,version:1,operation:`create`})],expectedLive:[],expectedUnknown:[]}];function z(e,t){return{sessionUpdate:`user_message_chunk`,content:{type:`text`,text:e},messageId:t}}function B(e,t){return{sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:e},messageId:t}}function V(e,t){return{sessionUpdate:`agent_thought_chunk`,content:{type:`text`,text:e},messageId:t}}function H(e,t,n){return{sessionUpdate:`usage_update`,used:e,size:2e5,_meta:{openacpagent:{usage:{cacheReadTokens:t,cacheWriteTokens:n}}}}}function Oe(e,t){return{...e,_meta:t}}function U(e,t,n,r,i=[],a){return{sessionUpdate:`tool_call`,toolCallId:e,...a===void 0?{}:{name:a},title:t,kind:n,status:`pending`,locations:i,rawInput:r}}function W(e,t,n,r,i,a,o){return{sessionUpdate:`tool_call_update`,toolCallId:e,...o.name===void 0?{}:{name:o.name},status:t,title:n,kind:r,locations:i,rawInput:a,rawOutput:{content:o.content??[],meta:o.meta,error:o.error},...o.contentFrames&&o.contentFrames.length>0?{content:o.contentFrames}:{},...o.meta!==void 0&&o.meta!==null?{_meta:{openacpagent:{toolMeta:o.meta}}}:{}}}const G=/^\/([a-z][a-z0-9_-]*)(?=$|[\s])/u,K=new Set([`plan`,`permission`,`export`]),ke={plan:`mode 单一真源 = configOption 通道(死防御——组合挂回 plan-mode 插件时已正确)`,permission:`权限档单一真源 = configOption 通道(dsh /permission 是会话中切档唯一写路径,投影制造第二写入口)`,export:`产物走 web 认证 GET 路由,ACP 客户端不可达`};function Ae(e){let t=e?.trim()??``,n=G.exec(t);if(n===null)return{hit:!1,name:``,shadow:!1};let r=n[1]??``;return{hit:!0,name:r,shadow:K.has(r)}}function je(e){return e.kind===`aborted`?{stopReason:`cancelled`}:{stopReason:`end_turn`,usage:{totalTokens:0,inputTokens:0,outputTokens:0}}}function Me(e,t){let n=new Map;for(let t of e){if(K.has(t.name))continue;let e=t.input?.hint;n.set(t.name,{name:t.name,description:t.description,...e===void 0?{}:{input:{hint:e}}})}for(let e of t)!e.invocation.userInvocable||n.has(e.name)||n.set(e.name,{name:e.name,description:e.description});return[...n.values()].sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}function q(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t===``?`question`:t}function J(e){let t=new Set;return e.map(e=>{let n=q(e.header??e.question),r=n,i=2;for(;t.has(r);)r=`${n}-${i}`,i+=1;return t.add(r),r})}function Ne(e){let t=e.options??[],n=e=>({const:e.label,title:e.description===void 0?e.label:`${e.label} — ${e.description}`}),r=e.intent===void 0?void 0:t.find(t=>t.label===e.intent?.approve),i=r===void 0?t:t.filter(e=>e!==r);return[...r===void 0?[]:[n(r)],...i.map(n),{const:`__custom__`,title:`Other — type your own answer below`}]}function Pe(e){let t=J(e),n={},r=[];return e.forEach((e,i)=>{let a=t[i]??`question-${i}`,o=e.detail===void 0?e.question:`${e.question}\n\n${e.detail}`;if(e.options!==void 0&&e.options.length>0){let t=Ne(e);n[a]=e.multiSelect===!0?{type:`array`,title:e.header??e.question,description:o,minItems:1,items:{anyOf:t}}:{type:`string`,title:e.header??e.question,description:o,oneOf:t}}else n[a]={type:`string`,title:e.header??e.question,description:o};n[`${a}_customText`]={type:`string`,title:`Custom answer`},r.push(a)}),{type:`object`,properties:n,required:r}}function Y(e,t){return t.has(e)}function Fe(e,t){let n=J(e);return{answers:e.map((e,r)=>{let i=n[r]??`question-${r}`,a=t[i];if(a===void 0)throw Error(`elicitation content missing property: ${i}`);let o=new Set((e.options??[]).map(e=>e.label));if(e.options!==void 0&&e.options.length>0&&e.multiSelect===!0){if(!Array.isArray(a)||a.some(e=>typeof e!=`string`))throw Error(`elicitation content property is not a string array: ${i}`);let t=a.filter(e=>Y(e,o)),n=a.filter(e=>!Y(e,o));return{id:e.id,selected:t,...n.length===0?{}:{custom:n.join(`
11
+ `)}}}if(typeof a!=`string`)throw Error(`elicitation content property is not a string: ${i}`);return e.options===void 0||e.options.length===0?{id:e.id,selected:[],...a===``?{}:{custom:a}}:Y(a,o)?{id:e.id,selected:[a]}:{id:e.id,selected:[],custom:a}})}}const X=`mode`,Ie=`model`,Le=`reasoning_effort`,Re=``,Z={build:{sandbox:`danger-full-access`,approval:`never`},plan:{sandbox:`read-only`,approval:`ask`}},Q={build:`build`,plan:`plan`},ze=[`build`,`plan`];function $(e){return e in Z}function Be(e){return $(e)?Z[e]:void 0}function Ve(e){return e===`read-only`?`plan`:`build`}function He(e){return{id:X,name:`Mode`,category:`mode`,type:`select`,currentValue:e,options:ze.map(e=>({value:e,name:Q[e]}))}}function Ue(e,t){return JSON.stringify([e,t])}export{G as COMMAND_GATE_PATTERN,T as LATEST_PROTOCOL_VERSION,o as LOCATIONS_ALLOWED,Ie as MODEL_CONFIG_ID,X as MODE_CONFIG_ID,Z as MODE_TABLE,w as PROTOCOL_VERSIONS,Re as PROVIDER_DEFAULT_REASONING_VALUE,Le as REASONING_CONFIG_ID,x as RpcErrorCode,K as SHADOW_COMMANDS,ke as SHADOW_COMMANDS_RATIONALE,xe as StreamAttemptState,oe as SubagentCatalogState,g as TOOL_TITLE_BUILDERS,ae as ToolJournal,be as TurnFoldTracker,De as WIRE_FIXTURES,f as absolutize,ie as agentCapabilities,Pe as buildElicitationSchema,v as buildToolResultTitle,_ as buildToolTitle,r as classify,Ae as commandGate,Me as commandsProjection,$ as isAcpSessionMode,i as isIgnorable,h as locationsForResult,ne as mapRpcError,He as modeConfigOption,Ve as modeFromSandbox,re as negotiateProtocolVersion,Fe as parseElicitationContent,b as parseToolArguments,d as pickNew,u as pickOld,l as pickPath,I as projectEvent,ve as projectRecord,ye as projectStreamFrame,me as projectSubagentChildEvent,Ue as resolveModelValue,je as settleToResponse,q as slugifyQuestion,C as stopReasonFromTurnEnd,m as toLocations,s as toolKind,Be as translateMode,y as withSubagentPrefix};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbox.cn/dsh-acp-bridge-core",
3
- "version": "0.1.0-rc.4",
3
+ "version": "0.1.0-rc.5",
4
4
  "type": "module",
5
5
  "description": "纯函数翻译核心:dsh 事件 → ACP update 投影、错误码映射、模式表、命令判定(运行时零依赖)",
6
6
  "main": "./lib/index.js",