@anusornneal/chat-relay 1.8.0 → 1.9.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.
- package/README.md +54 -0
- package/agent/capability-scheduler.mjs +1 -1
- package/agent/file-manager.mjs +183 -77
- package/agent/fs-batch-preview.mjs +70 -0
- package/agent/lifecycle.mjs +6 -0
- package/agent/local-agent.mjs +33 -10
- package/agent/local-usage.mjs +254 -0
- package/agent/protocol.mjs +5 -1
- package/agent/terminal-manager.mjs +53 -0
- package/agent/terminal-output.mjs +136 -0
- package/agent/toolcall-context.mjs +13 -5
- package/agent/toolcall-summary.mjs +10 -0
- package/package.json +5 -4
package/agent/local-agent.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import WebSocket from "ws";
|
|
2
2
|
import { DesktopManager, createDesktopPlatformAdapter } from "./desktop-manager.mjs";
|
|
3
3
|
import { FileManager } from "./file-manager.mjs";
|
|
4
|
+
import { LocalUsageHistory, usageFileForAgent } from "./local-usage.mjs";
|
|
4
5
|
import { GitWorktreeManager } from "./git-worktree-manager.mjs";
|
|
5
6
|
import { ProcessManager } from "./process-manager.mjs";
|
|
6
7
|
import { TerminalManager } from "./terminal-manager.mjs";
|
|
@@ -83,7 +84,7 @@ const desktop = new DesktopManager({
|
|
|
83
84
|
controlMaxQueued: process.env.DESKTOP_CONTROL_MAX_QUEUED,
|
|
84
85
|
controlQueueTimeoutMs: process.env.AGENT_QUEUE_TIMEOUT_MS,
|
|
85
86
|
});
|
|
86
|
-
const
|
|
87
|
+
const usage = new LocalUsageHistory({ file: process.env.CHAT_RELAY_USAGE_DISABLED === "1" ? null : usageFileForAgent(agentId) });
|
|
87
88
|
// Correlate asynchronous batch/session output with the project where work began.
|
|
88
89
|
// Local only, bounded and never queried from the Worker.
|
|
89
90
|
const recentToolProjects = new Map();
|
|
@@ -195,7 +196,11 @@ async function handlePayload(payload) {
|
|
|
195
196
|
},
|
|
196
197
|
});
|
|
197
198
|
case "agent.recentCalls":
|
|
198
|
-
return
|
|
199
|
+
return usage.recent(payload.limit);
|
|
200
|
+
case "agent.recentCalls.page":
|
|
201
|
+
return usage.page(payload.limit, payload.cursor);
|
|
202
|
+
case "agent.usageStats":
|
|
203
|
+
return usage.stats(payload.days);
|
|
199
204
|
case "agent.lifecycle.status":
|
|
200
205
|
return { ok: true, lifecycle: lifecycle.snapshot() };
|
|
201
206
|
case "agent.lifecycle.drain":
|
|
@@ -221,8 +226,16 @@ async function handlePayload(payload) {
|
|
|
221
226
|
return files.read(payload.path, payload.offset, payload.length, payload.maxBytes);
|
|
222
227
|
case "fs.readMany":
|
|
223
228
|
return files.readMany(payload.paths, payload.maxTotalBytes);
|
|
229
|
+
case "fs.readMany.relative":
|
|
230
|
+
return files.readMany(payload.paths, payload.maxTotalBytes, payload.basePath);
|
|
224
231
|
case "fs.batch":
|
|
225
232
|
return files.batch(payload.operations, payload.maxTotalBytes);
|
|
233
|
+
case "fs.batch.compact":
|
|
234
|
+
return files.batch(payload.operations, payload.maxTotalBytes, {
|
|
235
|
+
basePath: payload.basePath, deduplicatePreviews: payload.deduplicatePreviews,
|
|
236
|
+
});
|
|
237
|
+
case "fs.editMany":
|
|
238
|
+
return files.editMany(payload.operations, payload.basePath);
|
|
226
239
|
case "fs.artifact":
|
|
227
240
|
return files.exportArtifact(payload.path, payload.maxBytes);
|
|
228
241
|
case "fs.write":
|
|
@@ -270,6 +283,9 @@ async function handlePayload(payload) {
|
|
|
270
283
|
case "terminal.exec":
|
|
271
284
|
if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
|
|
272
285
|
return terminals.exec(payload.command, payload.cwd, payload.timeoutMs);
|
|
286
|
+
case "terminal.exec.compact":
|
|
287
|
+
if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
|
|
288
|
+
return terminals.execCompact(payload.command, payload.cwd, payload.timeoutMs, payload.outputMode, payload.outputChars);
|
|
273
289
|
case "terminal.batch.start":
|
|
274
290
|
if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
|
|
275
291
|
return terminals.batchStart(payload.jobs, { cwd: payload.cwd, timeoutMs: payload.timeoutMs, concurrency: payload.concurrency, observability: payload.observability });
|
|
@@ -279,6 +295,9 @@ async function handlePayload(payload) {
|
|
|
279
295
|
case "terminal.batch.read":
|
|
280
296
|
if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
|
|
281
297
|
return terminals.batchRead(payload.batchId, payload.maxChars);
|
|
298
|
+
case "terminal.batch.read.compact":
|
|
299
|
+
if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
|
|
300
|
+
return terminals.batchReadCompact(payload.batchId, payload.maxChars, payload.outputMode, payload.outputChars, payload.jobIndex);
|
|
282
301
|
case "terminal.batch.cancel":
|
|
283
302
|
if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
|
|
284
303
|
return terminals.batchCancel(payload.batchId);
|
|
@@ -291,6 +310,9 @@ async function handlePayload(payload) {
|
|
|
291
310
|
case "terminal.read":
|
|
292
311
|
if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
|
|
293
312
|
return terminals.readWithWait(payload.sessionId, payload.afterSeq, payload.maxChars, payload.waitMs ?? 0);
|
|
313
|
+
case "terminal.read.compact":
|
|
314
|
+
if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
|
|
315
|
+
return terminals.readCompact(payload.sessionId, payload.afterSeq, payload.maxChars, payload.waitMs ?? 0, payload.outputMode, payload.outputChars);
|
|
294
316
|
case "terminal.write":
|
|
295
317
|
if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
|
|
296
318
|
return terminals.write(payload.sessionId, payload.input, payload.appendNewline !== false);
|
|
@@ -535,7 +557,7 @@ function connect() {
|
|
|
535
557
|
let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
|
|
536
558
|
let handlerDurationMs = 0;
|
|
537
559
|
try {
|
|
538
|
-
const schedulingAction = action === "terminal.read" && Number(message.payload?.waitMs) > 0
|
|
560
|
+
const schedulingAction = (action === "terminal.read" || action === "terminal.read.compact") && Number(message.payload?.waitMs) > 0
|
|
539
561
|
? "terminal.read.wait" : action;
|
|
540
562
|
const result = await scheduler.run(schedulingAction, async (meta = {}) => {
|
|
541
563
|
scheduleMeta = { ...scheduleMeta, ...meta };
|
|
@@ -553,7 +575,8 @@ function connect() {
|
|
|
553
575
|
rememberToolProject(result?.sessionId, uiActivity.project);
|
|
554
576
|
}
|
|
555
577
|
}
|
|
556
|
-
|
|
578
|
+
if (action === "terminal.exec.compact") rememberToolProject(result?.rawOutputId, uiActivity.project);
|
|
579
|
+
const recentEntry = {
|
|
557
580
|
at: new Date().toISOString(),
|
|
558
581
|
action,
|
|
559
582
|
summary: callSummary,
|
|
@@ -564,14 +587,14 @@ function connect() {
|
|
|
564
587
|
...(timing ? { timing } : {}),
|
|
565
588
|
...(typeof result?.execMode === "string" ? { execMode: result.execMode } : {}),
|
|
566
589
|
ok: !(result && typeof result === "object" && result.ok === false),
|
|
567
|
-
}
|
|
568
|
-
if (recentCalls.length > 100) recentCalls.shift();
|
|
590
|
+
};
|
|
569
591
|
const responseMeta = {
|
|
570
592
|
agentQueueWaitMs: scheduleMeta.queueWaitMs,
|
|
571
593
|
agentHandlerMs: handlerDurationMs,
|
|
572
594
|
lane: scheduleMeta.lane,
|
|
573
595
|
};
|
|
574
596
|
const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, result, responseMeta), "utf8");
|
|
597
|
+
try { usage.record({ ...recentEntry, requestBytes, responseBytes }, message.payload, result); } catch {}
|
|
575
598
|
emitUi("tool:end", {
|
|
576
599
|
requestId: message.requestId,
|
|
577
600
|
action,
|
|
@@ -586,7 +609,7 @@ function connect() {
|
|
|
586
609
|
: result;
|
|
587
610
|
sendSocketResponse(socket, message.requestId, advised, responseMeta);
|
|
588
611
|
} catch (error) {
|
|
589
|
-
|
|
612
|
+
const recentEntry = {
|
|
590
613
|
at: new Date().toISOString(),
|
|
591
614
|
action,
|
|
592
615
|
summary: callSummary,
|
|
@@ -596,13 +619,13 @@ function connect() {
|
|
|
596
619
|
lane: scheduleMeta.lane,
|
|
597
620
|
ok: false,
|
|
598
621
|
error: error instanceof Error ? error.message : "agent_error",
|
|
599
|
-
}
|
|
600
|
-
if (recentCalls.length > 100) recentCalls.shift();
|
|
622
|
+
};
|
|
601
623
|
const errorPayload = {
|
|
602
624
|
ok: false,
|
|
603
625
|
error: error instanceof Error ? error.message : "agent_error",
|
|
604
626
|
};
|
|
605
627
|
const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, errorPayload), "utf8");
|
|
628
|
+
try { usage.record({ ...recentEntry, requestBytes, responseBytes }, message.payload, errorPayload); } catch {}
|
|
606
629
|
emitUi("tool:end", {
|
|
607
630
|
requestId: message.requestId,
|
|
608
631
|
action,
|
|
@@ -700,6 +723,6 @@ function shutdown(reason) {
|
|
|
700
723
|
|
|
701
724
|
process.once("SIGINT", () => shutdown("SIGINT"));
|
|
702
725
|
process.once("SIGTERM", () => shutdown("SIGTERM"));
|
|
703
|
-
process.once("exit", () => { terminals.close(); desktop.close(); });
|
|
726
|
+
process.once("exit", () => { usage.close(); terminals.close(); desktop.close(); });
|
|
704
727
|
|
|
705
728
|
connect();
|
|
@@ -0,0 +1,254 @@
|
|
|
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
|
+
stats(requestedDays = RETENTION_DAYS) {
|
|
200
|
+
const now = this.now();
|
|
201
|
+
this.#prune(now);
|
|
202
|
+
const days = Math.min(RETENTION_DAYS, Math.max(1, Math.trunc(Number(requestedDays) || RETENTION_DAYS)));
|
|
203
|
+
const from = dayKey(now - (days - 1) * DAY_MS), through = dayKey(now);
|
|
204
|
+
const tools = new Map(), totals = empty(), daily = [];
|
|
205
|
+
for (let i = days - 1; i >= 0; i--) {
|
|
206
|
+
const date = dayKey(now - i * DAY_MS);
|
|
207
|
+
const sum = empty();
|
|
208
|
+
for (const [action, row] of this.days.get(date) || []) {
|
|
209
|
+
let target = tools.get(action);
|
|
210
|
+
if (!target) { target = empty(); tools.set(action, target); }
|
|
211
|
+
add(target, row); add(sum, row); add(totals, row);
|
|
212
|
+
}
|
|
213
|
+
daily.push({ date, calls: sum.calls, failed: sum.failed, readBatches: sum.readBatches,
|
|
214
|
+
readItems: sum.readItems, estimatedSavedReadCalls: sum.estimatedSavedReadCalls });
|
|
215
|
+
}
|
|
216
|
+
const byTool = [...tools].map(([action, row]) => ({ action, ...row }))
|
|
217
|
+
.sort((a, b) => b.calls - a.calls || a.action.localeCompare(b.action));
|
|
218
|
+
const batchReads = byTool.filter(row => row.action === "fs.readMany" || row.action === "fs.batch");
|
|
219
|
+
const batchReadItems = batchReads.reduce((sum, row) => sum + row.readItems, 0);
|
|
220
|
+
return { retentionDays: RETENTION_DAYS, days, from, through, timezone: "UTC",
|
|
221
|
+
persistence: this.persistence, ...(this.loadWarning ? { warning: this.loadWarning } : {}),
|
|
222
|
+
recentRetained: this.retained, totals, byTool, daily, batchReadItems,
|
|
223
|
+
observedBatchReadCallShare: totals.readBatches + (tools.get("fs.read")?.calls || 0) > 0
|
|
224
|
+
? totals.readBatches / (totals.readBatches + (tools.get("fs.read")?.calls || 0)) : null,
|
|
225
|
+
averageSuccessfulReadsPerBatch: totals.readBatches ? batchReadItems / totals.readBatches : null };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
flush() {
|
|
229
|
+
if (!this.file || !this.dirty) return;
|
|
230
|
+
this.#prune();
|
|
231
|
+
const snapshot = { version: 1, days: Object.fromEntries([...this.days]
|
|
232
|
+
.map(([day, tools]) => [day, Object.fromEntries(tools)])) };
|
|
233
|
+
const text = JSON.stringify(snapshot);
|
|
234
|
+
const temporary = this.file + "." + randomUUID() + ".tmp";
|
|
235
|
+
try {
|
|
236
|
+
if (Buffer.byteLength(text, "utf8") > MAX_FILE_BYTES) throw new Error("usage_file_too_large");
|
|
237
|
+
fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
|
|
238
|
+
fs.writeFileSync(temporary, text, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
239
|
+
fs.renameSync(temporary, this.file);
|
|
240
|
+
this.dirty = false;
|
|
241
|
+
this.persistence = "local";
|
|
242
|
+
} catch {
|
|
243
|
+
this.persistence = "write-failed";
|
|
244
|
+
} finally {
|
|
245
|
+
try { fs.unlinkSync(temporary); } catch {}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
close() {
|
|
250
|
+
if (this.timer) clearTimeout(this.timer);
|
|
251
|
+
this.timer = null;
|
|
252
|
+
this.flush();
|
|
253
|
+
}
|
|
254
|
+
}
|
package/agent/protocol.mjs
CHANGED
|
@@ -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)) {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { compactTerminalResult, compactTerminalPage, CompactExecOutputStore, outputLimit, validateOutputMode } from "./terminal-output.mjs";
|
|
1
2
|
import { execFile, spawn } from "node:child_process";
|
|
2
3
|
import { randomUUID } from "node:crypto";
|
|
3
4
|
import os from "node:os";
|
|
@@ -535,6 +536,7 @@ export class TerminalManager {
|
|
|
535
536
|
this.shell = shellForPlatform(this.platform, options.shell);
|
|
536
537
|
this.sessions = new Map();
|
|
537
538
|
this.processEpoch = options.processEpoch ?? randomUUID();
|
|
539
|
+
this.execOutputs = new CompactExecOutputStore(this.processEpoch);
|
|
538
540
|
this.batches = new Map();
|
|
539
541
|
this.batchQueue = [];
|
|
540
542
|
this.activeBatchJobs = 0;
|
|
@@ -592,6 +594,19 @@ export class TerminalManager {
|
|
|
592
594
|
return this.#execIsolated(command, resolvedCwd, timeout);
|
|
593
595
|
}
|
|
594
596
|
|
|
597
|
+
async execCompact(command, cwd, timeoutMs, outputMode = "summary", outputChars) {
|
|
598
|
+
const mode = validateOutputMode(outputMode);
|
|
599
|
+
const limit = outputLimit(outputChars);
|
|
600
|
+
const startedAt = new Date().toISOString();
|
|
601
|
+
const start = Date.now();
|
|
602
|
+
const raw = await this.exec(command, cwd, timeoutMs);
|
|
603
|
+
const endedAt = new Date().toISOString();
|
|
604
|
+
const result = compactTerminalResult(raw, mode, limit);
|
|
605
|
+
return { ...result, durationMs: Date.now() - start,
|
|
606
|
+
...(result.omittedChars > 0 ? { rawOutputId: this.execOutputs.record(raw, startedAt, endedAt),
|
|
607
|
+
rawOutputExpiresInMs: 600000 } : {}) };
|
|
608
|
+
}
|
|
609
|
+
|
|
595
610
|
#execIsolated(command, resolvedCwd, timeout) {
|
|
596
611
|
return new Promise((resolve) => {
|
|
597
612
|
execFile(
|
|
@@ -705,6 +720,8 @@ export class TerminalManager {
|
|
|
705
720
|
}
|
|
706
721
|
|
|
707
722
|
read(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS) {
|
|
723
|
+
const replay = this.execOutputs.read(sessionId, afterSeq, maxChars);
|
|
724
|
+
if (replay) return replay;
|
|
708
725
|
this.#cleanup();
|
|
709
726
|
const session = this.#get(sessionId);
|
|
710
727
|
if (!session) return terminalSessionMiss(sessionId, this.processEpoch);
|
|
@@ -755,6 +772,14 @@ export class TerminalManager {
|
|
|
755
772
|
});
|
|
756
773
|
}
|
|
757
774
|
|
|
775
|
+
async readCompact(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, waitMs = 0,
|
|
776
|
+
outputMode = "summary", outputChars) {
|
|
777
|
+
const mode = validateOutputMode(outputMode);
|
|
778
|
+
const limit = outputLimit(outputChars);
|
|
779
|
+
const page = await this.readWithWait(sessionId, afterSeq, maxChars, waitMs);
|
|
780
|
+
return compactTerminalPage(page, mode, limit, afterSeq);
|
|
781
|
+
}
|
|
782
|
+
|
|
758
783
|
write(sessionId, input, appendNewline = true) {
|
|
759
784
|
const session = this.#get(sessionId);
|
|
760
785
|
if (!session) return terminalSessionMiss(sessionId, this.processEpoch);
|
|
@@ -865,6 +890,34 @@ export class TerminalManager {
|
|
|
865
890
|
return { ...this.#batchSummary(batch), jobs, truncated, maxChars: aggregateLimit };
|
|
866
891
|
}
|
|
867
892
|
|
|
893
|
+
batchReadCompact(batchId, maxChars = MAX_BATCH_READ_CHARS, outputMode = "summary", outputChars, jobIndex) {
|
|
894
|
+
const mode = validateOutputMode(outputMode);
|
|
895
|
+
const limit = outputLimit(outputChars);
|
|
896
|
+
this.#cleanup();
|
|
897
|
+
const batch = this.#getBatch(batchId);
|
|
898
|
+
if (jobIndex !== undefined && (!Number.isInteger(jobIndex) || jobIndex < 0 || jobIndex >= batch.jobs.length)) {
|
|
899
|
+
throw new Error("invalid_job_index");
|
|
900
|
+
}
|
|
901
|
+
const selected = jobIndex === undefined ? batch.jobs : [batch.jobs[jobIndex]];
|
|
902
|
+
if (mode === "full" && jobIndex === undefined) return this.batchRead(batchId, maxChars);
|
|
903
|
+
const aggregateLimit = normalizeInteger(maxChars, MAX_BATCH_READ_CHARS, 1024, MAX_BATCH_READ_CHARS);
|
|
904
|
+
let remaining = aggregateLimit;
|
|
905
|
+
let truncated = false;
|
|
906
|
+
const jobs = selected.map(job => {
|
|
907
|
+
const budget = Math.min(MAX_JOB_READ_CHARS, remaining, mode === "full" ? MAX_JOB_READ_CHARS : limit);
|
|
908
|
+
const raw = { ...this.#jobSummary(job), stdout: job.stdout, stderr: job.stderr };
|
|
909
|
+
const output = mode === "full" ? { ...raw, ...clipJobOutput(job.stdout, job.stderr, budget) }
|
|
910
|
+
: compactTerminalResult(raw, mode, budget);
|
|
911
|
+
remaining = Math.max(0, remaining - output.stdout.length - output.stderr.length);
|
|
912
|
+
const omitted = job.stdout.length + job.stderr.length - output.stdout.length - output.stderr.length;
|
|
913
|
+
truncated ||= job.outputTruncated || omitted > 0;
|
|
914
|
+
return { ...output, outputTruncated: job.outputTruncated || omitted > 0,
|
|
915
|
+
...(mode === "full" ? {} : { rawJobIndex: job.index }) };
|
|
916
|
+
});
|
|
917
|
+
return { ...this.#batchSummary(batch), jobs, truncated, maxChars: aggregateLimit, outputMode: mode,
|
|
918
|
+
...(jobIndex === undefined ? {} : { selectedJobIndex: jobIndex }) };
|
|
919
|
+
}
|
|
920
|
+
|
|
868
921
|
async batchCancel(batchId) {
|
|
869
922
|
this.#cleanup();
|
|
870
923
|
const batch = this.#getBatch(batchId);
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createTerminalSessionId } from "./terminal-continuity.mjs";
|
|
3
|
+
|
|
4
|
+
const MODES = new Set(["full", "tail", "summary", "errors"]);
|
|
5
|
+
const ERROR_LINE = /(?:\b(?:error|warning|fatal|failed|failure|exception|traceback|caused by)\b|^\s*[ew]:)/i;
|
|
6
|
+
const EXEC_REPLAY_TTL = 10 * 60_000;
|
|
7
|
+
const MAX_EXEC_REPLAYS = 16;
|
|
8
|
+
const REPLAY_CHUNK_CHARS = 1024;
|
|
9
|
+
const REPLAY_RESPONSE_BYTES = 40 * 1024;
|
|
10
|
+
|
|
11
|
+
export function outputLimit(value) {
|
|
12
|
+
if (value === undefined) return 2048;
|
|
13
|
+
if (!Number.isInteger(value) || value < 256 || value > 8192) throw new Error("invalid_output_chars");
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function validateOutputMode(mode = "full") {
|
|
18
|
+
if (!MODES.has(mode)) throw new Error("invalid_output_mode");
|
|
19
|
+
return mode;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function tail(text, limit) {
|
|
23
|
+
if (limit <= 0) return "";
|
|
24
|
+
if (text.length <= limit) return text;
|
|
25
|
+
let start = text.length - limit;
|
|
26
|
+
if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
|
|
27
|
+
return text.slice(start);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function diagnostic(text) {
|
|
31
|
+
return text.split(/\r?\n/).filter(line => ERROR_LINE.test(line)).join("\n");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function failed(result) {
|
|
35
|
+
return result.ok === false || ["failed", "cancelled", "killed"].includes(result.status) || Boolean(result.signal) ||
|
|
36
|
+
(typeof result.exitCode === "number" && result.exitCode !== 0);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// A compact view is a projection of captured output, never a new execution.
|
|
40
|
+
export function compactTerminalResult(result, mode, limit = 2048) {
|
|
41
|
+
validateOutputMode(mode);
|
|
42
|
+
if (mode === "full") return result;
|
|
43
|
+
const stdout = typeof result.stdout === "string" ? result.stdout : "";
|
|
44
|
+
const stderr = typeof result.stderr === "string" ? result.stderr : "";
|
|
45
|
+
let out = stdout, err = stderr;
|
|
46
|
+
if (mode === "summary" && !failed(result)) { out = ""; err = ""; }
|
|
47
|
+
else if (mode === "errors") {
|
|
48
|
+
out = diagnostic(stdout);
|
|
49
|
+
if (!out && !err && failed(result)) out = stdout;
|
|
50
|
+
}
|
|
51
|
+
const errBudget = out ? Math.min(err.length, Math.ceil(limit / 2)) : limit;
|
|
52
|
+
err = tail(err, errBudget);
|
|
53
|
+
out = tail(out, Math.max(0, limit - err.length));
|
|
54
|
+
return { ...result, stdout: out, stderr: err, outputMode: mode,
|
|
55
|
+
capturedChars: stdout.length + stderr.length,
|
|
56
|
+
omittedChars: Math.max(0, stdout.length + stderr.length - out.length - err.length) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function compactTerminalPage(page, mode, limit, afterSeq) {
|
|
60
|
+
validateOutputMode(mode);
|
|
61
|
+
if (mode === "full" || !Array.isArray(page.chunks)) return page;
|
|
62
|
+
const raw = page.chunks;
|
|
63
|
+
const capturedChars = raw.reduce((sum, c) => sum + c.text.length, 0);
|
|
64
|
+
let remaining = limit;
|
|
65
|
+
const chunks = [];
|
|
66
|
+
for (let i = raw.length - 1; i >= 0 && remaining > 0; i--) {
|
|
67
|
+
const c = raw[i];
|
|
68
|
+
let text = c.text;
|
|
69
|
+
if (mode === "summary" && !failed(page)) text = "";
|
|
70
|
+
else if (mode === "errors" && c.stream !== "stderr") text = diagnostic(text);
|
|
71
|
+
if (!text) continue;
|
|
72
|
+
text = tail(text, remaining);
|
|
73
|
+
if (text) { chunks.push({ ...c, text }); remaining -= text.length; }
|
|
74
|
+
}
|
|
75
|
+
if (!chunks.length && failed(page) && capturedChars && mode === "errors") {
|
|
76
|
+
for (let i = raw.length - 1; i >= 0 && remaining > 0; i--) {
|
|
77
|
+
const text = tail(raw[i].text, remaining);
|
|
78
|
+
if (text) { chunks.push({ ...raw[i], text }); remaining -= text.length; }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
chunks.reverse();
|
|
82
|
+
return { ...page, chunks, outputMode: mode, capturedChars, omittedChars: capturedChars - (limit - remaining),
|
|
83
|
+
// Re-read the original page with full mode and this cursor, not nextSeq.
|
|
84
|
+
rawAfterSeq: afterSeq };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Bounded process-local replay for compact short commands. No disk or extra RPC.
|
|
88
|
+
export class CompactExecOutputStore {
|
|
89
|
+
constructor(processEpoch, now = Date.now) {
|
|
90
|
+
this.processEpoch = processEpoch;
|
|
91
|
+
this.now = now;
|
|
92
|
+
this.entries = new Map();
|
|
93
|
+
}
|
|
94
|
+
#prune() {
|
|
95
|
+
const now = this.now();
|
|
96
|
+
for (const [id, entry] of this.entries) if (entry.expiresAt <= now) this.entries.delete(id);
|
|
97
|
+
}
|
|
98
|
+
record(result, startedAt, endedAt) {
|
|
99
|
+
this.#prune();
|
|
100
|
+
while (this.entries.size >= MAX_EXEC_REPLAYS) this.entries.delete(this.entries.keys().next().value);
|
|
101
|
+
const sessionId = createTerminalSessionId(this.processEpoch, randomUUID());
|
|
102
|
+
const chunks = [];
|
|
103
|
+
for (const stream of ["stdout", "stderr"]) {
|
|
104
|
+
const text = typeof result[stream] === "string" ? result[stream] : "";
|
|
105
|
+
for (let start = 0; start < text.length;) {
|
|
106
|
+
let end = Math.min(text.length, start + REPLAY_CHUNK_CHARS);
|
|
107
|
+
if (end < text.length && /[\uDC00-\uDFFF]/.test(text[end])) end--;
|
|
108
|
+
chunks.push({ seq: chunks.length + 1, stream, text: text.slice(start, end) });
|
|
109
|
+
start = end;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
this.entries.set(sessionId, { expiresAt: this.now() + EXEC_REPLAY_TTL, chunks,
|
|
113
|
+
summary: { sessionId, processEpoch: this.processEpoch, type: "exec-output", status: "exited",
|
|
114
|
+
exitCode: result.exitCode ?? null, startedAt, endedAt, error: result.error ?? null,
|
|
115
|
+
captureLimited: /maxBuffer|timed out/i.test(String(result.error || "")) } });
|
|
116
|
+
return sessionId;
|
|
117
|
+
}
|
|
118
|
+
read(sessionId, afterSeq = 0, maxChars = 24576) {
|
|
119
|
+
this.#prune();
|
|
120
|
+
const entry = this.entries.get(sessionId);
|
|
121
|
+
if (!entry) return null;
|
|
122
|
+
const limit = Math.min(Math.max(Number(maxChars) || 24576, 1024), 24576);
|
|
123
|
+
const chunks = [];
|
|
124
|
+
let chars = 0, bytes = 0;
|
|
125
|
+
for (const chunk of entry.chunks) {
|
|
126
|
+
if (chunk.seq <= afterSeq) continue;
|
|
127
|
+
const chunkBytes = Buffer.byteLength(JSON.stringify(chunk), "utf8");
|
|
128
|
+
if (chunks.length && (chars + chunk.text.length > limit || bytes + chunkBytes > REPLAY_RESPONSE_BYTES)) break;
|
|
129
|
+
chunks.push(chunk);
|
|
130
|
+
chars += chunk.text.length; bytes += chunkBytes;
|
|
131
|
+
}
|
|
132
|
+
const nextSeq = chunks.at(-1)?.seq ?? afterSeq;
|
|
133
|
+
return { ...entry.summary, chunks, oldestSeq: 1, nextSeq,
|
|
134
|
+
truncated: false, hasMore: nextSeq < entry.chunks.length };
|
|
135
|
+
}
|
|
136
|
+
}
|