@zhushanwen/subagent-engine-sdk 0.2.0

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.
Files changed (139) hide show
  1. package/dist/best-effort.cjs +88 -0
  2. package/dist/best-effort.d.cts +14 -0
  3. package/dist/best-effort.d.ts +14 -0
  4. package/dist/best-effort.js +8 -0
  5. package/dist/chunk-2DIMPZCQ.js +0 -0
  6. package/dist/chunk-365AUV6N.js +67 -0
  7. package/dist/chunk-3K2P2CM2.js +127 -0
  8. package/dist/chunk-75QEMUGV.js +58 -0
  9. package/dist/chunk-7I4XGL5J.js +95 -0
  10. package/dist/chunk-A75XDJIC.js +227 -0
  11. package/dist/chunk-DSQ7JQKM.js +39 -0
  12. package/dist/chunk-EJMF63R5.js +19 -0
  13. package/dist/chunk-GT6YLLN4.js +46 -0
  14. package/dist/chunk-HYES77BR.js +109 -0
  15. package/dist/chunk-JSBRDJBE.js +30 -0
  16. package/dist/chunk-LEOBWKRM.js +128 -0
  17. package/dist/chunk-N3RL6OVM.js +38 -0
  18. package/dist/chunk-OPMY4G4M.js +27 -0
  19. package/dist/chunk-PPEPBVCC.js +120 -0
  20. package/dist/chunk-PYO3YR7W.js +16 -0
  21. package/dist/chunk-RDH3ZOV6.js +46 -0
  22. package/dist/chunk-RULLX6C6.js +11 -0
  23. package/dist/chunk-X24SFZYW.js +6646 -0
  24. package/dist/chunk-YFSN3D5N.js +216 -0
  25. package/dist/chunk-ZOFFJNJD.js +136 -0
  26. package/dist/chunk-ZXEAW25V.js +132 -0
  27. package/dist/cli-entry.cjs +119 -0
  28. package/dist/cli-entry.d.cts +24 -0
  29. package/dist/cli-entry.d.ts +24 -0
  30. package/dist/cli-entry.js +8 -0
  31. package/dist/contract-types-sSlgppBC.d.cts +352 -0
  32. package/dist/contract-types-sSlgppBC.d.ts +352 -0
  33. package/dist/data-dir.cjs +117 -0
  34. package/dist/data-dir.d.cts +20 -0
  35. package/dist/data-dir.d.ts +20 -0
  36. package/dist/data-dir.js +12 -0
  37. package/dist/env.cjs +205 -0
  38. package/dist/env.d.cts +73 -0
  39. package/dist/env.d.ts +73 -0
  40. package/dist/env.js +16 -0
  41. package/dist/error-codes-DHco5-i_.d.cts +118 -0
  42. package/dist/error-codes-Dhss2Kmk.d.ts +118 -0
  43. package/dist/error-message.cjs +40 -0
  44. package/dist/error-message.d.cts +3 -0
  45. package/dist/error-message.d.ts +3 -0
  46. package/dist/error-message.js +7 -0
  47. package/dist/index.cjs +8375 -0
  48. package/dist/index.d.cts +23 -0
  49. package/dist/index.d.ts +23 -0
  50. package/dist/index.js +268 -0
  51. package/dist/journal-io.cjs +70 -0
  52. package/dist/journal-io.d.cts +12 -0
  53. package/dist/journal-io.d.ts +12 -0
  54. package/dist/journal-io.js +7 -0
  55. package/dist/journal-replay.cjs +256 -0
  56. package/dist/journal-replay.d.cts +45 -0
  57. package/dist/journal-replay.d.ts +45 -0
  58. package/dist/journal-replay.js +17 -0
  59. package/dist/kill-chain.cjs +221 -0
  60. package/dist/kill-chain.d.cts +74 -0
  61. package/dist/kill-chain.d.ts +74 -0
  62. package/dist/kill-chain.js +23 -0
  63. package/dist/logger.cjs +84 -0
  64. package/dist/logger.d.cts +24 -0
  65. package/dist/logger.d.ts +24 -0
  66. package/dist/logger.js +11 -0
  67. package/dist/logs/stderr-rotation.cjs +151 -0
  68. package/dist/logs/stderr-rotation.d.cts +37 -0
  69. package/dist/logs/stderr-rotation.d.ts +37 -0
  70. package/dist/logs/stderr-rotation.js +23 -0
  71. package/dist/nesting-guard.cjs +95 -0
  72. package/dist/nesting-guard.d.cts +65 -0
  73. package/dist/nesting-guard.d.ts +65 -0
  74. package/dist/nesting-guard.js +15 -0
  75. package/dist/node-executor.cjs +180 -0
  76. package/dist/node-executor.d.cts +63 -0
  77. package/dist/node-executor.d.ts +63 -0
  78. package/dist/node-executor.js +16 -0
  79. package/dist/paths.cjs +55 -0
  80. package/dist/paths.d.cts +8 -0
  81. package/dist/paths.d.ts +8 -0
  82. package/dist/paths.js +15 -0
  83. package/dist/port-contract.cjs +35 -0
  84. package/dist/port-contract.d.cts +88 -0
  85. package/dist/port-contract.d.ts +88 -0
  86. package/dist/port-contract.js +7 -0
  87. package/dist/protocol/index.cjs +400 -0
  88. package/dist/protocol/index.d.cts +685 -0
  89. package/dist/protocol/index.d.ts +685 -0
  90. package/dist/protocol/index.js +89 -0
  91. package/dist/relay-env.cjs +71 -0
  92. package/dist/relay-env.d.cts +37 -0
  93. package/dist/relay-env.d.ts +37 -0
  94. package/dist/relay-env.js +23 -0
  95. package/dist/schema-emulation.cjs +6680 -0
  96. package/dist/schema-emulation.d.cts +39 -0
  97. package/dist/schema-emulation.d.ts +39 -0
  98. package/dist/schema-emulation.js +11 -0
  99. package/dist/spawn.cjs +200 -0
  100. package/dist/spawn.d.cts +80 -0
  101. package/dist/spawn.d.ts +80 -0
  102. package/dist/spawn.js +16 -0
  103. package/dist/ui-channels.cjs +120 -0
  104. package/dist/ui-channels.d.cts +60 -0
  105. package/dist/ui-channels.d.ts +60 -0
  106. package/dist/ui-channels.js +9 -0
  107. package/dist/ui-types.cjs +18 -0
  108. package/dist/ui-types.d.cts +62 -0
  109. package/dist/ui-types.d.ts +62 -0
  110. package/dist/ui-types.js +1 -0
  111. package/package.json +58 -0
  112. package/src/best-effort.ts +37 -0
  113. package/src/cli-entry.ts +77 -0
  114. package/src/data-dir.ts +88 -0
  115. package/src/env.ts +265 -0
  116. package/src/error-message.ts +22 -0
  117. package/src/index.ts +63 -0
  118. package/src/journal-io.ts +82 -0
  119. package/src/journal-replay.ts +432 -0
  120. package/src/kill-chain.ts +265 -0
  121. package/src/logger.ts +105 -0
  122. package/src/logs/stderr-rotation.ts +166 -0
  123. package/src/nesting-guard.ts +140 -0
  124. package/src/node-executor.ts +272 -0
  125. package/src/paths.ts +48 -0
  126. package/src/port-contract.ts +117 -0
  127. package/src/protocol/contract-types.ts +378 -0
  128. package/src/protocol/engine-protocol.ts +81 -0
  129. package/src/protocol/error-codes.ts +179 -0
  130. package/src/protocol/frames.ts +145 -0
  131. package/src/protocol/index.ts +12 -0
  132. package/src/protocol/methods.ts +229 -0
  133. package/src/protocol/reverse-channels.ts +274 -0
  134. package/src/protocol/schema.ts +154 -0
  135. package/src/relay-env.ts +60 -0
  136. package/src/schema-emulation.ts +192 -0
  137. package/src/spawn.ts +246 -0
  138. package/src/ui-channels.ts +219 -0
  139. package/src/ui-types.ts +84 -0
