@anusornneal/chat-relay 1.8.0 → 2.0.1

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 (54) hide show
  1. package/README.md +60 -0
  2. package/agent/activity-capture.mjs +165 -0
  3. package/agent/capability-scheduler.mjs +83 -6
  4. package/agent/file-manager.mjs +188 -77
  5. package/agent/fs-batch-preview.mjs +70 -0
  6. package/agent/full-bridge.mjs +53 -0
  7. package/agent/full-desktop-actions.mjs +124 -0
  8. package/agent/full-desktop-auth.mjs +53 -0
  9. package/agent/full-desktop-broker.mjs +308 -0
  10. package/agent/full-host.mjs +153 -0
  11. package/agent/full-job-broker.mjs +360 -0
  12. package/agent/full-native-job.mjs +205 -0
  13. package/agent/full-presentation-changes.mjs +191 -0
  14. package/agent/full-remote-diagnostics.mjs +129 -0
  15. package/agent/full-resources.mjs +343 -0
  16. package/agent/full-runtime-supervisor.mjs +67 -0
  17. package/agent/full-session-dispatch.mjs +167 -0
  18. package/agent/full-workspace-broker.mjs +290 -0
  19. package/agent/git-worktree-manager.mjs +170 -4
  20. package/agent/lifecycle.mjs +17 -0
  21. package/agent/local-agent.mjs +182 -33
  22. package/agent/local-usage.mjs +275 -0
  23. package/agent/monitor-activity.mjs +111 -0
  24. package/agent/presentation-redaction.mjs +10 -0
  25. package/agent/process-manager.mjs +32 -0
  26. package/agent/protocol.mjs +5 -1
  27. package/agent/terminal-manager.mjs +240 -29
  28. package/agent/terminal-output.mjs +136 -0
  29. package/agent/toolcall-context.mjs +35 -5
  30. package/agent/toolcall-summary.mjs +10 -0
  31. package/agent/windows-desktop-runner.mjs +65 -61
  32. package/agent/windows-desktop-worker.ps1 +33 -18
  33. package/agent/windows-powershell.mjs +51 -0
  34. package/cli/full-background.mjs +69 -0
  35. package/cli/full-launch.mjs +94 -0
  36. package/cli/full-prepare-child.mjs +48 -0
  37. package/cli/full-prepare.mjs +171 -0
  38. package/cli/full-release-default.json +4 -0
  39. package/cli/full-release-files.mjs +36 -0
  40. package/cli/full-release-official.mjs +48 -0
  41. package/cli/full-release-source.mjs +37 -0
  42. package/cli/index.mjs +8 -4
  43. package/cli/mod-cache.mjs +170 -0
  44. package/cli/mod-loader.mjs +67 -0
  45. package/cli/mod-manifest.mjs +63 -0
  46. package/cli/remote.mjs +172 -17
  47. package/cli/runner-ownership.mjs +116 -3
  48. package/cli/self-update.mjs +1 -1
  49. package/cli/tui.mjs +2 -20
  50. package/package.json +9 -6
  51. package/packages/full-contracts/index.mjs +193 -0
  52. package/packages/full-contracts/native-job.mjs +13 -0
  53. package/packages/full-contracts/package.json +7 -0
  54. package/packages/full-contracts/remote-session.mjs +239 -0
@@ -1,12 +1,17 @@
1
1
  import WebSocket from "ws";
2
2
  import { DesktopManager, createDesktopPlatformAdapter } from "./desktop-manager.mjs";
3
3
  import { FileManager } from "./file-manager.mjs";
4
+ import { LocalUsageHistory, usageFileForAgent } from "./local-usage.mjs";
4
5
  import { GitWorktreeManager } from "./git-worktree-manager.mjs";
5
6
  import { ProcessManager } from "./process-manager.mjs";
6
7
  import { TerminalManager } from "./terminal-manager.mjs";
7
8
  import { CapabilityScheduler } from "./capability-scheduler.mjs";
8
9
  import { AgentConnectionState, safeConnectionReason } from "./connection-state.mjs";
