@anusornneal/chat-relay 1.9.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 (50) hide show
  1. package/README.md +6 -0
  2. package/agent/activity-capture.mjs +165 -0
  3. package/agent/capability-scheduler.mjs +82 -5
  4. package/agent/file-manager.mjs +8 -3
  5. package/agent/full-bridge.mjs +53 -0
  6. package/agent/full-desktop-actions.mjs +124 -0
  7. package/agent/full-desktop-auth.mjs +53 -0
  8. package/agent/full-desktop-broker.mjs +308 -0
  9. package/agent/full-host.mjs +153 -0
  10. package/agent/full-job-broker.mjs +360 -0
  11. package/agent/full-native-job.mjs +205 -0
  12. package/agent/full-presentation-changes.mjs +191 -0
  13. package/agent/full-remote-diagnostics.mjs +129 -0
  14. package/agent/full-resources.mjs +343 -0
  15. package/agent/full-runtime-supervisor.mjs +67 -0
  16. package/agent/full-session-dispatch.mjs +167 -0
  17. package/agent/full-workspace-broker.mjs +290 -0
  18. package/agent/git-worktree-manager.mjs +170 -4
  19. package/agent/lifecycle.mjs +11 -0
  20. package/agent/local-agent.mjs +150 -24
  21. package/agent/local-usage.mjs +21 -0
  22. package/agent/monitor-activity.mjs +111 -0
  23. package/agent/presentation-redaction.mjs +10 -0
  24. package/agent/process-manager.mjs +32 -0
  25. package/agent/terminal-manager.mjs +189 -31
  26. package/agent/toolcall-context.mjs +23 -1
  27. package/agent/windows-desktop-runner.mjs +65 -61
  28. package/agent/windows-desktop-worker.ps1 +33 -18
  29. package/agent/windows-powershell.mjs +51 -0
  30. package/cli/full-background.mjs +69 -0
  31. package/cli/full-launch.mjs +94 -0
  32. package/cli/full-prepare-child.mjs +48 -0
  33. package/cli/full-prepare.mjs +171 -0
  34. package/cli/full-release-default.json +4 -0
  35. package/cli/full-release-files.mjs +36 -0
  36. package/cli/full-release-official.mjs +48 -0
  37. package/cli/full-release-source.mjs +37 -0
  38. package/cli/index.mjs +8 -4
  39. package/cli/mod-cache.mjs +170 -0
  40. package/cli/mod-loader.mjs +67 -0
  41. package/cli/mod-manifest.mjs +63 -0
  42. package/cli/remote.mjs +172 -17
  43. package/cli/runner-ownership.mjs +116 -3
  44. package/cli/self-update.mjs +1 -1
  45. package/cli/tui.mjs +2 -20
  46. package/package.json +5 -3
  47. package/packages/full-contracts/index.mjs +193 -0
  48. package/packages/full-contracts/native-job.mjs +13 -0
  49. package/packages/full-contracts/package.json +7 -0
  50. package/packages/full-contracts/remote-session.mjs +239 -0
@@ -8,6 +8,10 @@ import { TerminalManager } from "./terminal-manager.mjs";
8
8
  import { CapabilityScheduler } from "./capability-scheduler.mjs";
9
9
  import { AgentConnectionState, safeConnectionReason } from "./connection-state.mjs";
10
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";
11
15
  import {
12
16
  AgentLifecycle,
13
17
  AGENT_RESTART_EXIT_CODE,
@@ -16,6 +20,8 @@ import {
16
20
  } from "./lifecycle.mjs";
17
21
  import { humanizeToolCall } from "./toolcall-summary.mjs";
18
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";
19
25
  import { toolErrorGuidance } from "./tool-error-guidance.mjs";
20
26
  import {
21
27
  HeartbeatAckWatchdog,
@@ -30,8 +36,30 @@ const reconnectMs = Number(process.env.RECONNECT_MS ?? 2000);
30
36
  const terminalEnabled = process.env.TERMINAL_ENABLED === "1";
31
37
  const desktopEnabled = process.env.DESKTOP_ENABLED === "1";
32
38
  const ipcUiEnabled = process.env.CHAT_RELAY_UI === "ipc";
33
-
34
- 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
+ }
35
63
  if (!ipcUiEnabled || typeof process.send !== "function") return;
36
64
  try { process.send({ type: "chat-relay-ui", event, at: new Date().toISOString(), ...payload }); } catch {}
37
65
  }