@@ -0,0 +1,179 @@
1
+ // src/protocol/error-codes.ts
2
+ //
3
+ // 协议错误码表(impl-plan §2.1「错误码表」逐项)+ 结构化错误载体 + kill-chain 消费的
4
+ // 具名错误文案构造器(自 core execution/engine/common/errors.ts 迁入 SDK 的引擎面
5
+ // 子集;core 侧错误 SSOT 留守,双侧错误码词表由测试互证)。
6
+ //
7
+ // 错误码语义与 core 侧处置(设计 §3.3 错误码表):
8
+ // engine_not_found 配置/清单里的 id 无对应包 → 列出已发现引擎 + 配置路径
9
+ // engine_protocol_mismatch 握手版本越界 → 该引擎不可用;升级 core 或引擎包
10
+ // engine_capability_unsupported core 的 gate 同步拦(manifest 少声明被 gate 四类之一)
11
+ // ——core 生成,不属「引擎 error 帧透传」
12
+ // engine_capability_mismatch manifest 声明 ≠ 握手能力位(被 gate 位多声明 → run 失败
13
+ // + 清理前置副作用;非 gate 位不一致 → 仅 warn)
14
+ // engine_model_unknown validateModel 未命中且 dynamic=false → 同步拒(record 不创建)
15
+ // engine_model_mismatch dynamic=true 运行期引擎拒绝 → run 失败 + record 标 failed
16
+ // engine_handshake_timeout initialize 超时(HANDSHAKE_TIMEOUT_MS=10s)→ 引擎不可用
17
+ // engine_crashed 进程意外退出 → 在途 run 失败(附 stderr 尾
18
+ // STDERR_TAIL_CHARS=400 字符);重建最多 3 次退避 1s/2s/4s
19
+ // engine_probe_failed probe 失败 → 既有 fallback 三守卫不变
20
+ // 其余 engine_* 引擎在 error 帧原样给出 → core 透传,文案契约不变
21
+
22
+ /** 协议核心错误码(引擎 error 帧 + core 同步拦截共用的固定词表)。 */
23
+ export const ENGINE_PROTOCOL_ERROR_CODES = [
24
+ "engine_not_found",
25
+ "engine_protocol_mismatch",
26
+ "engine_capability_unsupported",
27
+ "engine_capability_mismatch",
28
+ "engine_model_unknown",
29
+ "engine_model_mismatch",
30
+ "engine_handshake_timeout",
31
+ "engine_crashed",
32
+ "engine_probe_failed",
33
+ ] as const;
34
+
35
+ export type EngineProtocolErrorCode = (typeof ENGINE_PROTOCOL_ERROR_CODES)[number];
36
+
37
+ /** unknown → 协议错误码收窄(外部输入携带错误码时的运行时 guard;其余 engine_* 走透传)。 */
38
+ export function isEngineProtocolErrorCode(value: unknown): value is EngineProtocolErrorCode {
39
+ return (
40
+ typeof value === "string" &&
41
+ (ENGINE_PROTOCOL_ERROR_CODES as readonly string[]).includes(value)
42
+ );
43
+ }
44
+
45
+ /** 其余引擎自报错误码的前缀契约(透传面;core 不解释文案)。 */
46
+ export const ENGINE_ERROR_CODE_PREFIX = "engine_";
47
+
48
+ export function isEngineErrorPassthroughCode(value: string): boolean {
49
+ return (
50
+ !isEngineProtocolErrorCode(value) && value.startsWith(ENGINE_ERROR_CODE_PREFIX)
51
+ );
52
+ }
53
+
54
+ // ============================================================
55
+ // 结构化错误载体(协议 ProtocolError 的 TS 异常形态)
56
+ // ============================================================
57
+
58
+ import type { ProtocolError } from "./frames.ts";
59
+ import { SUPPORTED_PROTOCOL_RANGE } from "./engine-protocol.ts";
60
+ import type { EngineCapabilities } from "./contract-types.ts";
61
+
62
+ /**
63
+ * 结构化引擎错误(message 恒为 `<code>: <detail>` 前缀格式——AgentOutcome.error 与
64
+ * 协议 error 帧共用的错误码前缀约定);recovery 指向恢复动作。
65
+ * toStructured() 产出即协议 ProtocolError 形态(error 帧载荷直用)。
66
+ */
67
+ export class EngineSdkError extends Error {
68
+ readonly code: string;
69
+ readonly recovery: string;
70
+ readonly data?: Record<string, unknown>;
71
+
72
+ constructor(code: string, detail: string, recovery: string, data?: Record<string, unknown>) {
73
+ super(`${code}: ${detail}`);
74
+ this.name = "EngineSdkError";
75
+ this.code = code;
76
+ this.recovery = recovery;
77
+ this.data = data;
78
+ }
79
+
80
+ /** 协议 error 帧载荷投影。 */
81
+ toStructured(): ProtocolError {
82
+ return { code: this.code, message: this.message, recovery: this.recovery, data: this.data };
83
+ }
84
+ }
85
+
86
+ // ============================================================
87
+ // engine_protocol_mismatch 具名构造器(版本协商失败:含双方版本 + 升级指引)
88
+ // ============================================================
89
+
90
+ export function engineProtocolMismatchError(engineVersion: number): EngineSdkError {
91
+ return new EngineSdkError(
92
+ "engine_protocol_mismatch",
93
+ `engine speaks protocol v${engineVersion}, host supports [${SUPPORTED_PROTOCOL_RANGE.min}, ${SUPPORTED_PROTOCOL_RANGE.max})`,
94
+ "Upgrade the engine package (or the host) so both sides speak a protocol version in the supported range, then re-run the task. The engine is marked unavailable until then.",
95
+ {
96
+ engineProtocolVersion: engineVersion,
97
+ supportedMin: SUPPORTED_PROTOCOL_RANGE.min,
98
+ supportedMaxExclusive: SUPPORTED_PROTOCOL_RANGE.max,
99
+ },
100
+ );
101
+ }
102
+
103
+ // ============================================================
104
+ // [v1.x] conversation gate 位负向:chat 请求(run 会话形态)同步拒
105
+ // ============================================================
106
+
107
+ /**
108
+ * [v1.x] chat 会话形态的 gate 拒绝具名错误(chat-domain 设计 §3.2 D1-A +
109
+ * 验收 A6:manifest 无 conversation gate 位的引擎收到 chat 请求 → 同步拒)。
110
+ * 文案契约对齐 core capability-gate.ts conversation 分支(错误码
111
+ * engine_capability_unsupported + 「去掉参数 / 修 manifest / 升级引擎包」恢复指引)
112
+ * ——W3 chat 路由切协议客户端时以本构造器替换 core 内联文案,保持两侧一致。
113
+ */
114
+ export function engineConversationUnsupportedError(engineId: string): EngineSdkError {
115
+ return new EngineSdkError(
116
+ "engine_capability_unsupported",
117
+ `engine '${engineId}' 不支持 conversation(capabilities.conversation = 'unsupported',` +
118
+ `manifest 无 conversation gate 位——无同进程 idle 复用,message/close 交互控制面不可用)`,
119
+ `去掉 conversation 参数(一次性任务默认形态),或修 manifest capabilities / 升级引擎包(若引擎实际支持该能力)`,
120
+ { engineId, capability: "conversation", declared: "unsupported" },
121
+ );
122
+ }
123
+
124
+ /**
125
+ * [v1.x] chat 会话形态(run.params.chat / task.conversation=true)派发前的同步 gate:
126
+ * manifest conversation 位 unsupported 即抛 engineConversationUnsupportedError——
127
+ * 进程/record 创建前同步拒(A6:run 域不受影响,仅 chat 面被拦)。
128
+ * 判据单源:core 侧 capability-gate.assertTaskShapeSupported 的 conversation 分支
129
+ * 覆盖同一能力位,协议客户端路径(W3 接线)消费本函数,防两处判据漂移。
130
+ */
131
+ export function assertChatConversationSupported(
132
+ engineId: string,
133
+ capabilities: Pick<EngineCapabilities, "conversation">,
134
+ ): void {
135
+ if (capabilities.conversation === "unsupported") {
136
+ throw engineConversationUnsupportedError(engineId);
137
+ }
138
+ }
139
+
140
+ // ============================================================
141
+ // kill-chain 消费的引擎面错误文案(自 core errors.ts 迁入,逐字等价)
142
+ // ============================================================
143
+
144
+ /** 错误回显长度上限(截断长输出,避免错误消息爆炸)。 */
145
+ const DETAIL_ECHO_MAX_CHARS = 200;
146
+
147
+ /** stdout 尾部回显上限(engine_timeout / engine_run_failed 的错误规格载体系数)。 */
148
+ export const STDOUT_TAIL_ECHO_CHARS = 2000;
149
+
150
+ function truncate(text: string, max: number): string {
151
+ return text.length <= max ? text : `${text.slice(0, max)}...`;
152
+ }
153
+
154
+ /** engine_timeout 的恢复指引(kill-chain 超时杀链收尾文案)。 */
155
+ export const ENGINE_TIMEOUT_RECOVERY =
156
+ "The engine was killed by the host timeout chain. Inspect the captured stdout tail, then re-run with a larger " +
157
+ "timeout, a narrower task, or `engine: pi`.";
158
+
159
+ /**
160
+ * engine_timeout 的 outcome.error 文案:含 stdout 尾部 2000 字 + 恢复指引
161
+ * (kill-chain synthesizeTimeoutOutcome 消费;与 core errors.ts engineTimeoutDetail 逐字等价)。
162
+ */
163
+ export function engineTimeoutDetail(stdoutTail: string): string {
164
+ return (
165
+ `host timeout chain exhausted (SIGTERM -> grace -> SIGKILL). ` +
166
+ `Stdout tail (last ${STDOUT_TAIL_ECHO_CHARS} chars): ${truncate(stdoutTail, STDOUT_TAIL_ECHO_CHARS)}. ` +
167
+ `Recovery: ${ENGINE_TIMEOUT_RECOVERY}`
168
+ );
169
+ }
170
+
171
+ /** schema_emulation_failed 的终报文案(宿主编排层「重试一次仍失败」后消费)。 */
172
+ export function schemaEmulationFailedDetail(error: string, tail: string): string {
173
+ return (
174
+ `structured output emulation failed after tolerant extraction and one host-side retry: ${error}. ` +
175
+ `Raw output tail: ${truncate(tail, DETAIL_ECHO_MAX_CHARS)}. ` +
176
+ `Recovery: retry with a strengthened prompt or relax the schema; if it still fails switch to a ` +
177
+ `schema-native engine (engine: pi).`
178
+ );
179
+ }
@@ -0,0 +1,145 @@
1
+ // src/protocol/frames.ts
2
+ //
3
+ // 帧型四类(传输 = stdio NDJSON,每行一个 JSON 对象)。设计权威源:
4
+ // 设计 §3.3 帧型 + impl-plan §2.1「帧型四类」。
5
+ //
6
+ // ① 请求(core → 引擎) { id, method, params }
7
+ // ② 应答(引擎 → core) { id, result } | { id, error }
8
+ // ③ 通知(引擎 → core,无 id) { method: "event", params }
9
+ // ④ 反向请求(引擎 → core) { id, method: "host/*", params }(必须应答)
10
+ //
11
+ // id 形态:正向请求 id = number(core 单调计数);反向请求 id = string(引擎侧命名,
12
+ // 如 "rev-1");应答 id = 请求或反向请求 id 原样回传(number | string)。
13
+ // 实现面(行解析、请求关联、反向路由)归 W2 EngineClient;本文件只定帧型与判别。
14
+
15
+ import type { AgentEvent } from "./contract-types.ts";
16
+
17
+ /** 协议错误对象(error 帧载荷与反向请求错误应答共用形态)。 */
18
+ export interface ProtocolError {
19
+ /** 错误码(error-codes.ts 词表 + 其余 engine_* 引擎自报透传)。 */
20
+ code: string;
21
+ /** 人类可读详情。 */
22
+ message: string;
23
+ /** 恢复指引:指向具体下一步(命令 / 配置路径 / 升级动作),非安慰性文案。 */
24
+ recovery: string;
25
+ /** 结构化附参(如 engine_protocol_mismatch 的双方版本)。 */
26
+ data?: Record<string, unknown>;
27
+ }
28
+
29
+ // ============================================================
30
+ // ① 请求(core → 引擎)
31
+ // ============================================================
32
+
33
+ export interface RequestFrame {
34
+ id: number;
35
+ method: string;
36
+ params: unknown;
37
+ }
38
+
39
+ // ============================================================
40
+ // ② 应答(引擎 → core)
41
+ // ============================================================
42
+
43
+ export interface SuccessResponseFrame {
44
+ id: number | string;
45
+ result: unknown;
46
+ }
47
+
48
+ export interface ErrorResponseFrame {
49
+ id: number | string;
50
+ error: ProtocolError;
51
+ }
52
+
53
+ export type ResponseFrame = SuccessResponseFrame | ErrorResponseFrame;
54
+
55
+ // ============================================================
56
+ // ③ 通知(引擎 → core,无 id)
57
+ // ============================================================
58
+
59
+ /** event 通知载荷:runId 关联在途 run;seq 单调递增(基线①结构等价断言对象)。 */
60
+ export interface EventNotificationParams {
61
+ runId: string;
62
+ seq: number;
63
+ event: AgentEvent;
64
+ }
65
+
66
+ export interface NotificationFrame {
67
+ method: "event";
68
+ params: EventNotificationParams;
69
+ }
70
+
71
+ // ============================================================
72
+ // ④ 反向请求(引擎 → core,必须应答)
73
+ // ============================================================
74
+
75
+ export interface ReverseRequestFrame {
76
+ id: string;
77
+ method: string;
78
+ params: unknown;
79
+ }
80
+
81
+ /** 反向请求的应答(core → 引擎,沿 ResponseFrame 通道回传;id = 反向请求 id 原样)。 */
82
+ export type ReverseResponseResult =
83
+ /** 数据面类:处理确认。 */
84
+ | { ok: true }
85
+ /** 人机交互类(askUser/permission)两阶段第一阶段:已受理,结果异步到达(R9-2)。 */
86
+ | { ack: true }
87
+ /** 未实现的交互能力(设计:未实现回 unsupported,引擎自行降级)。 */
88
+ | { unsupported: true };
89
+
90
+ export type AnyFrame = RequestFrame | ResponseFrame | NotificationFrame | ReverseRequestFrame;
91
+
92
+ // ============================================================
93
+ // 判别守卫(W2 行解析器消费;结构判定,不抛错)
94
+ // ============================================================
95
+
96
+ function isRecord(v: unknown): v is Record<string, unknown> {
97
+ return typeof v === "object" && v !== null;
98
+ }
99
+
100
+ /** ① 请求:有数字 id + method + params,且无 result/error(与②应答区分)。 */
101
+ export function isRequestFrame(frame: unknown): frame is RequestFrame {
102
+ return (
103
+ isRecord(frame) &&
104
+ typeof frame.id === "number" &&
105
+ typeof frame.method === "string" &&
106
+ "params" in frame &&
107
+ !("result" in frame) &&
108
+ !("error" in frame)
109
+ );
110
+ }
111
+
112
+ /** ② 应答:有 id(number|string)且 result/error 二选一。 */
113
+ export function isResponseFrame(frame: unknown): frame is ResponseFrame {
114
+ if (!isRecord(frame) || !("id" in frame)) return false;
115
+ const idOk = typeof frame.id === "number" || typeof frame.id === "string";
116
+ if (!idOk) return false;
117
+ const hasResult = "result" in frame;
118
+ const hasError = "error" in frame;
119
+ return hasResult !== hasError;
120
+ }
121
+
122
+ /** ③ 通知:无 id,method === "event",params 含 runId/seq/event。 */
123
+ export function isNotificationFrame(frame: unknown): frame is NotificationFrame {
124
+ return (
125
+ isRecord(frame) &&
126
+ !("id" in frame) &&
127
+ frame.method === "event" &&
128
+ isRecord(frame.params) &&
129
+ typeof frame.params.runId === "string" &&
130
+ typeof frame.params.seq === "number" &&
131
+ isRecord(frame.params.event) &&
132
+ typeof frame.params.event.type === "string"
133
+ );
134
+ }
135
+
136
+ /** ④ 反向请求:有字符串 id + host/* method + params(与①的区别 = id 形态与 method 前缀)。 */
137
+ export function isReverseRequestFrame(frame: unknown): frame is ReverseRequestFrame {
138
+ return (
139
+ isRecord(frame) &&
140
+ typeof frame.id === "string" &&
141
+ typeof frame.method === "string" &&
142
+ frame.method.startsWith("host/") &&
143
+ "params" in frame
144
+ );
145
+ }
@@ -0,0 +1,12 @@
1
+ // src/protocol/index.ts
2
+ //
3
+ // 协议面 barrel(契约根公共出口)。W2 协议客户端(EngineClient/RemoteEngine)与
4
+ // 各引擎 CLI 包(W5/W7)从本入口消费帧型/方法/通道/错误码/契约类型/JSON Schema。
5
+
6
+ export * from "./engine-protocol.ts";
7
+ export * from "./frames.ts";
8
+ export * from "./methods.ts";
9
+ export * from "./reverse-channels.ts";
10
+ export * from "./error-codes.ts";
11
+ export * from "./contract-types.ts";
12
+ export * from "./schema.ts";
@@ -0,0 +1,229 @@
1
+ // src/protocol/methods.ts
2
+ //
3
+ // 10 正向方法(core → 引擎)params/result 逐方法写死(v1)。设计权威源:
4
+ // 设计 §3.3 方法集表 + impl-plan §2.1「10 正向方法」。
5
+ //
6
+ // [v1.x 增量(chat-domain 设计 §3.2 D1-A)]:方法集不变(chat 轮次 = run 会话形态
7
+ // + 既有 interact,不新造 chatRound 方法——D1-B 被否);增量以可选参数形态落在
8
+ // run.params.chat(会话形态参数 + 冷续 resume 锚点),major 不 bump。
9
+ //
10
+ // 应答面补充约定(设计 §3.3):initialize 应答仅诊断(与 manifest 不一致 → warn 留痕,
11
+ // 不参与同步成员判据;唯一阻断面 = 被 gate 能力位多声明 → engine_capability_mismatch);
12
+ // listModels / validateModel 为诊断面(宿主侧同步成员读 manifest,不经本方法);
13
+ // dispose 幂等;ping 为健康检查(ADR-0047:静默 ≠ 卡死,不据此杀任务)。
14
+
15
+ import type {
16
+ AgentCallOpts,
17
+ EngineCapabilities,
18
+ EngineHandleData,
19
+ AgentOutcome,
20
+ InteractAction,
21
+ InteractResult,
22
+ ModelCatalogEntry,
23
+ ProbeReport,
24
+ ResumeAnchor,
25
+ SessionView,
26
+ } from "./contract-types.ts";
27
+
28
+ /** 正向方法名联合(恰好 10 个;PROTOCOL_METHODS 常量数组与之同源互证)。 */
29
+ export type ProtocolMethod =
30
+ | "initialize"
31
+ | "probe"
32
+ | "run"
33
+ | "cancel"
34
+ | "interact"
35
+ | "read"
36
+ | "listModels"
37
+ | "validateModel"
38
+ | "dispose"
39
+ | "ping";
40
+
41
+ /** 方法名全集(运行时顺序化枚举;与 ProtocolMethod 的同源关系由测试断言)。 */
42
+ export const PROTOCOL_METHODS = [
43
+ "initialize",
44
+ "probe",
45
+ "run",
46
+ "cancel",
47
+ "interact",
48
+ "read",
49
+ "listModels",
50
+ "validateModel",
51
+ "dispose",
52
+ "ping",
53
+ ] as const satisfies readonly ProtocolMethod[];
54
+
55
+ // ============================================================
56
+ // run 专用载荷
57
+ // ============================================================
58
+
59
+ /**
60
+ * run 上下文(RunContext 字段映射的协议承载,设计 §3.3 RunContext 映射表)。
61
+ */
62
+ export interface RunContextParams {
63
+ /** 隔离池归属(journal 归属错 = 缺失后果)。 */
64
+ poolKey: string;
65
+ /** 任务工作目录(worktree 隔离时 = worktree 路径)。 */
66
+ cwd: string;
67
+ /** 请求模型 ref(未传 = 引擎缺省模型)。 */
68
+ model?: string;
69
+ /** 结构化输出 schema 的 env 注入形态(schemaEnv 降级通道)。 */
70
+ schemaEnv?: string;
71
+ /** 上下文模型 ref(与 run 模型分离的 ctx 模型)。 */
72
+ ctxModel?: string;
73
+ /** fallback 留痕(引擎回填 outcome.engineFallback 的种子)。 */
74
+ engineFallback?: { from: string; reason: string };
75
+ /** 事件粒度请求(引擎按 capabilities.eventGranularity 实际能力执行)。 */
76
+ streamMode?: "stream" | "coarse";
77
+ }
78
+
79
+ // ============================================================
80
+ // [v1.x] run 的 chat 会话形态参数(chat-domain 设计 §3.2 D1-A)
81
+ // ============================================================
82
+
83
+ /**
84
+ * [v1.x] chat 会话形态参数——HostChatRoundTicket 五字段过协议映射中「record」的
85
+ * 承载位(docs/design/chat-domain-v1x-liveness-governance.md §3.2 D1 五字段映射):
86
+ * - recordId:core 预建 record 的关联键(引擎据此回填 handle.sessionRef、上报
87
+ * host/childSpawned|childStateChanged 与 host/roundLifecycle 的 record 键形态);
88
+ * - resume:冷续锚点(重开已 idle 的 session 续聊;缺省 = 新 session)。对照
89
+ * core SpawnResumeOpts——sessionFile 经 anchor.sessionRef 携带,model/
90
+ * thinkingLevel 防漂移覆盖走既有 task/ctx 字段,不双写。
91
+ * task.conversation === true 时必传(chat 路由前置 gate:manifest conversation 位
92
+ * unsupported 的引擎同步拒 engine_capability_unsupported——见 error-codes.ts)。
93
+ */
94
+ export interface RunChatParams {
95
+ recordId: string;
96
+ resume?: ResumeAnchor;
97
+ }
98
+
99
+ // ============================================================
100
+ // params / result 逐方法映射(方法名 → 载荷)
101
+ // ============================================================
102
+
103
+ /** initialize 参数(engineConfig = L3 显式配置 engines.<id>.config 透传,不放凭据)。 */
104
+ export interface InitializeParams {
105
+ protocolVersion: number;
106
+ hostInfo: { name: string; version: string; dataRoot: string };
107
+ engineConfig: Record<string, string>;
108
+ }
109
+
110
+ /** initialize 应答(仅诊断面:capabilities/models 与 manifest 不一致 → warn,不参与判据)。 */
111
+ export interface InitializeResult {
112
+ protocolVersion: number;
113
+ engineId: string;
114
+ engineVersion: string;
115
+ adapterVersion: string;
116
+ capabilities: EngineCapabilities;
117
+ /** 模型目录(诊断面;省略/null = 无枚举面语义)。 */
118
+ models?: ModelCatalogEntry[] | null;
119
+ }
120
+
121
+ export interface ProbeParams {
122
+ force?: boolean;
123
+ }
124
+
125
+ export interface RunParams {
126
+ runId: string;
127
+ task: AgentCallOpts;
128
+ ctx: RunContextParams;
129
+ /**
130
+ * [v1.x 可选增量] chat 会话形态参数(task.conversation=true 的 chat 路由承载)。
131
+ * 缺省 = 一次性任务形态,v1 引擎/宿主语义不变(向后兼容:旧引擎忽略未知字段,
132
+ * 帧级 schema params 不做深校验)。续聊/关断不经此参数——走既有 interact。
133
+ */
134
+ chat?: RunChatParams;
135
+ }
136
+
137
+ /** run 终态应答(期间事件经 event 通知;长运行方法,应答到达即终态)。 */
138
+ export interface RunResult {
139
+ handle: EngineHandleData;
140
+ outcome: AgentOutcome;
141
+ }
142
+
143
+ export interface CancelParams {
144
+ runId: string;
145
+ reason: string;
146
+ }
147
+
148
+ /**
149
+ * cancel 应答(受理确认)。终态本体由该 run 的 run 终态应答承载(abort 合成终态经
150
+ * event/终态应答到达);引擎须 CANCEL_SETTLE_GRACE_MS(3s)内收敛,超时 core 走杀链。
151
+ */
152
+ export interface CancelResult {
153
+ ok: true;
154
+ }
155
+
156
+ export interface InteractParams {
157
+ handle: EngineHandleData;
158
+ action: InteractAction;
159
+ }
160
+
161
+ export interface ReadParams {
162
+ handle: EngineHandleData;
163
+ /** 数据根必填:存量池时代引擎自算池/journal 相对 dbPath 的定位需要它(设计钉死)。 */
164
+ dataDir: string;
165
+ }
166
+
167
+ export interface ListModelsParams {
168
+ /** 占位空参(帧形状一致性;未来诊断参数在此扩展)。 */
169
+ _placeholder?: never;
170
+ }
171
+
172
+ export interface ListModelsResult {
173
+ /** 数组 = 有枚举面;null = 无枚举面(buildCoreAlignedHint 语义,与 manifest 省略对齐)。 */
174
+ models: ModelCatalogEntry[] | null;
175
+ }
176
+
177
+ export interface ValidateModelParams {
178
+ modelRef?: string;
179
+ }
180
+
181
+ export interface ValidateModelResult {
182
+ canonicalRef: string;
183
+ }
184
+
185
+ export interface DisposeParams {
186
+ /** 占位空参(帧形状一致性;幂等语义)。 */
187
+ _placeholder?: never;
188
+ }
189
+
190
+ export interface DisposeResult {
191
+ ok: true;
192
+ }
193
+
194
+ export interface PingParams {
195
+ /** 占位空参(帧形状一致性)。 */
196
+ _placeholder?: never;
197
+ }
198
+
199
+ export interface PingResult {
200
+ pong: true;
201
+ }
202
+
203
+ /** 方法 → params 类型映射。 */
204
+ export interface ProtocolParamsMap {
205
+ initialize: InitializeParams;
206
+ probe: ProbeParams;
207
+ run: RunParams;
208
+ cancel: CancelParams;
209
+ interact: InteractParams;
210
+ read: ReadParams;
211
+ listModels: ListModelsParams;
212
+ validateModel: ValidateModelParams;
213
+ dispose: DisposeParams;
214
+ ping: PingParams;
215
+ }
216
+
217
+ /** 方法 → result 类型映射。 */
218
+ export interface ProtocolResultMap {
219
+ initialize: InitializeResult;
220
+ probe: ProbeReport;
221
+ run: RunResult;
222
+ cancel: CancelResult;
223
+ interact: InteractResult;
224
+ read: SessionView;
225
+ listModels: ListModelsResult;
226
+ validateModel: ValidateModelResult;
227
+ dispose: DisposeResult;
228
+ ping: PingResult;
229
+ }