@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
@@ -0,0 +1,275 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { configDir } from "../cli/config.mjs";
5
+
6
+ export const RECENT_CALL_CAPACITY = 1000;
7
+ const RETENTION_DAYS = 30;
8
+ const DAY_MS = 86400000;
9
+ const MAX_PAGE_BYTES = 48 * 1024;
10
+ const MAX_FILE_BYTES = 1024 * 1024;
11
+ const FLUSH_MS = 30_000;
12
+ const ACTIONS = new Set([
13
+ "ping", "agent.config", "agent.recentCalls", "agent.usageStats",
14
+ "agent.lifecycle.status", "agent.lifecycle.drain", "agent.lifecycle.resume",
15
+ "agent.lifecycle.restart", "agent.lifecycle.upgrade",
16
+ "fs.stat", "fs.list", "fs.read", "fs.readMany", "fs.batch", "fs.editMany",
17
+ "fs.artifact", "fs.write", "fs.edit", "fs.mkdir", "fs.move", "fs.delete",
18
+ "fs.search.start", "fs.search.results", "git.worktree.cleanup",
19
+ "process.list", "process.kill", "desktop.screenshot", "desktop.clipboard.read",
20
+ "desktop.clipboard.write", "desktop.window.list", "desktop.window.focus",
21
+ "desktop.mouse.click_image", "desktop.mouse.click", "desktop.keyboard.input", "desktop.step",
22
+ "terminal.exec", "terminal.batch.start", "terminal.batch.status", "terminal.batch.read",
23
+ "terminal.batch.cancel", "terminal.start", "terminal.shell.start", "terminal.read",
24
+ "terminal.write", "terminal.kill", "terminal.list", "terminal.observability", "other",
25
+ ]);
26
+ const ALIASES = new Map([
27
+ ["fs.readMany.relative", "fs.readMany"], ["fs.batch.compact", "fs.batch"],
28
+ ["terminal.exec.compact", "terminal.exec"], ["terminal.read.compact", "terminal.read"],
29
+ ["terminal.batch.read.compact", "terminal.batch.read"], ["agent.recentCalls.page", "agent.recentCalls"],
30
+ ]);
31
+ const COUNTERS = [
32
+ "calls", "failed", "durationMs", "requestBytes", "responseBytes", "batchRequested", "batchProcessed",
33
+ "batchSucceeded", "readBatches", "requestedReadItems", "readItems", "estimatedSavedReadCalls",
34
+ ];
35
+ const empty = () => Object.fromEntries(COUNTERS.map(key => [key, 0]));
36
+ const boundedCount = value => Number.isSafeInteger(value) && value >= 0 ? value : 0;
37
+ const dayKey = ms => new Date(ms).toISOString().slice(0, 10);
38
+ const actionKey = action => ALIASES.get(action) || (ACTIONS.has(action) ? action : "other");
39
+ function add(target, source) {
40
+ for (const key of COUNTERS) target[key] = Math.min(Number.MAX_SAFE_INTEGER, target[key] + boundedCount(source[key]));
41
+ return target;
42
+ }
43
+ function items(value) { return Array.isArray(value) ? value : []; }
44
+
45
+ function measure(action, entry, payload, result) {
46
+ payload = payload && typeof payload === "object" ? payload : {};
47
+ const row = empty();
48
+ row.calls = 1;
49
+ row.failed = entry.ok === false ? 1 : 0;
50
+ row.durationMs = boundedCount(entry.durationMs);
51
+ row.requestBytes = boundedCount(entry.requestBytes);
52
+ row.responseBytes = boundedCount(entry.responseBytes);
53
+ let requests = [], outcomes = [], readRequested = 0, readSucceeded = 0;
54
+ if (action === "fs.readMany") {
55
+ requests = items(payload.paths);
56
+ outcomes = items(result?.files);
57
+ readRequested = requests.length;
58
+ readSucceeded = outcomes.filter(item => item.ok === true).length;
59
+ } else if (action === "fs.batch" || action === "fs.editMany") {
60
+ requests = items(payload.operations);
61
+ outcomes = items(result?.results);
62
+ if (action === "fs.batch") {
63
+ readRequested = requests.filter(item => item?.op === "read").length;
64
+ readSucceeded = outcomes.filter(item => item.ok === true && item.op === "read").length;
65
+ }
66
+ } else if (action === "fs.read" && entry.ok !== false) {
67
+ row.readItems = 1;
68
+ }
69
+ if (["fs.readMany", "fs.batch", "fs.editMany"].includes(action)) {
70
+ row.batchRequested = Math.min(20, requests.length);
71
+ row.batchProcessed = Math.min(row.batchRequested, outcomes.length);
72
+ row.batchSucceeded = Math.min(row.batchProcessed, outcomes.filter(item => item.ok === true).length);
73
+ row.requestedReadItems = Math.min(20, readRequested);
74
+ row.readBatches = row.requestedReadItems > 0 ? 1 : 0;
75
+ row.readItems = Math.min(row.requestedReadItems, readSucceeded);
76
+ // Estimate against one filesystem read call per successful read operation.
77
+ // Partial file reads can still need continuation; this is not an E2E measurement.
78
+ row.estimatedSavedReadCalls = Math.max(0, row.readItems - 1);
79
+ }
80
+ return row;
81
+ }
82
+
83
+ export function usageFileForAgent(agentId, directory = configDir()) {
84
+ const key = createHash("sha256").update(String(agentId)).digest("hex").slice(0, 32);
85
+ return path.join(directory, "usage", key + ".json");
86
+ }
87
+
88
+ // Recent metadata stays in RAM; only bounded numerical daily aggregates go to disk.
89
+ // The timer is dirty-only, unref'ed, and never runs on every tool call.
90
+ export class LocalUsageHistory {
91
+ constructor({ file = null, now = Date.now, autoFlush = true } = {}) {
92
+ this.file = file;
93
+ this.now = now;
94
+ this.autoFlush = autoFlush;
95
+ this.epoch = randomUUID();
96
+ this.ring = new Array(RECENT_CALL_CAPACITY);
97
+ this.nextSeq = 1;
98
+ this.retained = 0;
99
+ this.days = new Map();
100
+ this.lastDay = null;
101
+ this.dirty = false;
102
+ this.timer = null;
103
+ this.persistence = file ? "local" : "memory-only";
104
+ this.loadWarning = null;
105
+ if (file) this.#load();
106
+ }
107
+
108
+ #prune(now = this.now()) {
109
+ const earliest = dayKey(now - (RETENTION_DAYS - 1) * DAY_MS);
110
+ const latest = dayKey(now);
111
+ for (const key of this.days.keys()) if (key < earliest || key > latest) {
112
+ this.days.delete(key); this.dirty = true;
113
+ }
114
+ this.lastDay = latest;
115
+ }
116
+
117
+ #load() {
118
+ try {
119
+ if (fs.statSync(this.file).size > MAX_FILE_BYTES) throw new Error("usage_file_too_large");
120
+ const parsed = JSON.parse(fs.readFileSync(this.file, "utf8"));
121
+ if (parsed.version !== 1 || !parsed.days || typeof parsed.days !== "object" || Array.isArray(parsed.days)) {
122
+ throw new Error("invalid_usage_file");
123
+ }
124
+ for (const [day, tools] of Object.entries(parsed.days)) {
125
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day) || !tools || typeof tools !== "object") continue;
126
+ const rows = new Map();
127
+ for (const [action, values] of Object.entries(tools)) {
128
+ if (!ACTIONS.has(action) || !values || typeof values !== "object") continue;
129
+ rows.set(action, add(empty(), values));
130
+ }
131
+ this.days.set(day, rows);
132
+ }
133
+ this.#prune();
134
+ } catch (error) {
135
+ if (error?.code !== "ENOENT") this.loadWarning = "usage_history_unavailable";
136
+ }
137
+ }
138
+
139
+ record(entry, payload = {}, result = null) {
140
+ const seq = this.nextSeq++;
141
+ this.ring[(seq - 1) % RECENT_CALL_CAPACITY] = {
142
+ ...entry, seq, action: String(entry.action || "other").slice(0, 100),
143
+ summary: String(entry.summary || "").slice(0, 160),
144
+ ...(entry.error === undefined ? {} : { error: String(entry.error).slice(0, 256) }),
145
+ };
146
+ this.retained = Math.min(RECENT_CALL_CAPACITY, this.retained + 1);
147
+ const now = this.now(), day = dayKey(now), action = actionKey(entry.action);
148
+ if (day !== this.lastDay) this.#prune(now);
149
+ let rows = this.days.get(day);
150
+ if (!rows) { rows = new Map(); this.days.set(day, rows); }
151
+ let row = rows.get(action);
152
+ if (!row) { row = empty(); rows.set(action, row); }
153
+ add(row, measure(action, entry, payload, result));
154
+ this.dirty = true;
155
+ this.#schedule();
156
+ }
157
+
158
+ #schedule() {
159
+ if (!this.file || !this.autoFlush || this.timer) return;
160
+ this.timer = setTimeout(() => {
161
+ this.timer = null;
162
+ this.flush();
163
+ }, FLUSH_MS);
164
+ this.timer.unref?.();
165
+ }
166
+
167
+ page(limit = 50, cursor) {
168
+ const count = Math.min(100, Math.max(1, Math.trunc(Number(limit) || 50)));
169
+ let before = this.nextSeq;
170
+ if (cursor !== undefined) {
171
+ const [epoch, raw, extra] = String(cursor).split(":");
172
+ before = Number(raw);
173
+ if (epoch !== this.epoch) throw new Error("recent_history_epoch_mismatch");
174
+ if (extra !== undefined || !Number.isSafeInteger(before) || before < 1 || before > this.nextSeq) {
175
+ throw new Error("invalid_history_cursor");
176
+ }
177
+ }
178
+ const oldest = this.nextSeq - this.retained;
179
+ const calls = [];
180
+ let bytes = 256;
181
+ for (let seq = before - 1; seq >= oldest && calls.length < count; seq--) {
182
+ const entry = this.ring[(seq - 1) % RECENT_CALL_CAPACITY];
183
+ const cost = Buffer.byteLength(JSON.stringify(entry), "utf8") + 1;
184
+ if (bytes + cost > MAX_PAGE_BYTES) break;
185
+ calls.push(entry); bytes += cost;
186
+ }
187
+ calls.reverse();
188
+ const first = calls[0]?.seq ?? before;
189
+ return { calls, retained: this.retained, capacity: RECENT_CALL_CAPACITY, historyEpoch: this.epoch,
190
+ oldestSeq: oldest, newestSeq: this.nextSeq - 1,
191
+ nextCursor: first > oldest ? this.epoch + ":" + first : null,
192
+ evicted: before <= oldest && oldest > 1 };
193
+ }
194
+
195
+ recent(limit) {
196
+ return this.page(limit).calls.map(({ seq, ...entry }) => entry);
197
+ }
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
+
220
+ stats(requestedDays = RETENTION_DAYS) {
221
+ const now = this.now();
222
+ this.#prune(now);
223
+ const days = Math.min(RETENTION_DAYS, Math.max(1, Math.trunc(Number(requestedDays) || RETENTION_DAYS)));
224
+ const from = dayKey(now - (days - 1) * DAY_MS), through = dayKey(now);
225
+ const tools = new Map(), totals = empty(), daily = [];
226
+ for (let i = days - 1; i >= 0; i--) {
227
+ const date = dayKey(now - i * DAY_MS);
228
+ const sum = empty();
229
+ for (const [action, row] of this.days.get(date) || []) {
230
+ let target = tools.get(action);
231
+ if (!target) { target = empty(); tools.set(action, target); }
232
+ add(target, row); add(sum, row); add(totals, row);
233
+ }
234
+ daily.push({ date, calls: sum.calls, failed: sum.failed, readBatches: sum.readBatches,
235
+ readItems: sum.readItems, estimatedSavedReadCalls: sum.estimatedSavedReadCalls });
236
+ }
237
+ const byTool = [...tools].map(([action, row]) => ({ action, ...row }))
238
+ .sort((a, b) => b.calls - a.calls || a.action.localeCompare(b.action));
239
+ const batchReads = byTool.filter(row => row.action === "fs.readMany" || row.action === "fs.batch");
240
+ const batchReadItems = batchReads.reduce((sum, row) => sum + row.readItems, 0);
241
+ return { retentionDays: RETENTION_DAYS, days, from, through, timezone: "UTC",
242
+ persistence: this.persistence, ...(this.loadWarning ? { warning: this.loadWarning } : {}),
243
+ recentRetained: this.retained, totals, byTool, daily, batchReadItems,
244
+ observedBatchReadCallShare: totals.readBatches + (tools.get("fs.read")?.calls || 0) > 0
245
+ ? totals.readBatches / (totals.readBatches + (tools.get("fs.read")?.calls || 0)) : null,
246
+ averageSuccessfulReadsPerBatch: totals.readBatches ? batchReadItems / totals.readBatches : null };
247
+ }
248
+
249
+ flush() {
250
+ if (!this.file || !this.dirty) return;
251
+ this.#prune();
252
+ const snapshot = { version: 1, days: Object.fromEntries([...this.days]
253
+ .map(([day, tools]) => [day, Object.fromEntries(tools)])) };
254
+ const text = JSON.stringify(snapshot);
255
+ const temporary = this.file + "." + randomUUID() + ".tmp";
256
+ try {
257
+ if (Buffer.byteLength(text, "utf8") > MAX_FILE_BYTES) throw new Error("usage_file_too_large");
258
+ fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
259
+ fs.writeFileSync(temporary, text, { encoding: "utf8", mode: 0o600, flag: "wx" });
260
+ fs.renameSync(temporary, this.file);
261
+ this.dirty = false;
262
+ this.persistence = "local";
263
+ } catch {
264
+ this.persistence = "write-failed";
265
+ } finally {
266
+ try { fs.unlinkSync(temporary); } catch {}
267
+ }
268
+ }
269
+
270
+ close() {
271
+ if (this.timer) clearTimeout(this.timer);
272
+ this.timer = null;
273
+ this.flush();
274
+ }
275
+ }
@@ -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) {
@@ -28,6 +28,10 @@ export function getAgentCapabilities(options = {}) {
28
28
  "filesystem.read",
29
29
  "filesystem.readMany",
30
30
  "filesystem.batch",
31
+ "filesystem.batch.relative",
32
+ "filesystem.batch.deduplicatePreviews",
33
+ "filesystem.editMany",
34
+ "agent.usageStats",
31
35
  "filesystem.artifact",
32
36
  "filesystem.write",
33
37
  "filesystem.edit",
@@ -41,7 +45,7 @@ export function getAgentCapabilities(options = {}) {
41
45
  ];
42
46
 
43
47
  if (terminalEnabled) {
44
- capabilities.push("terminal.exec", "terminal.sessions", "terminal.batch", "terminal.read.wait");
48
+ capabilities.push("terminal.exec", "terminal.sessions", "terminal.batch", "terminal.read.wait", "terminal.output.compact");
45
49
  }
46
50
 
47
51
  if (desktopEnabled && ["win32", "darwin"].includes(platform)) {