@anusornneal/chat-relay 1.9.0 → 2.1.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 (54) hide show
  1. package/README.md +8 -0
  2. package/agent/activity-capture.mjs +218 -0
  3. package/agent/auto-session-binding.mjs +46 -0
  4. package/agent/capability-scheduler.mjs +82 -5
  5. package/agent/file-manager.mjs +33 -8
  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 +318 -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 +171 -4
  20. package/agent/lifecycle.mjs +11 -0
  21. package/agent/local-agent.mjs +177 -24
  22. package/agent/local-usage.mjs +21 -0
  23. package/agent/monitor-activity.mjs +135 -0
  24. package/agent/presentation-redaction.mjs +10 -0
  25. package/agent/process-manager.mjs +32 -0
  26. package/agent/terminal-manager.mjs +189 -31
  27. package/agent/toolcall-context.mjs +27 -1
  28. package/agent/toolcall-summary.mjs +1 -1
  29. package/agent/windows-desktop-runner.mjs +65 -61
  30. package/agent/windows-desktop-worker.ps1 +33 -18
  31. package/agent/windows-powershell.mjs +51 -0
  32. package/cli/full-background.mjs +69 -0
  33. package/cli/full-launch.mjs +76 -0
  34. package/cli/full-prepare-child.mjs +48 -0
  35. package/cli/full-prepare.mjs +171 -0
  36. package/cli/full-release-default.json +4 -0
  37. package/cli/full-release-files.mjs +36 -0
  38. package/cli/full-release-official.mjs +48 -0
  39. package/cli/full-release-source.mjs +37 -0
  40. package/cli/index.mjs +9 -5
  41. package/cli/mod-cache.mjs +170 -0
  42. package/cli/mod-loader.mjs +67 -0
  43. package/cli/mod-manifest.mjs +63 -0
  44. package/cli/remote.mjs +173 -18
  45. package/cli/runner-ownership.mjs +116 -3
  46. package/cli/self-update.mjs +1 -1
  47. package/cli/tui.mjs +2 -20
  48. package/package.json +5 -3
  49. package/packages/full-contracts/auto-session.mjs +14 -0
  50. package/packages/full-contracts/index.mjs +193 -0
  51. package/packages/full-contracts/monitor-metadata.mjs +28 -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,4 +1,5 @@
1
1
  import WebSocket from "ws";
2
+ import {createHash} from "node:crypto";
2
3
  import { DesktopManager, createDesktopPlatformAdapter } from "./desktop-manager.mjs";
3
4
  import { FileManager } from "./file-manager.mjs";
4
5
  import { LocalUsageHistory, usageFileForAgent } from "./local-usage.mjs";
@@ -8,6 +9,11 @@ import { TerminalManager } from "./terminal-manager.mjs";
8
9
  import { CapabilityScheduler } from "./capability-scheduler.mjs";
9
10
  import { AgentConnectionState, safeConnectionReason } from "./connection-state.mjs";
10
11
  import { buildAgentHello } from "./protocol.mjs";