9
10
  import { buildAgentHello } from "./protocol.mjs";
11
+ import { createCoreEventBridge, fullUnavailable, hasFullSessionRequest } from "./full-bridge.mjs";
12
+ import { takeFullBootstrap, FULL_STARTUP_EXIT_CODE } from "./full-session-dispatch.mjs";
13
+ import { startSupervisedFull } from "./full-runtime-supervisor.mjs";
14
+ import { createParentAuthorizationClient } from "./full-desktop-auth.mjs";
10
15
  import {
11
16
  AgentLifecycle,
12
17
  AGENT_RESTART_EXIT_CODE,
@@ -15,6 +20,8 @@ import {
15
20
  } from "./lifecycle.mjs";
16
21
  import { humanizeToolCall } from "./toolcall-summary.mjs";
17
22
  import { describeToolActivity } from "./toolcall-context.mjs";
23
+ import { createMonitorActivity, describeFullMonitorActivity } from "./monitor-activity.mjs";
24
+ import {captureActivityFor,runActivityCapture,finishActivityCapture,describeLocalSearch} from "./activity-capture.mjs";
18
25
  import { toolErrorGuidance } from "./tool-error-guidance.mjs";
19
26
  import {
20
27
  HeartbeatAckWatchdog,
@@ -29,8 +36,30 @@ const reconnectMs = Number(process.env.RECONNECT_MS ?? 2000);
29
36
  const terminalEnabled = process.env.TERMINAL_ENABLED === "1";
30
37
  const desktopEnabled = process.env.DESKTOP_ENABLED === "1";
31
38
  const ipcUiEnabled = process.env.CHAT_RELAY_UI === "ipc";
32
-
33
- function emitUi(event, payload = {}) {
39
+ let fullBootstrap,fullRuntime=null,fullStarting=null;
40
+ try{fullBootstrap=takeFullBootstrap();}catch{
41
+ console.error("Full runtime unavailable: invalid local bootstrap. No Core fallback was started.");
42
+ process.exit(FULL_STARTUP_EXIT_CODE);
43
+ }
44
+ const fullEvents = process.env.CHAT_RELAY_FULL_EVENTS === "1" && typeof process.send === "function"
45
+ ? createCoreEventBridge({ enabled: true, send: (message, done) => process.send(message, done) })
46
+ : null;
47
+
48
+ const monitorEnabled=fullBootstrap?.headless===false;
49
+ const monitorAccountId=monitorEnabled?fullBootstrap.localPrincipal?.accountId:null;
50
+ const monitorActivity=monitorEnabled?createMonitorActivity():null;
51
+ function monitorSnapshot(){
52
+ const connection=connectionState.snapshot();
53
+ let relayHost="";try{relayHost=new URL(relayUrl).host.slice(0,200);}catch{}
54
+ return {agentName:String(agentName).slice(0,128).toWellFormed(),agentId,version:agentHello.agentVersion,
55
+ relayHost,connection:connection.state,reconnects:connection.reconnectCount,uptimeSeconds:Math.floor(process.uptime()),
56
+ terminalEnabled,desktopEnabled:desktopEnabled&&desktopAdapter.supported,
57
+ ...monitorActivity?.snapshot(),work:currentWorkSummary()};
58
+ }
59
+ function emitUi(event, payload = {}, activityDetails = null) {
60
+ if(monitorEnabled&&fullRuntime){
61
+ if(monitorActivity.accept(event,activityDetails?{...payload,activityDetails}:payload)||event==="connection"||event==="system")fullRuntime.monitorChanged();
62
+ }
34
63
  if (!ipcUiEnabled || typeof process.send !== "function") return;
35
64
  try { process.send({ type: "chat-relay-ui", event, at: new Date().toISOString(), ...payload }); } catch {}
36
65
  }
@@ -40,10 +69,7 @@ function plainLog(...args) {
40
69
  }
41
70
 
42
71
  function plainError(...args) {
43
- if (!ipcUiEnabled) {
44
- console.error(...args);
45
- return;
46
- }
72
+ if (!ipcUiEnabled) console.error(...args);
47
73
  emitUi("system", { level: "error", message: args.map((item) => String(item)).join(" ") });
48
74
  }
49
75
  const desktopAdapter = createDesktopPlatformAdapter({ platform: process.platform });
@@ -61,6 +87,7 @@ const terminals = new TerminalManager({
61
87
  fastExecIdleMs: process.env.TERMINAL_FAST_EXEC_IDLE_MS,
62
88
  });
63
89
  const scheduler = new CapabilityScheduler({
90
+ full:!!fullBootstrap,
64
91
  maxQueued: process.env.AGENT_MAX_QUEUED,
65
92
  queueTimeoutMs: process.env.AGENT_QUEUE_TIMEOUT_MS,
66
93
  fileConcurrency: process.env.AGENT_FILE_CONCURRENCY,
@@ -83,7 +110,7 @@ const desktop = new DesktopManager({
83
110
  controlMaxQueued: process.env.DESKTOP_CONTROL_MAX_QUEUED,
84
111
  controlQueueTimeoutMs: process.env.AGENT_QUEUE_TIMEOUT_MS,
85
112
  });
86
- const recentCalls = [];
113
+ const usage = new LocalUsageHistory({ file: process.env.CHAT_RELAY_USAGE_DISABLED === "1" ? null : usageFileForAgent(agentId) });
87
114
  // Correlate asynchronous batch/session output with the project where work began.
88
115
  // Local only, bounded and never queried from the Worker.
89
116
  const recentToolProjects = new Map();
@@ -127,12 +154,25 @@ const heartbeatAckWatchdog = new HeartbeatAckWatchdog({
127
154
  },
128
155
  });
129
156
 
157
+ // Legacy requests do not carry a task binding. While a Full terminal job
158
+ // holds agent-wide effects, reject overlapping legacy mutations. Existing
159
+ // legacy terminal sessions/batches must finish before a new owned job starts.
160
+ let legacyEffectsInFlight=0;
161
+ const LEGACY_EFFECTS=new Set(["fs.editMany","fs.write","fs.edit","fs.mkdir","fs.move","fs.delete","git.worktree.cleanup","process.kill",
162
+ "desktop.clipboard.write","desktop.window.focus","desktop.mouse.click_image","desktop.mouse.click","desktop.keyboard.input","desktop.step",
163
+ "terminal.exec","terminal.exec.compact","terminal.batch.start","terminal.batch.cancel","terminal.start","terminal.shell.start","terminal.write","terminal.kill"]);
164
+ function legacyBusy(){
165
+ if(legacyEffectsInFlight)return true;
166
+ const observed=terminals.observability();
167
+ return observed.sessions.some(s=>s.status==="running")||observed.drainingSessions>0||observed.activeExecJobs>0||observed.queuedJobs>0;
168
+ }
130
169
  function currentWorkSummary() {
131
- return summarizeAgentWork({
170
+ const work=summarizeAgentWork({
132
171
  terminal: terminals.observability(),
133
172
  scheduler: scheduler.snapshot(),
134
173
  desktop: desktop.getConfig(),
135
174
  });
175
+ return fullRuntime?{...work,activeFullRequests:fullRuntime.pending}:work;
136
176
  }
137
177
 
138
178
  const lifecycle = new AgentLifecycle({ workSummary: currentWorkSummary });
@@ -158,9 +198,16 @@ function serializeResponse(requestId, payload, meta) {
158
198
  });
159
199
  }
160
200
 
161
- async function handlePayload(payload) {
201
+ async function handlePayload(payload, metadata) {
162
202
  if (!payload || typeof payload !== "object") return payload;
163
203
  const action = String(payload.action ?? "");
204
+ if (action === "full.invoke") {
205
+ if (stopping || reauthorizationRequired || !fullRuntime?.available) return fullUnavailable();
206
+ const gate=lifecycle.guard(String(payload.operation??action));
207
+ if(gate)return gate;
208
+ return fullRuntime.dispatch(payload,metadata);
209
+ }
210
+ if (hasFullSessionRequest(payload) || action.startsWith("full.")) return fullUnavailable();
164
211
  const lifecycleGate = lifecycle.guard(action);
165
212
  if (lifecycleGate) return lifecycleGate;
166
213
 
@@ -182,6 +229,7 @@ async function handlePayload(payload) {
182
229
  connection: { ...connectionState.snapshot(), processId: process.pid },
183
230
  heartbeatAckWatchdog: heartbeatAckWatchdog.snapshot(),
184
231
  lifecycle: lifecycle.snapshot(),
232
+ ...(fullRuntime?{full:fullRuntime.status}:{}),
185
233
  terminalContinuity: {
186
234
  processId: process.pid,
187
235
  ...terminals.getContinuityConfig(),
@@ -191,11 +239,15 @@ async function handlePayload(payload) {
191
239
  agentVersion: agentHello.agentVersion,
192
240
  platform: agentHello.platform,
193
241
  arch: agentHello.arch,
194
- capabilities: agentHello.capabilities,
242
+ capabilities: fullRuntime ? [...agentHello.capabilities, ...fullRuntime.capabilities] : agentHello.capabilities,
195
243
  },
196
244
  });
197
245
  case "agent.recentCalls":
198
- return recentCalls.slice(-(Math.min(Math.max(Number(payload.limit) || 50, 1), 100)));
246
+ return usage.recent(payload.limit);
247
+ case "agent.recentCalls.page":
248
+ return usage.page(payload.limit, payload.cursor);
249
+ case "agent.usageStats":
250
+ return usage.stats(payload.days);
199
251
  case "agent.lifecycle.status":
200
252
  return { ok: true, lifecycle: lifecycle.snapshot() };
201
253
  case "agent.lifecycle.drain":
@@ -208,6 +260,9 @@ async function handlePayload(payload) {
208
260
  return result;
209
261
  }
210
262
  case "agent.lifecycle.upgrade": {
263
+ // The next Core release must be checked against the pinned Full artifact.
264
+ // Do not hand an opted-in runner to an older CLI that may ignore --full.
265
+ if(fullRuntime)return {ok:false,error:"full_manual_upgrade_required"};
211
266
  const result = lifecycle.requestUpgrade();
212
267
  if (result.ok) setTimeout(upgradeAgentProcess, 150);
213
268
  return result;
@@ -221,8 +276,16 @@ async function handlePayload(payload) {
221
276
  return files.read(payload.path, payload.offset, payload.length, payload.maxBytes);
222
277
  case "fs.readMany":
223
278
  return files.readMany(payload.paths, payload.maxTotalBytes);
279
+ case "fs.readMany.relative":
280
+ return files.readMany(payload.paths, payload.maxTotalBytes, payload.basePath);
224
281
  case "fs.batch":
225
282
  return files.batch(payload.operations, payload.maxTotalBytes);
283
+ case "fs.batch.compact":
284
+ return files.batch(payload.operations, payload.maxTotalBytes, {
285
+ basePath: payload.basePath, deduplicatePreviews: payload.deduplicatePreviews,
286
+ });
287
+ case "fs.editMany":
288
+ return files.editMany(payload.operations, payload.basePath);
226
289
  case "fs.artifact":
227
290
  return files.exportArtifact(payload.path, payload.maxBytes);
228
291
  case "fs.write":
@@ -270,6 +333,9 @@ async function handlePayload(payload) {
270
333
  case "terminal.exec":
271
334
  if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
272
335
  return terminals.exec(payload.command, payload.cwd, payload.timeoutMs);
336
+ case "terminal.exec.compact":
337
+ if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
338
+ return terminals.execCompact(payload.command, payload.cwd, payload.timeoutMs, payload.outputMode, payload.outputChars);
273
339
  case "terminal.batch.start":
274
340
  if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
275
341
  return terminals.batchStart(payload.jobs, { cwd: payload.cwd, timeoutMs: payload.timeoutMs, concurrency: payload.concurrency, observability: payload.observability });
@@ -279,6 +345,9 @@ async function handlePayload(payload) {
279
345
  case "terminal.batch.read":
280
346
  if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
281
347
  return terminals.batchRead(payload.batchId, payload.maxChars);
348
+ case "terminal.batch.read.compact":
349
+ if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
350
+ return terminals.batchReadCompact(payload.batchId, payload.maxChars, payload.outputMode, payload.outputChars, payload.jobIndex);
282
351
  case "terminal.batch.cancel":
283
352
  if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
284
353
  return terminals.batchCancel(payload.batchId);
@@ -291,6 +360,9 @@ async function handlePayload(payload) {
291
360
  case "terminal.read":
292
361
  if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
293
362
  return terminals.readWithWait(payload.sessionId, payload.afterSeq, payload.maxChars, payload.waitMs ?? 0);
363
+ case "terminal.read.compact":
364
+ if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
365
+ return terminals.readCompact(payload.sessionId, payload.afterSeq, payload.maxChars, payload.waitMs ?? 0, payload.outputMode, payload.outputChars);
294
366
  case "terminal.write":
295
367
  if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
296
368
  return terminals.write(payload.sessionId, payload.input, payload.appendNewline !== false);
@@ -434,7 +506,7 @@ function requireProtocolUpdate(details = {}) {
434
506
  const expected = details.expectedProtocolVersion ?? "current";
435
507
  const received = details.receivedProtocolVersion ?? agentHello.protocolVersion;
436
508
  plainError(`Agent protocol is incompatible (local=${received}, relay=${expected}). Update Chat Relay, then reconnect.`);
437
- setImmediate(() => process.exit(3));
509
+ exitWithFullDrain(3);
438
510
  }
439
511
 
440
512
  function requireReauthorization(reason = "credential_revoked") {
@@ -450,7 +522,7 @@ function requireReauthorization(reason = "credential_revoked") {
450
522
  desktop.close();
451
523
  plainError("Agent credential was revoked or rejected.");
452
524
  plainError('Recovery: run "chat-relay login --force", then "chat-relay remote".');
453
- setImmediate(() => process.exit(2));
525
+ exitWithFullDrain(2);
454
526
  }
455
527
 
456
528
  function connect() {
@@ -473,7 +545,7 @@ function connect() {
473
545
 
474
546
  socket.on("open", () => {
475
547
  if (socket !== activeSocket) return;
476
- socket.send(JSON.stringify(agentHello));
548
+ socket.send(JSON.stringify(fullRuntime ? { ...agentHello, capabilities: [...agentHello.capabilities, ...fullRuntime.capabilities] } : agentHello));
477
549
  connectionState.markConnected();
478
550
  emitUi("connection", { state: "connected", reconnects: connectionState.snapshot().reconnectCount });
479
551
  startHeartbeat(socket);
@@ -531,17 +603,28 @@ function connect() {
531
603
  const callSummary = humanizeToolCall(message.payload);
532
604
  const uiActivity = describeToolActivity(message.payload, files.getRoots(), recentToolProjects);
533
605
  const requestBytes = Buffer.byteLength(JSON.stringify(message), "utf8");
534
- emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary, ...uiActivity, requestBytes });
606
+ const ownedFull=action==="full.invoke"&&monitorAccountId&&message.payload?.principal?.accountId===monitorAccountId&&message.payload?.principal?.agentId===agentId;
607
+ const capture=monitorEnabled&&(action!=="full.invoke"||ownedFull)?captureActivityFor(message.payload):null;
608
+ const captured=result=>{try{return finishActivityCapture(capture,message.payload,result);}catch{return null;}};
609
+ emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary, ...uiActivity, requestBytes,
610
+ ...(monitorEnabled&&(action!=="full.invoke"||ownedFull)?describeLocalSearch(message.payload):{}),
611
+ ...(ownedFull?{monitorAction:message.payload.operation,monitorOperation:describeFullMonitorActivity(message.payload.operation,message.payload.input),monitorTaskSessionId:message.payload.input?.taskSessionId}: {}) });
612
+ fullEvents?.publish("tool.accepted", message.requestId, action, message.payload?.observability);
535
613
  let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
536
614
  let handlerDurationMs = 0;
537
615
  try {
538
- const schedulingAction = action === "terminal.read" && Number(message.payload?.waitMs) > 0
616
+ const schedulingAction = (action === "terminal.read" || action === "terminal.read.compact") && Number(message.payload?.waitMs) > 0
539
617
  ? "terminal.read.wait" : action;
540
- const result = await scheduler.run(schedulingAction, async (meta = {}) => {
618
+ const run=action==="full.invoke"?work=>work({lane:"fullBroker"}):work=>scheduler.run(schedulingAction,work);
619
+ const result = await run(async (meta = {}) => {
541
620
  scheduleMeta = { ...scheduleMeta, ...meta };
542
621
  const handlerStartedAt = Date.now();
543
622
  try {
544
- return await handlePayload(message.payload);
623
+ const effect=!!fullRuntime&&LEGACY_EFFECTS.has(action);
624
+ if(effect&&fullRuntime.blocksLegacyEffects())return {ok:false,error:"full_scoped_effect_active"};
625
+ if(effect)legacyEffectsInFlight++;
626
+ try{return await runActivityCapture(capture,()=>handlePayload(message.payload,{requestId:message.requestId,requestBytes}));}
627
+ finally{if(effect)legacyEffectsInFlight--;}
545
628
  } finally {
546
629
  handlerDurationMs = Math.max(0, Date.now() - handlerStartedAt);
547
630
  }
@@ -553,7 +636,8 @@ function connect() {
553
636
  rememberToolProject(result?.sessionId, uiActivity.project);
554
637
  }
555
638
  }
556
- recentCalls.push({
639
+ if (action === "terminal.exec.compact") rememberToolProject(result?.rawOutputId, uiActivity.project);
640
+ const recentEntry = {
557
641
  at: new Date().toISOString(),
558
642
  action,
559
643
  summary: callSummary,
@@ -564,29 +648,35 @@ function connect() {
564
648
  ...(timing ? { timing } : {}),
565
649
  ...(typeof result?.execMode === "string" ? { execMode: result.execMode } : {}),
566
650
  ok: !(result && typeof result === "object" && result.ok === false),
567
- });
568
- if (recentCalls.length > 100) recentCalls.shift();
651
+ };
569
652
  const responseMeta = {
570
653
  agentQueueWaitMs: scheduleMeta.queueWaitMs,
571
654
  agentHandlerMs: handlerDurationMs,
572
655
  lane: scheduleMeta.lane,
573
656
  };
574
657
  const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, result, responseMeta), "utf8");
658
+ try { usage.record({ ...recentEntry, requestBytes, responseBytes }, message.payload, result); } catch {}
659
+ const activityDetails=captured(result);
660
+ const partialFailure=activityDetails?.files.some(file=>file.outcome==="failed")||ownedFull&&result?.result?.ok===false;
575
661
  emitUi("tool:end", {
576
662
  requestId: message.requestId,
577
663
  action,
578
664
  summary: callSummary,
579
- ok: !(result && typeof result === "object" && result.ok === false),
665
+ ok: !(result && typeof result === "object" && result.ok === false)&&!partialFailure,
580
666
  durationMs: Date.now() - startedAt,
581
667
  responseBytes,
582
- ...(result && typeof result === "object" && result.ok === false && result.error ? { error: String(result.error) } : {}),
668
+ ...(result && typeof result === "object" && result.ok === false && result.error ? { error: String(result.error) } : partialFailure?{error:"partial_failure"}:{}),
669
+ },activityDetails);
670
+ if(ownedFull&&message.payload.operation==="full.session.delete"&&result?.ok===true&&result.result?.acknowledged===true)monitorActivity?.forgetSession(message.payload.input.taskSessionId);
671
+ fullEvents?.publish("tool.completed", message.requestId, action, message.payload?.observability, {
672
+ ok: !(result && typeof result === "object" && result.ok === false), durationMs: Date.now() - startedAt,
583
673
  });
584
674
  const advised = result && typeof result === "object" && result.ok === false && result.error
585
675
  ? { ...result, ...toolErrorGuidance(action, String(result.error), message.payload) }
586
676
  : result;
587
677
  sendSocketResponse(socket, message.requestId, advised, responseMeta);
588
678
  } catch (error) {
589
- recentCalls.push({
679
+ const recentEntry = {
590
680
  at: new Date().toISOString(),
591
681
  action,
592
682
  summary: callSummary,
@@ -596,13 +686,13 @@ function connect() {
596
686
  lane: scheduleMeta.lane,
597
687
  ok: false,
598
688
  error: error instanceof Error ? error.message : "agent_error",
599
- });
600
- if (recentCalls.length > 100) recentCalls.shift();
689
+ };
601
690
  const errorPayload = {
602
691
  ok: false,
603
692
  error: error instanceof Error ? error.message : "agent_error",
604
693
  };
605
694
  const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, errorPayload), "utf8");
695
+ try { usage.record({ ...recentEntry, requestBytes, responseBytes }, message.payload, errorPayload); } catch {}
606
696
  emitUi("tool:end", {
607
697
  requestId: message.requestId,
608
698
  action,
@@ -611,7 +701,8 @@ function connect() {
611
701
  durationMs: Date.now() - startedAt,
612
702
  responseBytes,
613
703
  error: errorPayload.error,
614
- });
704
+ },captured(errorPayload));
705
+ fullEvents?.publish("tool.completed", message.requestId, action, message.payload?.observability, { ok: false, durationMs: Date.now() - startedAt });
615
706
  sendSocketResponse(socket, message.requestId, { ...errorPayload, ...toolErrorGuidance(action, errorPayload.error, message.payload) });
616
707
  }
617
708
  });
@@ -667,7 +758,7 @@ function restartAgentProcess() {
667
758
  try { socket?.close(1012, "restart_requested"); } catch {}
668
759
  terminals.close();
669
760
  desktop.close();
670
- setTimeout(() => process.exit(AGENT_RESTART_EXIT_CODE), 50);
761
+ exitWithFullDrain(AGENT_RESTART_EXIT_CODE, 50);
671
762
  }
672
763
 
673
764
  function upgradeAgentProcess() {
@@ -681,7 +772,7 @@ function upgradeAgentProcess() {
681
772
  try { socket?.close(1012, "upgrade_requested"); } catch {}
682
773
  terminals.close();
683
774
  desktop.close();
684
- setTimeout(() => process.exit(AGENT_UPGRADE_EXIT_CODE), 50);
775
+ exitWithFullDrain(AGENT_UPGRADE_EXIT_CODE, 50);
685
776
  }
686
777
 
687
778
  function shutdown(reason) {
@@ -695,11 +786,69 @@ function shutdown(reason) {
695
786
  try { socket?.close(1000, "client_shutdown"); } catch {}
696
787
  terminals.close();
697
788
  desktop.close();
698
- setTimeout(() => process.exit(0), 50);
789
+ exitWithFullDrain(0, 50);
790
+ }
791
+
792
+ function exitWithFullDrain(code,delay=0) {
793
+ if(!fullRuntime&&!fullStarting){if(delay)setTimeout(()=>process.exit(code),delay);else setImmediate(()=>process.exit(code));return;}
794
+ void (async()=>{
795
+ try {
796
+ const runtime=fullRuntime??await fullStarting;
797
+ const result=await runtime.dispose();
798
+ if(!result?.confirmed||result.code!==0||result.forced){
799
+ plainError("Full shutdown requires guarded recovery before further scoped writes.");
800
+ process.exit(FULL_STARTUP_EXIT_CODE);
801
+ }
802
+ }catch{process.exit(FULL_STARTUP_EXIT_CODE);}
803
+ process.exit(code);
804
+ })();
699
805
  }
700
806
 
701
807
  process.once("SIGINT", () => shutdown("SIGINT"));
702
808
  process.once("SIGTERM", () => shutdown("SIGTERM"));
703
- process.once("exit", () => { terminals.close(); desktop.close(); });
704
-
705
- connect();
809
+ process.once("exit", () => { fullEvents?.close(); usage.close(); terminals.close(); desktop.close(); });
810
+
811
+ if(fullBootstrap){
812
+ // Runner IPC is private to the parent/child pair, not the relay socket.
813
+ let desktopOpening=false;
814
+ process.on("message",message=>{
815
+ if(message?.type==="chat-relay-runner"&&message.command==="shutdown"){shutdown("runner_shutdown");return;}
816
+ if(message?.type!=="chat-relay-full-desktop"||message.kind!=="open"||
817
+ typeof message.requestId!=="string"||!/^[a-f0-9-]{36}$/.test(message.requestId)||
818
+ typeof message.accountId!=="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(message.accountId)||
819
+ Object.keys(message).some(key=>!["type","kind","requestId","accountId"].includes(key)))return;
820
+ const reply=result=>{if(process.connected)try{
821
+ process.send({type:"chat-relay-full-desktop",kind:"result",requestId:message.requestId,...result},()=>{});
822
+ }catch{}};
823
+ if(stopping||reauthorizationRequired||desktopOpening){reply({ok:false,error:"full_unavailable"});return;}
824
+ desktopOpening=true;
825
+ void (async()=>{
826
+ const runtime=fullRuntime??await fullStarting;
827
+ if(stopping||reauthorizationRequired||!runtime?.available)throw Object.assign(new Error("full_unavailable"),{code:"full_unavailable"});
828
+ const result=await runtime.openDesktop({accountId:message.accountId});
829
+ reply({ok:true,alreadyOpen:result.alreadyOpen});
830
+ })().catch(error=>reply({ok:false,error:typeof error?.code==="string"&&/^full_[a-z0-9_]+$/.test(error.code)?error.code:"full_desktop_reopen_unavailable"}))
831
+ .finally(()=>{desktopOpening=false;});
832
+ });
833
+ process.once("disconnect",()=>shutdown("runner_disconnected"));
834
+ const desktopAuthorization=fullBootstrap.headless?null:createParentAuthorizationClient();
835
+ if(desktopAuthorization)process.once("exit",()=>desktopAuthorization.close());
836
+ try {
837
+ fullStarting=startSupervisedFull({bootstrap:fullBootstrap,agentId,authorizePrincipal:desktopAuthorization?.authorize,monitorSnapshot,monitorDetails:monitorActivity?(activityId,fileId)=>monitorActivity.detail(activityId,fileId):undefined,requestQuit:()=>{setTimeout(()=>shutdown("local_gui_quit"),250);},workspaceBroker:{git:gitWorktrees,roots:()=>files.getRoots(),files,scheduler,terminalEnabled,legacyBusy,desktop},onState:state=>{
838
+ if(stopping||reauthorizationRequired)return;
839
+ plainError("Full host: "+state.state+" ("+state.reason+"). Core remains connected; unknown effects remain fenced.");
840
+ if(activeSocket?.readyState===WebSocket.OPEN)try{activeSocket.send(JSON.stringify({...agentHello,capabilities:[...agentHello.capabilities,...(fullRuntime?.capabilities??[])]}));}catch{}
841
+ }});
842
+ fullRuntime=await fullStarting;
843
+ fullStarting=null;
844
+ fullBootstrap=null;
845
+ if(!fullRuntime.available&&!stopping)throw new Error("full_unavailable");
846
+ if(monitorEnabled&&process.connected&&fullRuntime.desktopStatus?.state==="running"){
847
+ try{process.send({type:"chat-relay-runner",event:"full-gui-ready"},()=>{});}catch{}
848
+ }
849
+ } catch(error) {
850
+ plainError("Full runtime unavailable: "+(typeof error?.code==="string"?error.code:"full_startup_failed")+". No Core fallback was started.");
851
+ process.exit(FULL_STARTUP_EXIT_CODE);
852
+ }
853
+ }
854
+ if(!stopping&&!reauthorizationRequired)connect();