@mininglamp-oss/octo-runtime 1.1.9 → 1.1.10

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 (111) hide show
  1. package/README.md +1 -1
  2. package/{node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/runtime-configuration.d.ts → apps/cli/dist/adapter-configuration.d.ts} +1 -0
  3. package/{node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/runtime-configuration.js → apps/cli/dist/adapter-configuration.js} +1 -0
  4. package/apps/cli/dist/adapter-configurations.d.ts +1 -1
  5. package/apps/cli/dist/adapter-configurations.js +1 -1
  6. package/apps/cli/dist/adapters.d.ts +7 -0
  7. package/apps/cli/dist/adapters.js +51 -0
  8. package/apps/cli/dist/build-info.json +2 -2
  9. package/apps/cli/dist/help.js +1 -1
  10. package/apps/cli/dist/index.js +4 -0
  11. package/apps/cli/dist/main.d.ts +2 -0
  12. package/apps/cli/dist/main.js +10 -12
  13. package/apps/cli/dist/manifest.json +0 -5
  14. package/apps/cli/dist/output.js +2 -7
  15. package/apps/cli/dist/playboard-interrupt.d.ts +6 -0
  16. package/apps/cli/dist/playboard-interrupt.js +86 -0
  17. package/apps/cli/dist/playboard.d.ts +2 -0
  18. package/apps/cli/dist/playboard.js +9 -10
  19. package/dist/public/executor-kernel.d.ts +0 -1
  20. package/dist/public/executor-kernel.js +0 -1
  21. package/node_modules/@mininglamp-oss/octo-runtime-acp-client/package.json +3 -3
  22. package/node_modules/@mininglamp-oss/octo-runtime-adapter-acp/package.json +4 -4
  23. package/node_modules/@mininglamp-oss/octo-runtime-adapter-antigravity/package.json +3 -3
  24. package/node_modules/@mininglamp-oss/octo-runtime-adapter-claude-code/package.json +3 -3
  25. package/node_modules/@mininglamp-oss/octo-runtime-adapter-codebuddy/package.json +4 -4
  26. package/node_modules/@mininglamp-oss/octo-runtime-adapter-codex/package.json +3 -3
  27. package/node_modules/@mininglamp-oss/octo-runtime-adapter-dsh/package.json +3 -3
  28. package/node_modules/@mininglamp-oss/octo-runtime-adapter-grok-build/package.json +5 -5
  29. package/node_modules/@mininglamp-oss/octo-runtime-adapter-hermes/package.json +2 -2
  30. package/node_modules/@mininglamp-oss/octo-runtime-adapter-kimi-code/package.json +2 -2
  31. package/node_modules/@mininglamp-oss/octo-runtime-adapter-mcode/package.json +2 -2
  32. package/node_modules/@mininglamp-oss/octo-runtime-adapter-openclaw/package.json +3 -3
  33. package/node_modules/@mininglamp-oss/octo-runtime-adapter-opencode/package.json +4 -4
  34. package/node_modules/@mininglamp-oss/octo-runtime-adapter-qodercli/package.json +2 -2
  35. package/node_modules/@mininglamp-oss/octo-runtime-adapter-qoderclicn/package.json +2 -2
  36. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/dist/reasoning.js +1 -2
  37. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/dist/service-status.d.ts +1 -1
  38. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/dist/service-status.js +12 -30
  39. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/package.json +2 -2
  40. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/adapter-configuration.d.ts +3 -0
  41. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/adapter-configuration.js +125 -0
  42. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/adapter-configurations.d.ts +1 -1
  43. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/adapter-configurations.js +1 -1
  44. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/adapters.d.ts +7 -0
  45. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/adapters.js +51 -0
  46. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/build-info.json +2 -2
  47. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/help.js +1 -1
  48. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/index.js +4 -0
  49. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/main.d.ts +2 -0
  50. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/main.js +10 -12
  51. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/manifest.json +0 -5
  52. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/output.js +2 -7
  53. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/playboard-interrupt.d.ts +6 -0
  54. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/playboard-interrupt.js +86 -0
  55. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/playboard.d.ts +2 -0
  56. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/playboard.js +9 -10
  57. package/node_modules/@mininglamp-oss/octo-runtime-cli/package.json +23 -24
  58. package/node_modules/@mininglamp-oss/octo-runtime-cross-service/package.json +1 -1
  59. package/node_modules/@mininglamp-oss/octo-runtime-executor-core/dist/index.d.ts +3 -3
  60. package/node_modules/@mininglamp-oss/octo-runtime-executor-core/dist/index.js +26 -7
  61. package/node_modules/@mininglamp-oss/octo-runtime-executor-core/package.json +3 -3
  62. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/client.d.ts +2 -0
  63. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/client.js +2 -0
  64. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/execution-source.d.ts +17 -0
  65. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/execution-source.js +21 -0
  66. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/host-run-service.d.ts +9 -9
  67. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/host-run-service.js +1 -1
  68. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/index.d.ts +1 -6
  69. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/index.js +2 -6
  70. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/invocation-manifest.d.ts +14 -13
  71. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/invocation-manifest.js +84 -187
  72. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/server.d.ts +5 -8
  73. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/server.js +45 -38
  74. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/service.d.ts +5 -1
  75. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/service.js +15 -3
  76. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/package.json +4 -12
  77. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/package.json +6 -6
  78. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-wecom/package.json +5 -5
  79. package/node_modules/@mininglamp-oss/octo-runtime-extra-webui/dist/web/assets/{index-BVxePruX.js → index-BLMf2Etg.js} +1 -3
  80. package/node_modules/@mininglamp-oss/octo-runtime-extra-webui/dist/web/index.html +1 -1
  81. package/node_modules/@mininglamp-oss/octo-runtime-extra-webui/package.json +2 -2
  82. package/node_modules/@mininglamp-oss/octo-runtime-host-sdk/package.json +4 -4
  83. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/generated/protocol-types.d.ts +0 -15
  84. package/node_modules/@mininglamp-oss/octo-runtime-protocol/package.json +1 -1
  85. package/package.json +26 -28
  86. package/packages/octo-runtime-protocol/schema/protocol.schema.json +1 -37
  87. package/apps/cli/dist/worker.d.ts +0 -1
  88. package/apps/cli/dist/worker.js +0 -18
  89. package/node_modules/@mininglamp-oss/octo-runtime-adapter-zcode-gui/dist/app-server.d.ts +0 -63
  90. package/node_modules/@mininglamp-oss/octo-runtime-adapter-zcode-gui/dist/app-server.js +0 -846
  91. package/node_modules/@mininglamp-oss/octo-runtime-adapter-zcode-gui/dist/index.d.ts +0 -54
  92. package/node_modules/@mininglamp-oss/octo-runtime-adapter-zcode-gui/dist/index.js +0 -154
  93. package/node_modules/@mininglamp-oss/octo-runtime-adapter-zcode-gui/package.json +0 -15
  94. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/worker.d.ts +0 -1
  95. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/worker.js +0 -18
  96. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/heartbeat.d.ts +0 -16
  97. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/heartbeat.js +0 -59
  98. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/manifest-adapters.d.ts +0 -6
  99. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/manifest-adapters.js +0 -88
  100. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/module-specifier.d.ts +0 -1
  101. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/module-specifier.js +0 -2
  102. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/process.d.ts +0 -42
  103. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/process.js +0 -292
  104. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/rpc.d.ts +0 -64
  105. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/rpc.js +0 -674
  106. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/runner.d.ts +0 -2
  107. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/runner.js +0 -5
  108. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/serve.d.ts +0 -10
  109. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/serve.js +0 -96
  110. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/supervisor.d.ts +0 -15
  111. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/supervisor.js +0 -279