@@ -41,10 +69,7 @@ function plainLog(...args) {
41
69
  }
42
70
 
43
71
  function plainError(...args) {
44
- if (!ipcUiEnabled) {
45
- console.error(...args);
46
- return;
47
- }
72
+ if (!ipcUiEnabled) console.error(...args);
48
73
  emitUi("system", { level: "error", message: args.map((item) => String(item)).join(" ") });
49
74
  }
50
75
  const desktopAdapter = createDesktopPlatformAdapter({ platform: process.platform });
@@ -62,6 +87,7 @@ const terminals = new TerminalManager({
62
87
  fastExecIdleMs: process.env.TERMINAL_FAST_EXEC_IDLE_MS,
63
88
  });
64
89
  const scheduler = new CapabilityScheduler({
90
+ full:!!fullBootstrap,
65
91
  maxQueued: process.env.AGENT_MAX_QUEUED,
66
92
  queueTimeoutMs: process.env.AGENT_QUEUE_TIMEOUT_MS,
67
93
  fileConcurrency: process.env.AGENT_FILE_CONCURRENCY,
@@ -128,12 +154,25 @@ const heartbeatAckWatchdog = new HeartbeatAckWatchdog({
128
154
  },
129
155
  });
130
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
+ }
131
169
  function currentWorkSummary() {
132
- return summarizeAgentWork({
170
+ const work=summarizeAgentWork({
133
171
  terminal: terminals.observability(),
134
172
  scheduler: scheduler.snapshot(),
135
173
  desktop: desktop.getConfig(),
136
174
  });
175
+ return fullRuntime?{...work,activeFullRequests:fullRuntime.pending}:work;
137
176
  }
138
177
 
139
178
  const lifecycle = new AgentLifecycle({ workSummary: currentWorkSummary });
@@ -159,9 +198,16 @@ function serializeResponse(requestId, payload, meta) {
159
198
  });
160
199
  }
161
200
 
