@dev-anywhere/proxy 0.10.9 → 0.11.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 (59) hide show
  1. package/dist/{autostart-Y7PAITXN.js → autostart-ZEUB5VIE.js} +5 -5
  2. package/dist/{chunk-AR6KNZ2D.js → chunk-5DGT5OCO.js} +5 -5
  3. package/dist/chunk-7DIHPKGQ.js +892 -0
  4. package/dist/chunk-7DIHPKGQ.js.map +1 -0
  5. package/dist/{chunk-EMWUDUL4.js → chunk-7TJUPVKD.js} +2 -2
  6. package/dist/{chunk-D6G3TKLY.js → chunk-F73NHGQP.js} +3 -3
  7. package/dist/chunk-F73NHGQP.js.map +1 -0
  8. package/dist/{chunk-52OJHVZO.js → chunk-GBNUJCH4.js} +2 -2
  9. package/dist/chunk-GBNUJCH4.js.map +1 -0
  10. package/dist/{chunk-Q3CPWHHP.js → chunk-GGLHFEXA.js} +2 -2
  11. package/dist/{chunk-7BNZO6DB.js → chunk-GKG5ZNSI.js} +61 -4
  12. package/dist/chunk-GKG5ZNSI.js.map +1 -0
  13. package/dist/{chunk-RQKKZC5T.js → chunk-GSYEOTS5.js} +23 -9
  14. package/dist/chunk-GSYEOTS5.js.map +1 -0
  15. package/dist/{chunk-M3NPN6JZ.js → chunk-RSHWLFLA.js} +14 -11
  16. package/dist/chunk-RSHWLFLA.js.map +1 -0
  17. package/dist/{chunk-V3JJ352Q.js → chunk-SERCDXCV.js} +1 -1
  18. package/dist/chunk-SERCDXCV.js.map +1 -0
  19. package/dist/{chunk-AWAVTR2H.js → chunk-UOWFBLU4.js} +15 -8
  20. package/dist/chunk-UOWFBLU4.js.map +1 -0
  21. package/dist/{chunk-S2QVJFCM.js → chunk-XCQ7CGLY.js} +2 -52
  22. package/dist/chunk-XCQ7CGLY.js.map +1 -0
  23. package/dist/{chunk-5OJFDJ65.js → chunk-XEEHK4YQ.js} +101 -8
  24. package/dist/{chunk-5OJFDJ65.js.map → chunk-XEEHK4YQ.js.map} +1 -1
  25. package/dist/{chunk-RW32NTSD.js → chunk-YFCPLWNV.js} +3 -2
  26. package/dist/chunk-YFCPLWNV.js.map +1 -0
  27. package/dist/index.js +14 -14
  28. package/dist/{logger-U5XYVVXY.js → logger-4E3T7YWT.js} +3 -3
  29. package/dist/preview-worker.js +5 -5
  30. package/dist/{relay-token-LFUK2JW6.js → relay-token-YP4HZGIJ.js} +4 -4
  31. package/dist/serve.js +222 -88
  32. package/dist/serve.js.map +1 -1
  33. package/dist/{service-host-XIAWRF4P.js → service-host-XIBF772J.js} +3 -3
  34. package/dist/session-worker.js +48 -646
  35. package/dist/session-worker.js.map +1 -1
  36. package/dist/{terminal-ATPVD7KA.js → terminal-D2E4NE43.js} +16 -13
  37. package/dist/terminal-D2E4NE43.js.map +1 -0
  38. package/dist/terminal-worker.js +10 -10
  39. package/dist/update-runner.js +2 -2
  40. package/package.json +3 -3
  41. package/dist/chunk-44IM5SVF.js +0 -205
  42. package/dist/chunk-44IM5SVF.js.map +0 -1
  43. package/dist/chunk-52OJHVZO.js.map +0 -1
  44. package/dist/chunk-7BNZO6DB.js.map +0 -1
  45. package/dist/chunk-AWAVTR2H.js.map +0 -1
  46. package/dist/chunk-D6G3TKLY.js.map +0 -1
  47. package/dist/chunk-M3NPN6JZ.js.map +0 -1
  48. package/dist/chunk-RQKKZC5T.js.map +0 -1
  49. package/dist/chunk-RW32NTSD.js.map +0 -1
  50. package/dist/chunk-S2QVJFCM.js.map +0 -1
  51. package/dist/chunk-V3JJ352Q.js.map +0 -1
  52. package/dist/terminal-ATPVD7KA.js.map +0 -1
  53. /package/dist/{autostart-Y7PAITXN.js.map → autostart-ZEUB5VIE.js.map} +0 -0
  54. /package/dist/{chunk-AR6KNZ2D.js.map → chunk-5DGT5OCO.js.map} +0 -0
  55. /package/dist/{chunk-EMWUDUL4.js.map → chunk-7TJUPVKD.js.map} +0 -0
  56. /package/dist/{chunk-Q3CPWHHP.js.map → chunk-GGLHFEXA.js.map} +0 -0
  57. /package/dist/{logger-U5XYVVXY.js.map → logger-4E3T7YWT.js.map} +0 -0
  58. /package/dist/{relay-token-LFUK2JW6.js.map → relay-token-YP4HZGIJ.js.map} +0 -0
  59. /package/dist/{service-host-XIAWRF4P.js.map → service-host-XIBF772J.js.map} +0 -0