@@ -1,846 +0,0 @@
1
- import { createProcessCleanup } from "@mininglamp-oss/octo-runtime-adapter-sdk/process-cleanup";
2
- import { DriverQueue, watchLineLimit, initialControlInstructions, hasImageInput, freshFallbackInputText, providerInputText } from "@mininglamp-oss/octo-runtime-adapter-sdk";
3
- import { canonicalTerminalStatus, resolveStreamLimitPolicy } from "@mininglamp-oss/octo-runtime-protocol";
4
- import { spawn } from "node:child_process";
5
- import { createInterface } from "node:readline";
6
- const REQUEST_TIMEOUT_MS = 30_000;
7
- const CLOSE_GRACE_MS = 250;
8
- const STDERR_TAIL_LIMIT = 64 * 1_024;
9
- const MAX_PUBLIC_TEXT_CHARS = 1_000;
10
- export class ZcodeAppServerRpcError extends Error {
11
- method;
12
- code;
13
- data;
14
- constructor(method, code, message, data) {
15
- super(`${method}: ${message}`);
16
- this.method = method;
17
- this.code = code;
18
- this.data = data;
19
- this.name = "ZcodeAppServerRpcError";
20
- }
21
- }
22
- export class ZcodeAppServerProcessError extends Error {
23
- exit;
24
- constructor(message, exit) {
25
- super(message);
26
- this.exit = exit;
27
- this.name = "ZcodeAppServerProcessError";
28
- }
29
- }
30
- export class ZcodeEventNormalizer {
31
- #state;
32
- constructor(runId) {
33
- this.#state = {
34
- stepId: `zcode-gui:${runId}`,
35
- stepStarted: false,
36
- stepFinished: false,
37
- finalMessageStarted: false,
38
- reasoningMessageStarted: false,
39
- publicText: "",
40
- tools: new Map()
41
- };
42
- }
43
- normalize(event) {
44
- return normalizeZcodeEvent(event, this.#state);
45
- }
46
- }
47
- export function normalizeZcodeEvent(event, state) {
48
- const payload = asRecord(event.payload) ?? {};
49
- const events = [];
50
- const ensureStep = () => {
51
- if (state.stepStarted)
52
- return;
53
- state.stepStarted = true;
54
- events.push({
55
- protocolVersion: 2,
56
- type: "model_step.started",
57
- payload: { stepId: state.stepId }
58
- });
59
- };
60
- if (event.type === "turn.started") {
61
- ensureStep();
62
- return events;
63
- }
64
- if (event.type === "model.streaming") {
65
- ensureStep();
66
- const kind = stringField(payload, "kind");
67
- if (kind === "text_delta") {
68
- const text = stringField(payload, "delta");
69
- if (!text)
70
- return events;
71
- if (!state.finalMessageStarted) {
72
- state.finalMessageStarted = true;
73
- events.push({
74
- protocolVersion: 2,
75
- type: "message.create",
76
- payload: {
77
- messageId: `${state.stepId}:final`,
78
- role: "assistant",
79
- status: "streaming",
80
- channel: "final",
81
- stepId: state.stepId
82
- }
83
- });
84
- }
85
- appendPublicText(state, text);
86
- events.push({
87
- protocolVersion: 2,
88
- type: "message.delta",
89
- payload: {
90
- messageId: `${state.stepId}:final`,
91
- text,
92
- channel: "final",
93
- stepId: state.stepId
94
- }
95
- });
96
- return events;
97
- }
98
- if (kind === "reasoning_delta") {
99
- const text = stringField(payload, "delta");
100
- if (!text)
101
- return events;
102
- if (!state.reasoningMessageStarted) {
103
- state.reasoningMessageStarted = true;
104
- events.push({
105
- protocolVersion: 2,
106
- type: "message.create",
107
- payload: {
108
- messageId: `${state.stepId}:reasoning`,
109
- role: "assistant",
110
- status: "streaming",
111
- channel: "analysis",
112
- exposure: "public_reasoning",
113
- stepId: state.stepId
114
- }
115
- });
116
- }
117
- events.push({
118
- protocolVersion: 2,
119
- type: "message.delta",
120
- payload: {
121
- messageId: `${state.stepId}:reasoning`,
122
- text,
123
- channel: "analysis",
124
- exposure: "public_reasoning",
125
- stepId: state.stepId,
126
- provenance: { provider: "zcode-gui", nativeEvent: event.type }
127
- }
128
- });
129
- return events;
130
- }
131
- if (kind === "tool_call") {
132
- const id = stringField(payload, "toolCallId");
133
- if (id && !state.tools.has(id)) {
134
- state.tools.set(id, {
135
- name: stringField(payload, "toolName") ?? "zcode_tool",
136
- input: payload.input,
137
- terminal: false,
138
- created: false
139
- });
140
- }
141
- }
142
- return events;
143
- }
144
- if (event.type === "tool.updated") {
145
- ensureStep();
146
- const kind = stringField(payload, "kind") ?? "progress";
147
- if (kind === "batch") {
148
- const ids = Array.isArray(payload.toolCallIds) ? payload.toolCallIds.filter(isString) : [];
149
- const status = numberField(payload, "errorCount") && numberField(payload, "errorCount") > 0
150
- ? "failed"
151
- : "completed";
152
- for (const id of ids) {
153
- const tool = state.tools.get(id);
154
- if (!tool || tool.terminal)
155
- continue;
156
- tool.terminal = true;
157
- events.push({
158
- protocolVersion: 2,
159
- type: "tool_call.update",
160
- payload: {
161
- id,
162
- name: tool.name,
163
- args: tool.input,
164
- status: canonicalTerminalStatus(status),
165
- stepId: state.stepId
166
- }
167
- });
168
- }
169
- return events;
170
- }
171
- const id = stringField(payload, "toolCallId");
172
- if (!id)
173
- return events;
174
- let tool = state.tools.get(id);
175
- if (!tool) {
176
- tool = {
177
- name: stringField(payload, "toolName") ?? "zcode_tool",
178
- input: payload.input,
179
- terminal: false,
180
- created: false
181
- };
182
- state.tools.set(id, tool);
183
- }
184
- else {
185
- tool.name = stringField(payload, "toolName") ?? tool.name;
186
- if (payload.input !== undefined)
187
- tool.input = payload.input;
188
- }
189
- if (tool.terminal)
190
- return events;
191
- if (kind !== "result" &&
192
- kind !== "error" &&
193
- (kind === "scheduled" || !toolCreated(events, state, id))) {
194
- const created = ensureToolCreated(state, id);
195
- if (created)
196
- events.push(created);
197
- }
198
- if (kind === "scheduled")
199
- return events;
200
- if (kind === "started") {
201
- return events;
202
- }
203
- if (kind === "progress") {
204
- events.push({
205
- protocolVersion: 2,
206
- type: "tool_call.delta",
207
- payload: {
208
- id,
209
- outputSnapshot: printableValue(payload.stdoutTail ?? payload.stderrTail, ""),
210
- stepId: state.stepId
211
- }
212
- });
213
- return events;
214
- }
215
- if (kind === "result") {
216
- tool.terminal = true;
217
- events.push({
218
- protocolVersion: 2,
219
- type: "tool_call.update",
220
- payload: {
221
- id,
222
- name: tool.name,
223
- args: tool.input,
224
- status: canonicalTerminalStatus("completed"),
225
- output: payload.result,
226
- stepId: state.stepId
227
- }
228
- });
229
- return events;
230
- }
231
- if (kind === "error") {
232
- tool.terminal = true;
233
- events.push({
234
- protocolVersion: 2,
235
- type: "tool_call.update",
236
- payload: {
237
- id,
238
- name: tool.name,
239
- args: tool.input,
240
- status: canonicalTerminalStatus("failed"),
241
- error: asRecord(payload.error) ?? {
242
- message: printableValue(payload.error, "ZCode tool failed")
243
- },
244
- stepId: state.stepId
245
- }
246
- });
247
- }
248
- return events;
249
- }
250
- if (event.type === "session.updated") {
251
- const usage = asRecord(payload.usage);
252
- if (usage)
253
- events.push({
254
- protocolVersion: 2,
255
- type: "usage.update",
256
- payload: {
257
- ...usage,
258
- ...(payload.contextWindow !== undefined ? { contextWindow: payload.contextWindow } : {})
259
- }
260
- });
261
- return events;
262
- }
263
- if (event.type === "turn.completed" || event.type === "turn.failed") {
264
- const failed = event.type === "turn.failed";
265
- const resultType = stringField(payload, "resultType") ?? (failed ? "error" : "success");
266
- const cancelled = /cancel|abort|stop|interrupt/i.test(resultType);
267
- const usage = asRecord(payload.usage);
268
- if (usage)
269
- events.push({ protocolVersion: 2, type: "usage.update", payload: { ...usage } });
270
- if (state.stepStarted && !state.stepFinished) {
271
- state.stepFinished = true;
272
- events.push({
273
- protocolVersion: 2,
274
- type: "model_step.finished",
275
- payload: {
276
- stepId: state.stepId,
277
- status: canonicalTerminalStatus(failed ? "failed" : cancelled ? "cancelled" : "completed"),
278
- finishReason: resultType
279
- }
280
- });
281
- }
282
- if (state.reasoningMessageStarted) {
283
- events.push({
284
- protocolVersion: 2,
285
- type: "message.update",
286
- payload: {
287
- messageId: `${state.stepId}:reasoning`,
288
- role: "assistant",
289
- status: failed ? "failed" : cancelled ? "stopped" : "completed"
290
- }
291
- });
292
- }
293
- if (state.finalMessageStarted) {
294
- events.push({
295
- protocolVersion: 2,
296
- type: "message.update",
297
- payload: {
298
- messageId: `${state.stepId}:final`,
299
- role: "assistant",
300
- status: failed ? "failed" : cancelled ? "stopped" : "completed"
301
- }
302
- });
303
- }
304
- if (failed) {
305
- const error = asRecord(payload.error);
306
- events.push({
307
- protocolVersion: 2,
308
- type: "run.failed",
309
- payload: {
310
- adapterType: "zcode-gui",
311
- code: error?.code ?? "ZCODE_TURN_FAILED",
312
- message: stringField(error, "message") ?? "ZCode turn failed"
313
- }
314
- });
315
- }
316
- else if (cancelled) {
317
- events.push({ protocolVersion: 2, type: "run.cancelled", payload: { reason: resultType } });
318
- }
319
- else {
320
- events.push({ protocolVersion: 2, type: "run.completed", payload: {} });
321
- }
322
- }
323
- return events;
324
- }
325
- export async function* runZcodeAppServerTurn({ request, spec, spawnFn = defaultSpawn, context, approvalBridge }) {
326
- if (hasImageInput(request))
327
- throw new Error("UNSUPPORTED_INPUT_MODALITY: zcode-gui does not encode image input");
328
- if (request.approvalMode === "assisted" || (request.approvalMode === "ask" && !approvalBridge))
329
- throw new Error("APPROVAL_MODE_UNSUPPORTED");
330
- if (request.agentConfig.model)
331
- throw new Error("EXECUTION_SELECTION_UNSUPPORTED: zcode independent model selection is not qualified");
332
- const autoApprove = request.approvalMode === "full_access";
333
- const client = new ZcodeAppServerClient({
334
- spec,
335
- spawnFn,
336
- requestTimeoutMs: requestTimeout(request),
337
- autoApprove,
338
- streamLimits: context?.streamLimits,
339
- permissionHandler: approvalBridge
340
- ? async (params, write) => {
341
- const permission = {
342
- toolCall: {
343
- title: typeof params.reason === "string" ? params.reason : "ZCode tool permission"
344
- },
345
- options: [
346
- { kind: "allow_once", optionId: "allow" },
347
- { kind: "reject_once", optionId: "deny" }
348
- ]
349
- };
350
- try {
351
- const result = await approvalBridge.requestPermission(permission);
352
- await write({
353
- decision: result.outcome?.optionId === "allow" ? "allow" : "deny"
354
- });
355
- approvalBridge.responseWritten(permission);
356
- }
357
- catch (error) {
358
- approvalBridge.responseFailed(permission, error instanceof Error ? error : new Error(String(error)));
359
- throw error;
360
- }
361
- }
362
- : undefined
363
- });
364
- approvalBridge?.bindTransport(() => client.close());
365
- let sessionId;
366
- let terminal = false;
367
- let abortTimer;
368
- const abort = () => {
369
- if (sessionId)
370
- client.notify("session/stop", { sessionId });
371
- abortTimer ??= setTimeout(() => {
372
- void client.close().catch(() => undefined);
373
- }, CLOSE_GRACE_MS);
374
- abortTimer.unref();
375
- };
376
- if (request.signal?.aborted)
377
- abort();
378
- else
379
- request.signal?.addEventListener("abort", abort, { once: true });
380
- try {
381
- throwIfAborted(request.signal);
382
- const requestedSessionId = request.providerSession?.sessionId;
383
- let resumed = false;
384
- let resumeFallback;
385
- const workspace = { workspacePath: request.workdir, workspaceKey: request.workdir };
386
- let sessionResult;
387
- if (requestedSessionId) {
388
- try {
389
- sessionResult = await client.request("session/resume", {
390
- sessionId: requestedSessionId,
391
- workspace
392
- });
393
- sessionId = extractSessionId(sessionResult) ?? requestedSessionId;
394
- resumed = true;
395
- }
396
- catch (error) {
397
- resumeFallback = failureReason(error);
398
- }
399
- }
400
- if (!sessionId) {
401
- const mode = zcodeMode(request);
402
- sessionResult = await client.request("session/create", { workspace, mode });
403
- sessionId = extractSessionId(sessionResult);
404
- if (!sessionId)
405
- throw new Error("ZCode session/create returned no session id");
406
- }
407
- client.setActiveSession(sessionId);
408
- await client.request("session/subscribe", {
409
- sessionId,
410
- deliveryKind: "desktop-continuous",
411
- includeSnapshot: false,
412
- afterSeq: 0
413
- });
414
- const input = resumeFallback ? freshFallbackInputText(request) : providerInputText(request);
415
- const content = initialControlInstructions(request, !resumed)
416
- ? `${input}\n\n${initialControlInstructions(request, !resumed)}`
417
- : input;
418
- const sendResult = await client.request("session/send", { sessionId, content });
419
- if (asRecord(sendResult)?.accepted === false)
420
- throw new Error("ZCode session/send was not accepted");
421
- yield {
422
- protocolVersion: 2,
423
- type: "session.update",
424
- payload: {
425
- providerSession: {
426
- sessionId,
427
- resumable: true,
428
- ...(resumed ? { resumeOutcome: "resumed" } : {}),
429
- ...(resumeFallback
430
- ? {
431
- resumeOutcome: "fresh_fallback",
432
- resumeFallback,
433
- contextInputVariant: request.freshFallbackModelInput ? "recovery" : "primary"
434
- }
435
- : {})
436
- }
437
- }
438
- };
439
- const normalizer = new ZcodeEventNormalizer(request.runId);
440
- for await (const nativeEvent of client.events()) {
441
- const events = normalizer.normalize(nativeEvent);
442
- if (events.length === 0)
443
- continue;
444
- for (const event of events) {
445
- terminal ||= isTerminal(event);
446
- yield event;
447
- }
448
- if (terminal)
449
- break;
450
- }
451
- if (!terminal) {
452
- const exit = await client.exit();
453
- throw new ZcodeAppServerProcessError(client.processErrorMessage(exit), exit);
454
- }
455
- }
456
- catch (error) {
457
- if (!terminal) {
458
- if (request.signal?.aborted) {
459
- yield {
460
- protocolVersion: 2,
461
- type: "run.cancelled",
462
- payload: { reason: String(request.signal.reason ?? "cancelled") }
463
- };
464
- }
465
- else {
466
- yield {
467
- protocolVersion: 2,
468
- type: "run.failed",
469
- payload: {
470
- adapterType: "zcode-gui",
471
- code: errorCode(error),
472
- message: client.errorMessage(error)
473
- }
474
- };
475
- }
476
- }
477
- }
478
- finally {
479
- request.signal?.removeEventListener("abort", abort);
480
- if (abortTimer)
481
- clearTimeout(abortTimer);
482
- await closeZcodeResources(client, spec);
483
- }
484
- }
485
- async function closeZcodeResources(client, spec) {
486
- const failures = [];
487
- try {
488
- await client.close();
489
- }
490
- catch (error) {
491
- failures.push(error);
492
- }
493
- try {
494
- await spec.cleanup?.();
495
- }
496
- catch (error) {
497
- failures.push(error);
498
- }
499
- if (failures.length === 1)
500
- throw failures[0];
501
- if (failures.length)
502
- throw new AggregateError(failures, "ZCode resource cleanup failed");
503
- }
504
- class ZcodeAppServerClient {
505
- #child;
506
- #pending = new Map();
507
- #events;
508
- #streamLimits;
509
- #requestTimeoutMs;
510
- #autoApprove;
511
- #permissionHandler;
512
- #exitPromise;
513
- #resolveExit;
514
- #nextId = 1;
515
- #stderr = "";
516
- #activeSession;
517
- #lastSeq = 0;
518
- #closed = false;
519
- #cleanup;
520
- #reader;
521
- #closePromise;
522
- #failure;
523
- #removeLineGuard;
524
- constructor({ spec, spawnFn, requestTimeoutMs, autoApprove, streamLimits, permissionHandler }) {
525
- this.#streamLimits = resolveStreamLimitPolicy(streamLimits);
526
- this.#events = new DriverQueue({
527
- limits: this.#streamLimits,
528
- boundary: "zcode.event_queue",
529
- onFailure: (error) => this.#failAll(error)
530
- });
531
- this.#requestTimeoutMs = requestTimeoutMs;
532
- this.#autoApprove = autoApprove;
533
- this.#permissionHandler = permissionHandler;
534
- this.#exitPromise = new Promise((resolve) => {
535
- this.#resolveExit = resolve;
536
- });
537
- this.#child = spawnFn(spec.command, spec.args, {
538
- cwd: spec.cwd,
539
- env: spec.env,
540
- detached: process.platform !== "win32"
541
- });
542
- this.#cleanup = createProcessCleanup(this.#child, {
543
- processGroup: process.platform !== "win32"
544
- });
545
- this.#child.stderr.setEncoding("utf8");
546
- this.#child.stderr.on("data", (value) => {
547
- this.#stderr = (this.#stderr + value.toString()).slice(-STDERR_TAIL_LIMIT);
548
- });
549
- for (const source of [this.#child.stdin, this.#child.stdout, this.#child.stderr]) {
550
- source.on("error", (error) => this.#failAll(error));
551
- }
552
- // ZCode 不支持图片输入,所有原生行使用本 invocation 的 Provider 上限。
553
- // .octospec/tasks/pr1-yujiawei-review/assessment.md
554
- this.#removeLineGuard = watchLineLimit(this.#child.stdout, this.#streamLimits.rawMessageMaxBytes, (error) => {
555
- Object.assign(error, { boundary: "zcode.stdout" });
556
- this.#failAll(error);
557
- this.#child.stdout.destroy();
558
- });
559
- this.#reader = createInterface({ input: this.#child.stdout });
560
- this.#reader.on("error", (error) => this.#failAll(error));
561
- this.#reader.on("line", (line) => this.#receiveLine(line));
562
- this.#child.once("error", (error) => {
563
- this.#resolveExit({ code: null, signal: null });
564
- this.#failAll(error);
565
- });
566
- // leader exit 启动组回收,close 后才认定 stdout 已排空。
567
- this.#child.once("exit", () => {
568
- void this.#cleanup().catch((error) => this.#failAll(error));
569
- });
570
- this.#child.once("close", (code, signal) => {
571
- const exit = { code, signal };
572
- this.#resolveExit(exit);
573
- if (!this.#closed)
574
- this.#failAll(new ZcodeAppServerProcessError(this.processErrorMessage(exit), exit), code !== 0);
575
- });
576
- }
577
- reserveRequestId() {
578
- return this.#nextId++;
579
- }
580
- setActiveSession(sessionId) {
581
- this.#activeSession = sessionId;
582
- }
583
- request(method, params, onWritten, requestId) {
584
- if (this.#failure)
585
- return Promise.reject(this.#failure);
586
- if (this.#closed)
587
- return Promise.reject(new Error("ZCode app-server client closed"));
588
- const id = requestId ?? this.reserveRequestId();
589
- let timer;
590
- const result = new Promise((resolve, reject) => {
591
- timer = setTimeout(() => {
592
- this.#pending.delete(id);
593
- reject(new Error(`ZCode ${method} timed out after ${this.#requestTimeoutMs}ms`));
594
- }, this.#requestTimeoutMs);
595
- timer.unref();
596
- this.#pending.set(id, { method, resolve, reject, timer });
597
- });
598
- this.#write({ id, method, params }, onWritten);
599
- return result;
600
- }
601
- notify(method, params = {}) {
602
- this.#write({ method, params });
603
- }
604
- events() {
605
- return this.#events;
606
- }
607
- exit() {
608
- return this.#exitPromise;
609
- }
610
- errorMessage(error) {
611
- const base = error instanceof Error ? error.message : String(error);
612
- const stderr = this.#stderr.trim();
613
- return stderr && !base.includes(stderr) ? `${base}: ${stderr}` : base;
614
- }
615
- processErrorMessage(exit) {
616
- return (this.#stderr.trim() ||
617
- `ZCode app-server exited before a terminal event: ${exit.code ?? exit.signal ?? "unknown"}`);
618
- }
619
- // S03:leader 先退出仍须回收其独立组;所有关闭路径等待同一 Promise。
620
- // .octospec/tasks/pr1-yujiawei-review/assessment.md
621
- close() {
622
- return (this.#closePromise ??= this.#close());
623
- }
624
- async #close() {
625
- this.#closed = true;
626
- this.#reader.close();
627
- this.#failAll(new Error("ZCode app-server client closed"));
628
- await this.#cleanup();
629
- }
630
- #receiveLine(line) {
631
- if (this.#failure || this.#closed)
632
- return;
633
- let message;
634
- try {
635
- message = asRecord(JSON.parse(line)) ?? {};
636
- }
637
- catch {
638
- return;
639
- }
640
- const id = rpcId(message.id);
641
- const method = stringField(message, "method");
642
- if (id !== undefined && (method === undefined || this.#pending.has(id))) {
643
- const pending = this.#pending.get(id);
644
- if (!pending)
645
- return;
646
- clearTimeout(pending.timer);
647
- this.#pending.delete(id);
648
- const error = asRecord(message.error);
649
- if (error) {
650
- pending.reject(new ZcodeAppServerRpcError(pending.method, typeof error.code === "string" || typeof error.code === "number"
651
- ? error.code
652
- : "ZCODE_RPC_ERROR", stringField(error, "message") ?? "ZCode RPC failed", error.detail));
653
- }
654
- else {
655
- pending.resolve(message.result);
656
- }
657
- return;
658
- }
659
- if (id !== undefined && method !== undefined) {
660
- this.#handleServerRequest(id, method, asRecord(message.params) ?? {});
661
- return;
662
- }
663
- if (method !== "session/event")
664
- return;
665
- const params = asRecord(message.params);
666
- const sessionId = stringField(params, "sessionId");
667
- const type = stringField(params, "type");
668
- const seq = numberField(params, "seq");
669
- if (!sessionId || !type || sessionId !== this.#activeSession)
670
- return;
671
- if (seq !== undefined && seq <= this.#lastSeq)
672
- return;
673
- if (seq !== undefined)
674
- this.#lastSeq = seq;
675
- this.#events.push({
676
- sessionId,
677
- type,
678
- ...(seq !== undefined ? { seq } : {}),
679
- payload: asRecord(params?.payload)
680
- });
681
- }
682
- #handleServerRequest(id, method, params) {
683
- if (method === "session/requestRuntimePreferences") {
684
- this.#reply(id, {
685
- nativeSearchEnhancementsEnabled: false,
686
- memoryEnabled: false,
687
- askUserQuestionAutoResolutionEnabled: false
688
- });
689
- return;
690
- }
691
- if (method === "interaction/requestPermission") {
692
- if (this.#permissionHandler) {
693
- void this.#permissionHandler(params, (result) => new Promise((resolve, reject) => {
694
- this.#child.stdin.write(`${JSON.stringify({ id, result })}\n`, (error) => error ? reject(error) : resolve());
695
- })).catch((error) => this.#failAll(error instanceof Error ? error : new Error(String(error))));
696
- return;
697
- }
698
- this.#reply(id, this.#autoApprove
699
- ? { decision: "allow" }
700
- : { decision: "deny", reason: "Octo Runtime unattended policy denied this tool request" });
701
- return;
702
- }
703
- if (method === "interaction/requestUserInput") {
704
- const planApproval = asRecord(params.schema)?.interaction === "plan_approval";
705
- this.#reply(id, this.#autoApprove && planApproval
706
- ? { action: "accept", content: { answer_0: "approve" } }
707
- : { action: "decline", reason: "Octo Runtime has no interactive input channel for ZCode" });
708
- return;
709
- }
710
- this.#write({
711
- id,
712
- error: { code: -32601, message: `unsupported ZCode client request: ${method}` }
713
- });
714
- }
715
- #reply(id, result) {
716
- this.#write({ id, result });
717
- }
718
- #write(message, onWritten) {
719
- if (this.#failure || this.#closed)
720
- return;
721
- if (this.#child.stdin.destroyed) {
722
- this.#failAll(new Error("ZCode stdin closed"));
723
- return;
724
- }
725
- this.#child.stdin.write(`${JSON.stringify(message)}\n`, (error) => {
726
- if (error)
727
- this.#failAll(error);
728
- else
729
- onWritten?.();
730
- });
731
- }
732
- #failAll(error, discard = true) {
733
- if (this.#failure)
734
- return;
735
- this.#failure = error;
736
- this.#reader.close();
737
- this.#removeLineGuard();
738
- void this.#cleanup().catch(() => undefined);
739
- for (const pending of this.#pending.values()) {
740
- clearTimeout(pending.timer);
741
- pending.reject(error);
742
- }
743
- this.#pending.clear();
744
- if (discard)
745
- this.#events.drain();
746
- this.#events.close(error);
747
- }
748
- }
749
- function ensureToolCreated(state, id) {
750
- const tool = state.tools.get(id);
751
- if (!tool || tool.created)
752
- return undefined;
753
- tool.created = true;
754
- return {
755
- protocolVersion: 2,
756
- type: "tool_call.create",
757
- payload: {
758
- id,
759
- name: tool.name,
760
- args: asRecord(tool.input) ?? (tool.input === undefined ? {} : { value: tool.input }),
761
- status: "running",
762
- stepId: state.stepId
763
- }
764
- };
765
- }
766
- function toolCreated(events, state, id) {
767
- return (events.some((event) => event.type === "tool_call.create" && event.payload.id === id) ||
768
- state.tools.get(id)?.created === true);
769
- }
770
- function appendPublicText(state, value) {
771
- const remaining = MAX_PUBLIC_TEXT_CHARS - Array.from(state.publicText).length;
772
- if (remaining > 0)
773
- state.publicText += Array.from(value).slice(0, remaining).join("");
774
- }
775
- function extractSessionId(value) {
776
- const result = asRecord(value);
777
- return stringField(asRecord(result?.session), "sessionId") ?? stringField(result, "sessionId");
778
- }
779
- function zcodeMode(request) {
780
- return request.approvalMode === "full_access" ? "yolo" : "build";
781
- }
782
- function requestTimeout(request) {
783
- const configured = request.agentConfig.providerOptions?.appServerRequestTimeoutMs;
784
- return typeof configured === "number" && Number.isFinite(configured) && configured > 0
785
- ? Math.floor(configured)
786
- : REQUEST_TIMEOUT_MS;
787
- }
788
- function failureReason(error) {
789
- if (error instanceof ZcodeAppServerRpcError)
790
- return `rpc_${String(error.code)
791
- .replace(/[^A-Za-z0-9]+/g, "_")
792
- .toLowerCase()}`;
793
- return "session_resume_failed";
794
- }
795
- function errorCode(error) {
796
- if (error instanceof Error && "code" in error && typeof error.code === "string")
797
- return error.code;
798
- if (error instanceof ZcodeAppServerRpcError)
799
- return error.code;
800
- if (error instanceof ZcodeAppServerProcessError)
801
- return "ZCODE_PROCESS_EXITED";
802
- return "ZCODE_ADAPTER_ERROR";
803
- }
804
- function throwIfAborted(signal) {
805
- if (signal?.aborted)
806
- throw signal.reason instanceof Error
807
- ? signal.reason
808
- : new Error(String(signal.reason ?? "cancelled"));
809
- }
810
- function isTerminal(event) {
811
- return (event.type === "run.completed" || event.type === "run.failed" || event.type === "run.cancelled");
812
- }
813
- function defaultSpawn(command, args, options) {
814
- return spawn(command, [...args], { ...options, stdio: ["pipe", "pipe", "pipe"] });
815
- }
816
- function asRecord(value) {
817
- return value !== null && typeof value === "object" && !Array.isArray(value)
818
- ? value
819
- : undefined;
820
- }
821
- function stringField(value, key) {
822
- const field = value?.[key];
823
- return typeof field === "string" && field.length > 0 ? field : undefined;
824
- }
825
- function numberField(value, key) {
826
- const field = value?.[key];
827
- return typeof field === "number" && Number.isFinite(field) ? field : undefined;
828
- }
829
- function rpcId(value) {
830
- return typeof value === "string" || typeof value === "number" ? value : undefined;
831
- }
832
- function isString(value) {
833
- return typeof value === "string";
834
- }
835
- function printableValue(value, fallback) {
836
- if (typeof value === "string")
837
- return value;
838
- if (value === undefined || value === null)
839
- return fallback;
840
- try {
841
- return JSON.stringify(value);
842
- }
843
- catch {
844
- return fallback;
845
- }
846
- }