162
- async function handlePayload(payload) {
201
+ async function handlePayload(payload, metadata) {
163
202
  if (!payload || typeof payload !== "object") return payload;
164
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();
165
211
  const lifecycleGate = lifecycle.guard(action);
166
212
  if (lifecycleGate) return lifecycleGate;
167
213
 
@@ -183,6 +229,7 @@ async function handlePayload(payload) {
183
229
  connection: { ...connectionState.snapshot(), processId: process.pid },
184
230
  heartbeatAckWatchdog: heartbeatAckWatchdog.snapshot(),
185
231
  lifecycle: lifecycle.snapshot(),
232
+ ...(fullRuntime?{full:fullRuntime.status}:{}),
186
233
  terminalContinuity: {
187
234
  processId: process.pid,
188
235
  ...terminals.getContinuityConfig(),
@@ -192,7 +239,7 @@ async function handlePayload(payload) {
192
239
  agentVersion: agentHello.agentVersion,
193
240
  platform: agentHello.platform,
194
241
  arch: agentHello.arch,
195
- capabilities: agentHello.capabilities,
242
+ capabilities: fullRuntime ? [...agentHello.capabilities, ...fullRuntime.capabilities] : agentHello.capabilities,
196
243
  },
197
244
  });
198
245
  case "agent.recentCalls":
@@ -213,6 +260,9 @@ async function handlePayload(payload) {
213
260
  return result;
214
261
  }
215
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"};
216
266
  const result = lifecycle.requestUpgrade();
217
267
  if (result.ok) setTimeout(upgradeAgentProcess, 150);
218
268
  return result;
@@ -456,7 +506,7 @@ function requireProtocolUpdate(details = {}) {
456
506
  const expected = details.expectedProtocolVersion ?? "current";
457
507
  const received = details.receivedProtocolVersion ?? agentHello.protocolVersion;
458
508
  plainError(`Agent protocol is incompatible (local=${received}, relay=${expected}). Update Chat Relay, then reconnect.`);
459
- setImmediate(() => process.exit(3));
509
+ exitWithFullDrain(3);
460
510
  }
461
511
 
462
512
  function requireReauthorization(reason = "credential_revoked") {
@@ -472,7 +522,7 @@ function requireReauthorization(reason = "credential_revoked") {
472
522
  desktop.close();
473
523
  plainError("Agent credential was revoked or rejected.");
474
524
  plainError('Recovery: run "chat-relay login --force", then "chat-relay remote".');
475
- setImmediate(() => process.exit(2));
525
+ exitWithFullDrain(2);
476
526
  }
477
527
 
478
528
  function connect() {
@@ -495,7 +545,7 @@ function connect() {
495
545
 
496
546
  socket.on("open", () => {
497
547
  if (socket !== activeSocket) return;
498
- socket.send(JSON.stringify(agentHello));
548
+ socket.send(JSON.stringify(fullRuntime ? { ...agentHello, capabilities: [...agentHello.capabilities, ...fullRuntime.capabilities] } : agentHello));
499
549
  connectionState.markConnected();
500
550
  emitUi("connection", { state: "connected", reconnects: connectionState.snapshot().reconnectCount });
501
551
  startHeartbeat(socket);
@@ -553,17 +603,28 @@ function connect() {
553
603
  const callSummary = humanizeToolCall(message.payload);
554
604
  const uiActivity = describeToolActivity(message.payload, files.getRoots(), recentToolProjects);
555
605
  const requestBytes = Buffer.byteLength(JSON.stringify(message), "utf8");
556
- 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);
557
613
  let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
558
614
  let handlerDurationMs = 0;
559
615
  try {
560
616
  const schedulingAction = (action === "terminal.read" || action === "terminal.read.compact") && Number(message.payload?.waitMs) > 0
561
617
  ? "terminal.read.wait" : action;
562
- 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 = {}) => {
563
620
  scheduleMeta = { ...scheduleMeta, ...meta };
564
621
  const handlerStartedAt = Date.now();
565
622
  try {
566
- 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--;}
567
628
  } finally {
568
629
  handlerDurationMs = Math.max(0, Date.now() - handlerStartedAt);
569
630
  }
@@ -595,14 +656,20 @@ function connect() {
595
656
  };
596
657
  const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, result, responseMeta), "utf8");
597
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;
598
661
  emitUi("tool:end", {
599
662
  requestId: message.requestId,
600
663
  action,
601
664
  summary: callSummary,
602
- ok: !(result && typeof result === "object" && result.ok === false),
665
+ ok: !(result && typeof result === "object" && result.ok === false)&&!partialFailure,
603
666
  durationMs: Date.now() - startedAt,
604
667
  responseBytes,
605
- ...(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,
606
673
  });
607
674
  const advised = result && typeof result === "object" && result.ok === false && result.error
608
675
  ? { ...result, ...toolErrorGuidance(action, String(result.error), message.payload) }
@@ -634,7 +701,8 @@ function connect() {
634
701
  durationMs: Date.now() - startedAt,
635
702
  responseBytes,
636
703
  error: errorPayload.error,
637
- });
704
+ },captured(errorPayload));
705
+ fullEvents?.publish("tool.completed", message.requestId, action, message.payload?.observability, { ok: false, durationMs: Date.now() - startedAt });
638
706
  sendSocketResponse(socket, message.requestId, { ...errorPayload, ...toolErrorGuidance(action, errorPayload.error, message.payload) });
639
707
  }
640
708
  });
@@ -690,7 +758,7 @@ function restartAgentProcess() {
690
758
  try { socket?.close(1012, "restart_requested"); } catch {}
691
759
  terminals.close();
692
760
  desktop.close();
693
- setTimeout(() => process.exit(AGENT_RESTART_EXIT_CODE), 50);
761
+ exitWithFullDrain(AGENT_RESTART_EXIT_CODE, 50);
694
762
  }
695
763
 
696
764
  function upgradeAgentProcess() {
@@ -704,7 +772,7 @@ function upgradeAgentProcess() {
704
772
  try { socket?.close(1012, "upgrade_requested"); } catch {}
705
773
  terminals.close();
706
774
  desktop.close();
707
- setTimeout(() => process.exit(AGENT_UPGRADE_EXIT_CODE), 50);
775
+ exitWithFullDrain(AGENT_UPGRADE_EXIT_CODE, 50);
708
776
  }
709
777
 
710
778
  function shutdown(reason) {
@@ -718,11 +786,69 @@ function shutdown(reason) {
718
786
  try { socket?.close(1000, "client_shutdown"); } catch {}
719
787
  terminals.close();
720
788
  desktop.close();
721
- 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
+ })();
722
805
  }
