@anusornneal/chat-relay 1.7.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.
@@ -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 recentCalls = [];
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 recentCalls.slice(-(Math.min(Math.max(Number(payload.limit) || 50, 1), 100)));
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);
@@ -290,7 +309,10 @@ async function handlePayload(payload) {
290
309
  return terminals.startShell(payload.cwd, payload.observability);
291
310
  case "terminal.read":
292
311
  if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
293
- return terminals.read(payload.sessionId, payload.afterSeq, payload.maxChars);
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,9 @@ function connect() {
535
557
  let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
536
558
  let handlerDurationMs = 0;
537
559
  try {
538
- const result = await scheduler.run(action, async (meta = {}) => {
560
+ const schedulingAction = (action === "terminal.read" || action === "terminal.read.compact") && Number(message.payload?.waitMs) > 0
561
+ ? "terminal.read.wait" : action;
562
+ const result = await scheduler.run(schedulingAction, async (meta = {}) => {
539
563
  scheduleMeta = { ...scheduleMeta, ...meta };
540
564
  const handlerStartedAt = Date.now();
541
565
  try {
@@ -551,7 +575,8 @@ function connect() {
551
575
  rememberToolProject(result?.sessionId, uiActivity.project);
552
576
  }
553
577
  }
554
- recentCalls.push({
578
+ if (action === "terminal.exec.compact") rememberToolProject(result?.rawOutputId, uiActivity.project);
579
+ const recentEntry = {
555
580
  at: new Date().toISOString(),
556
581
  action,
557
582
  summary: callSummary,
@@ -562,14 +587,14 @@ function connect() {
562
587
  ...(timing ? { timing } : {}),
563
588
  ...(typeof result?.execMode === "string" ? { execMode: result.execMode } : {}),
564
589
  ok: !(result && typeof result === "object" && result.ok === false),
565
- });
566
- if (recentCalls.length > 100) recentCalls.shift();
590
+ };
567
591
  const responseMeta = {
568
592
  agentQueueWaitMs: scheduleMeta.queueWaitMs,
569
593
  agentHandlerMs: handlerDurationMs,
570
594
  lane: scheduleMeta.lane,
571
595
  };
572
596
  const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, result, responseMeta), "utf8");
597
+ try { usage.record({ ...recentEntry, requestBytes, responseBytes }, message.payload, result); } catch {}
573
598
  emitUi("tool:end", {
574
599
  requestId: message.requestId,
575
600
  action,
@@ -584,7 +609,7 @@ function connect() {
584
609
  : result;
585
610
  sendSocketResponse(socket, message.requestId, advised, responseMeta);
586
611
  } catch (error) {
587
- recentCalls.push({
612
+ const recentEntry = {
588
613
  at: new Date().toISOString(),
589
614
  action,
590
615
  summary: callSummary,
@@ -594,13 +619,13 @@ function connect() {
594
619
  lane: scheduleMeta.lane,
595
620
  ok: false,
596
621
  error: error instanceof Error ? error.message : "agent_error",
597
- });
598
- if (recentCalls.length > 100) recentCalls.shift();
622
+ };
599
623
  const errorPayload = {
600
624
  ok: false,
601
625
  error: error instanceof Error ? error.message : "agent_error",
602
626
  };
603
627
  const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, errorPayload), "utf8");
628
+ try { usage.record({ ...recentEntry, requestBytes, responseBytes }, message.payload, errorPayload); } catch {}
604
629
  emitUi("tool:end", {
605
630
  requestId: message.requestId,
606
631
  action,
@@ -698,6 +723,6 @@ function shutdown(reason) {
698
723
 
699
724
  process.once("SIGINT", () => shutdown("SIGINT"));
700
725
  process.once("SIGTERM", () => shutdown("SIGTERM"));
701
- process.once("exit", () => { terminals.close(); desktop.close(); });
726
+ process.once("exit", () => { usage.close(); terminals.close(); desktop.close(); });
702
727
 
703
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
+ }
@@ -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");
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";
@@ -11,6 +12,8 @@ import {
11
12
  const MAX_EXEC_BUFFER = 48 * 1024;
12
13
  const MAX_SESSION_BUFFER = 256 * 1024;
13
14
  const MAX_READ_CHARS = 24 * 1024;
15
+ const MAX_OUTPUT_WAIT_MS = 15_000;
16
+ const MAX_WAITERS_PER_SESSION = 8;
14
17
  const MAX_INPUT_CHARS = 8 * 1024;
15
18
  const MAX_SESSIONS = 8;
16
19
  const MAX_BATCH_SIZE = 20;
@@ -533,6 +536,7 @@ export class TerminalManager {
533
536
  this.shell = shellForPlatform(this.platform, options.shell);
534
537
  this.sessions = new Map();
535
538
  this.processEpoch = options.processEpoch ?? randomUUID();
539
+ this.execOutputs = new CompactExecOutputStore(this.processEpoch);
536
540
  this.batches = new Map();
537
541
  this.batchQueue = [];
538
542
  this.activeBatchJobs = 0;
@@ -590,6 +594,19 @@ export class TerminalManager {
590
594
  return this.#execIsolated(command, resolvedCwd, timeout);
591
595
  }
592
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
+
593
610
  #execIsolated(command, resolvedCwd, timeout) {
594
611
  return new Promise((resolve) => {
595
612
  execFile(
@@ -626,6 +643,7 @@ export class TerminalManager {
626
643
  }
627
644
 
628
645
  close() {
646
+ for (const session of this.sessions.values()) this.#notifyWaiters(session);
629
647
  this.fastExecPool?.close();
630
648
  }
631
649
 
@@ -702,6 +720,8 @@ export class TerminalManager {
702
720
  }
703
721
 
704
722
  read(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS) {
723
+ const replay = this.execOutputs.read(sessionId, afterSeq, maxChars);
724
+ if (replay) return replay;
705
725
  this.#cleanup();
706
726
  const session = this.#get(sessionId);
707
727
  if (!session) return terminalSessionMiss(sessionId, this.processEpoch);
@@ -726,6 +746,40 @@ export class TerminalManager {
726
746
  };
727
747
  }
728
748
 
749
+ async readWithWait(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, waitMs = 0) {
750
+ if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > MAX_OUTPUT_WAIT_MS) {
751
+ throw new Error("invalid_wait_ms");
752
+ }
753
+ const initial = this.read(sessionId, afterSeq, maxChars);
754
+ if (!waitMs || initial.status !== "running" || initial.chunks.length || initial.truncated) {
755
+ return initial;
756
+ }
757
+ const session = this.#get(sessionId);
758
+ if (!session) return initial;
759
+ if (session.waiters.size >= MAX_WAITERS_PER_SESSION) throw new Error("too_many_terminal_waiters");
760
+
761
+ return new Promise((resolve) => {
762
+ let timer = null;
763
+ const finish = () => {
764
+ if (timer === null) return;
765
+ clearTimeout(timer);
766
+ timer = null;
767
+ session.waiters.delete(finish);
768
+ resolve(this.read(sessionId, afterSeq, maxChars));
769
+ };
770
+ session.waiters.add(finish);
771
+ timer = setTimeout(finish, waitMs);
772
+ });
773
+ }
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
+
729
783
  write(sessionId, input, appendNewline = true) {
730
784
  const session = this.#get(sessionId);
731
785
  if (!session) return terminalSessionMiss(sessionId, this.processEpoch);
@@ -836,6 +890,34 @@ export class TerminalManager {
836
890
  return { ...this.#batchSummary(batch), jobs, truncated, maxChars: aggregateLimit };
837
891
  }
838
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
+
839
921
  async batchCancel(batchId) {
840
922
  this.#cleanup();
841
923
  const batch = this.#getBatch(batchId);
@@ -897,6 +979,7 @@ export class TerminalManager {
897
979
  chunks: [],
898
980
  nextSeq: 1,
899
981
  totalChars: 0,
982
+ waiters: new Set(),
900
983
  observability: observability ?? null,
901
984
  };
902
985
 
@@ -909,6 +992,7 @@ export class TerminalManager {
909
992
  session.exitCode = code;
910
993
  session.signal = signal;
911
994
  session.endedAt = new Date().toISOString();
995
+ this.#notifyWaiters(session);
912
996
  });
913
997
 
914
998
  return this.#summary(session);
@@ -1016,6 +1100,11 @@ export class TerminalManager {
1016
1100
  const removed = session.chunks.shift();
1017
1101
  session.totalChars -= removed.text.length;
1018
1102
  }
1103
+ if (text.length) this.#notifyWaiters(session);
1104
+ }
1105
+
1106
+ #notifyWaiters(session) {
1107
+ for (const notify of session.waiters) notify();
1019
1108
  }
1020
1109
 
1021
1110
  #summary(session) {