12
+ import { createCoreEventBridge, fullUnavailable, hasFullSessionRequest } from "./full-bridge.mjs";
13
+ import { takeFullBootstrap, FULL_STARTUP_EXIT_CODE } from "./full-session-dispatch.mjs";
14
+ import { startSupervisedFull } from "./full-runtime-supervisor.mjs";
15
+ import { createAutomaticSessionBinding } from "./auto-session-binding.mjs";
16
+ import { createParentAuthorizationClient } from "./full-desktop-auth.mjs";
11
17
  import {
12
18
  AgentLifecycle,
13
19
  AGENT_RESTART_EXIT_CODE,
@@ -16,6 +22,8 @@ import {
16
22
  } from "./lifecycle.mjs";
17
23
  import { humanizeToolCall } from "./toolcall-summary.mjs";
18
24
  import { describeToolActivity } from "./toolcall-context.mjs";
25
+ import { createMonitorActivity, describeFullMonitorActivity } from "./monitor-activity.mjs";
26
+ import {captureActivityFor,runActivityCapture,finishActivityCapture,describeLocalSearch} from "./activity-capture.mjs";
19
27
  import { toolErrorGuidance } from "./tool-error-guidance.mjs";
20
28
  import {
21
29
  HeartbeatAckWatchdog,
@@ -30,8 +38,31 @@ const reconnectMs = Number(process.env.RECONNECT_MS ?? 2000);
30
38
  const terminalEnabled = process.env.TERMINAL_ENABLED === "1";
31
39
  const desktopEnabled = process.env.DESKTOP_ENABLED === "1";
32
40
  const ipcUiEnabled = process.env.CHAT_RELAY_UI === "ipc";
33
-
34
- function emitUi(event, payload = {}) {
41
+ let fullBootstrap,fullRuntime=null,fullStarting=null;
42
+ try{fullBootstrap=takeFullBootstrap();}catch{
43
+ console.error("Full runtime unavailable: invalid local bootstrap. No Core fallback was started.");
44
+ process.exit(FULL_STARTUP_EXIT_CODE);
45
+ }
46
+ const fullEvents = process.env.CHAT_RELAY_FULL_EVENTS === "1" && typeof process.send === "function"
47
+ ? createCoreEventBridge({ enabled: true, send: (message, done) => process.send(message, done) })
48
+ : null;
49
+
50
+ const monitorEnabled=fullBootstrap?.headless===false;
51
+ const monitorAccountId=monitorEnabled?fullBootstrap.localPrincipal?.accountId:null;
52
+ const monitorActivity=monitorEnabled?createMonitorActivity():null;
53
+ const automaticSessions=fullBootstrap?createAutomaticSessionBinding({agentId,available:()=>!stopping&&!reauthorizationRequired&&fullRuntime?.available===true,dispatch:invocation=>fullRuntime.dispatch(invocation)}):null;
54
+ function monitorSnapshot(){
55
+ const connection=connectionState.snapshot();
56
+ let relayHost="";try{relayHost=new URL(relayUrl).host.slice(0,200);}catch{}
57
+ return {agentName:String(agentName).slice(0,128).toWellFormed(),agentId,version:agentHello.agentVersion,
58
+ relayHost,connection:connection.state,reconnects:connection.reconnectCount,uptimeSeconds:Math.floor(process.uptime()),
59
+ terminalEnabled,desktopEnabled:desktopEnabled&&desktopAdapter.supported,
60
+ ...monitorActivity?.snapshot(),work:currentWorkSummary()};
61
+ }
62
+ function emitUi(event, payload = {}, activityDetails = null) {
63
+ if(monitorEnabled&&fullRuntime){
64
+ if(monitorActivity.accept(event,activityDetails?{...payload,activityDetails}:payload)||event==="connection"||event==="system")fullRuntime.monitorChanged();
65
+ }
35
66
  if (!ipcUiEnabled || typeof process.send !== "function") return;
36
67
  try { process.send({ type: "chat-relay-ui", event, at: new Date().toISOString(), ...payload }); } catch {}
37
68
  }
@@ -41,10 +72,7 @@ function plainLog(...args) {
41
72
  }
42
73
 
43
74
  function plainError(...args) {
44
- if (!ipcUiEnabled) {
45
- console.error(...args);
46
- return;
47
- }
75
+ if (!ipcUiEnabled) console.error(...args);
48
76
  emitUi("system", { level: "error", message: args.map((item) => String(item)).join(" ") });
49
77
  }
50
78
  const desktopAdapter = createDesktopPlatformAdapter({ platform: process.platform });
@@ -62,6 +90,7 @@ const terminals = new TerminalManager({
62
90
  fastExecIdleMs: process.env.TERMINAL_FAST_EXEC_IDLE_MS,
63
91
  });
64
92
  const scheduler = new CapabilityScheduler({
93
+ full:!!fullBootstrap,
65
94
  maxQueued: process.env.AGENT_MAX_QUEUED,
66
95
  queueTimeoutMs: process.env.AGENT_QUEUE_TIMEOUT_MS,
67
96
  fileConcurrency: process.env.AGENT_FILE_CONCURRENCY,
@@ -128,12 +157,25 @@ const heartbeatAckWatchdog = new HeartbeatAckWatchdog({
128
157
  },
129
158
  });
130
159
 
160
+ // Legacy requests do not carry a task binding. While a Full terminal job
161
+ // holds agent-wide effects, reject overlapping legacy mutations. Existing
162
+ // legacy terminal sessions/batches must finish before a new owned job starts.
163
+ let legacyEffectsInFlight=0;
164
+ const LEGACY_EFFECTS=new Set(["fs.editMany","fs.write","fs.edit","fs.mkdir","fs.move","fs.delete","git.worktree.cleanup","process.kill",
165
+ "desktop.clipboard.write","desktop.window.focus","desktop.mouse.click_image","desktop.mouse.click","desktop.keyboard.input","desktop.step",
166
+ "terminal.exec","terminal.exec.compact","terminal.batch.start","terminal.batch.cancel","terminal.start","terminal.shell.start","terminal.write","terminal.kill"]);
167
+ function legacyBusy(){
168
+ if(legacyEffectsInFlight)return true;
169
+ const observed=terminals.observability();
170
+ return observed.sessions.some(s=>s.status==="running")||observed.drainingSessions>0||observed.activeExecJobs>0||observed.queuedJobs>0;
171
+ }
131
172
  function currentWorkSummary() {
132
- return summarizeAgentWork({
173
+ const work=summarizeAgentWork({
133
174
  terminal: terminals.observability(),
134
175
  scheduler: scheduler.snapshot(),
135
176
  desktop: desktop.getConfig(),
136
177
  });
178
+ return fullRuntime?{...work,activeFullRequests:fullRuntime.pending}:work;
137
179
  }
138
180
 
139
181
  const lifecycle = new AgentLifecycle({ workSummary: currentWorkSummary });
@@ -159,9 +201,16 @@ function serializeResponse(requestId, payload, meta) {
159
201
  });
160
202
  }
161
203
 
162
- async function handlePayload(payload) {
204
+ async function handlePayload(payload, metadata) {
163
205
  if (!payload || typeof payload !== "object") return payload;
164
206
  const action = String(payload.action ?? "");
207
+ if (action === "full.invoke") {
208
+ if (stopping || reauthorizationRequired || !fullRuntime?.available) return fullUnavailable();
209
+ const gate=lifecycle.guard(String(payload.operation??action));
210
+ if(gate)return gate;
211
+ return fullRuntime.dispatch(payload,metadata);
212
+ }
213
+ if (hasFullSessionRequest(payload) || action.startsWith("full.")) return fullUnavailable();
165
214
  const lifecycleGate = lifecycle.guard(action);
166
215
  if (lifecycleGate) return lifecycleGate;
167
216
 
@@ -183,6 +232,7 @@ async function handlePayload(payload) {
183
232
  connection: { ...connectionState.snapshot(), processId: process.pid },
184
233
  heartbeatAckWatchdog: heartbeatAckWatchdog.snapshot(),
185
234
  lifecycle: lifecycle.snapshot(),
235
+ ...(fullRuntime?{full:fullRuntime.status}:{}),
186
236
  terminalContinuity: {
187
237
  processId: process.pid,
188
238
  ...terminals.getContinuityConfig(),
@@ -192,7 +242,7 @@ async function handlePayload(payload) {
192
242
  agentVersion: agentHello.agentVersion,
193
243
  platform: agentHello.platform,
194
244
  arch: agentHello.arch,
195
- capabilities: agentHello.capabilities,
245
+ capabilities: fullRuntime ? [...agentHello.capabilities, ...fullRuntime.capabilities] : agentHello.capabilities,
196
246
  },
197
247
  });
198
248
  case "agent.recentCalls":
@@ -213,6 +263,9 @@ async function handlePayload(payload) {
213
263
  return result;
214
264
  }
215
265
  case "agent.lifecycle.upgrade": {
266
+ // The next Core release must be checked against the pinned Full artifact.
267
+ // Do not hand an opted-in runner to an older CLI that may ignore --full.
268
+ if(fullRuntime)return {ok:false,error:"full_manual_upgrade_required"};
216
269
  const result = lifecycle.requestUpgrade();
217
270
  if (result.ok) setTimeout(upgradeAgentProcess, 150);
218
271
  return result;
@@ -456,7 +509,7 @@ function requireProtocolUpdate(details = {}) {
456
509
  const expected = details.expectedProtocolVersion ?? "current";
457
510
  const received = details.receivedProtocolVersion ?? agentHello.protocolVersion;
458
511
  plainError(`Agent protocol is incompatible (local=${received}, relay=${expected}). Update Chat Relay, then reconnect.`);
459
- setImmediate(() => process.exit(3));
512
+ exitWithFullDrain(3);
460
513
  }
461
514
 
462
515
  function requireReauthorization(reason = "credential_revoked") {
@@ -472,7 +525,7 @@ function requireReauthorization(reason = "credential_revoked") {
472
525
  desktop.close();
473
526
  plainError("Agent credential was revoked or rejected.");
474
527
  plainError('Recovery: run "chat-relay login --force", then "chat-relay remote".');
475
- setImmediate(() => process.exit(2));
528
+ exitWithFullDrain(2);
476
529
  }
477
530
 
478
531
  function connect() {
@@ -495,7 +548,7 @@ function connect() {
495
548
 
496
549
  socket.on("open", () => {
497
550
  if (socket !== activeSocket) return;
498
- socket.send(JSON.stringify(agentHello));
551
+ socket.send(JSON.stringify(fullRuntime ? { ...agentHello, capabilities: [...agentHello.capabilities, ...fullRuntime.capabilities] } : agentHello));
499
552
  connectionState.markConnected();
500
553
  emitUi("connection", { state: "connected", reconnects: connectionState.snapshot().reconnectCount });
501
554
  startHeartbeat(socket);
@@ -529,7 +582,12 @@ function connect() {
529
582
  if (message?.control === "learn_activity") {
530
583
  const activity = message.activity && typeof message.activity === "object" ? message.activity : null;
531
584
  const change = message.change && typeof message.change === "object" ? message.change : null;
585
+ if(monitorEnabled&&activity?.accountId&&activity.accountId!==monitorAccountId)return;
586
+ const learnContext=monitorEnabled&&activity?.accountId===monitorAccountId&&activity.activityId?{accountId:activity.accountId,activityId:activity.activityId}:null;
587
+ const learnSessionId=learnContext?automaticSessions?.lookup(learnContext):null;
532
588
  emitUi("learn", {
589
+ ...(learnContext?{monitorConversationId:learnContext.activityId}:{}),
590
+ ...(learnSessionId?{monitorTaskSessionId:learnSessionId}:{}),
533
591
  ...(activity ? { activity } : {}),
534
592
  ...(change ? { change } : {}),
535
593
  });
@@ -553,17 +611,44 @@ function connect() {
553
611
  const callSummary = humanizeToolCall(message.payload);
554
612
  const uiActivity = describeToolActivity(message.payload, files.getRoots(), recentToolProjects);
555
613
  const requestBytes = Buffer.byteLength(JSON.stringify(message), "utf8");
556
- emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary, ...uiActivity, requestBytes });
614
+ const ownedFull=action==="full.invoke"&&monitorAccountId&&message.payload?.principal?.accountId===monitorAccountId&&message.payload?.principal?.agentId===agentId;
615
+ const autoContext=automaticSessions&&action!=="full.invoke"&&message.autoSession&&(!monitorEnabled||message.autoSession.accountId===monitorAccountId)?message.autoSession:null;
616
+ const autoSessionId=autoContext?automaticSessions.lookup(autoContext):null;
617
+ const pollTarget=ownedFull&&message.payload.operation==="full.job.read"?message.payload.input?.jobId:action==="terminal.read"||action==="terminal.read.compact"?message.payload.sessionId:null;
618
+ const pollOwner=ownedFull?[message.payload.principal.accountId,message.payload.input?.taskSessionId]:autoContext?[autoContext.accountId,autoContext.activityId]:null;
619
+ const monitorPollKey=monitorEnabled&&pollOwner&&typeof pollTarget==="string"&&pollTarget.length>0&&pollTarget.length<=256?createHash("sha256").update(JSON.stringify([pollOwner,pollTarget])).digest("hex").slice(0,24):null;
620
+ const capture=monitorEnabled&&(action!=="full.invoke"||ownedFull)?captureActivityFor(message.payload):null;
621
+ const captured=result=>{try{return finishActivityCapture(capture,message.payload,result);}catch{return null;}};
622
+ emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary, ...uiActivity, requestBytes,
623
+ ...(monitorPollKey?{monitorPollKey}:{}),
624
+ ...(monitorEnabled&&(action!=="full.invoke"||ownedFull)?describeLocalSearch(message.payload):{}),
625
+ ...(ownedFull?{monitorAction:message.payload.operation,monitorOperation:describeFullMonitorActivity(message.payload.operation,message.payload.input),monitorTaskSessionId:message.payload.input?.taskSessionId}:autoSessionId?{monitorTaskSessionId:autoSessionId}:{}) });
626
+ // Automatic attribution never changes the legacy command, its authority,
627
+ // or its workspace. One local ensure is shared by concurrent first calls.
628
+ if(autoContext&&!autoSessionId){
629
+ void automaticSessions.resolve(autoContext).then(id=>{
630
+ if(!id||!monitorActivity)return;
631
+ const callBound=monitorActivity.bindSession(message.requestId,id);
632
+ const learnBound=monitorActivity.bindConversation(autoContext.activityId,id);
633
+ if(callBound||learnBound)fullRuntime?.monitorChanged();
634
+ }).catch(()=>{});
635
+ }
636
+ fullEvents?.publish("tool.accepted", message.requestId, action, message.payload?.observability);
557
637
  let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
558
638
  let handlerDurationMs = 0;
559
639
  try {
560
640
  const schedulingAction = (action === "terminal.read" || action === "terminal.read.compact") && Number(message.payload?.waitMs) > 0
561
641
  ? "terminal.read.wait" : action;
562
- const result = await scheduler.run(schedulingAction, async (meta = {}) => {
642
+ const run=action==="full.invoke"?work=>work({lane:"fullBroker"}):work=>scheduler.run(schedulingAction,work);
643
+ const result = await run(async (meta = {}) => {
563
644
  scheduleMeta = { ...scheduleMeta, ...meta };
564
645
  const handlerStartedAt = Date.now();
565
646
  try {
566
- return await handlePayload(message.payload);
647
+ const effect=!!fullRuntime&&LEGACY_EFFECTS.has(action);
648
+ if(effect&&fullRuntime.blocksLegacyEffects())return {ok:false,error:"full_scoped_effect_active"};
649
+ if(effect)legacyEffectsInFlight++;
650
+ try{return await runActivityCapture(capture,()=>handlePayload(message.payload,{requestId:message.requestId,requestBytes}));}
651
+ finally{if(effect)legacyEffectsInFlight--;}
567
652
  } finally {
568
653
  handlerDurationMs = Math.max(0, Date.now() - handlerStartedAt);
569
654
  }
@@ -595,14 +680,23 @@ function connect() {
595
680
  };
596
681
  const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, result, responseMeta), "utf8");
597
682
  try { usage.record({ ...recentEntry, requestBytes, responseBytes }, message.payload, result); } catch {}
683
+ const activityDetails=captured(result);
684
+ const partialFailure=activityDetails?.files.some(file=>file.outcome==="failed")||ownedFull&&result?.result?.ok===false;
598
685
  emitUi("tool:end", {
599
686
  requestId: message.requestId,
600
687
  action,
601
688
  summary: callSummary,
602
- ok: !(result && typeof result === "object" && result.ok === false),
689
+ ok: !(result && typeof result === "object" && result.ok === false)&&!partialFailure,
603
690
  durationMs: Date.now() - startedAt,
604
691
  responseBytes,
605
- ...(result && typeof result === "object" && result.ok === false && result.error ? { error: String(result.error) } : {}),
692
+ ...(result && typeof result === "object" && result.ok === false && result.error ? { error: String(result.error) } : partialFailure?{error:"partial_failure"}:{}),
693
+ },activityDetails);
694
+ if(action==="full.invoke"&&message.payload.operation==="full.session.delete"&&result?.ok===true&&result.result?.acknowledged===true){
695
+ automaticSessions?.forget(message.payload.principal.accountId,message.payload.input.taskSessionId);
696
+ if(ownedFull)monitorActivity?.forgetSession(message.payload.input.taskSessionId);
697
+ }
698
+ fullEvents?.publish("tool.completed", message.requestId, action, message.payload?.observability, {
699
+ ok: !(result && typeof result === "object" && result.ok === false), durationMs: Date.now() - startedAt,
606
700
  });
607
701
  const advised = result && typeof result === "object" && result.ok === false && result.error
608
702
  ? { ...result, ...toolErrorGuidance(action, String(result.error), message.payload) }
@@ -634,7 +728,8 @@ function connect() {
634
728
  durationMs: Date.now() - startedAt,
635
729
  responseBytes,
636
730
  error: errorPayload.error,
637
- });
731
+ },captured(errorPayload));
732
+ fullEvents?.publish("tool.completed", message.requestId, action, message.payload?.observability, { ok: false, durationMs: Date.now() - startedAt });
638
733
  sendSocketResponse(socket, message.requestId, { ...errorPayload, ...toolErrorGuidance(action, errorPayload.error, message.payload) });
639
734
  }
640
735
  });
@@ -690,7 +785,7 @@ function restartAgentProcess() {
690
785
  try { socket?.close(1012, "restart_requested"); } catch {}
691
786
  terminals.close();
692
787
  desktop.close();
693
- setTimeout(() => process.exit(AGENT_RESTART_EXIT_CODE), 50);
788
+ exitWithFullDrain(AGENT_RESTART_EXIT_CODE, 50);
694
789
  }
695
790
 
696
791
  function upgradeAgentProcess() {
@@ -704,7 +799,7 @@ function upgradeAgentProcess() {
704
799
  try { socket?.close(1012, "upgrade_requested"); } catch {}
705
800
  terminals.close();
706
801
  desktop.close();
707
- setTimeout(() => process.exit(AGENT_UPGRADE_EXIT_CODE), 50);
802
+ exitWithFullDrain(AGENT_UPGRADE_EXIT_CODE, 50);
708
803
  }
709
804
 
710
805
  function shutdown(reason) {
@@ -718,11 +813,69 @@ function shutdown(reason) {
718
813
  try { socket?.close(1000, "client_shutdown"); } catch {}
719
814
  terminals.close();
720
815
  desktop.close();
721
- setTimeout(() => process.exit(0), 50);
816
+ exitWithFullDrain(0, 50);
817
+ }
818
+
819
+ function exitWithFullDrain(code,delay=0) {
820
+ if(!fullRuntime&&!fullStarting){if(delay)setTimeout(()=>process.exit(code),delay);else setImmediate(()=>process.exit(code));return;}
821
+ void (async()=>{
822
+ try {
823
+ const runtime=fullRuntime??await fullStarting;
824
+ const result=await runtime.dispose();
825
+ if(!result?.confirmed||result.code!==0||result.forced){
826
+ plainError("Full shutdown requires guarded recovery before further scoped writes.");
827
+ process.exit(FULL_STARTUP_EXIT_CODE);
828
+ }
829
+ }catch{process.exit(FULL_STARTUP_EXIT_CODE);}
830
+ process.exit(code);
831
+ })();
722
832
  }
723
833
 
724
834
  process.once("SIGINT", () => shutdown("SIGINT"));
725
835
  process.once("SIGTERM", () => shutdown("SIGTERM"));
726
- process.once("exit", () => { usage.close(); terminals.close(); desktop.close(); });
727
-
728
- connect();
836
+ process.once("exit", () => { fullEvents?.close(); usage.close(); terminals.close(); desktop.close(); });
837
+
838
+ if(fullBootstrap){
839
+ // Runner IPC is private to the parent/child pair, not the relay socket.
840
+ let desktopOpening=false;
841
+ process.on("message",message=>{
842
+ if(message?.type==="chat-relay-runner"&&message.command==="shutdown"){shutdown("runner_shutdown");return;}
843
+ if(message?.type!=="chat-relay-full-desktop"||message.kind!=="open"||
844
+ typeof message.requestId!=="string"||!/^[a-f0-9-]{36}$/.test(message.requestId)||
845
+ typeof message.accountId!=="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(message.accountId)||
846
+ Object.keys(message).some(key=>!["type","kind","requestId","accountId"].includes(key)))return;
847
+ const reply=result=>{if(process.connected)try{
848
+ process.send({type:"chat-relay-full-desktop",kind:"result",requestId:message.requestId,...result},()=>{});
849
+ }catch{}};
850
+ if(stopping||reauthorizationRequired||desktopOpening){reply({ok:false,error:"full_unavailable"});return;}
851
+ desktopOpening=true;
852
+ void (async()=>{
853
+ const runtime=fullRuntime??await fullStarting;
854
+ if(stopping||reauthorizationRequired||!runtime?.available)throw Object.assign(new Error("full_unavailable"),{code:"full_unavailable"});
855
+ const result=await runtime.openDesktop({accountId:message.accountId});
856
+ reply({ok:true,alreadyOpen:result.alreadyOpen});
857
+ })().catch(error=>reply({ok:false,error:typeof error?.code==="string"&&/^full_[a-z0-9_]+$/.test(error.code)?error.code:"full_desktop_reopen_unavailable"}))
858
+ .finally(()=>{desktopOpening=false;});
859
+ });
860
+ process.once("disconnect",()=>shutdown("runner_disconnected"));
861
+ const desktopAuthorization=fullBootstrap.headless?null:createParentAuthorizationClient();
862
+ if(desktopAuthorization)process.once("exit",()=>desktopAuthorization.close());
863
+ try {
864
+ 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=>{
865
+ if(stopping||reauthorizationRequired)return;
866
+ plainError("Full host: "+state.state+" ("+state.reason+"). Core remains connected; unknown effects remain fenced.");
867
+ if(activeSocket?.readyState===WebSocket.OPEN)try{activeSocket.send(JSON.stringify({...agentHello,capabilities:[...agentHello.capabilities,...(fullRuntime?.capabilities??[])]}));}catch{}
868
+ }});
869
+ fullRuntime=await fullStarting;
870
+ fullStarting=null;
871
+ fullBootstrap=null;
872
+ if(!fullRuntime.available&&!stopping)throw new Error("full_unavailable");
873
+ if(monitorEnabled&&process.connected&&fullRuntime.desktopStatus?.state==="running"){
874
+ try{process.send({type:"chat-relay-runner",event:"full-gui-ready"},()=>{});}catch{}
875
+ }
876
+ } catch(error) {
877
+ plainError("Full runtime unavailable: "+(typeof error?.code==="string"?error.code:"full_startup_failed")+". No Core fallback was started.");
878
+ process.exit(FULL_STARTUP_EXIT_CODE);
879
+ }
880
+ }
881
+ if(!stopping&&!reauthorizationRequired)connect();
@@ -196,6 +196,27 @@ export class LocalUsageHistory {
196
196
  return this.page(limit).calls.map(({ seq, ...entry }) => entry);
197
197
  }
198
198
 
199
+ // Opt-in Full diagnostics: the existing Lite API and stored counters are
200
+ // unchanged. Never forward humanized summaries, errors, paths or arguments.
201
+ diagnosticSnapshot(limit = 50) {
202
+ const count = Math.min(100, Math.max(1, Math.trunc(Number(limit) || 50)));
203
+ const rows = [];
204
+ const oldest = Math.max(this.nextSeq - this.retained, this.nextSeq - count);
205
+ for (let seq = oldest; seq < this.nextSeq; seq++) {
206
+ const entry = this.ring[(seq - 1) % RECENT_CALL_CAPACITY];
207
+ if (!entry) continue;
208
+ const ms = v => Number.isFinite(v) && v >= 0 ? v : null;
209
+ const totalMs = ms(entry.durationMs), queueMs = ms(entry.queueWaitMs), handlerMs = ms(entry.handlerDurationMs);
210
+ const residualMs = totalMs !== null && queueMs !== null && handlerMs !== null && totalMs >= queueMs + handlerMs
211
+ ? totalMs - queueMs - handlerMs : null;
212
+ rows.push({ seq, action: actionKey(entry.action), ok: typeof entry.ok === "boolean" ? entry.ok : null,
213
+ // Existing Core durations use Date.now; do not relabel them as monotonic.
214
+ timing: { source: "core-wall-clock-reported", totalMs, queueMs, handlerMs, residualMs },
215
+ requestBytes: ms(entry.requestBytes), responseBytes: ms(entry.responseBytes) });
216
+ }
217
+ return { historyEpoch: this.epoch, oldestSeq: oldest, newestSeq: this.nextSeq - 1, rows, omitted: this.retained - rows.length };
218
+ }
219
+
199
220
  stats(requestedDays = RETENTION_DAYS) {
200
221
  const now = this.now();
201
222
  this.#prune(now);
@@ -0,0 +1,135 @@
1
+ import {humanizeToolCall} from "./toolcall-summary.mjs";
2
+ import {activityIcon} from "./toolcall-context.mjs";
3
+ import {historicalDiff,projectActivityDetails,displayActivityPath,activityChangeTotals} from "./activity-capture.mjs";
4
+ import {monitorActivityId,normalizeLearnMonitorMetadata} from "../packages/full-contracts/monitor-metadata.mjs";
5
+
6
+ // The local monitor reuses Core's TUI activity projection. One bounded row per
7
+ // request (not one per start/end); never retain raw request bodies or output.
8
+ export const MAX_MONITOR_ROWS=100;
9
+ const DETAIL_TTL_MS=15*60*1000;
10
+ const clean=(value,n)=>typeof value==="string"?value.replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim().slice(0,n).toWellFormed():"";
11
+ const code=value=>typeof value==="string"&&/^[A-Za-z0-9_.:-]{1,100}$/.test(value)?value:"tool";
12
+ const detailed=new Set(["fs.read","fs.write","fs.edit","fs.delete","fs.stat","fs.list","fs.readMany","fs.readMany.relative","fs.editMany","fs.batch","fs.batch.compact","terminal.exec","terminal.exec.compact","terminal.batch.start","terminal.batch.read","terminal.batch.read.compact","terminal.batch.status","terminal.read","terminal.read.compact","terminal.list"]);
13
+ const learnLabels={learn_prepare:"Load relevant Learn context",learn_get:"Read Learn memories",learn_put:"Update Learn memory",learn_delete:"Delete Learn memory",learn_feedback:"Rate Learn memory",learn_usage_report:"Report Learn usage"};
14
+
15
+ // Safe bounded metadata; never expose raw commands, search terms, edit bodies or output.
16
+ export function describeFullMonitorActivity(action,input={}){
17
+ input=input&&typeof input==="object"?input:{};
18
+ const name=value=>clean((typeof value==="string"?value:"").replace(/\\/g,"/").split("/").filter(Boolean).at(-1),90);
19
+ const count=value=>Array.isArray(value)?value.length:0;
20
+ const files=(verb,values)=>{
21
+ const paths=Array.isArray(values)?[...new Set(values.filter(v=>typeof v==="string"&&v.length>0))]:[];
22
+ return paths.length===1?verb+" "+(name(paths[0])||"file"):paths.length?verb+" "+paths.length+" files":verb+" files";
23
+ };
24
+ switch(action){
25
+ case "full.workspace.read":return files("Read",input.relativePaths??[input.relativePath]);
26
+ case "full.workspace.edit":return files("Edit",(Array.isArray(input.operations)?input.operations:[]).map(o=>o?.relativePath??o?.path));
27
+ case "full.intelligence.refresh":return "Refresh code index";
28
+ case "full.intelligence.context":return "Read task context";
29
+ case "full.intelligence.acknowledge":return "Acknowledge task context";
30
+ case "full.intelligence.search":return "Search code index";
31
+ case "full.intelligence.symbols":return "Find code symbols";
32
+ case "full.intelligence.dependencies":return "Inspect dependencies";
33
+ case "full.intelligence.impact":return "Review affected code";
34
+ case "full.session.ensure":return "Prepare task session";
35
+ case "full.session.list":return "List task sessions";
36
+ case "full.session.snapshot":return "Read task session";
37
+ case "full.session.delete":return "Remove task session";
38
+ case "full.session.acknowledge":return "Acknowledge session history";
39
+ case "full.session.export":return "Export task session";
40
+ case "full.task.checkpoint":return "Save task checkpoint";
41
+ case "full.task.plan":return "Update task plan";
42
+ case "full.task.phase":return "Update task phase";
43
+ case "full.task.narrative":return "Update task progress";
44
+ case "full.task.status":return "Update task status";
45
+ case "full.workspace.ensure":return "Prepare task workspace";
46
+ case "full.job.start":return "Start background command";
47
+ case "full.job.read":return "Read job output";
48
+ case "full.job.status":return "Check job status";
49
+ case "full.job.cancel":return "Cancel job";
50
+ case "full.job.reconcile":return "Reconcile job state";
51
+ case "full.verification.plan":return "Plan verification";
52
+ case "full.verification.record":return "Record verification";
53
+ case "full.verification.assess":return "Assess verification";
54
+ case "full.desktop.step":return "Desktop actions · "+count(input.actions)+" steps";
55
+ case "full.desktop.windows":return "List open windows";
56
+ case "full.diagnostics.snapshot":return "Read task diagnostics";
57
+ case "full.diagnostics.mode":return "Change diagnostic mode";
58
+ case "full.diagnostics.export":return "Export diagnostics";
59
+ default:return humanizeToolCall({action});
60
+ }
61
+ }
62
+ const bytes=value=>Number.isSafeInteger(value)&&value>=0?value:null;
63
+ const safeError=value=>typeof value==="string"&&/^[a-z][a-z0-9_]{1,95}$/.test(value)?value:"";
64
+
65
+ export function createMonitorActivity({now=()=>new Date()}={}){
66
+ const rows=new Map(),running=new Set(),details=new Map();
67
+ const localTime=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});
68
+ let calls=0,errors=0,learnEvents=0,sequence=0;
69
+ const remember=(key,row)=>{rows.set(key,row);while(rows.size>MAX_MONITOR_ROWS){const first=rows.keys().next().value;details.delete(rows.get(first).requestId);rows.delete(first);}};
70
+ const stamp=()=>{const at=now();return {at:at.toISOString(),time:localTime.format(at)};};
71
+ const prune=()=>{const cutoff=now().getTime()-DETAIL_TTL_MS;for(const row of rows.values())if(Date.parse(row.at)<cutoff)details.delete(row.requestId);};
72
+ return {
73
+ accept(event,payload={}){
74
+ if(event==="tool:start"){
75
+ const key=payload.requestId;
76
+ if(typeof key!=="string"||running.has(key))return;
77
+ calls++;running.add(key);
78
+ const action=code(payload.monitorAction??payload.action),category=action.startsWith("full.")?"Full":clean(payload.category,32)||"Agent";
79
+ // The TUI's descriptive operations are reused only for known routes
80
+ // that do not embed arbitrary request data. Search/filter and unknown
81
+ // arguments are deliberately not forwarded.
82
+ const label=action.startsWith("full.")?clean(payload.monitorOperation,128)||describeFullMonitorActivity(action):action==="fs.artifact"?("Export "+(displayActivityPath(payload.detail).split("/").at(-1)||"file")):action==="terminal.start"?"Start background task":action.startsWith("fs.search.")?(action==="fs.search.start"?"Search project files":"Read search results"):detailed.has(action)?clean(payload.operation,128):humanizeToolCall({action});
83
+ remember(key,{requestId:"monitor-"+(++sequence),...stamp(),action,category,icon:activityIcon({action,category,operation:label})||(category==="Full"?"⚙":"·"),operation:label||humanizeToolCall({action}),project:clean(payload.project,64),taskSessionId:typeof payload.monitorTaskSessionId==="string"?code(payload.monitorTaskSessionId):null,status:"running",ok:null,durationMs:null,requestBytes:bytes(payload.requestBytes),responseBytes:null,error:"",pollKey:typeof payload.monitorPollKey==="string"&&/^[a-f0-9]{24}$/.test(payload.monitorPollKey)?payload.monitorPollKey:null,query:clean(payload.query,180),searchScope:clean(payload.searchScope,180),detail:detailed.has(action)?clean(payload.detail,160):""});
84
+ }else if(event==="tool:end"){
85
+ const key=payload.requestId;if(!running.delete(key))return;
86
+ const exitFailed=Number.isInteger(payload.activityDetails?.exitCode)&&payload.activityDetails.exitCode!==0;
87
+ const failed=payload.ok===false||exitFailed;
88
+ if(failed)errors++;
89
+ const row=rows.get(key);if(row){
90
+ if(payload.activityDetails){
91
+ details.set(row.requestId,payload.activityDetails);
92
+ const totals=activityChangeTotals(payload.activityDetails);
93
+ if(totals)Object.assign(row,totals);
94
+ }
95
+ Object.assign(row,{status:payload.status==="cancelled"?"cancelled":failed?"failed":"done",ok:!failed,durationMs:bytes(payload.durationMs)===null?null:Math.min(86400000,payload.durationMs),responseBytes:bytes(payload.responseBytes),error:safeError(payload.error)||(exitFailed?"command_exit_nonzero":"")});
96
+ }
97
+ }else if(event==="learn"){
98
+ learnEvents++;
99
+ const activity=payload.activity??{},tool=code(activity.tool);
100
+ const change=activity.change??{},rowId="learn-"+(++sequence),metadata=activity.ok===false?null:normalizeLearnMonitorMetadata(activity.metadata);
101
+ const retrieved=metadata?.retrieved;
102
+ const operation=retrieved!==undefined?(tool==="learn_get"?"Read ":"Load ")+retrieved+(retrieved===1?" Learn memory":" Learn memories"):learnLabels[tool]||"Learn activity";
103
+ const detail=metadata?.evaluated!==undefined?metadata.evaluated+" evaluated · "+metadata.applied+" applied · "+metadata.verified+" verified":[clean(change.key,100),clean(change.scope??activity.scopeSummary,50)].filter(Boolean).join(" · ");
104
+ remember(rowId,{requestId:rowId,...stamp(),conversationId:monitorActivityId(payload.monitorConversationId),taskSessionId:typeof payload.monitorTaskSessionId==="string"?code(payload.monitorTaskSessionId):null,action:"learn",category:"Learn",icon:"🧠",operation,project:clean(change.scope==="project"?change.scopeKey:activity.projectKey,64),detail,status:activity.ok===false?"failed":"done",ok:activity.ok!==false,durationMs:bytes(activity.durationMs)});
105
+ if(retrieved!==undefined&&retrieved>0)details.set(rowId,{files:[],omitted:0,learn:metadata});
106
+ }else return false;
107
+ return true;
108
+ },
109
+ snapshot(){prune();const current=now().getTime();return {calls,errors,active:running.size,learnEvents,activity:[...rows.values()].slice(-MAX_MONITOR_ROWS).map(({conversationId,...row})=>({...row,elapsedMs:row.status==="running"?Math.max(0,current-Date.parse(row.at)):null,hasDetails:details.has(row.requestId)}))};},
110
+ bindSession(requestId,taskSessionId){
111
+ const row=rows.get(requestId);
112
+ if(!row||row.taskSessionId||typeof taskSessionId!=="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(taskSessionId))return false;
113
+ row.taskSessionId=taskSessionId;return true;
114
+ },
115
+ bindConversation(conversationId,taskSessionId){
116
+ if(!monitorActivityId(conversationId)||typeof taskSessionId!=="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(taskSessionId))return false;
117
+ let changed=false;
118
+ for(const row of rows.values())if(row.conversationId===conversationId&&!row.taskSessionId){row.taskSessionId=taskSessionId;changed=true;}
119
+ return changed;
120
+ },
121
+ forgetSession(taskSessionId){
122
+ for(const [key,row] of rows){if(row.taskSessionId===taskSessionId){details.delete(row.requestId);rows.delete(key);}}
123
+ },
124
+ detail(activityId,fileId){
125
+ prune();
126
+ const row=[...rows.values()].find(item=>item.requestId===activityId);
127
+ const detail=row?details.get(activityId):null;
128
+ if(fileId!==undefined){
129
+ const file=detail?.files.find(f=>f.fileId===fileId);
130
+ return {activityId,fileId,...historicalDiff(file?.pair)};
131
+ }
132
+ return {activityId,...projectActivityDetails(detail),...(detail?.learn?{learn:detail.learn}:{})};
133
+ }
134
+ };
135
+ }
@@ -0,0 +1,10 @@
1
+ const text=(v,n=512)=>typeof v==="string"?v.slice(0,n).toWellFormed():"";
2
+ export function redactPresentationText(value,max=12000){
3
+ // Best-effort display redaction, not a claim to recognize arbitrary secrets.
4
+ return text(value,max).replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[private key redacted]")
5
+ .replace(/\b(Bearer\s+)[A-Za-z0-9._~+\/-]+/gi,"$1[redacted]")
6
+ .replace(/\b((?:password|passwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|authorization)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,"$1[redacted]")
7
+ .replace(/\b(sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,})\b/g,"[credential redacted]")
8
+ .replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@")
9
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"");
10
+ }
@@ -1,4 +1,5 @@
1
1
  import { execFile } from "node:child_process";
2
+ import fs from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import os from "node:os";
4
5
 
@@ -85,6 +86,37 @@ export class ProcessManager {
85
86
  throw new Error("unsupported_platform");
86
87
  }
87
88
 
89
+ // A PID alone is not an identity. This is observation only; no new privilege
90
+ // or termination authority is created for the Full runtime.
91
+ async inspectIdentity(pid) {
92
+ if(!Number.isSafeInteger(pid)||pid<=0)return {state:"unknown"};
93
+ try {
94
+ if(this.platform==="win32"){
95
+ const stdout=await execPowerShell("$ErrorActionPreference='Stop'; $p=Get-CimInstance Win32_Process -Filter 'ProcessId = "+pid+"'; if($p){$p.CreationDate.ToUniversalTime().ToString('o')}");
96
+ const birth=stdout.trim();
97
+ return birth?{state:"present",pid,scheme:"windows-creation-time",birth}:{state:"absent",pid};
98
+ }
99
+ if(this.platform==="linux"){
100
+ try{
101
+ const stat=await fs.readFile("/proc/"+pid+"/stat","utf8");
102
+ const boot=await fs.readFile("/proc/sys/kernel/random/boot_id","utf8").catch(()=>null);
103
+ if(!boot)return {state:"unknown",pid};
104
+ const close=stat.lastIndexOf(")");
105
+ const birth=stat.slice(close+2).trim().split(/\s+/)[19];
106
+ if(close<0||!/^\d+$/.test(birth??"")||!boot.trim())return {state:"unknown",pid};
107
+ return {state:"present",pid,scheme:"linux-boot-start-ticks",birth:boot.trim()+":"+birth};
108
+ }catch(error){if(error.code==="ENOENT"||error.code==="ESRCH")return {state:"absent",pid};throw error;}
109
+ }
110
+ if(this.platform==="darwin"){
111
+ const birth=(await execCommand("/bin/ps",["-p",String(pid),"-o","lstart="])).trim();
112
+ // Coarse precision: insufficient by itself for destructive PID-based
113
+ // operations or a full descendant-tree proof.
114
+ return birth?{state:"present",pid,scheme:"posix-lstart-coarse",birth}:{state:"unknown",pid};
115
+ }
116
+ }catch{}
117
+ return {state:"unknown",pid};
118
+ }
119
+
88
120
  async kill(pid) {
89
121
  const value = Number(pid);
90
122
  if (!Number.isInteger(value) || value <= 100 || value === process.pid) {