723
806
 
724
807
  process.once("SIGINT", () => shutdown("SIGINT"));
725
808
  process.once("SIGTERM", () => shutdown("SIGTERM"));
726
- process.once("exit", () => { usage.close(); terminals.close(); desktop.close(); });
727
-
728
- 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();
@@ -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,111 @@
1
+ import {humanizeToolCall} from "./toolcall-summary.mjs";
2
+ import {activityIcon} from "./toolcall-context.mjs";
3
+ import {historicalDiff,projectActivityDetails} from "./activity-capture.mjs";
4
+
5
+ // The local monitor reuses Core's TUI activity projection. One bounded row per
6
+ // request (not one per start/end); never retain raw request bodies or output.
7
+ const MAX_ROWS=40,DETAIL_TTL_MS=15*60*1000;
8
+ const clean=(value,n)=>typeof value==="string"?value.replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim().slice(0,n).toWellFormed():"";
9
+ const code=value=>typeof value==="string"&&/^[A-Za-z0-9_.:-]{1,100}$/.test(value)?value:"tool";
10
+ const detailed=new Set(["fs.read","fs.write","fs.edit","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"]);
11
+ 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"};
12
+
13
+ // Safe bounded metadata; never expose raw commands, search terms, edit bodies or output.
14
+ export function describeFullMonitorActivity(action,input={}){
15
+ input=input&&typeof input==="object"?input:{};
16
+ const name=value=>clean((typeof value==="string"?value:"").replace(/\\/g,"/").split("/").filter(Boolean).at(-1),90);
17
+ const count=value=>Array.isArray(value)?value.length:0;
18
+ const files=(verb,values)=>{
19
+ const paths=Array.isArray(values)?[...new Set(values.filter(v=>typeof v==="string"&&v.length>0))]:[];
20
+ return paths.length===1?verb+" "+(name(paths[0])||"file"):paths.length?verb+" "+paths.length+" files":verb+" files";
21
+ };
22
+ switch(action){
23
+ case "full.workspace.read":return files("Read",input.relativePaths??[input.relativePath]);
24
+ case "full.workspace.edit":return files("Edit",(Array.isArray(input.operations)?input.operations:[]).map(o=>o?.relativePath??o?.path));
25
+ case "full.intelligence.refresh":return "Refresh code index";
26
+ case "full.intelligence.context":return "Read task context";
27
+ case "full.intelligence.acknowledge":return "Acknowledge task context";
28
+ case "full.intelligence.search":return "Search code index";
29
+ case "full.intelligence.symbols":return "Find code symbols";
30
+ case "full.intelligence.dependencies":return "Inspect dependencies";
31
+ case "full.intelligence.impact":return "Review affected code";
32
+ case "full.session.ensure":return "Prepare task session";
33
+ case "full.session.list":return "List task sessions";
34
+ case "full.session.snapshot":return "Read task session";
35
+ case "full.session.delete":return "Remove task session";
36
+ case "full.session.acknowledge":return "Acknowledge session history";
37
+ case "full.session.export":return "Export task session";
38
+ case "full.task.checkpoint":return "Save task checkpoint";
39
+ case "full.task.plan":return "Update task plan";
40
+ case "full.task.phase":return "Update task phase";
41
+ case "full.task.narrative":return "Update task progress";
42
+ case "full.task.status":return "Update task status";
43
+ case "full.workspace.ensure":return "Prepare task workspace";
44
+ case "full.job.start":return "Start background command";
45
+ case "full.job.read":return "Read job output";
46
+ case "full.job.status":return "Check job status";
47
+ case "full.job.cancel":return "Cancel job";
48
+ case "full.job.reconcile":return "Reconcile job state";
49
+ case "full.verification.plan":return "Plan verification";
50
+ case "full.verification.record":return "Record verification";
51
+ case "full.verification.assess":return "Assess verification";
52
+ case "full.desktop.step":return "Desktop actions · "+count(input.actions)+" steps";
53
+ case "full.desktop.windows":return "List open windows";
54
+ case "full.diagnostics.snapshot":return "Read task diagnostics";
55
+ case "full.diagnostics.mode":return "Change diagnostic mode";
56
+ case "full.diagnostics.export":return "Export diagnostics";
57
+ default:return humanizeToolCall({action});
58
+ }
59
+ }
60
+ const bytes=value=>Number.isSafeInteger(value)&&value>=0?value:null;
61
+ const safeError=value=>typeof value==="string"&&/^[a-z][a-z0-9_]{1,95}$/.test(value)?value:"";
62
+
63
+ export function createMonitorActivity({now=()=>new Date()}={}){
64
+ const rows=new Map(),running=new Set(),details=new Map();
65
+ const localTime=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});
66
+ let calls=0,errors=0,learnEvents=0,sequence=0;
67
+ const remember=(key,row)=>{rows.set(key,row);while(rows.size>MAX_ROWS){const first=rows.keys().next().value;details.delete(rows.get(first).requestId);rows.delete(first);}};
68
+ const stamp=()=>{const at=now();return {at:at.toISOString(),time:localTime.format(at)};};
69
+ 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);};
70
+ return {
71
+ accept(event,payload={}){
72
+ if(event==="tool:start"){
73
+ const key=payload.requestId;
74
+ if(typeof key!=="string"||running.has(key))return;
75
+ calls++;running.add(key);
76
+ const action=code(payload.monitorAction??payload.action),category=action.startsWith("full.")?"Full":clean(payload.category,32)||"Agent";
77
+ // The TUI's descriptive operations are reused only for known routes
78
+ // that do not embed arbitrary request data. Search/filter and unknown
79
+ // arguments are deliberately not forwarded.
80
+ const label=action.startsWith("full.")?clean(payload.monitorOperation,128)||describeFullMonitorActivity(action):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});
81
+ 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:"",query:clean(payload.query,180),searchScope:clean(payload.searchScope,180),detail:detailed.has(action)?clean(payload.detail,160):""});
82
+ }else if(event==="tool:end"){
83
+ const key=payload.requestId;if(!running.delete(key))return;
84
+ if(payload.ok===false)errors++;
85
+ const row=rows.get(key);if(row){
86
+ if(payload.activityDetails)details.set(row.requestId,payload.activityDetails);
87
+ Object.assign(row,{status:payload.status==="cancelled"?"cancelled":payload.ok===false?"failed":"done",ok:payload.ok!==false,durationMs:bytes(payload.durationMs)===null?null:Math.min(86400000,payload.durationMs),responseBytes:bytes(payload.responseBytes),error:safeError(payload.error)});
88
+ }
89
+ }else if(event==="learn"){
90
+ learnEvents++;
91
+ const activity=payload.activity??{},tool=code(activity.tool);
92
+ const change=activity.change??{},rowId="learn-"+(++sequence);remember(rowId,{requestId:rowId,...stamp(),action:"learn",category:"Learn",icon:"🧠",operation:learnLabels[tool]||"Learn activity",project:clean(change.scope==="project"?change.scopeKey:activity.projectKey,64),detail:[clean(change.key,100),clean(change.scope??activity.scopeSummary,50)].filter(Boolean).join(" · "),status:activity.ok===false?"failed":"done",ok:activity.ok!==false,durationMs:bytes(activity.durationMs)});
93
+ }else return false;
94
+ return true;
95
+ },
96
+ snapshot(){prune();const current=now().getTime();return {calls,errors,active:running.size,learnEvents,activity:[...rows.values()].slice(-MAX_ROWS).map(row=>({...row,elapsedMs:row.status==="running"?Math.max(0,current-Date.parse(row.at)):null,hasDetails:details.has(row.requestId)}))};},
97
+ forgetSession(taskSessionId){
98
+ for(const [key,row] of rows){if(row.taskSessionId===taskSessionId){details.delete(row.requestId);rows.delete(key);}}
99
+ },
100
+ detail(activityId,fileId){
101
+ prune();
102
+ const row=[...rows.values()].find(item=>item.requestId===activityId);
103
+ const detail=row?details.get(activityId):null;
104
+ if(fileId!==undefined){
105
+ const file=detail?.files.find(f=>f.fileId===fileId);
106
+ return {activityId,fileId,...historicalDiff(file?.pair)};
107
+ }
108
+ return {activityId,...projectActivityDetails(detail)};
109
+ }
110
+ };
111
+ }
@@ -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) {