@@ -0,0 +1,892 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ atomicWriteFileSync
4
+ } from "./chunk-NQDJ6QAM.js";
5
+ import {
6
+ ANTIGRAVITY_PROVIDER,
7
+ KIMI_PROVIDER,
8
+ resolveAntigravityAcpMode,
9
+ resolveKimiAcpMode
10
+ } from "./chunk-XEEHK4YQ.js";
11
+ import {
12
+ LineBuffer
13
+ } from "./chunk-UOWFBLU4.js";
14
+ import {
15
+ terminateOwnedProcessTree
16
+ } from "./chunk-JZ7MWN24.js";
17
+ import {
18
+ PROXY_VERSION
19
+ } from "./chunk-EGNWMOPC.js";
20
+ import {
21
+ spawnCommand
22
+ } from "./chunk-EWIHC4BK.js";
23
+ import {
24
+ sessionPaths
25
+ } from "./chunk-GKG5ZNSI.js";
26
+
27
+ // src/providers/acp-session.ts
28
+ var CLIENT_INFO = {
29
+ name: "dev-anywhere",
30
+ title: "Dev Anywhere",
31
+ version: PROXY_VERSION
32
+ };
33
+ var DEFAULT_REQUEST_TIMEOUT_MS = 1e4;
34
+ var DEFAULT_CANCEL_ACKNOWLEDGE_TIMEOUT_MS = 2e3;
35
+ var STDERR_TAIL_LIMIT = 8192;
36
+ var CANCELLED_RESPONSE_TOMBSTONE_LIMIT = 128;
37
+ var denyPermission = () => ({
38
+ behavior: "deny",
39
+ message: "Tool use denied by default policy. Remote approval is not configured."
40
+ });
41
+ function isRecord(value) {
42
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
43
+ }
44
+ function toError(error) {
45
+ return error instanceof Error ? error : new Error(String(error));
46
+ }
47
+ function normalizeApprovalInput(value) {
48
+ if (!isRecord(value)) return {};
49
+ const input = { ...value };
50
+ if (Array.isArray(input.command)) {
51
+ input.command = input.command.map((part) => String(part)).join(" ");
52
+ }
53
+ return input;
54
+ }
55
+ function parsePermissionOptions(value) {
56
+ if (!Array.isArray(value)) return [];
57
+ const options = [];
58
+ for (const candidate of value) {
59
+ if (!isRecord(candidate) || typeof candidate.optionId !== "string") continue;
60
+ options.push({
61
+ ...candidate,
62
+ optionId: candidate.optionId,
63
+ name: typeof candidate.name === "string" ? candidate.name : candidate.optionId,
64
+ kind: typeof candidate.kind === "string" ? candidate.kind : ""
65
+ });
66
+ }
67
+ return options;
68
+ }
69
+ function normalizedOptionText(option) {
70
+ return `${option.optionId} ${option.name}`.toLowerCase().replace(/[^a-z0-9]+/g, " ");
71
+ }
72
+ function isAllowOption(option) {
73
+ const text = normalizedOptionText(option);
74
+ return option.kind.startsWith("allow") || /\b(allow|approve|accept)\b/.test(text);
75
+ }
76
+ function isAlwaysOption(option) {
77
+ const text = normalizedOptionText(option);
78
+ return option.kind === "allow_always" || /\b(always|session|persist)\b/.test(text);
79
+ }
80
+ function isDenyOption(option) {
81
+ const text = normalizedOptionText(option);
82
+ return option.kind.startsWith("reject") || /\b(reject|deny|decline|cancel|skip)\b/.test(text);
83
+ }
84
+ function optionMatchesBehavior(option, behavior) {
85
+ if (behavior === "deny") return isDenyOption(option);
86
+ if (behavior === "allow_always") {
87
+ return isAllowOption(option) && isAlwaysOption(option);
88
+ }
89
+ return isAllowOption(option) && !isAlwaysOption(option);
90
+ }
91
+ function selectPermissionOption(options, behavior) {
92
+ if (behavior === "deny") {
93
+ return options.find((option) => option.kind.startsWith("reject")) ?? options.find(isDenyOption);
94
+ }
95
+ if (behavior === "allow_always") {
96
+ return options.find((option) => option.kind === "allow_always") ?? options.find((option) => isAllowOption(option) && isAlwaysOption(option)) ?? // Never upgrade a one-shot decision, but safely downgrade a persistent allow when the
97
+ // provider only advertises allow-once.
98
+ options.find((option) => option.kind === "allow_once") ?? options.find((option) => isAllowOption(option) && !isAlwaysOption(option));
99
+ }
100
+ return options.find((option) => option.kind === "allow_once") ?? options.find((option) => isAllowOption(option) && !isAlwaysOption(option));
101
+ }
102
+ function promptResult(value) {
103
+ return isRecord(value) ? value : {};
104
+ }
105
+ var AcpRpcError = class extends Error {
106
+ constructor(label, method, code, message, data) {
107
+ super(`${label} ${method} failed${code === void 0 ? "" : ` (${code})`}: ${message}`);
108
+ this.method = method;
109
+ this.code = code;
110
+ this.data = data;
111
+ this.name = "AcpRpcError";
112
+ }
113
+ method;
114
+ code;
115
+ data;
116
+ };
117
+ var AcpProtocolError = class extends Error {
118
+ constructor(message, payload) {
119
+ super(message);
120
+ this.payload = payload;
121
+ this.name = "AcpProtocolError";
122
+ }
123
+ payload;
124
+ };
125
+ var AcpSession = class {
126
+ child = null;
127
+ stderrTail = "";
128
+ nextRequestId = 1;
129
+ pendingRequests = /* @__PURE__ */ new Map();
130
+ pendingPermissions = /* @__PURE__ */ new Map();
131
+ cancelledResponseIds = /* @__PURE__ */ new Set();
132
+ toolCalls = /* @__PURE__ */ new Map();
133
+ sessionReady;
134
+ resolveSessionReady = () => {
135
+ };
136
+ rejectSessionReady = () => {
137
+ };
138
+ sessionReadySettled = false;
139
+ exitReported = false;
140
+ closed = false;
141
+ transportFailure = null;
142
+ sessionId = null;
143
+ activePrompt = null;
144
+ promptQueue = Promise.resolve();
145
+ workDir;
146
+ resumeSessionId;
147
+ provider;
148
+ env;
149
+ label;
150
+ permissionMode;
151
+ acpMode;
152
+ requestTimeoutMs;
153
+ promptTimeoutMs;
154
+ cancelAcknowledgeTimeoutMs;
155
+ onUpdate;
156
+ onNotification;
157
+ onPermissionRequest;
158
+ onPromptStart;
159
+ onPromptComplete;
160
+ onPromptError;
161
+ onSessionId;
162
+ onProtocolError;
163
+ onProcessError;
164
+ onExitCb;
165
+ constructor(options = {}) {
166
+ this.workDir = options.cwd ?? options.workDir ?? process.cwd();
167
+ this.env = options.env ?? process.env;
168
+ this.resumeSessionId = options.resumeSessionId;
169
+ const antigravity = options.provider === "antigravity";
170
+ this.provider = antigravity ? ANTIGRAVITY_PROVIDER : KIMI_PROVIDER;
171
+ this.label = antigravity ? "Antigravity ACP" : "Kimi ACP";
172
+ this.permissionMode = options.permissionMode;
173
+ this.acpMode = antigravity ? resolveAntigravityAcpMode(options.permissionMode) : resolveKimiAcpMode(options.permissionMode);
174
+ this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
175
+ this.promptTimeoutMs = options.promptTimeoutMs ?? 0;
176
+ this.cancelAcknowledgeTimeoutMs = options.cancelAcknowledgeTimeoutMs ?? DEFAULT_CANCEL_ACKNOWLEDGE_TIMEOUT_MS;
177
+ this.onUpdate = options.onUpdate;
178
+ this.onNotification = options.onNotification;
179
+ this.onPermissionRequest = options.onPermissionRequest ?? denyPermission;
180
+ this.onPromptStart = options.onPromptStart;
181
+ this.onPromptComplete = options.onPromptComplete;
182
+ this.onPromptError = options.onPromptError;
183
+ this.onSessionId = options.onSessionId;
184
+ this.onProtocolError = options.onProtocolError;
185
+ this.onProcessError = options.onProcessError;
186
+ this.onExitCb = options.onExit;
187
+ this.sessionReady = new Promise((resolve, reject) => {
188
+ this.resolveSessionReady = resolve;
189
+ this.rejectSessionReady = reject;
190
+ });
191
+ }
192
+ getNativeSessionId() {
193
+ return this.sessionId;
194
+ }
195
+ getPendingPermission(requestId) {
196
+ return this.pendingPermissions.get(requestId)?.request;
197
+ }
198
+ start() {
199
+ const pid = this.spawnServer();
200
+ void this.initializeSession().catch((error) => this.rejectSessionReadyOnce(toError(error)));
201
+ return pid;
202
+ }
203
+ spawnServer() {
204
+ if (this.child) throw new Error(`${this.label} session has already been started`);
205
+ const command = this.provider.buildJsonCommand(
206
+ { cwd: this.workDir, permissionMode: this.permissionMode },
207
+ this.env
208
+ );
209
+ this.child = spawnCommand(command.command, command.args, {
210
+ cwd: this.workDir,
211
+ stdio: ["pipe", "pipe", "pipe"],
212
+ env: command.env
213
+ });
214
+ this.setupStdoutParsing();
215
+ this.setupStderrCollection();
216
+ this.child.stdin?.on("error", (error) => this.rejectAllPendingRequests(error));
217
+ this.setupExitHandler();
218
+ if (!this.child.pid) throw new Error(`${this.label} failed to start: missing child pid`);
219
+ return this.child.pid;
220
+ }
221
+ async listSessions() {
222
+ return this.queryServer(async (capabilities) => {
223
+ if (!isRecord(capabilities.sessionCapabilities) || !capabilities.sessionCapabilities.list) {
224
+ return [];
225
+ }
226
+ const records = [];
227
+ const seen = /* @__PURE__ */ new Set();
228
+ const deadline = Date.now() + this.requestTimeoutMs;
229
+ let cursor;
230
+ do {
231
+ const timeLeft = deadline - Date.now();
232
+ if (timeLeft <= 0) break;
233
+ const page = await this.request("session/list", cursor ? { cursor } : {}, timeLeft);
234
+ if (!isRecord(page) || !Array.isArray(page.sessions)) break;
235
+ records.push(...page.sessions);
236
+ cursor = typeof page.nextCursor === "string" ? page.nextCursor : void 0;
237
+ if (!cursor || seen.has(cursor)) break;
238
+ seen.add(cursor);
239
+ } while (Date.now() < deadline);
240
+ return records;
241
+ });
242
+ }
243
+ async loadHistory(sessionId) {
244
+ await this.queryServer(async (capabilities) => {
245
+ if (capabilities.loadSession !== true) return;
246
+ await this.request("session/load", { sessionId, cwd: this.workDir, mcpServers: [] });
247
+ });
248
+ }
249
+ async queryServer(query) {
250
+ void this.sessionReady.catch(() => {
251
+ });
252
+ try {
253
+ this.spawnServer();
254
+ return await query(await this.initialize());
255
+ } finally {
256
+ await this.stop(200);
257
+ }
258
+ }
259
+ waitUntilReady() {
260
+ return this.sessionReady;
261
+ }
262
+ sendMessage(content) {
263
+ this.promptQueue = this.promptQueue.then(() => this.runPrompt(content));
264
+ }
265
+ async interruptCurrentTurn() {
266
+ const activePrompt = this.activePrompt;
267
+ if (!activePrompt || activePrompt.cancelled || !this.sessionId) return false;
268
+ activePrompt.cancelled = true;
269
+ if (!this.writeLine({
270
+ jsonrpc: "2.0",
271
+ method: "session/cancel",
272
+ params: { sessionId: this.sessionId }
273
+ })) {
274
+ activePrompt.cancelled = false;
275
+ return false;
276
+ }
277
+ this.cancelPendingPermissions();
278
+ if (this.cancelAcknowledgeTimeoutMs <= 0) {
279
+ this.abortUnacknowledgedCancellation(activePrompt);
280
+ } else {
281
+ activePrompt.cancelSettleTimer = setTimeout(
282
+ () => this.abortUnacknowledgedCancellation(activePrompt),
283
+ this.cancelAcknowledgeTimeoutMs
284
+ );
285
+ activePrompt.cancelSettleTimer.unref?.();
286
+ }
287
+ return true;
288
+ }
289
+ async close() {
290
+ if (this.closed) return;
291
+ if (!this.child) throw new Error(`${this.label} session has not been started`);
292
+ const sessionId = this.sessionId ?? await this.sessionReady;
293
+ await this.request("session/close", { sessionId });
294
+ this.closed = true;
295
+ }
296
+ async stop(gracePeriodMs = 5e3) {
297
+ const child = this.child;
298
+ if (!child || !this.isAlive()) return;
299
+ if (this.activePrompt) await this.interruptCurrentTurn();
300
+ if (this.sessionId && !this.closed) {
301
+ try {
302
+ await this.close();
303
+ } catch (error) {
304
+ this.appendStderr(`${this.label} close failed: ${toError(error).message}
305
+ `);
306
+ }
307
+ }
308
+ terminateOwnedProcessTree(child, "SIGTERM");
309
+ const startedAt = Date.now();
310
+ while (Date.now() - startedAt < gracePeriodMs) {
311
+ if (!this.isChildAlive(child)) return;
312
+ await new Promise((resolve) => setTimeout(resolve, 200));
313
+ }
314
+ if (this.isChildAlive(child)) terminateOwnedProcessTree(child, "SIGKILL");
315
+ }
316
+ isAlive() {
317
+ return this.child ? this.isChildAlive(this.child) : false;
318
+ }
319
+ getStderr() {
320
+ return this.stderrTail;
321
+ }
322
+ isChildAlive(child) {
323
+ if (!child.pid) return false;
324
+ try {
325
+ process.kill(child.pid, 0);
326
+ return true;
327
+ } catch {
328
+ return false;
329
+ }
330
+ }
331
+ async initialize() {
332
+ const result = await this.request("initialize", {
333
+ protocolVersion: 1,
334
+ clientCapabilities: {
335
+ fs: { readTextFile: false, writeTextFile: false },
336
+ terminal: false
337
+ },
338
+ clientInfo: CLIENT_INFO
339
+ });
340
+ return isRecord(result) && isRecord(result.agentCapabilities) ? result.agentCapabilities : {};
341
+ }
342
+ async initializeSession() {
343
+ await this.initialize();
344
+ const result = this.resumeSessionId ? await this.request("session/resume", {
345
+ sessionId: this.resumeSessionId,
346
+ cwd: this.workDir,
347
+ mcpServers: []
348
+ }) : await this.request("session/new", {
349
+ cwd: this.workDir,
350
+ mcpServers: []
351
+ });
352
+ const sessionId = this.resumeSessionId ?? this.sessionIdFromResult(result);
353
+ if (!sessionId) throw new Error(`${this.label} session/new did not return a session id`);
354
+ await this.request("session/set_mode", { sessionId, modeId: this.acpMode });
355
+ this.sessionId = sessionId;
356
+ this.onSessionId?.(sessionId);
357
+ this.resolveSessionReadyOnce(sessionId);
358
+ }
359
+ sessionIdFromResult(result) {
360
+ if (!isRecord(result)) return null;
361
+ return typeof result.sessionId === "string" ? result.sessionId : null;
362
+ }
363
+ async runPrompt(content) {
364
+ let prompt = null;
365
+ try {
366
+ const sessionId = await this.sessionReady;
367
+ if (this.transportFailure) throw this.transportFailure;
368
+ const currentPrompt = { cancelled: false };
369
+ prompt = currentPrompt;
370
+ this.activePrompt = currentPrompt;
371
+ this.invokeCallback(() => this.onPromptStart?.(), "session/prompt start callback failed");
372
+ const result = await this.request(
373
+ "session/prompt",
374
+ {
375
+ sessionId,
376
+ prompt: [{ type: "text", text: content }]
377
+ },
378
+ this.promptTimeoutMs,
379
+ (requestId) => {
380
+ if (this.activePrompt === currentPrompt) currentPrompt.requestId = requestId;
381
+ }
382
+ );
383
+ if (!prompt.cancelled) {
384
+ this.invokeCallback(
385
+ () => this.onPromptComplete?.(promptResult(result)),
386
+ "session/prompt completion callback failed"
387
+ );
388
+ }
389
+ } catch (error) {
390
+ if (!prompt?.cancelled) {
391
+ this.invokeCallback(
392
+ () => this.onPromptError?.(toError(error)),
393
+ "session/prompt error callback failed"
394
+ );
395
+ }
396
+ } finally {
397
+ if (prompt?.cancelSettleTimer) clearTimeout(prompt.cancelSettleTimer);
398
+ if (this.activePrompt === prompt) this.activePrompt = null;
399
+ this.toolCalls.clear();
400
+ }
401
+ }
402
+ request(method, params, timeoutMs = this.requestTimeoutMs, onRequestId) {
403
+ const id = this.nextRequestId++;
404
+ onRequestId?.(id);
405
+ const payload = { jsonrpc: "2.0", id, method, params };
406
+ return new Promise((resolve, reject) => {
407
+ const timeout = timeoutMs > 0 ? setTimeout(() => {
408
+ this.pendingRequests.delete(id);
409
+ reject(new Error(`${this.label} request ${method} timed out after ${timeoutMs}ms`));
410
+ }, timeoutMs) : void 0;
411
+ timeout?.unref?.();
412
+ this.pendingRequests.set(id, { method, resolve, reject, timeout });
413
+ if (!this.writeLine(payload)) {
414
+ if (timeout) clearTimeout(timeout);
415
+ this.pendingRequests.delete(id);
416
+ reject(new Error(`${this.label} stdin is not writable for ${method}`));
417
+ }
418
+ });
419
+ }
420
+ writeLine(payload) {
421
+ if (this.transportFailure || !this.child?.stdin?.writable) return false;
422
+ try {
423
+ this.child.stdin.write(`${JSON.stringify(payload)}
424
+ `);
425
+ return true;
426
+ } catch (error) {
427
+ this.reportProtocolError(
428
+ new AcpProtocolError(`Failed to write ${this.label} message`, error)
429
+ );
430
+ return false;
431
+ }
432
+ }
433
+ setupStdoutParsing() {
434
+ const child = this.child;
435
+ if (!child?.stdout) return;
436
+ const lineBuffer = new LineBuffer();
437
+ child.stdout.pipe(lineBuffer);
438
+ lineBuffer.on("data", (line) => {
439
+ const text = typeof line === "string" ? line : line.toString();
440
+ let message;
441
+ try {
442
+ message = JSON.parse(text);
443
+ } catch (error) {
444
+ this.reportProtocolError(
445
+ new AcpProtocolError(`Invalid ${this.label} JSON: ${toError(error).message}`, text),
446
+ text
447
+ );
448
+ return;
449
+ }
450
+ this.handleAcpMessage(message);
451
+ });
452
+ }
453
+ handleAcpMessage(message) {
454
+ if (!isRecord(message)) {
455
+ this.reportProtocolError(
456
+ new AcpProtocolError(`${this.label} message must be an object`, message)
457
+ );
458
+ return;
459
+ }
460
+ const id = message.id;
461
+ const method = message.method;
462
+ if (typeof method === "string" && (typeof id === "string" || typeof id === "number")) {
463
+ this.handleServerRequest({ id, method, params: message.params });
464
+ return;
465
+ }
466
+ if (typeof method === "string") {
467
+ this.handleNotification(method, message.params);
468
+ return;
469
+ }
470
+ if (typeof id === "string" || typeof id === "number") {
471
+ this.handleResponse(id, message);
472
+ return;
473
+ }
474
+ this.reportProtocolError(new AcpProtocolError(`Unrecognized ${this.label} message`, message));
475
+ }
476
+ handleResponse(id, message) {
477
+ const pending = this.pendingRequests.get(id);
478
+ if (!pending) {
479
+ if (this.cancelledResponseIds.delete(id)) return;
480
+ this.reportProtocolError(
481
+ new AcpProtocolError(`Unexpected ${this.label} response id: ${String(id)}`, message)
482
+ );
483
+ return;
484
+ }
485
+ this.pendingRequests.delete(id);
486
+ if (pending.timeout) clearTimeout(pending.timeout);
487
+ if (isRecord(message.error)) {
488
+ pending.reject(
489
+ new AcpRpcError(
490
+ this.label,
491
+ pending.method,
492
+ typeof message.error.code === "number" ? message.error.code : void 0,
493
+ typeof message.error.message === "string" ? message.error.message : "Request failed",
494
+ message.error.data
495
+ )
496
+ );
497
+ return;
498
+ }
499
+ pending.resolve(message.result);
500
+ }
501
+ abortUnacknowledgedCancellation(prompt) {
502
+ const requestId = prompt.requestId;
503
+ if (requestId === void 0) return;
504
+ const pending = this.pendingRequests.get(requestId);
505
+ if (!pending || pending.method !== "session/prompt") return;
506
+ const error = new Error(
507
+ `${this.label} did not acknowledge session/cancel within ${this.cancelAcknowledgeTimeoutMs}ms; terminating the unsafe transport`
508
+ );
509
+ this.transportFailure = error;
510
+ this.pendingRequests.delete(requestId);
511
+ if (pending.timeout) clearTimeout(pending.timeout);
512
+ this.cancelledResponseIds.add(requestId);
513
+ if (this.cancelledResponseIds.size > CANCELLED_RESPONSE_TOMBSTONE_LIMIT) {
514
+ const oldest = this.cancelledResponseIds.values().next().value;
515
+ if (oldest !== void 0) this.cancelledResponseIds.delete(oldest);
516
+ }
517
+ this.appendStderr(`${error.message}
518
+ `);
519
+ this.cancelPendingPermissions();
520
+ pending.reject(error);
521
+ if (this.child) terminateOwnedProcessTree(this.child, "SIGKILL");
522
+ }
523
+ handleNotification(method, rawParams) {
524
+ const params = isRecord(rawParams) ? rawParams : {};
525
+ if (method === "session/update") {
526
+ this.trackToolCall(params);
527
+ this.invokeCallback(() => this.onUpdate?.(params), "session/update callback failed");
528
+ }
529
+ this.invokeCallback(
530
+ () => this.onNotification?.(method, params),
531
+ `${method} notification callback failed`
532
+ );
533
+ }
534
+ trackToolCall(params) {
535
+ if (!isRecord(params.update) || typeof params.update.toolCallId !== "string") return;
536
+ const previous = this.toolCalls.get(params.update.toolCallId) ?? {};
537
+ const next = { ...previous, ...params.update };
538
+ if (next.status === "completed" || next.status === "failed") {
539
+ this.toolCalls.delete(params.update.toolCallId);
540
+ return;
541
+ }
542
+ this.toolCalls.set(params.update.toolCallId, next);
543
+ }
544
+ handleServerRequest(request) {
545
+ if (request.method === "session/request_permission") {
546
+ void this.handlePermissionRequest(request.id, request.params);
547
+ return;
548
+ }
549
+ this.writeLine({
550
+ jsonrpc: "2.0",
551
+ id: request.id,
552
+ error: {
553
+ code: -32601,
554
+ message: `Unsupported ${this.label} client request: ${request.method}`
555
+ }
556
+ });
557
+ }
558
+ async handlePermissionRequest(id, rawParams) {
559
+ const params = isRecord(rawParams) ? rawParams : {};
560
+ const incomingToolCall = isRecord(params.toolCall) ? params.toolCall : {};
561
+ const toolCallId = typeof incomingToolCall.toolCallId === "string" ? incomingToolCall.toolCallId : void 0;
562
+ const trackedToolCall = toolCallId ? this.toolCalls.get(toolCallId) ?? {} : {};
563
+ const toolCall = { ...trackedToolCall, ...incomingToolCall };
564
+ const rawInput = isRecord(incomingToolCall.rawInput) ? incomingToolCall.rawInput : trackedToolCall.rawInput;
565
+ const request = {
566
+ requestId: id,
567
+ sessionId: typeof params.sessionId === "string" ? params.sessionId : this.sessionId ?? "",
568
+ toolName: typeof incomingToolCall.title === "string" ? incomingToolCall.title : typeof trackedToolCall.title === "string" ? trackedToolCall.title : "Tool",
569
+ input: normalizeApprovalInput(rawInput),
570
+ rawToolCall: incomingToolCall,
571
+ toolCall,
572
+ options: parsePermissionOptions(params.options),
573
+ rawParams: params
574
+ };
575
+ if (this.transportFailure || this.activePrompt?.cancelled) {
576
+ this.writeLine({
577
+ jsonrpc: "2.0",
578
+ id,
579
+ result: { outcome: { outcome: "cancelled" } }
580
+ });
581
+ return;
582
+ }
583
+ const pending = { request, responded: false };
584
+ this.pendingPermissions.set(id, pending);
585
+ let decision;
586
+ try {
587
+ decision = await this.onPermissionRequest(request);
588
+ } catch (error) {
589
+ decision = { behavior: "deny", message: toError(error).message };
590
+ }
591
+ if (pending.responded) return;
592
+ pending.responded = true;
593
+ this.pendingPermissions.delete(id);
594
+ const requestedOptionId = typeof decision.optionId === "string" && decision.optionId.trim().length > 0 ? decision.optionId : void 0;
595
+ const explicitOption = requestedOptionId ? request.options.find((candidate) => candidate.optionId === requestedOptionId) : void 0;
596
+ const cancelled = decision.cancelled === true || decision.behavior === "cancel";
597
+ const behavior = decision.behavior === "allow_once" || decision.behavior === "allow_always" || decision.behavior === "deny" ? decision.behavior : void 0;
598
+ const validExplicitOption = explicitOption && (!behavior || optionMatchesBehavior(explicitOption, behavior)) ? explicitOption : void 0;
599
+ const option = cancelled || requestedOptionId || !behavior ? void 0 : selectPermissionOption(request.options, behavior);
600
+ const selectedOptionId = cancelled ? void 0 : validExplicitOption?.optionId || option?.optionId;
601
+ const outcome = selectedOptionId ? { outcome: "selected", optionId: selectedOptionId } : { outcome: "cancelled" };
602
+ if (!this.writeLine({ jsonrpc: "2.0", id, result: { outcome } })) {
603
+ this.reportProtocolError(
604
+ new AcpProtocolError(`Failed to respond to permission request ${String(id)}`)
605
+ );
606
+ }
607
+ }
608
+ cancelPendingPermissions() {
609
+ for (const [id, pending] of this.pendingPermissions) {
610
+ if (pending.responded) continue;
611
+ pending.responded = true;
612
+ this.writeLine({
613
+ jsonrpc: "2.0",
614
+ id,
615
+ result: { outcome: { outcome: "cancelled" } }
616
+ });
617
+ }
618
+ this.pendingPermissions.clear();
619
+ }
620
+ setupStderrCollection() {
621
+ const child = this.child;
622
+ if (!child?.stderr) return;
623
+ child.stderr.on("data", (chunk) => {
624
+ this.appendStderr(typeof chunk === "string" ? chunk : chunk.toString());
625
+ });
626
+ }
627
+ setupExitHandler() {
628
+ const child = this.child;
629
+ if (!child) return;
630
+ child.on("error", (error) => {
631
+ const wrapped = new Error(`${this.label} failed to start: ${error.message}`);
632
+ this.appendStderr(`${wrapped.message}
633
+ `);
634
+ this.rejectAllPendingRequests(wrapped);
635
+ this.rejectSessionReadyOnce(wrapped);
636
+ this.onProcessError?.(wrapped);
637
+ this.reportExit(1);
638
+ });
639
+ child.on("exit", (code) => {
640
+ const exitCode = code ?? 1;
641
+ const error = new Error(
642
+ this.sessionReadySettled ? `${this.label} exited (code ${exitCode})` : `${this.label} exited before ready (code ${exitCode})`
643
+ );
644
+ this.rejectAllPendingRequests(error);
645
+ this.pendingPermissions.clear();
646
+ this.rejectSessionReadyOnce(error);
647
+ if (exitCode !== 0) this.onProcessError?.(error);
648
+ this.reportExit(exitCode);
649
+ });
650
+ }
651
+ invokeCallback(callback, message) {
652
+ try {
653
+ callback();
654
+ } catch (error) {
655
+ this.reportProtocolError(new AcpProtocolError(`${message}: ${toError(error).message}`));
656
+ }
657
+ }
658
+ reportProtocolError(error, line) {
659
+ this.appendStderr(`${error.message}
660
+ `);
661
+ try {
662
+ this.onProtocolError?.(error, line);
663
+ } catch {
664
+ }
665
+ }
666
+ appendStderr(chunk) {
667
+ this.stderrTail = `${this.stderrTail}${chunk}`.slice(-STDERR_TAIL_LIMIT);
668
+ }
669
+ resolveSessionReadyOnce(sessionId) {
670
+ if (this.sessionReadySettled) return;
671
+ this.sessionReadySettled = true;
672
+ this.resolveSessionReady(sessionId);
673
+ }
674
+ rejectSessionReadyOnce(error) {
675
+ if (this.sessionReadySettled) return;
676
+ this.sessionReadySettled = true;
677
+ this.rejectSessionReady(error);
678
+ }
679
+ rejectAllPendingRequests(error) {
680
+ for (const pending of this.pendingRequests.values()) {
681
+ if (pending.timeout) clearTimeout(pending.timeout);
682
+ pending.reject(error);
683
+ }
684
+ this.pendingRequests.clear();
685
+ this.cancelledResponseIds.clear();
686
+ }
687
+ reportExit(code) {
688
+ if (this.exitReported) return;
689
+ this.exitReported = true;
690
+ this.onExitCb?.(code);
691
+ }
692
+ };
693
+
694
+ // src/common/seq-counter.ts
695
+ import { mkdirSync, readFileSync, existsSync } from "fs";
696
+ var RESERVATION_BATCH = 100;
697
+ var SeqCounter = class {
698
+ seq = 0;
699
+ // 已持久化的高水位; seq <= reservedUpTo 时 next() 不需要写盘
700
+ reservedUpTo = 0;
701
+ filePath;
702
+ constructor(sessionId, baseDir) {
703
+ const dir = baseDir ?? sessionPaths(sessionId).dir;
704
+ mkdirSync(dir, { recursive: true });
705
+ this.filePath = `${dir}/seq`;
706
+ this.load();
707
+ }
708
+ next() {
709
+ this.seq++;
710
+ if (this.seq > this.reservedUpTo) {
711
+ this.reservedUpTo = this.seq + RESERVATION_BATCH - 1;
712
+ this.save();
713
+ }
714
+ return this.seq;
715
+ }
716
+ current() {
717
+ return this.seq;
718
+ }
719
+ // 显式持久化当前 seq, 不再保留 batch——优雅退出时调用, 让重启续号尽量贴近真实进度。
720
+ flush() {
721
+ if (this.seq !== this.reservedUpTo) {
722
+ this.reservedUpTo = this.seq;
723
+ this.save();
724
+ }
725
+ }
726
+ load() {
727
+ if (!existsSync(this.filePath)) return;
728
+ const content = readFileSync(this.filePath, "utf-8").trim();
729
+ const parsed = parseInt(content, 10);
730
+ if (isNaN(parsed) || parsed < 0) {
731
+ throw new Error(`Corrupt seq file: ${this.filePath} contains "${content}"`);
732
+ }
733
+ this.seq = parsed;
734
+ this.reservedUpTo = parsed;
735
+ }
736
+ save() {
737
+ atomicWriteFileSync(this.filePath, String(this.reservedUpTo));
738
+ }
739
+ };
740
+ var seqCounterCache = /* @__PURE__ */ new Map();
741
+ function getSeqCounterFor(sessionId, baseDir) {
742
+ let counter = seqCounterCache.get(sessionId);
743
+ if (!counter) {
744
+ counter = new SeqCounter(sessionId, baseDir);
745
+ seqCounterCache.set(sessionId, counter);
746
+ }
747
+ return counter;
748
+ }
749
+ function disposeSeqCounter(sessionId) {
750
+ seqCounterCache.delete(sessionId);
751
+ }
752
+
753
+ // src/common/approval-request-id.ts
754
+ function createApprovalRequestIdFactory(scope, now = Date.now) {
755
+ let seq = 0;
756
+ return () => `${scope}-${now()}-${seq++}`;
757
+ }
758
+ function createScopedApprovalRequestIdFactory(now = Date.now) {
759
+ let seq = 0;
760
+ return (scope) => `${scope}-${now()}-${seq++}`;
761
+ }
762
+
763
+ // src/common/stream-json-schema.ts
764
+ import { z } from "zod";
765
+ var TextBlockSchema = z.object({
766
+ type: z.literal("text"),
767
+ text: z.string()
768
+ }).passthrough();
769
+ var ThinkingBlockSchema = z.object({
770
+ type: z.literal("thinking"),
771
+ thinking: z.string(),
772
+ signature: z.string().optional()
773
+ }).passthrough();
774
+ var ToolUseBlockSchema = z.object({
775
+ type: z.literal("tool_use"),
776
+ id: z.string(),
777
+ name: z.string(),
778
+ input: z.record(z.string(), z.unknown())
779
+ }).passthrough();
780
+ var ToolResultBlockSchema = z.object({
781
+ type: z.literal("tool_result"),
782
+ tool_use_id: z.string(),
783
+ content: z.unknown(),
784
+ is_error: z.boolean().optional()
785
+ }).passthrough();
786
+ var KnownContentBlockSchema = z.discriminatedUnion("type", [
787
+ TextBlockSchema,
788
+ ThinkingBlockSchema,
789
+ ToolUseBlockSchema,
790
+ ToolResultBlockSchema
791
+ ]);
792
+ var AssistantEventSchema = z.object({
793
+ type: z.literal("assistant"),
794
+ message: z.object({
795
+ content: z.array(z.unknown())
796
+ }).passthrough()
797
+ }).passthrough();
798
+ var UserEventSchema = z.object({
799
+ type: z.literal("user"),
800
+ message: z.object({
801
+ content: z.union([z.array(z.unknown()), z.string()])
802
+ }).passthrough()
803
+ }).passthrough();
804
+ var ResultEventSchema = z.object({
805
+ type: z.literal("result"),
806
+ subtype: z.string(),
807
+ is_error: z.boolean().optional()
808
+ }).passthrough();
809
+ var SystemEventSchema = z.object({
810
+ type: z.literal("system"),
811
+ subtype: z.string().optional(),
812
+ status: z.string().optional(),
813
+ content: z.unknown().optional()
814
+ }).passthrough();
815
+ var TextDeltaSchema = z.object({
816
+ type: z.literal("text_delta"),
817
+ text: z.string()
818
+ }).passthrough();
819
+ var ThinkingDeltaSchema = z.object({
820
+ type: z.literal("thinking_delta"),
821
+ thinking: z.string()
822
+ }).passthrough();
823
+ var SignatureDeltaSchema = z.object({
824
+ type: z.literal("signature_delta"),
825
+ signature: z.string()
826
+ }).passthrough();
827
+ var ContentBlockDeltaSchema = z.object({
828
+ type: z.literal("content_block_delta"),
829
+ index: z.number(),
830
+ delta: z.discriminatedUnion("type", [
831
+ TextDeltaSchema,
832
+ ThinkingDeltaSchema,
833
+ SignatureDeltaSchema
834
+ ])
835
+ }).passthrough();
836
+ var StreamEventSchema = z.object({
837
+ type: z.literal("stream_event"),
838
+ event: z.object({ type: z.string() }).passthrough()
839
+ }).passthrough();
840
+ var CanUseToolRequestSchema = z.object({
841
+ subtype: z.literal("can_use_tool"),
842
+ tool_name: z.string(),
843
+ input: z.record(z.string(), z.unknown())
844
+ }).passthrough();
845
+ var ControlRequestEventSchema = z.object({
846
+ type: z.literal("control_request"),
847
+ request_id: z.string(),
848
+ request: CanUseToolRequestSchema
849
+ }).passthrough();
850
+ var ControlResponseEventSchema = z.object({
851
+ type: z.literal("control_response"),
852
+ response: z.object({
853
+ subtype: z.literal("success"),
854
+ request_id: z.string(),
855
+ response: z.discriminatedUnion("behavior", [
856
+ z.object({
857
+ behavior: z.literal("allow"),
858
+ updatedInput: z.record(z.string(), z.unknown())
859
+ }).passthrough(),
860
+ z.object({
861
+ behavior: z.literal("deny"),
862
+ message: z.string()
863
+ }).passthrough()
864
+ ])
865
+ }).passthrough()
866
+ }).passthrough();
867
+ var StreamJsonEventSchema = z.discriminatedUnion("type", [
868
+ AssistantEventSchema,
869
+ UserEventSchema,
870
+ ResultEventSchema,
871
+ SystemEventSchema,
872
+ StreamEventSchema,
873
+ ControlRequestEventSchema,
874
+ ControlResponseEventSchema
875
+ ]);
876
+ var IGNORED_EVENT_TYPES = /* @__PURE__ */ new Set(["rate_limit_event"]);
877
+
878
+ export {
879
+ AcpRpcError,
880
+ AcpSession,
881
+ KnownContentBlockSchema,
882
+ ContentBlockDeltaSchema,
883
+ ControlRequestEventSchema,
884
+ StreamJsonEventSchema,
885
+ IGNORED_EVENT_TYPES,
886
+ SeqCounter,
887
+ getSeqCounterFor,
888
+ disposeSeqCounter,
889
+ createApprovalRequestIdFactory,
890
+ createScopedApprovalRequestIdFactory
891
+ };
892
+ //# sourceMappingURL=chunk-7DIHPKGQ.js.map