@treestructuredplanning/gateway 0.1.1 → 0.1.2

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,8 +1,9 @@
1
1
  import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
2
 
3
3
  // ../tsp-shared/src/generated/constants.ts
4
- var GATEWAY_PACKAGE_VERSION = "0.1.1";
4
+ var GATEWAY_PACKAGE_VERSION = "0.1.2";
5
5
  var GATEWAY_PROTOCOL_VERSION = 1;
6
+ var SESSION_ACTIVITY_COUNT_MAX = 1e6;
6
7
  var AGENT_SESSION_STATE = {
7
8
  STARTING: "starting",
8
9
  WORKING: "working",
@@ -32,6 +33,11 @@ var LAUNCH_REFUSAL_REASON = {
32
33
  REQUESTER_MISMATCH: "requester_mismatch",
33
34
  PROTOCOL_OUTDATED: "protocol_outdated",
34
35
  START_FAILED: "start_failed",
36
+ SHELL_STARTUP_TIMEOUT: "shell_startup_timeout",
37
+ SHELL_STARTUP_FAILED: "shell_startup_failed",
38
+ REPOSITORY_FOLDER_UNAVAILABLE: "repository_folder_unavailable",
39
+ HARNESS_EXITED: "harness_exited",
40
+ START_UNCERTAIN: "start_uncertain",
35
41
  STOP_FAILED: "stop_failed",
36
42
  SESSION_NOT_FOUND: "session_not_found",
37
43
  MACHINE_OFFLINE: "machine_offline",
@@ -45,6 +51,22 @@ var LAUNCH_REFUSAL_REASON = {
45
51
  CONTROL_EXPIRED: "control_expired",
46
52
  CONTROL_WITHDRAWN: "control_withdrawn"
47
53
  };
54
+ var SESSION_ACTIVITY_KIND = {
55
+ /** Between steps: reasoning, writing, or reading a tool's result. */
56
+ THINKING: "thinking",
57
+ /** Reading or searching the repository. */
58
+ READING: "reading",
59
+ /** Changing files. */
60
+ EDITING: "editing",
61
+ /** Running a shell command that is not only a read. */
62
+ RUNNING_COMMAND: "running_command",
63
+ /** Calling TSP's own tools: reading or updating the plan. */
64
+ USING_PLAN: "using_plan",
65
+ /** Waiting on a subagent it started. */
66
+ DELEGATING: "delegating",
67
+ /** Any other tool: the web, a skill, another MCP server. */
68
+ USING_TOOL: "using_tool"
69
+ };
48
70
  var GATEWAY_CLOSE_DISPOSITION_BY_CODE = {
49
71
  "1006": "reconnectable",
50
72
  "4501": "terminal",
@@ -57,6 +79,174 @@ var GATEWAY_CLOSE_DISPOSITION_BY_CODE = {
57
79
  "4508": "reconnectable"
58
80
  };
59
81
 
82
+ // src/session-activity.ts
83
+ var REPORTING_LEVELS = ["activity", "off"];
84
+ var DEFAULT_REPORTING = "activity";
85
+ function decodeReporting(value) {
86
+ const level = REPORTING_LEVELS.find((candidate) => candidate === value);
87
+ if (!level)
88
+ throw new Error(
89
+ value === "transcript" ? "reporting level transcript is reserved and not available yet" : `reporting must be one of: ${REPORTING_LEVELS.join(", ")}`
90
+ );
91
+ return level;
92
+ }
93
+ function toWire(snapshot, working, nowMs) {
94
+ return {
95
+ kind: working ? snapshot.kind : null,
96
+ idle_ms: Math.max(0, Math.floor(nowMs - snapshot.lastActiveMs)),
97
+ files_edited: snapshot.filesEdited,
98
+ commands_run: snapshot.commandsRun
99
+ };
100
+ }
101
+ var PENDING_LIMIT = 256;
102
+ var ActivityTally = class {
103
+ files = /* @__PURE__ */ new Set();
104
+ pending = /* @__PURE__ */ new Map();
105
+ commands = 0;
106
+ settled = null;
107
+ lastActiveMs = null;
108
+ /** A recognised step at `atMs`; an unknown time does not move the last-active time. */
109
+ stepped(atMs) {
110
+ if (atMs !== null && Number.isFinite(atMs))
111
+ this.lastActiveMs = Math.max(this.lastActiveMs ?? 0, atMs);
112
+ }
113
+ /** Reasoning, writing or reading a result: between steps. */
114
+ between() {
115
+ this.settled = SESSION_ACTIVITY_KIND.THINKING;
116
+ }
117
+ /** A tool started; it is current until `finished(id)`. */
118
+ started(id, kind) {
119
+ this.pending.delete(id);
120
+ this.pending.set(id, kind);
121
+ if (this.pending.size > PENDING_LIMIT) {
122
+ const oldest = this.pending.keys().next().value;
123
+ if (oldest !== void 0) this.pending.delete(oldest);
124
+ }
125
+ }
126
+ finished(id) {
127
+ this.pending.delete(id);
128
+ this.settled = SESSION_ACTIVITY_KIND.THINKING;
129
+ }
130
+ ranCommand() {
131
+ this.commands = Math.min(this.commands + 1, SESSION_ACTIVITY_COUNT_MAX);
132
+ }
133
+ editedFile(path) {
134
+ if (this.files.size < SESSION_ACTIVITY_COUNT_MAX) this.files.add(path);
135
+ }
136
+ snapshot() {
137
+ if (this.lastActiveMs === null) return null;
138
+ return {
139
+ kind: [...this.pending.values()].at(-1) ?? this.settled,
140
+ lastActiveMs: this.lastActiveMs,
141
+ filesEdited: this.files.size,
142
+ commandsRun: this.commands
143
+ };
144
+ }
145
+ };
146
+
147
+ // src/activity-reporting.ts
148
+ var ACTIVITY_KIND_WINDOW_MS = 5e3;
149
+ var ACTIVITY_HEARTBEAT_MS = 15e3;
150
+ var ActivityCoalescer = class {
151
+ constructor(now = Date.now, kindWindowMs = ACTIVITY_KIND_WINDOW_MS, heartbeatMs = ACTIVITY_HEARTBEAT_MS) {
152
+ this.now = now;
153
+ this.kindWindowMs = kindWindowMs;
154
+ this.heartbeatMs = heartbeatMs;
155
+ }
156
+ sent = /* @__PURE__ */ new Map();
157
+ /** Whether to send now; a true answer records the observation as sent. */
158
+ offer(session, base, activity) {
159
+ const now = this.now();
160
+ const last = this.sent.get(session);
161
+ if (!this.due(last, base, activity, now)) return false;
162
+ this.sent.set(session, { base, at: now, activity });
163
+ return true;
164
+ }
165
+ /** The next observation of this session is sent whatever it holds. */
166
+ forget(session) {
167
+ this.sent.delete(session);
168
+ }
169
+ clear() {
170
+ this.sent.clear();
171
+ }
172
+ /** Whether this update carries nothing the last frame sent for the session did not. */
173
+ repeats(session, base) {
174
+ return this.sent.get(session)?.base === base;
175
+ }
176
+ due(last, base, activity, now) {
177
+ if (!last || last.base !== base) return true;
178
+ if (!activity) return false;
179
+ const previous = last.activity;
180
+ if (!previous) return true;
181
+ const elapsed = now - last.at;
182
+ if (activity.kind !== previous.kind) return elapsed >= this.kindWindowMs;
183
+ const moved = activity.lastActiveMs !== previous.lastActiveMs || activity.filesEdited !== previous.filesEdited || activity.commandsRun !== previous.commandsRun;
184
+ return moved && elapsed >= this.heartbeatMs;
185
+ }
186
+ };
187
+ var ActivityReporter = class {
188
+ constructor(level = async () => DEFAULT_REPORTING, now = Date.now) {
189
+ this.level = level;
190
+ this.now = now;
191
+ this.coalescer = new ActivityCoalescer(now);
192
+ }
193
+ coalescer;
194
+ /** Per session, the snapshot the hub still shows with a kind (it keeps one on omission). */
195
+ shown = /* @__PURE__ */ new Map();
196
+ /** An unreadable config reports nothing rather than guessing the person's choice. */
197
+ async enabled() {
198
+ try {
199
+ return await this.level() === "activity";
200
+ } catch {
201
+ return false;
202
+ }
203
+ }
204
+ /**
205
+ * The update to send for this observation, with its activity, or null when nothing
206
+ * is due. With reporting off no activity goes out, except one frame that clears a
207
+ * kind the hub still shows.
208
+ */
209
+ frame(update, snapshot, reporting = true) {
210
+ const session = update.action_id;
211
+ const base = JSON.stringify(update);
212
+ const working = update.state === "working";
213
+ const observed = reporting ? snapshot : this.clearing(session, base, working);
214
+ const current = observed && { ...observed, kind: working ? observed.kind : null };
215
+ if (!this.coalescer.offer(session, base, current)) return null;
216
+ if (current?.kind) this.shown.set(session, current);
217
+ else if (current || !working) this.shown.delete(session);
218
+ return current ? { ...update, activity: toWire(current, working, this.now()) } : update;
219
+ }
220
+ /**
221
+ * The kind-cleared snapshot for a session whose hub still shows a kind, sent only in
222
+ * a frame that repeats the last one: a server that refuses `activity` (rolled back
223
+ * below 0.1.2) then loses the clear and never a state change.
224
+ */
225
+ clearing(session, base, working) {
226
+ const shown = this.shown.get(session);
227
+ return shown && working && this.coalescer.repeats(session, base) ? { ...shown, kind: null } : null;
228
+ }
229
+ /**
230
+ * The next observation of this session is sent whatever it holds. The hub's
231
+ * snapshot is untouched, so a kind it still shows is still cleared.
232
+ */
233
+ forget(session) {
234
+ this.coalescer.forget(session);
235
+ }
236
+ /** An update sent outside `frame` (a command's own observation), without activity. */
237
+ noteSent(update) {
238
+ if (update.state !== "working") this.shown.delete(update.action_id);
239
+ }
240
+ /** The session is no longer bound here: nothing of it is sent again. */
241
+ release(session) {
242
+ this.coalescer.forget(session);
243
+ this.shown.delete(session);
244
+ }
245
+ clear() {
246
+ this.coalescer.clear();
247
+ }
248
+ };
249
+
60
250
  // src/protocol.ts
61
251
  import { readFileSync } from "node:fs";
62
252
  var schemas = JSON.parse(
@@ -81,7 +271,7 @@ function matchesString(schema, value) {
81
271
  return typeof value === "string" && [...value].length >= (schema.minLength ?? 0) && [...value].length <= (schema.maxLength ?? Infinity) && (!schema.pattern || new RegExp(schema.pattern, "u").test(value)) && (schema.format !== "date-time" || /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u.test(value) && Number.isFinite(Date.parse(value)));
82
272
  }
83
273
  function matchesInteger(schema, value) {
84
- return typeof value === "number" && Number.isSafeInteger(value) && value >= (schema.minimum ?? -Infinity);
274
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= (schema.minimum ?? -Infinity) && value <= (schema.maximum ?? Infinity);
85
275
  }
86
276
  function matches(schema, value) {
87
277
  if (schema.$ref) return matches(requiredSchema(schema.$ref.split("/").at(-1) ?? ""), value);
@@ -133,18 +323,217 @@ function decodeRegistration(value) {
133
323
  throw new Error("Invalid machine hub path");
134
324
  return registration;
135
325
  }
136
- function parseJson(text2) {
137
- return JSON.parse(text2);
326
+ function parseJson(text3) {
327
+ return JSON.parse(text3);
138
328
  }
139
329
  function decodeHubText(data) {
140
330
  if (typeof data !== "string" || data.length > 131072) throw new Error("Invalid frame");
141
331
  return decodeHub(parseJson(data));
142
332
  }
143
333
 
334
+ // src/claude-transcript.ts
335
+ import { open, readdir, stat } from "node:fs/promises";
336
+ import { join } from "node:path";
337
+ var TRANSCRIPT_READ_BYTES = 1 << 20;
338
+ var LINE_LIMIT_BYTES = 8 << 20;
339
+ var SEARCH_INTERVAL_MS = 3e4;
340
+ var IDLE_FORGET_MS = 60 * 6e4;
341
+ var READING = /* @__PURE__ */ new Set(["Read", "Grep", "Glob", "LS", "NotebookRead"]);
342
+ var EDITING = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
343
+ var COMMANDS = /* @__PURE__ */ new Set(["Bash", "BashOutput"]);
344
+ var DELEGATING = /* @__PURE__ */ new Set(["Agent", "Task"]);
345
+ function claudeToolKind(name) {
346
+ if (READING.has(name)) return SESSION_ACTIVITY_KIND.READING;
347
+ if (EDITING.has(name)) return SESSION_ACTIVITY_KIND.EDITING;
348
+ if (COMMANDS.has(name)) return SESSION_ACTIVITY_KIND.RUNNING_COMMAND;
349
+ if (DELEGATING.has(name)) return SESSION_ACTIVITY_KIND.DELEGATING;
350
+ if (/^mcp__.+__tsp_/.test(name)) return SESSION_ACTIVITY_KIND.USING_PLAN;
351
+ return SESSION_ACTIVITY_KIND.USING_TOOL;
352
+ }
353
+ function claudeProjectFolder(cwd) {
354
+ return cwd.replace(/[^A-Za-z0-9]/g, "-");
355
+ }
356
+ function text(value) {
357
+ return typeof value === "string" ? value : null;
358
+ }
359
+ var ClaudeTranscripts = class {
360
+ constructor(now = Date.now) {
361
+ this.now = now;
362
+ }
363
+ cursors = /* @__PURE__ */ new Map();
364
+ edits = /* @__PURE__ */ new Map();
365
+ async activity(conversationId, cwd, configDir) {
366
+ try {
367
+ return await this.read(conversationId, cwd, configDir);
368
+ } catch {
369
+ return null;
370
+ }
371
+ }
372
+ /** Sessions nobody asked about for an hour are forgotten; asking again re-reads from the start. */
373
+ prune() {
374
+ for (const [id, cursor] of this.cursors)
375
+ if (this.now() - cursor.readAt > IDLE_FORGET_MS) {
376
+ this.cursors.delete(id);
377
+ this.edits.delete(id);
378
+ }
379
+ }
380
+ async read(conversationId, cwd, configDir) {
381
+ this.prune();
382
+ let cursor = this.cursors.get(conversationId);
383
+ if (!cursor) {
384
+ cursor = this.fresh(null);
385
+ this.cursors.set(conversationId, cursor);
386
+ }
387
+ cursor.readAt = this.now();
388
+ cursor.path ??= await this.locate(cursor, conversationId, cwd, configDir);
389
+ if (!cursor.path) return null;
390
+ let size;
391
+ try {
392
+ size = (await stat(cursor.path)).size;
393
+ } catch {
394
+ this.cursors.set(conversationId, this.fresh(null));
395
+ return null;
396
+ }
397
+ if (size < cursor.offset) {
398
+ cursor = this.fresh(cursor.path);
399
+ this.cursors.set(conversationId, cursor);
400
+ this.edits.delete(conversationId);
401
+ }
402
+ if (size > cursor.offset) await this.advance(conversationId, cursor, size);
403
+ return cursor.caughtUp ? cursor.tally.snapshot() : null;
404
+ }
405
+ fresh(path) {
406
+ return {
407
+ path,
408
+ readAt: this.now(),
409
+ searchedAt: 0,
410
+ offset: 0,
411
+ remainder: Buffer.alloc(0),
412
+ tally: new ActivityTally(),
413
+ caughtUp: false
414
+ };
415
+ }
416
+ async locate(cursor, conversationId, cwd, configDir) {
417
+ const projects = join(configDir, "projects");
418
+ const file = `${conversationId}.jsonl`;
419
+ const expected = join(projects, claudeProjectFolder(cwd), file);
420
+ if (await exists(expected)) return expected;
421
+ if (this.now() - cursor.searchedAt < SEARCH_INTERVAL_MS) return null;
422
+ cursor.searchedAt = this.now();
423
+ for (const entry of await readdir(projects, { withFileTypes: true })) {
424
+ if (!entry.isDirectory()) continue;
425
+ const candidate = join(projects, entry.name, file);
426
+ if (await exists(candidate)) return candidate;
427
+ }
428
+ return null;
429
+ }
430
+ async advance(conversationId, cursor, size) {
431
+ const length = Math.min(size - cursor.offset, TRANSCRIPT_READ_BYTES);
432
+ const handle = await open(cursor.path, "r");
433
+ let chunk;
434
+ try {
435
+ const buffer = Buffer.alloc(length);
436
+ const { bytesRead } = await handle.read(buffer, 0, length, cursor.offset);
437
+ chunk = buffer.subarray(0, bytesRead);
438
+ } finally {
439
+ await handle.close();
440
+ }
441
+ cursor.offset += chunk.length;
442
+ cursor.caughtUp = cursor.offset >= size;
443
+ let data = cursor.remainder.length ? Buffer.concat([cursor.remainder, chunk]) : chunk;
444
+ let newline = data.indexOf(10);
445
+ while (newline !== -1) {
446
+ this.entry(conversationId, cursor.tally, data.subarray(0, newline));
447
+ data = data.subarray(newline + 1);
448
+ newline = data.indexOf(10);
449
+ }
450
+ cursor.remainder = data.length > LINE_LIMIT_BYTES ? Buffer.alloc(0) : Buffer.from(data);
451
+ }
452
+ entry(conversationId, tally, line) {
453
+ const entry = parseEntry(line);
454
+ if (!entry) return;
455
+ const { role, content, at } = entry;
456
+ if (typeof content === "string") {
457
+ if (role === "user") {
458
+ tally.stepped(at);
459
+ tally.between();
460
+ }
461
+ return;
462
+ }
463
+ const edits = this.editsOf(conversationId);
464
+ for (const block of content) {
465
+ const kind = field(block, "type");
466
+ if (kind === "text" || kind === "thinking") {
467
+ tally.stepped(at);
468
+ tally.between();
469
+ } else if (kind === "tool_use" && role === "assistant")
470
+ toolUse(tally, edits, block, at);
471
+ else if (kind === "tool_result" && role === "user") toolResult(tally, edits, block, at);
472
+ }
473
+ }
474
+ editsOf(conversationId) {
475
+ let edits = this.edits.get(conversationId);
476
+ if (!edits) {
477
+ edits = /* @__PURE__ */ new Map();
478
+ this.edits.set(conversationId, edits);
479
+ }
480
+ return edits;
481
+ }
482
+ };
483
+ function parseEntry(line) {
484
+ let value;
485
+ try {
486
+ value = JSON.parse(line.toString("utf8"));
487
+ } catch {
488
+ return null;
489
+ }
490
+ if (!isObject(value) || field(value, "isSidechain") === true) return null;
491
+ const role = field(value, "type");
492
+ if (role !== "user" && role !== "assistant") return null;
493
+ const message = field(value, "message");
494
+ if (!isObject(message)) return null;
495
+ const content = field(message, "content");
496
+ const at = Date.parse(text(field(value, "timestamp")) ?? "");
497
+ if (typeof content === "string") return { role, content, at };
498
+ if (!Array.isArray(content)) return null;
499
+ return { role, content: content.filter(isObject), at };
500
+ }
501
+ function toolUse(tally, edits, block, at) {
502
+ const id = text(field(block, "id"));
503
+ const name = text(field(block, "name"));
504
+ if (!id || !name) return;
505
+ tally.stepped(at);
506
+ const kind = claudeToolKind(name);
507
+ tally.started(id, kind);
508
+ if (name === "Bash") tally.ranCommand();
509
+ if (kind !== SESSION_ACTIVITY_KIND.EDITING) return;
510
+ const input = field(block, "input");
511
+ const path = isObject(input) ? text(field(input, "file_path")) ?? text(field(input, "notebook_path")) : null;
512
+ if (!path) return;
513
+ edits.set(id, path);
514
+ if (edits.size > 256) edits.delete(edits.keys().next().value);
515
+ }
516
+ function toolResult(tally, edits, block, at) {
517
+ const id = text(field(block, "tool_use_id"));
518
+ if (!id) return;
519
+ tally.stepped(at);
520
+ tally.finished(id);
521
+ const path = edits.get(id);
522
+ edits.delete(id);
523
+ if (path && field(block, "is_error") !== true) tally.editedFile(path);
524
+ }
525
+ async function exists(path) {
526
+ try {
527
+ return (await stat(path)).isFile();
528
+ } catch {
529
+ return false;
530
+ }
531
+ }
532
+
144
533
  // src/claude-trust.ts
145
- import { open } from "node:fs/promises";
534
+ import { open as open2 } from "node:fs/promises";
146
535
  import { homedir } from "node:os";
147
- import { join } from "node:path";
536
+ import { join as join2 } from "node:path";
148
537
  var MAX_CONFIG_BYTES = 4 * 1024 * 1024;
149
538
  var ClaudeTrust = class {
150
539
  constructor(environment = process.env, home = homedir()) {
@@ -159,11 +548,11 @@ var ClaudeTrust = class {
159
548
  async projects(folder) {
160
549
  try {
161
550
  const env = typeof this.environment === "function" ? await this.environment(folder) : this.environment;
162
- const path = join(env["CLAUDE_CONFIG_DIR"] ?? env["HOME"] ?? this.home, ".claude.json");
551
+ const path = join2(env["CLAUDE_CONFIG_DIR"] ?? env["HOME"] ?? this.home, ".claude.json");
163
552
  const previous = this.paths.get(folder);
164
553
  if (previous !== void 0 && path !== previous) this.observed.delete(folder);
165
554
  this.paths.set(folder, path);
166
- const handle = await open(path, "r");
555
+ const handle = await open2(path, "r");
167
556
  try {
168
557
  const info = await handle.stat();
169
558
  if (!info.isFile() || info.size > MAX_CONFIG_BYTES) return null;
@@ -208,6 +597,9 @@ var ClaudeTrust = class {
208
597
  function isTerminalSessionState(state) {
209
598
  return state === AGENT_SESSION_STATE.DONE || state === AGENT_SESSION_STATE.STOPPED || state === AGENT_SESSION_STATE.ENDED || state === AGENT_SESSION_STATE.FAILED;
210
599
  }
600
+ function wantsActivity(query, id) {
601
+ return query !== void 0 && "refs" in query && query.activity === true && query.refs.includes(id);
602
+ }
211
603
  var HarnessRefusal = class extends Error {
212
604
  constructor(reason) {
213
605
  super(reason);
@@ -221,7 +613,7 @@ import { isAbsolute } from "node:path";
221
613
  function defaultLaunchConfig() {
222
614
  return { mode: "login-shell", wrapper: [], env: {} };
223
615
  }
224
- function text(value) {
616
+ function text2(value) {
225
617
  return typeof value === "string" && !value.includes("\0");
226
618
  }
227
619
  function decodeLaunchConfig(value) {
@@ -232,7 +624,7 @@ function decodeLaunchConfig(value) {
232
624
  const wrapper = Object.hasOwn(value, "wrapper") ? field(value, "wrapper") : [];
233
625
  const env = Object.hasOwn(value, "env") ? field(value, "env") : {};
234
626
  if (mode !== "login-shell" && mode !== "direct") throw new Error("Invalid launch.mode");
235
- if (shell !== void 0 && (!text(shell) || !isAbsolute(shell)))
627
+ if (shell !== void 0 && (!text2(shell) || !isAbsolute(shell)))
236
628
  throw new Error("launch.shell must be an absolute executable path");
237
629
  return {
238
630
  mode,
@@ -242,7 +634,7 @@ function decodeLaunchConfig(value) {
242
634
  };
243
635
  }
244
636
  function decodeWrapper(wrapper) {
245
- if (!Array.isArray(wrapper) || !wrapper.every(text) || wrapper.length > 0 && !wrapper[0])
637
+ if (!Array.isArray(wrapper) || !wrapper.every(text2) || wrapper.length > 0 && !wrapper[0])
246
638
  throw new Error("launch.wrapper must be an argv array with a nonempty executable");
247
639
  const executable2 = wrapper[0];
248
640
  if (executable2 !== void 0 && !isAbsolute(executable2) && !/^[A-Za-z0-9_][A-Za-z0-9_.+-]*$/.test(executable2))
@@ -256,7 +648,7 @@ function decodeVariables(env) {
256
648
  const variables = {};
257
649
  for (const name of Object.keys(env)) {
258
650
  const entry = field(env, name);
259
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || !text(entry))
651
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || !text2(entry))
260
652
  throw new Error("launch.env must contain valid names and NUL-free string values");
261
653
  Object.defineProperty(variables, name, { value: entry, enumerable: true });
262
654
  }
@@ -309,7 +701,7 @@ function pidAlive(pid) {
309
701
 
310
702
  // src/shell-strategy.ts
311
703
  import { constants } from "node:fs";
312
- import { access, stat } from "node:fs/promises";
704
+ import { access, stat as stat2 } from "node:fs/promises";
313
705
  import { userInfo } from "node:os";
314
706
  import { basename, isAbsolute as isAbsolute2 } from "node:path";
315
707
  var posix = {
@@ -344,7 +736,7 @@ async function executable(path) {
344
736
  if (!isAbsolute2(path)) return false;
345
737
  try {
346
738
  await access(path, constants.X_OK);
347
- return (await stat(path)).isFile();
739
+ return (await stat2(path)).isFile();
348
740
  } catch {
349
741
  return false;
350
742
  }
@@ -401,6 +793,7 @@ import { resolve } from "node:path";
401
793
  // src/shell-process.ts
402
794
  import { spawn as spawn2 } from "node:child_process";
403
795
  import { randomUUID } from "node:crypto";
796
+ import { existsSync } from "node:fs";
404
797
  import { basename as basename2, resolve as resolvePath } from "node:path";
405
798
 
406
799
  // src/shell-output.ts
@@ -426,8 +819,8 @@ var ShellOutput = class {
426
819
  return output;
427
820
  }
428
821
  };
429
- function decodeEnvironment(text2) {
430
- const value = parseJson(text2);
822
+ function decodeEnvironment(text3) {
823
+ const value = parseJson(text3);
431
824
  if (!isObject(value)) throw new Error("Invalid shell environment capture");
432
825
  const env = {};
433
826
  for (const name of Object.keys(value)) {
@@ -474,7 +867,7 @@ var CAPTURE_ENVIRONMENT = 'const fs=require("node:fs"),s=process.argv[1];if(!fs.
474
867
  import { closeSync, constants as constants2, openSync, writeSync } from "node:fs";
475
868
  import { mkdtemp, rm } from "node:fs/promises";
476
869
  import { tmpdir } from "node:os";
477
- import { join as join2 } from "node:path";
870
+ import { join as join3 } from "node:path";
478
871
  var ShellRelease = class _ShellRelease {
479
872
  constructor(path, directory, fd) {
480
873
  this.path = path;
@@ -482,8 +875,8 @@ var ShellRelease = class _ShellRelease {
482
875
  this.fd = fd;
483
876
  }
484
877
  static async create() {
485
- const directory = await mkdtemp(join2(tmpdir(), "tsp-shell-"));
486
- const path = join2(directory, "release");
878
+ const directory = await mkdtemp(join3(tmpdir(), "tsp-shell-"));
879
+ const path = join3(directory, "release");
487
880
  try {
488
881
  const result = await execute("/usr/bin/mkfifo", ["-m", "600", path], {});
489
882
  if (result.code !== 0) throw new Error("Could not create login-shell release FIFO");
@@ -508,6 +901,12 @@ var ShellRelease = class _ShellRelease {
508
901
  };
509
902
 
510
903
  // src/shell-process.ts
904
+ var ShellStartupError = class extends Error {
905
+ constructor(problem, message) {
906
+ super(message);
907
+ this.problem = problem;
908
+ }
909
+ };
511
910
  async function executeShell(path, argv, env, options) {
512
911
  const release = options.requireLive ? await ShellRelease.create() : void 0;
513
912
  try {
@@ -561,7 +960,8 @@ function runShell(path, argv, env, options) {
561
960
  };
562
961
  let timer = setTimeout(
563
962
  () => fail(
564
- new Error(
963
+ new ShellStartupError(
964
+ "timed_out",
565
965
  `Login shell startup timed out after ${startupMs}ms before harness exec (${path.shell})`
566
966
  )
567
967
  ),
@@ -593,7 +993,12 @@ function runShell(path, argv, env, options) {
593
993
  stderr = (stderr + err.read(chunk)).slice(-16e3);
594
994
  ready();
595
995
  });
596
- child.once("error", fail);
996
+ child.once(
997
+ "error",
998
+ (error) => fail(
999
+ error.code === "ENOENT" && cwd && !existsSync(cwd) ? new ShellStartupError("folder_unavailable", CWD_ERROR_PREFIX + cwd) : error
1000
+ )
1001
+ );
597
1002
  child.once("close", (code) => {
598
1003
  if (settled) return;
599
1004
  clearTimeout(timer);
@@ -611,9 +1016,15 @@ function runShell(path, argv, env, options) {
611
1016
  function shellExitError(options) {
612
1017
  const { path, code, started, stderr, cwd } = options;
613
1018
  if (code === 125 && stderr.includes(CWD_ERROR_PREFIX))
614
- return new Error(CWD_ERROR_PREFIX + (cwd ?? process.cwd()));
1019
+ return new ShellStartupError(
1020
+ "folder_unavailable",
1021
+ CWD_ERROR_PREFIX + (cwd ?? process.cwd())
1022
+ );
615
1023
  if (!started)
616
- return new Error(`Login shell exited before harness exec (${path.shell}, exit ${code})`);
1024
+ return new ShellStartupError(
1025
+ "exited",
1026
+ `Login shell exited before harness exec (${path.shell}, exit ${code})`
1027
+ );
617
1028
  return void 0;
618
1029
  }
619
1030
 
@@ -628,8 +1039,11 @@ var HarnessExecutor = class {
628
1039
  captures = /* @__PURE__ */ new Map();
629
1040
  revision;
630
1041
  lastPath;
1042
+ /** The most recent successful capture in any folder, for a folder with none of its own. */
1043
+ latest;
631
1044
  invalidate() {
632
1045
  this.captures.clear();
1046
+ this.latest = void 0;
633
1047
  this.revision = void 0;
634
1048
  this.lastPath = void 0;
635
1049
  }
@@ -658,16 +1072,31 @@ var HarnessExecutor = class {
658
1072
  wrapper: config.wrapper[0] ?? null,
659
1073
  wrapper_arguments: Math.max(0, config.wrapper.length - 1),
660
1074
  env_names: Object.keys(config.env),
661
- environment_cached: [...this.captures.values()].some(
662
- (capture) => capture.environment !== void 0
663
- )
1075
+ environment_cached: this.latest !== void 0
664
1076
  };
665
1077
  }
1078
+ log(message) {
1079
+ (this.options.log ?? console.error)(message);
1080
+ }
1081
+ /**
1082
+ * What stands in for a login shell too slow to start: this folder's last capture, else
1083
+ * the most recent capture in any folder, run from this one.
1084
+ */
1085
+ cached(cwd) {
1086
+ const own = this.captures.get(cwd)?.captured;
1087
+ if (own) return { environment: own, source: cwd };
1088
+ if (!this.latest) return void 0;
1089
+ return { environment: { ...this.latest.environment, PWD: cwd }, source: this.latest.cwd };
1090
+ }
1091
+ startupMs(cwd) {
1092
+ const startupMs = this.options.startupMs ?? 1e4;
1093
+ return this.cached(cwd) ? startupMs : this.options.uncachedStartupMs ?? startupMs * 3;
1094
+ }
666
1095
  record(path) {
667
1096
  const changed = JSON.stringify(path) !== JSON.stringify(this.lastPath);
668
1097
  this.lastPath = path;
669
1098
  if (changed) {
670
- (this.options.log ?? console.error)(
1099
+ this.log(
671
1100
  `TSP gateway launch path: ${path.mode} shell=${JSON.stringify(path.shell)} reason=${path.reason}`
672
1101
  );
673
1102
  this.options.changed?.();
@@ -687,10 +1116,13 @@ var HarnessExecutor = class {
687
1116
  path,
688
1117
  overlaid.length ? ["/usr/bin/env", ...overlaid, ...argv] : argv,
689
1118
  this.env,
690
- { cwd, startupMs: this.options.startupMs ?? 1e4, requireLive }
1119
+ { cwd, startupMs: this.startupMs(cwd), requireLive }
691
1120
  );
692
1121
  if (result.code === 0 && this.captures.get(cwd) === capture && generation === capture.generation) {
693
- capture.environment = { ...result.environment, ...config.env };
1122
+ const environment = { ...result.environment, ...config.env };
1123
+ capture.environment = capture.captured = environment;
1124
+ capture.standIn = false;
1125
+ this.latest = { cwd, environment };
694
1126
  this.options.changed?.();
695
1127
  }
696
1128
  return { code: result.code, stdout: result.stdout, stderr: result.stderr };
@@ -703,20 +1135,47 @@ var HarnessExecutor = class {
703
1135
  capture,
704
1136
  requireLive
705
1137
  );
706
- (this.options.log ?? console.error)(
707
- error instanceof Error ? error.message : "Login shell startup failed"
708
- );
1138
+ this.log(error instanceof Error ? error.message : "Login shell startup failed");
709
1139
  throw error;
710
1140
  }
711
1141
  }
712
1142
  capture(cwd) {
713
1143
  let capture = this.captures.get(cwd);
714
1144
  if (!capture) {
715
- capture = { cwd, generation: 0, environment: void 0, initialization: void 0 };
1145
+ capture = {
1146
+ cwd,
1147
+ generation: 0,
1148
+ environment: void 0,
1149
+ captured: void 0,
1150
+ standIn: false,
1151
+ initialization: void 0
1152
+ };
716
1153
  this.captures.set(cwd, capture);
717
1154
  }
718
1155
  return capture;
719
1156
  }
1157
+ /**
1158
+ * A launch runs the harness from a fresh login shell. When that shell takes too long to
1159
+ * start, it runs from the last captured environment instead, and does not wait on a
1160
+ * shell that just timed out in this folder. Only a launch gated by `requireLive` is
1161
+ * provably unstarted on a timeout: its shell waits for that release before exec.
1162
+ */
1163
+ async launch(path, argv, config, capture, requireLive) {
1164
+ const { cwd } = capture;
1165
+ const standIn = capture.standIn && requireLive ? capture.environment : void 0;
1166
+ let cached = standIn && { environment: standIn, source: cwd };
1167
+ if (!cached) {
1168
+ try {
1169
+ return await this.shell(path, argv, config, capture, requireLive);
1170
+ } catch (error) {
1171
+ cached = requireLive && slowShell(error) ? this.cached(cwd) : void 0;
1172
+ if (!cached) throw error;
1173
+ }
1174
+ }
1175
+ this.log(`Launching with the login-shell environment captured in ${cached.source}`);
1176
+ requireLive();
1177
+ return execute(argv[0], argv.slice(1), cached.environment, cwd);
1178
+ }
720
1179
  /** Read/control calls share a cold capture per cwd; repository-free calls use home. */
721
1180
  async execute(file, args, purpose = "read", cwd = this.home, requireLive) {
722
1181
  cwd = resolve(cwd);
@@ -734,7 +1193,7 @@ var HarnessExecutor = class {
734
1193
  requireLive?.();
735
1194
  return execute(argv[0], argv.slice(1), { ...this.env, ...config.env }, cwd);
736
1195
  }
737
- if (purpose === "launch") return this.shell(path, argv, config, capture, requireLive);
1196
+ if (purpose === "launch") return this.launch(path, argv, config, capture, requireLive);
738
1197
  const environment = await this.environment(false, cwd);
739
1198
  requireLive?.();
740
1199
  return execute(argv[0], argv.slice(1), environment, cwd);
@@ -746,6 +1205,7 @@ var HarnessExecutor = class {
746
1205
  if (fresh) {
747
1206
  capture.generation++;
748
1207
  capture.environment = void 0;
1208
+ capture.standIn = false;
749
1209
  capture.initialization = void 0;
750
1210
  }
751
1211
  const generation = capture.generation;
@@ -768,6 +1228,15 @@ var HarnessExecutor = class {
768
1228
  });
769
1229
  try {
770
1230
  await initialization;
1231
+ } catch (error) {
1232
+ const cached = slowShell(error) ? this.cached(cwd) : void 0;
1233
+ if (!cached) throw error;
1234
+ this.log(`Using the login-shell environment captured in ${cached.source}`);
1235
+ if (this.captures.get(cwd) === capture && generation === capture.generation) {
1236
+ capture.environment = cached.environment;
1237
+ capture.standIn = true;
1238
+ }
1239
+ return cached.environment;
771
1240
  } finally {
772
1241
  if (capture.initialization === initialization) capture.initialization = void 0;
773
1242
  }
@@ -785,17 +1254,22 @@ var HarnessExecutor = class {
785
1254
  return spawn3(argv[0], argv.slice(1), { cwd, env, stdio: "pipe", windowsHide: true });
786
1255
  }
787
1256
  };
1257
+ function slowShell(error) {
1258
+ return error instanceof ShellStartupError && error.problem === "timed_out";
1259
+ }
788
1260
 
789
1261
  // src/claude-driver.ts
1262
+ import { homedir as homedir3 } from "node:os";
1263
+ import { isAbsolute as isAbsolute3, join as join4 } from "node:path";
790
1264
  import { setTimeout as delay } from "node:timers/promises";
791
1265
  function opaque(value) {
792
1266
  if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value))
793
1267
  throw new Error("Invalid local session id");
794
1268
  return value;
795
1269
  }
796
- function sanitizeWaiting(text2) {
1270
+ function sanitizeWaiting(text3) {
797
1271
  return [
798
- ...text2.replace(
1272
+ ...text3.replace(
799
1273
  /(?:\\\\[?.]\\|\\\?\?\\|\\\\|[A-Za-z]:[\\/]|~?\/|\.\.?\/)[^\s"'<>]+/g,
800
1274
  "[local path]"
801
1275
  ).split("").map((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127 ? " " : char).join("")
@@ -811,7 +1285,7 @@ function backgroundSession(row) {
811
1285
  } catch {
812
1286
  return null;
813
1287
  }
814
- const name = field(row, "name"), pid = field(row, "pid"), state = field(row, "state"), waiting = field(row, "waitingFor"), startedAt = field(row, "startedAt");
1288
+ const name = field(row, "name"), pid = field(row, "pid"), state = field(row, "state"), waiting = field(row, "waitingFor"), startedAt = field(row, "startedAt"), cwd = field(row, "cwd");
815
1289
  if (typeof name !== "string" || typeof state !== "string" || !(pid === void 0 || typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0))
816
1290
  return null;
817
1291
  return {
@@ -822,19 +1296,22 @@ function backgroundSession(row) {
822
1296
  state,
823
1297
  waiting,
824
1298
  idle: field(row, "status") === "idle",
825
- startedAt: typeof startedAt === "number" ? startedAt : null
1299
+ startedAt: typeof startedAt === "number" ? startedAt : null,
1300
+ cwd: typeof cwd === "string" && isAbsolute3(cwd) ? cwd : null
826
1301
  };
827
1302
  }
828
1303
  var ClaudeDriver = class {
829
- constructor(env, executable2 = "claude", trust = void 0, executor = new HarnessExecutor(env)) {
1304
+ constructor(env, executable2 = "claude", trust = void 0, executor = new HarnessExecutor(env), transcripts = new ClaudeTranscripts()) {
830
1305
  this.executable = executable2;
831
1306
  this.executor = executor;
1307
+ this.transcripts = transcripts;
832
1308
  this.trust = trust ?? new ClaudeTrust((folder) => this.executor.environment(false, folder));
833
1309
  }
834
1310
  trust;
835
1311
  repositorySetupInstruction = "Run claude in that folder once and accept its trust prompt.";
836
- signInInstruction = "Claude Code isn't signed in here. Run claude and sign in.";
837
- installInstruction = "Claude Code was not found. Install it with npm install --global @anthropic-ai/claude-code, then run connect again.";
1312
+ displayName = "Claude Code";
1313
+ signInInstruction = "Run claude and sign in.";
1314
+ installInstruction = "Install it with npm install --global @anthropic-ai/claude-code, then run connect again.";
838
1315
  unknownTrustAdmits = true;
839
1316
  capabilities = {
840
1317
  start: true,
@@ -881,9 +1358,6 @@ var ClaudeDriver = class {
881
1358
  }
882
1359
  }
883
1360
  async start(command, folder, requireLive) {
884
- const detection = await this.detect(folder);
885
- if (!detection.available) throw new HarnessRefusal("harness_unavailable");
886
- if (detection.signed_in === false) throw new HarnessRefusal("not_signed_in");
887
1361
  requireLive();
888
1362
  const result = await this.call(
889
1363
  ["--bg", "--name", command.session_name, "--", command.seed],
@@ -897,7 +1371,7 @@ var ClaudeDriver = class {
897
1371
  throw new HarnessRefusal("workspace_untrusted");
898
1372
  }
899
1373
  if (await this.signedIn(folder) === false) throw new HarnessRefusal("not_signed_in");
900
- throw new HarnessRefusal("start_failed");
1374
+ throw new HarnessRefusal("harness_exited");
901
1375
  }
902
1376
  const id = /backgrounded\s*·\s*([A-Za-z0-9_-]+)(?=\s*(?:·|$))/m.exec(result.stdout)?.[1];
903
1377
  if (!id) throw new Error("Uncertain launch result; inspect local harness");
@@ -905,7 +1379,7 @@ var ClaudeDriver = class {
905
1379
  this.trust.mark(folder, "trusted");
906
1380
  return sessionId;
907
1381
  }
908
- async list(folder) {
1382
+ async list(folder, _requireLive, query) {
909
1383
  const result = await this.call(["agents", "--json", "--all"], folder);
910
1384
  if (result.code !== 0) throw new Error("Cannot list local sessions");
911
1385
  const rows = parseJson(result.stdout);
@@ -915,7 +1389,7 @@ var ClaudeDriver = class {
915
1389
  for (const row of rows) {
916
1390
  const session = backgroundSession(row);
917
1391
  if (!session) continue;
918
- const { id, conversationId, name, pid, state, waiting, idle, startedAt } = session;
1392
+ const { id, conversationId, name, pid, state, waiting, idle, startedAt, cwd } = session;
919
1393
  let mapped = "unknown";
920
1394
  let waitingFor = null;
921
1395
  if (state === "working")
@@ -932,10 +1406,29 @@ var ClaudeDriver = class {
932
1406
  waitingFor = "Claude Code is not signed in. Run claude auth login.";
933
1407
  } else mapped = "needs_input";
934
1408
  }
935
- sessions.push({ id, conversationId, name, pid, state: mapped, waitingFor });
1409
+ sessions.push({
1410
+ id,
1411
+ conversationId,
1412
+ name,
1413
+ pid,
1414
+ state: mapped,
1415
+ waitingFor,
1416
+ ...wantsActivity(query, id) ? { activity: await this.activity(conversationId, cwd, folder) } : {}
1417
+ });
936
1418
  }
937
1419
  return sessions;
938
1420
  }
1421
+ /** What the session's transcript says it is doing; null when it cannot say. */
1422
+ async activity(conversationId, cwd, folder) {
1423
+ if (!cwd) return null;
1424
+ try {
1425
+ const env = await this.executor.environment(false, folder);
1426
+ const configDir = env["CLAUDE_CONFIG_DIR"] ?? join4(env["HOME"] ?? homedir3(), ".claude");
1427
+ return await this.transcripts.activity(conversationId, cwd, configDir);
1428
+ } catch {
1429
+ return null;
1430
+ }
1431
+ }
939
1432
  async stop(session, folder, requireLive) {
940
1433
  requireLive();
941
1434
  const result = await this.call(
@@ -946,7 +1439,7 @@ var ClaudeDriver = class {
946
1439
  );
947
1440
  if (result.code !== 0) throw new HarnessRefusal("stop_failed");
948
1441
  }
949
- async resume(session, text2, folder, requireLive) {
1442
+ async resume(session, text3, folder, requireLive) {
950
1443
  if (session.state === "working" || session.state === "needs_input")
951
1444
  throw new HarnessRefusal("unsupported_command");
952
1445
  if (session.pid !== null) {
@@ -954,13 +1447,13 @@ var ClaudeDriver = class {
954
1447
  const until = performance.now() + 1e4;
955
1448
  while (pidAlive(session.pid)) {
956
1449
  requireLive();
957
- if (performance.now() >= until) throw new HarnessRefusal("start_failed");
1450
+ if (performance.now() >= until) throw new HarnessRefusal("stop_failed");
958
1451
  await delay(50);
959
1452
  }
960
1453
  }
961
1454
  await this.executor.environment(true, folder);
962
1455
  if (await this.signedIn(folder) === false) throw new HarnessRefusal("not_signed_in");
963
- const prompt = text2 ?? (session.state === "stopped" ? RESUME_CONTINUATION : null);
1456
+ const prompt = text3 ?? (session.state === "stopped" ? RESUME_CONTINUATION : null);
964
1457
  requireLive();
965
1458
  const result = await this.call(
966
1459
  [
@@ -973,7 +1466,7 @@ var ClaudeDriver = class {
973
1466
  "launch",
974
1467
  requireLive
975
1468
  );
976
- if (result.code !== 0) throw new HarnessRefusal("start_failed");
1469
+ if (result.code !== 0) throw new HarnessRefusal("harness_exited");
977
1470
  const copy = /started a copy as\s+([A-Za-z0-9_-]+)/.exec(result.stdout)?.[1];
978
1471
  const background = /backgrounded\s*·\s*([A-Za-z0-9_-]+)(?=\s*(?:·|$))/m.exec(
979
1472
  result.stdout
@@ -1014,10 +1507,241 @@ var ClaudeDriver = class {
1014
1507
  }
1015
1508
  };
1016
1509
 
1510
+ // src/codex-protocol.ts
1511
+ var STATES = {
1512
+ active: { state: AGENT_SESSION_STATE.WORKING, waitingFor: null },
1513
+ waitingOnApproval: {
1514
+ state: AGENT_SESSION_STATE.NEEDS_INPUT,
1515
+ waitingFor: "Codex needs approval. Open the session locally."
1516
+ },
1517
+ waitingOnUserInput: {
1518
+ state: AGENT_SESSION_STATE.NEEDS_INPUT,
1519
+ waitingFor: "Codex needs your input. Open the session locally."
1520
+ },
1521
+ idle: { state: AGENT_SESSION_STATE.NEEDS_INPUT, waitingFor: "Codex is waiting for a prompt." },
1522
+ completed: { state: AGENT_SESSION_STATE.DONE, waitingFor: null },
1523
+ interrupted: { state: AGENT_SESSION_STATE.STOPPED, waitingFor: null },
1524
+ failed: { state: AGENT_SESSION_STATE.FAILED, waitingFor: null },
1525
+ inProgress: { state: AGENT_SESSION_STATE.WORKING, waitingFor: null },
1526
+ systemError: { state: AGENT_SESSION_STATE.FAILED, waitingFor: null },
1527
+ unknown: { state: AGENT_SESSION_STATE.UNKNOWN, waitingFor: null }
1528
+ };
1529
+ function codexId(value) {
1530
+ if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value))
1531
+ throw new Error("Invalid Codex session identity");
1532
+ return value;
1533
+ }
1534
+ function member(value, choices, fallback) {
1535
+ return typeof value === "string" && choices.includes(value) ? value : fallback;
1536
+ }
1537
+ function codexThread(value) {
1538
+ if (!isObject(value)) throw new Error("Invalid Codex thread");
1539
+ const cwd = field(value, "cwd"), name = field(value, "name"), status = field(value, "status"), turns = field(value, "turns");
1540
+ if (typeof cwd !== "string" || !isObject(status))
1541
+ throw new Error("Invalid Codex thread metadata");
1542
+ const flags = field(status, "activeFlags");
1543
+ return {
1544
+ id: codexId(field(value, "id")),
1545
+ cwd,
1546
+ name: typeof name === "string" ? name : "",
1547
+ status: member(
1548
+ field(status, "type"),
1549
+ ["active", "idle", "systemError", "notLoaded", "unknown"],
1550
+ "unknown"
1551
+ ),
1552
+ activeFlags: Array.isArray(flags) ? flags.filter(
1553
+ (flag) => flag === "waitingOnApproval" || flag === "waitingOnUserInput"
1554
+ ) : [],
1555
+ turns: Array.isArray(turns) ? turns.map(codexTurn) : []
1556
+ };
1557
+ }
1558
+ function codexTurn(value) {
1559
+ if (!isObject(value)) throw new Error("Invalid Codex turn");
1560
+ return {
1561
+ id: codexId(field(value, "id")),
1562
+ status: member(
1563
+ field(value, "status"),
1564
+ ["completed", "interrupted", "failed", "inProgress", "unknown"],
1565
+ "unknown"
1566
+ )
1567
+ };
1568
+ }
1569
+ function latestTurn(value) {
1570
+ if (!isObject(value)) throw new Error("Invalid Codex turn page");
1571
+ const data = field(value, "data");
1572
+ if (!Array.isArray(data) || data.length > 1) throw new Error("Invalid Codex turn page");
1573
+ return data.length ? codexTurn(data[0]) : null;
1574
+ }
1575
+ function threadResult(value) {
1576
+ return codexThread(isObject(value) ? field(value, "thread") : null);
1577
+ }
1578
+ function page(value, decode) {
1579
+ if (!isObject(value)) throw new Error("Invalid Codex thread list");
1580
+ const data = field(value, "data"), cursor = field(value, "nextCursor");
1581
+ if (!Array.isArray(data) || !(cursor === null || typeof cursor === "string"))
1582
+ throw new Error("Invalid Codex thread page");
1583
+ return { threads: data.map(decode), cursor };
1584
+ }
1585
+ function threadPage(value) {
1586
+ return page(value, codexThread);
1587
+ }
1588
+ function loadedThreadPage(value) {
1589
+ return page(value, codexId);
1590
+ }
1591
+ function sessionFromThread(thread) {
1592
+ const key = thread.status === "active" ? thread.activeFlags.find((flag) => flag === "waitingOnApproval") ?? thread.activeFlags[0] ?? "active" : thread.status === "idle" || thread.status === "notLoaded" ? thread.turns.at(-1)?.status ?? "idle" : thread.status;
1593
+ return {
1594
+ id: thread.id,
1595
+ conversationId: thread.id,
1596
+ name: thread.name,
1597
+ pid: null,
1598
+ ...STATES[key]
1599
+ };
1600
+ }
1601
+
1602
+ // src/codex-activity.ts
1603
+ var PAGE_SIZE = 20;
1604
+ var PAGE_LIMIT = 5;
1605
+ var IDLE_FORGET_MS2 = 60 * 6e4;
1606
+ var SETTLED_MEMORY = 200;
1607
+ var READ_ACTIONS = /* @__PURE__ */ new Set(["read", "listFiles", "search"]);
1608
+ var BETWEEN = /* @__PURE__ */ new Set(["reasoning", "agentMessage", "plan", "userMessage", "hookPrompt"]);
1609
+ function readOnly(item) {
1610
+ const actions = field(item, "commandActions");
1611
+ return Array.isArray(actions) && actions.length > 0 && actions.every(
1612
+ (action) => isObject(action) && READ_ACTIONS.has(String(field(action, "type")))
1613
+ );
1614
+ }
1615
+ function codexItemKind(item) {
1616
+ const type = field(item, "type");
1617
+ if (type === "commandExecution")
1618
+ return readOnly(item) ? SESSION_ACTIVITY_KIND.READING : SESSION_ACTIVITY_KIND.RUNNING_COMMAND;
1619
+ if (type === "fileChange") return SESSION_ACTIVITY_KIND.EDITING;
1620
+ if (type === "mcpToolCall") {
1621
+ const tool = field(item, "tool");
1622
+ return typeof tool === "string" && /^tsp[._]/.test(tool) ? SESSION_ACTIVITY_KIND.USING_PLAN : SESSION_ACTIVITY_KIND.USING_TOOL;
1623
+ }
1624
+ if (type === "collabAgentToolCall" || type === "subAgentActivity")
1625
+ return SESSION_ACTIVITY_KIND.DELEGATING;
1626
+ if (typeof type === "string" && BETWEEN.has(type)) return SESSION_ACTIVITY_KIND.THINKING;
1627
+ return SESSION_ACTIVITY_KIND.USING_TOOL;
1628
+ }
1629
+ function entryOf(value) {
1630
+ if (!isObject(value)) return null;
1631
+ const item = field(value, "item");
1632
+ if (!isObject(item)) return null;
1633
+ const id = field(item, "id");
1634
+ if (typeof id !== "string" || !id) return null;
1635
+ const status = field(item, "status");
1636
+ const finite = (time) => typeof time === "number" && Number.isFinite(time);
1637
+ const completedAt = field(value, "completedAtMs");
1638
+ const times = [field(value, "startedAtMs"), completedAt].filter(finite);
1639
+ return {
1640
+ id,
1641
+ item,
1642
+ status: typeof status === "string" ? status : null,
1643
+ at: times.length ? Math.max(...times) : null,
1644
+ completed: finite(completedAt)
1645
+ };
1646
+ }
1647
+ var CodexActivity = class {
1648
+ constructor(now = Date.now) {
1649
+ this.now = now;
1650
+ }
1651
+ threads = /* @__PURE__ */ new Map();
1652
+ async activity(server, threadId) {
1653
+ try {
1654
+ return await this.read(server, threadId);
1655
+ } catch {
1656
+ return null;
1657
+ }
1658
+ }
1659
+ async read(server, threadId) {
1660
+ for (const [id, thread2] of this.threads)
1661
+ if (this.now() - thread2.readAt > IDLE_FORGET_MS2) this.threads.delete(id);
1662
+ let thread = this.threads.get(threadId);
1663
+ if (!thread) {
1664
+ thread = {
1665
+ tally: new ActivityTally(),
1666
+ settled: /* @__PURE__ */ new Set(),
1667
+ running: /* @__PURE__ */ new Set(),
1668
+ commands: /* @__PURE__ */ new Set(),
1669
+ readAt: this.now()
1670
+ };
1671
+ this.threads.set(threadId, thread);
1672
+ }
1673
+ thread.readAt = this.now();
1674
+ const entries = [];
1675
+ const unseen = new Set(thread.running);
1676
+ let cursor = null;
1677
+ for (let page2 = 0; page2 < PAGE_LIMIT; page2++) {
1678
+ const response = await server.request("thread/items/list", {
1679
+ threadId: codexId(threadId),
1680
+ limit: PAGE_SIZE,
1681
+ sortDirection: "desc",
1682
+ ...cursor ? { cursor } : {}
1683
+ });
1684
+ if (!isObject(response) || !Array.isArray(field(response, "data")))
1685
+ throw new Error("Unrecognised Codex item page");
1686
+ let reachedSettled = false;
1687
+ for (const raw of field(response, "data")) {
1688
+ const entry = entryOf(raw);
1689
+ if (!entry) continue;
1690
+ if (thread.settled.has(entry.id)) {
1691
+ reachedSettled = true;
1692
+ continue;
1693
+ }
1694
+ unseen.delete(entry.id);
1695
+ entries.push(entry);
1696
+ }
1697
+ const next = field(response, "nextCursor");
1698
+ cursor = typeof next === "string" && next ? next : null;
1699
+ if (!cursor || reachedSettled && unseen.size === 0) break;
1700
+ }
1701
+ for (const id of unseen) {
1702
+ thread.running.delete(id);
1703
+ thread.commands.delete(id);
1704
+ thread.tally.finished(id);
1705
+ }
1706
+ for (const entry of entries.reverse()) this.apply(thread, entry);
1707
+ return thread.tally.snapshot();
1708
+ }
1709
+ apply(thread, { id, item, status, at, completed }) {
1710
+ const kind = codexItemKind(item);
1711
+ thread.tally.stepped(at);
1712
+ if (kind === SESSION_ACTIVITY_KIND.RUNNING_COMMAND && !thread.commands.has(id)) {
1713
+ thread.commands.add(id);
1714
+ thread.tally.ranCommand();
1715
+ }
1716
+ const open6 = status === null && !completed && kind !== SESSION_ACTIVITY_KIND.THINKING;
1717
+ if (status === "inProgress" || open6) {
1718
+ thread.running.add(id);
1719
+ thread.tally.started(id, kind);
1720
+ return;
1721
+ }
1722
+ thread.running.delete(id);
1723
+ if (kind === SESSION_ACTIVITY_KIND.THINKING) thread.tally.between();
1724
+ else thread.tally.finished(id);
1725
+ if (field(item, "type") === "fileChange" && status === "completed") {
1726
+ const changes = field(item, "changes");
1727
+ if (Array.isArray(changes))
1728
+ for (const change of changes) {
1729
+ const path = isObject(change) ? field(change, "path") : null;
1730
+ if (typeof path === "string") thread.tally.editedFile(path);
1731
+ }
1732
+ }
1733
+ if (status === null && !completed) return;
1734
+ thread.settled.add(id);
1735
+ if (thread.settled.size > SETTLED_MEMORY)
1736
+ thread.settled.delete(thread.settled.values().next().value);
1737
+ thread.commands.delete(id);
1738
+ }
1739
+ };
1740
+
1017
1741
  // src/codex-trust.ts
1018
- import { open as open2, realpath } from "node:fs/promises";
1019
- import { homedir as homedir3 } from "node:os";
1020
- import { basename as basename3, dirname, join as join3, resolve as resolve2 } from "node:path";
1742
+ import { open as open3, realpath } from "node:fs/promises";
1743
+ import { homedir as homedir4 } from "node:os";
1744
+ import { basename as basename3, dirname, join as join5, resolve as resolve2 } from "node:path";
1021
1745
  import { parseToml } from "./vendor.js";
1022
1746
  var MAX_CONFIG_BYTES2 = 4 * 1024 * 1024;
1023
1747
  var CodexTrust = class {
@@ -1053,11 +1777,11 @@ var CodexTrust = class {
1053
1777
  for (const part of prefix.stdout.trim().split("/").filter(Boolean)) {
1054
1778
  if (part) given = dirname(given);
1055
1779
  }
1056
- const path = join3(
1057
- env["CODEX_HOME"] ?? join3(env["HOME"] ?? homedir3(), ".codex"),
1780
+ const path = join5(
1781
+ env["CODEX_HOME"] ?? join5(env["HOME"] ?? homedir4(), ".codex"),
1058
1782
  "config.toml"
1059
1783
  );
1060
- const file = await open2(path, "r");
1784
+ const file = await open3(path, "r");
1061
1785
  let contents;
1062
1786
  try {
1063
1787
  if (!(await file.stat()).isFile()) return "unknown";
@@ -1225,7 +1949,12 @@ var CodexAppServer = class _CodexAppServer {
1225
1949
  }
1226
1950
  }
1227
1951
  request(method, params, requireLive) {
1228
- return this.sendRequest(method, params, requireLive, this.timeouts.requestMs);
1952
+ return this.sendRequest(
1953
+ method,
1954
+ params,
1955
+ requireLive,
1956
+ method === "thread/start" ? this.timeouts.threadStartMs : this.timeouts.requestMs
1957
+ );
1229
1958
  }
1230
1959
  sendRequest(method, params, requireLive, timeoutMs) {
1231
1960
  if (this.closed || this.failure)
@@ -1283,106 +2012,14 @@ var CodexAppServer = class _CodexAppServer {
1283
2012
  }
1284
2013
  };
1285
2014
 
1286
- // src/codex-protocol.ts
1287
- var STATES = {
1288
- active: { state: AGENT_SESSION_STATE.WORKING, waitingFor: null },
1289
- waitingOnApproval: {
1290
- state: AGENT_SESSION_STATE.NEEDS_INPUT,
1291
- waitingFor: "Codex needs approval. Open the session locally."
1292
- },
1293
- waitingOnUserInput: {
1294
- state: AGENT_SESSION_STATE.NEEDS_INPUT,
1295
- waitingFor: "Codex needs your input. Open the session locally."
1296
- },
1297
- idle: { state: AGENT_SESSION_STATE.NEEDS_INPUT, waitingFor: "Codex is waiting for a prompt." },
1298
- completed: { state: AGENT_SESSION_STATE.DONE, waitingFor: null },
1299
- interrupted: { state: AGENT_SESSION_STATE.STOPPED, waitingFor: null },
1300
- failed: { state: AGENT_SESSION_STATE.FAILED, waitingFor: null },
1301
- inProgress: { state: AGENT_SESSION_STATE.WORKING, waitingFor: null },
1302
- systemError: { state: AGENT_SESSION_STATE.FAILED, waitingFor: null },
1303
- unknown: { state: AGENT_SESSION_STATE.UNKNOWN, waitingFor: null }
1304
- };
1305
- function codexId(value) {
1306
- if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value))
1307
- throw new Error("Invalid Codex session identity");
1308
- return value;
1309
- }
1310
- function member(value, choices, fallback) {
1311
- return typeof value === "string" && choices.includes(value) ? value : fallback;
1312
- }
1313
- function codexThread(value) {
1314
- if (!isObject(value)) throw new Error("Invalid Codex thread");
1315
- const cwd = field(value, "cwd"), name = field(value, "name"), status = field(value, "status"), turns = field(value, "turns");
1316
- if (typeof cwd !== "string" || !isObject(status))
1317
- throw new Error("Invalid Codex thread metadata");
1318
- const flags = field(status, "activeFlags");
1319
- return {
1320
- id: codexId(field(value, "id")),
1321
- cwd,
1322
- name: typeof name === "string" ? name : "",
1323
- status: member(
1324
- field(status, "type"),
1325
- ["active", "idle", "systemError", "notLoaded", "unknown"],
1326
- "unknown"
1327
- ),
1328
- activeFlags: Array.isArray(flags) ? flags.filter(
1329
- (flag) => flag === "waitingOnApproval" || flag === "waitingOnUserInput"
1330
- ) : [],
1331
- turns: Array.isArray(turns) ? turns.map(codexTurn) : []
1332
- };
1333
- }
1334
- function codexTurn(value) {
1335
- if (!isObject(value)) throw new Error("Invalid Codex turn");
1336
- return {
1337
- id: codexId(field(value, "id")),
1338
- status: member(
1339
- field(value, "status"),
1340
- ["completed", "interrupted", "failed", "inProgress", "unknown"],
1341
- "unknown"
1342
- )
1343
- };
1344
- }
1345
- function latestTurn(value) {
1346
- if (!isObject(value)) throw new Error("Invalid Codex turn page");
1347
- const data = field(value, "data");
1348
- if (!Array.isArray(data) || data.length > 1) throw new Error("Invalid Codex turn page");
1349
- return data.length ? codexTurn(data[0]) : null;
1350
- }
1351
- function threadResult(value) {
1352
- return codexThread(isObject(value) ? field(value, "thread") : null);
1353
- }
1354
- function page(value, decode) {
1355
- if (!isObject(value)) throw new Error("Invalid Codex thread list");
1356
- const data = field(value, "data"), cursor = field(value, "nextCursor");
1357
- if (!Array.isArray(data) || !(cursor === null || typeof cursor === "string"))
1358
- throw new Error("Invalid Codex thread page");
1359
- return { threads: data.map(decode), cursor };
1360
- }
1361
- function threadPage(value) {
1362
- return page(value, codexThread);
1363
- }
1364
- function loadedThreadPage(value) {
1365
- return page(value, codexId);
1366
- }
1367
- function sessionFromThread(thread) {
1368
- const key = thread.status === "active" ? thread.activeFlags.find((flag) => flag === "waitingOnApproval") ?? thread.activeFlags[0] ?? "active" : thread.status === "idle" || thread.status === "notLoaded" ? thread.turns.at(-1)?.status ?? "idle" : thread.status;
1369
- return {
1370
- id: thread.id,
1371
- conversationId: thread.id,
1372
- name: thread.name,
1373
- pid: null,
1374
- ...STATES[key]
1375
- };
1376
- }
1377
-
1378
2015
  // src/codex-sessions.ts
1379
2016
  import { realpath as realpath2 } from "node:fs/promises";
1380
- import { isAbsolute as isAbsolute3, relative, resolve as resolve3, sep } from "node:path";
2017
+ import { isAbsolute as isAbsolute4, relative, resolve as resolve3, sep } from "node:path";
1381
2018
  async function inside(folder, cwd) {
1382
- if (!isAbsolute3(cwd)) return false;
2019
+ if (!isAbsolute4(cwd)) return false;
1383
2020
  const path = await realpath2(cwd).catch(() => resolve3(cwd));
1384
2021
  const child = relative(folder, path);
1385
- return child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute3(child);
2022
+ return child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute4(child);
1386
2023
  }
1387
2024
  async function lastTurn(server, id) {
1388
2025
  return latestTurn(
@@ -1451,7 +2088,7 @@ async function* threads(server, folder, query) {
1451
2088
  } while (cursor);
1452
2089
  }
1453
2090
  }
1454
- async function listCodexSessions(server, folder, query) {
2091
+ async function listCodexSessions(server, folder, query, activity) {
1455
2092
  const root = await realpath2(folder);
1456
2093
  const sessions = [];
1457
2094
  for await (let thread of threads(server, folder, query)) {
@@ -1465,7 +2102,10 @@ async function listCodexSessions(server, folder, query) {
1465
2102
  thread = { ...thread, status: "unknown" };
1466
2103
  }
1467
2104
  }
1468
- sessions.push(sessionFromThread(thread));
2105
+ const session = sessionFromThread(thread);
2106
+ if (activity && wantsActivity(query, session.id))
2107
+ session.activity = await activity.activity(server, session.id);
2108
+ sessions.push(session);
1469
2109
  }
1470
2110
  return sessions;
1471
2111
  }
@@ -1473,7 +2113,7 @@ async function listCodexSessions(server, folder, query) {
1473
2113
  // src/codex-driver.ts
1474
2114
  var MINIMUM_CODEX_VERSION = "0.162.1";
1475
2115
  function supportedCodexVersion(version) {
1476
- const parts = (text2) => (text2.split(/[-+]/)[0] ?? "").split(".").map(Number);
2116
+ const parts = (text3) => (text3.split(/[-+]/)[0] ?? "").split(".").map(Number);
1477
2117
  if (!version) return true;
1478
2118
  const found = parts(version), minimum = parts(MINIMUM_CODEX_VERSION);
1479
2119
  for (const [index, part] of minimum.entries()) {
@@ -1482,17 +2122,29 @@ function supportedCodexVersion(version) {
1482
2122
  }
1483
2123
  return true;
1484
2124
  }
2125
+ var CODEX_TIMEOUTS = {
2126
+ startupMs: 1e4,
2127
+ requestMs: 1e4,
2128
+ // Three times the slowest start seen, on a machine at load 150 while Codex updated itself.
2129
+ threadStartMs: 6e4
2130
+ };
2131
+ async function discardThread(server, threadId) {
2132
+ try {
2133
+ await server.request("thread/delete", { threadId });
2134
+ } catch {
2135
+ }
2136
+ }
1485
2137
  var CodexDriver = class {
1486
- constructor(env, executable2 = "codex", executor = new HarnessExecutor(env), requestTimeoutMs = 1e4, startupTimeoutMs = 1e4) {
2138
+ constructor(env, executable2 = "codex", executor = new HarnessExecutor(env), timeouts = {}) {
1487
2139
  this.executable = executable2;
1488
2140
  this.executor = executor;
1489
- this.requestTimeoutMs = requestTimeoutMs;
1490
- this.startupTimeoutMs = startupTimeoutMs;
1491
2141
  this.trust = new CodexTrust(executor);
2142
+ this.timeouts = { ...CODEX_TIMEOUTS, ...timeouts };
1492
2143
  }
1493
2144
  repositorySetupInstruction = "Run codex in that folder once and accept its trust prompt.";
1494
- signInInstruction = "Codex isn't signed in here. Run codex login and sign in.";
1495
- installInstruction = `Codex ${MINIMUM_CODEX_VERSION} or newer was not found. Install or update it with npm install --global @openai/codex, then run connect again.`;
2145
+ displayName = "Codex";
2146
+ signInInstruction = "Run codex login and sign in.";
2147
+ installInstruction = `Install Codex ${MINIMUM_CODEX_VERSION} or newer with npm install --global @openai/codex, then run connect again.`;
1496
2148
  /** Codex refuses a folder it has no trust record for, so unknown trust is a step to take. */
1497
2149
  unknownTrustAdmits = false;
1498
2150
  capabilities = {
@@ -1503,6 +2155,8 @@ var CodexDriver = class {
1503
2155
  answer_input: false
1504
2156
  };
1505
2157
  trust;
2158
+ activity = new CodexActivity();
2159
+ timeouts;
1506
2160
  async detect(folder) {
1507
2161
  if (folder) await this.executor.environment(true, folder);
1508
2162
  return this.probe(folder);
@@ -1531,8 +2185,8 @@ var CodexDriver = class {
1531
2185
  "read",
1532
2186
  folder
1533
2187
  );
1534
- const text2 = login.stdout + login.stderr;
1535
- detection.signed_in = /not logged in/i.test(text2) ? false : login.code === 0 && /logged in/i.test(text2) ? true : null;
2188
+ const text3 = login.stdout + login.stderr;
2189
+ detection.signed_in = /not logged in/i.test(text3) ? false : login.code === 0 && /logged in/i.test(text3) ? true : null;
1536
2190
  }
1537
2191
  } catch {
1538
2192
  }
@@ -1544,10 +2198,12 @@ var CodexDriver = class {
1544
2198
  }
1545
2199
  async open(folder, requireLive) {
1546
2200
  try {
1547
- return await CodexAppServer.connect(this.executor, this.executable, folder, {
1548
- startupMs: this.startupTimeoutMs,
1549
- requestMs: this.requestTimeoutMs
1550
- });
2201
+ return await CodexAppServer.connect(
2202
+ this.executor,
2203
+ this.executable,
2204
+ folder,
2205
+ this.timeouts
2206
+ );
1551
2207
  } catch (error) {
1552
2208
  if (!requireLive) throw error;
1553
2209
  await this.requireTrusted(folder);
@@ -1563,7 +2219,7 @@ var CodexDriver = class {
1563
2219
  this.executor,
1564
2220
  this.executable,
1565
2221
  folder,
1566
- { startupMs: this.startupTimeoutMs, requestMs: this.requestTimeoutMs },
2222
+ this.timeouts,
1567
2223
  requireLive
1568
2224
  );
1569
2225
  }
@@ -1586,9 +2242,6 @@ var CodexDriver = class {
1586
2242
  }
1587
2243
  }
1588
2244
  async start(command, folder, requireLive, checkpoint) {
1589
- const detected = await this.detect(folder);
1590
- if (!detected.available) throw new HarnessRefusal("harness_unavailable");
1591
- if (detected.signed_in === false) throw new HarnessRefusal("not_signed_in");
1592
2245
  await this.requireTrusted(folder);
1593
2246
  return this.connection(
1594
2247
  folder,
@@ -1598,19 +2251,24 @@ var CodexDriver = class {
1598
2251
  await server.request("thread/start", { cwd: folder }, requireLive)
1599
2252
  );
1600
2253
  await checkpoint?.(thread.id);
1601
- await server.request(
1602
- "thread/name/set",
1603
- { threadId: thread.id, name: command.session_name },
1604
- requireLive
1605
- );
1606
- await server.request(
1607
- "turn/start",
1608
- {
1609
- threadId: thread.id,
1610
- input: [{ type: "text", text: command.seed, text_elements: [] }]
1611
- },
1612
- requireLive
1613
- );
2254
+ try {
2255
+ await server.request(
2256
+ "thread/name/set",
2257
+ { threadId: thread.id, name: command.session_name },
2258
+ requireLive
2259
+ );
2260
+ await server.request(
2261
+ "turn/start",
2262
+ {
2263
+ threadId: thread.id,
2264
+ input: [{ type: "text", text: command.seed, text_elements: [] }]
2265
+ },
2266
+ requireLive
2267
+ );
2268
+ } catch (error) {
2269
+ if (error instanceof HarnessRefusal) await discardThread(server, thread.id);
2270
+ throw error;
2271
+ }
1614
2272
  return thread.id;
1615
2273
  },
1616
2274
  requireLive
@@ -1633,7 +2291,7 @@ var CodexDriver = class {
1633
2291
  throw error;
1634
2292
  }
1635
2293
  if (!await inside(await realpath3(folder), thread.cwd))
1636
- throw new HarnessRefusal("start_failed");
2294
+ throw new HarnessRefusal("start_uncertain");
1637
2295
  const turn = await lastTurn(server, thread.id);
1638
2296
  if (turn) return sessionFromThread({ ...thread, turns: [turn] });
1639
2297
  await this.requireTrusted(folder);
@@ -1670,16 +2328,16 @@ var CodexDriver = class {
1670
2328
  const turn = await this.connection(folder, (server) => lastTurn(server, session.id));
1671
2329
  return turn ? [turn.id] : [];
1672
2330
  },
1673
- reconcile: async (session, text2, observedRefs, folder, requireLive) => {
2331
+ reconcile: async (session, text3, observedRefs, folder, requireLive) => {
1674
2332
  const turn = await this.connection(folder, (server) => lastTurn(server, session.id));
1675
2333
  if (turn && !observedRefs.includes(turn.id)) return session.id;
1676
- return this.resume(session, text2, folder, requireLive);
2334
+ return this.resume(session, text3, folder, requireLive);
1677
2335
  }
1678
2336
  };
1679
2337
  async list(folder, requireLive, query) {
1680
2338
  return this.connection(
1681
2339
  folder,
1682
- (server) => listCodexSessions(server, folder, query),
2340
+ (server) => listCodexSessions(server, folder, query, this.activity),
1683
2341
  requireLive
1684
2342
  );
1685
2343
  }
@@ -1698,7 +2356,7 @@ var CodexDriver = class {
1698
2356
  requireLive
1699
2357
  );
1700
2358
  }
1701
- async resume(session, text2, folder, requireLive) {
2359
+ async resume(session, text3, folder, requireLive) {
1702
2360
  if (session.state === "working" || session.state === "needs_input")
1703
2361
  throw new HarnessRefusal("unsupported_command");
1704
2362
  const detected = await this.detect(folder);
@@ -1714,8 +2372,8 @@ var CodexDriver = class {
1714
2372
  { threadId: id, excludeTurns: true },
1715
2373
  requireLive
1716
2374
  );
1717
- const turn = text2 === null ? await lastTurn(server, id) : null;
1718
- const prompt = text2 ?? (turn?.status === "interrupted" ? RESUME_CONTINUATION : null);
2375
+ const turn = text3 === null ? await lastTurn(server, id) : null;
2376
+ const prompt = text3 ?? (turn?.status === "interrupted" ? RESUME_CONTINUATION : null);
1719
2377
  if (prompt !== null)
1720
2378
  await server.request(
1721
2379
  "turn/start",
@@ -1821,12 +2479,12 @@ var CommandLifetime = class {
1821
2479
 
1822
2480
  // src/local-store.ts
1823
2481
  import { randomUUID as randomUUID2 } from "node:crypto";
1824
- import { chmod, mkdir, open as open3, readFile, realpath as realpath4, rename } from "node:fs/promises";
1825
- import { homedir as homedir4 } from "node:os";
1826
- import { dirname as dirname2, isAbsolute as isAbsolute4, join as join4, resolve as resolve4 } from "node:path";
1827
- function locations(env = process.env, platform = process.platform, home = homedir4()) {
1828
- const configRoot = platform === "win32" ? env["APPDATA"] ?? join4(home, "AppData", "Roaming") : env["XDG_CONFIG_HOME"] ?? join4(home, ".config");
1829
- const stateRoot = platform === "win32" ? env["LOCALAPPDATA"] ?? join4(home, "AppData", "Local") : env["XDG_STATE_HOME"] ?? join4(home, ".local", "state");
2482
+ import { chmod, mkdir, open as open4, readFile, realpath as realpath4, rename } from "node:fs/promises";
2483
+ import { homedir as homedir5 } from "node:os";
2484
+ import { dirname as dirname2, isAbsolute as isAbsolute5, join as join6, resolve as resolve4 } from "node:path";
2485
+ function locations(env = process.env, platform = process.platform, home = homedir5()) {
2486
+ const configRoot = platform === "win32" ? env["APPDATA"] ?? join6(home, "AppData", "Roaming") : env["XDG_CONFIG_HOME"] ?? join6(home, ".config");
2487
+ const stateRoot = platform === "win32" ? env["LOCALAPPDATA"] ?? join6(home, "AppData", "Local") : env["XDG_STATE_HOME"] ?? join6(home, ".local", "state");
1830
2488
  return {
1831
2489
  config: resolve4(configRoot, "tsp-gateway", "config.json"),
1832
2490
  state: resolve4(stateRoot, "tsp-gateway")
@@ -1839,7 +2497,7 @@ async function privateDirectory(path) {
1839
2497
  async function privateWrite(path, value) {
1840
2498
  await privateDirectory(dirname2(path));
1841
2499
  const temporary = `${path}.${randomUUID2()}.tmp`;
1842
- const handle = await open3(temporary, "wx", 384);
2500
+ const handle = await open4(temporary, "wx", 384);
1843
2501
  try {
1844
2502
  await handle.writeFile(value);
1845
2503
  await handle.sync();
@@ -1849,32 +2507,34 @@ async function privateWrite(path, value) {
1849
2507
  await rename(temporary, path);
1850
2508
  }
1851
2509
  async function readConfig(path) {
1852
- let text2;
2510
+ let text3;
1853
2511
  try {
1854
- text2 = await readFile(path, "utf8");
2512
+ text3 = await readFile(path, "utf8");
1855
2513
  } catch (error) {
1856
2514
  if (isObject(error) && field(error, "code") === "ENOENT")
1857
2515
  return {
1858
2516
  repositories: {},
1859
2517
  pairing: null,
1860
2518
  loginPath: null,
1861
- launch: defaultLaunchConfig()
2519
+ launch: defaultLaunchConfig(),
2520
+ reporting: DEFAULT_REPORTING
1862
2521
  };
1863
2522
  throw error;
1864
2523
  }
1865
- const value = parseJson(text2);
2524
+ const value = parseJson(text3);
1866
2525
  if (!isObject(value) || Object.keys(value).some(
1867
- (key) => !["repositories", "pairing", "loginPath", "launch"].includes(key)
2526
+ (key) => !["repositories", "pairing", "loginPath", "launch", "reporting"].includes(key)
1868
2527
  ))
1869
2528
  throw new Error("Invalid gateway config");
1870
2529
  const launch = Object.hasOwn(value, "launch") ? decodeLaunchConfig(field(value, "launch")) : defaultLaunchConfig();
2530
+ const reporting = Object.hasOwn(value, "reporting") ? decodeReporting(field(value, "reporting")) : DEFAULT_REPORTING;
1871
2531
  const repositories = field(value, "repositories"), pairing = field(value, "pairing"), loginPath = field(value, "loginPath");
1872
2532
  if (!isObject(repositories) || !(loginPath === null || typeof loginPath === "string"))
1873
2533
  throw new Error("Invalid gateway config");
1874
2534
  const map = {};
1875
2535
  for (const slug of Object.keys(repositories)) {
1876
2536
  const folder = field(repositories, slug);
1877
- if (!validSlug(slug) || typeof folder !== "string" || !isAbsolute4(folder))
2537
+ if (!validSlug(slug) || typeof folder !== "string" || !isAbsolute5(folder))
1878
2538
  throw new Error("Invalid repository registry");
1879
2539
  map[slug] = folder;
1880
2540
  }
@@ -1894,7 +2554,7 @@ async function readConfig(path) {
1894
2554
  clientId
1895
2555
  };
1896
2556
  }
1897
- return { repositories: map, pairing: paired, loginPath, launch };
2557
+ return { repositories: map, pairing: paired, loginPath, launch, reporting };
1898
2558
  }
1899
2559
  function saveConfig(path, config) {
1900
2560
  return privateWrite(path, JSON.stringify(config, null, 2) + "\n");
@@ -1935,7 +2595,7 @@ async function registerFolder(folder, env = process.env) {
1935
2595
 
1936
2596
  // src/journal.ts
1937
2597
  import { createHash } from "node:crypto";
1938
- import { open as open4, readFile as readFile2, truncate } from "node:fs/promises";
2598
+ import { open as open5, readFile as readFile2, truncate } from "node:fs/promises";
1939
2599
  import { dirname as dirname3 } from "node:path";
1940
2600
 
1941
2601
  // src/journal-codec.ts
@@ -1967,14 +2627,14 @@ function readCommand(value) {
1967
2627
  throw new Error("Invalid stored identity");
1968
2628
  const ttl_ms = nonnegative(field(row, "ttl_ms"));
1969
2629
  if (!Number.isSafeInteger(ttl_ms)) throw new Error("Invalid stored lifetime");
1970
- const identity = { command_id, action_id, ttl_ms };
2630
+ const identity2 = { command_id, action_id, ttl_ms };
1971
2631
  switch (field(row, "kind")) {
1972
2632
  case "launch": {
1973
2633
  const session_name = string(field(row, "session_name"));
1974
2634
  if (session_name !== `tsp-${action_id.slice(3)}`)
1975
2635
  throw new Error("Invalid stored session name");
1976
2636
  return {
1977
- ...identity,
2637
+ ...identity2,
1978
2638
  kind: "launch",
1979
2639
  session_name,
1980
2640
  harness: member2(field(row, "harness"), Object.values(HARNESS_KIND)),
@@ -1983,10 +2643,10 @@ function readCommand(value) {
1983
2643
  };
1984
2644
  }
1985
2645
  case "stop":
1986
- return { ...identity, kind: "stop", session_ref: string(field(row, "session_ref")) };
2646
+ return { ...identity2, kind: "stop", session_ref: string(field(row, "session_ref")) };
1987
2647
  case "resume":
1988
2648
  return {
1989
- ...identity,
2649
+ ...identity2,
1990
2650
  kind: "resume",
1991
2651
  session_ref: string(field(row, "session_ref")),
1992
2652
  text: nullable(field(row, "text"))
@@ -2098,12 +2758,12 @@ function canonical(value) {
2098
2758
  return JSON.stringify(value);
2099
2759
  }
2100
2760
  function commandDigest(command) {
2101
- const identity = {
2761
+ const identity2 = {
2102
2762
  ...command,
2103
2763
  ttl_ms: null,
2104
2764
  ...command.kind === "resume" ? { text: command.text ?? null } : {}
2105
2765
  };
2106
- return createHash("sha256").update(canonical(identity)).digest("hex");
2766
+ return createHash("sha256").update(canonical(identity2)).digest("hex");
2107
2767
  }
2108
2768
  var Journal = class {
2109
2769
  constructor(path) {
@@ -2157,7 +2817,7 @@ var Journal = class {
2157
2817
  }
2158
2818
  }
2159
2819
  async append(entry) {
2160
- const handle = await open4(this.path, "a", 384);
2820
+ const handle = await open5(this.path, "a", 384);
2161
2821
  try {
2162
2822
  await handle.chmod(384);
2163
2823
  await handle.writeFile(JSON.stringify(storeJournalEntry(entry)) + "\n");
@@ -2217,16 +2877,16 @@ async function launchSession(journal, request) {
2217
2877
  const matching = sessions.filter(
2218
2878
  (row) => knownRef ? row.id === knownRef : row.name === command.session_name
2219
2879
  );
2220
- if (matching.length > 1) throw new HarnessRefusal("start_failed");
2880
+ if (matching.length > 1) throw new HarnessRefusal("start_uncertain");
2221
2881
  session = matching[0];
2222
- if (knownRef && !session) throw new HarnessRefusal("start_failed");
2882
+ if (knownRef && !session) throw new HarnessRefusal("session_not_found");
2223
2883
  if (session && driver.reconcileLaunch) {
2224
2884
  await checkpoint(session.id);
2225
2885
  session = await driver.reconcileLaunch(session.id, command, folder, requireLive);
2226
2886
  }
2227
2887
  }
2228
2888
  if (session) return { ref: session.id, session };
2229
- if (knownRef || retry && !driver.reconcileLaunch) throw new HarnessRefusal("start_failed");
2889
+ if (retry && !driver.reconcileLaunch) throw new HarnessRefusal("start_uncertain");
2230
2890
  requireLive();
2231
2891
  const ref = await driver.start(command, folder, requireLive, checkpoint);
2232
2892
  return { ref };
@@ -2256,7 +2916,7 @@ async function resumeSession(journal, request) {
2256
2916
  (row) => row.conversationId === intent.conversationId && !intent.observedRefs.includes(row.id)
2257
2917
  );
2258
2918
  if (!intent.conversationId || candidates.length !== 1)
2259
- throw new HarnessRefusal("start_failed");
2919
+ throw new HarnessRefusal("start_uncertain");
2260
2920
  return candidates[0].id;
2261
2921
  }
2262
2922
  intent.observedRefs = sessions.filter((row) => row.conversationId === session.conversationId).map((row) => row.id);
@@ -2264,7 +2924,7 @@ async function resumeSession(journal, request) {
2264
2924
  requireLive();
2265
2925
  return await driver.resume(session, command.text ?? null, folder, requireLive);
2266
2926
  }
2267
- async function observeSessions(drivers, contexts) {
2927
+ async function observeSessions(drivers, contexts, activity = false) {
2268
2928
  const contextList = [...contexts];
2269
2929
  const observations = /* @__PURE__ */ new Map();
2270
2930
  for (const { harness, folder } of contextList) {
@@ -2279,7 +2939,8 @@ async function observeSessions(drivers, contexts) {
2279
2939
  sessions: folder ? await drivers.get(harness).list(folder, void 0, {
2280
2940
  refs: contextList.filter(
2281
2941
  (context) => context.harness === harness && context.folder === folder
2282
- ).map((context) => context.ref)
2942
+ ).map((context) => context.ref),
2943
+ activity
2283
2944
  }) : [],
2284
2945
  listed: Boolean(folder)
2285
2946
  });
@@ -2289,29 +2950,53 @@ async function observeSessions(drivers, contexts) {
2289
2950
  }
2290
2951
  return observations;
2291
2952
  }
2292
-
2293
- // src/commands.ts
2294
2953
  var MISSING_SESSION_POLLS = 3;
2295
- function unreadableCommandReason(command) {
2296
- return command.kind === "stop" ? "stop_failed" : "start_failed";
2954
+ var UNREADABLE_SESSION_POLLS = 3;
2955
+ function unobservedState(binding) {
2956
+ if (binding.state === "ended" || binding.missingPolls >= MISSING_SESSION_POLLS) return "ended";
2957
+ if (isTerminalSessionState(binding.state)) return null;
2958
+ return binding.missingPolls > 0 || binding.unreadablePolls >= UNREADABLE_SESSION_POLLS ? "unknown" : null;
2297
2959
  }
2960
+ function unreadState(binding) {
2961
+ return isTerminalSessionState(binding.state) ? binding.state : "unknown";
2962
+ }
2963
+
2964
+ // src/command-refusals.ts
2965
+ var STARTUP_REASONS = {
2966
+ timed_out: "shell_startup_timeout",
2967
+ exited: "shell_startup_failed",
2968
+ folder_unavailable: "repository_folder_unavailable"
2969
+ };
2970
+ function unreadableCommandRefusal(command) {
2971
+ return new HarnessRefusal(command.kind === "stop" ? "stop_failed" : "start_uncertain");
2972
+ }
2973
+ function provenRefusal(error, retry) {
2974
+ if (error instanceof HarnessRefusal) return error;
2975
+ if (retry || !(error instanceof ShellStartupError)) return null;
2976
+ return new HarnessRefusal(STARTUP_REASONS[error.problem]);
2977
+ }
2978
+
2979
+ // src/commands.ts
2298
2980
  var Commands = class {
2299
- constructor(journal, drivers, repositories, stopSettleMs = 5e3, clock = lifetimeClock) {
2981
+ constructor(journal, drivers, repositories, options = {}) {
2300
2982
  this.journal = journal;
2301
2983
  this.drivers = drivers;
2302
2984
  this.repositories = repositories;
2303
- this.stopSettleMs = stopSettleMs;
2304
- this.clock = clock;
2985
+ this.stopSettleMs = options.stopSettleMs ?? 5e3;
2986
+ this.clock = options.clock ?? lifetimeClock;
2987
+ this.activity = options.activity ?? new ActivityReporter();
2305
2988
  for (const entry of journal.entries.values()) {
2306
2989
  this.remember(entry);
2307
2990
  this.lifetimes.set(
2308
2991
  entry.command.command_id,
2309
- new CommandLifetime(entry.command.ttl_ms, clock, entry.lifetime)
2992
+ new CommandLifetime(entry.command.ttl_ms, this.clock, entry.lifetime)
2310
2993
  );
2311
2994
  }
2312
2995
  }
2996
+ stopSettleMs;
2997
+ clock;
2998
+ activity;
2313
2999
  bindings = /* @__PURE__ */ new Map();
2314
- lastUpdates = /* @__PURE__ */ new Map();
2315
3000
  lifetimes = /* @__PURE__ */ new Map();
2316
3001
  resolutions = /* @__PURE__ */ new Map();
2317
3002
  /** Called at socket receipt, before joining the serial work queue. */
@@ -2331,6 +3016,7 @@ var Commands = class {
2331
3016
  harness: command.kind === "launch" ? command.harness : previous.harness,
2332
3017
  state: update.state,
2333
3018
  missingPolls: 0,
3019
+ unreadablePolls: 0,
2334
3020
  repository: command.kind === "launch" ? command.repository.toLowerCase() : previous.repository,
2335
3021
  ref: update.resumed_as ?? update.session_ref,
2336
3022
  conversationId: entry.conversationId
@@ -2380,7 +3066,7 @@ var Commands = class {
2380
3066
  try {
2381
3067
  if (!previous) lifetime.requireLive(command);
2382
3068
  if (this.journal.unreadableCommandIds.has(command.command_id))
2383
- throw new HarnessRefusal(unreadableCommandReason(command));
3069
+ throw unreadableCommandRefusal(command);
2384
3070
  const result = command.kind === "launch" ? await this.launch(
2385
3071
  intent,
2386
3072
  Boolean(previous),
@@ -2399,13 +3085,14 @@ var Commands = class {
2399
3085
  action_id: command.action_id
2400
3086
  };
2401
3087
  } catch (error) {
2402
- if (!(error instanceof HarnessRefusal)) throw error;
3088
+ const refusal = provenRefusal(error, Boolean(previous));
3089
+ if (!refusal) throw error;
2403
3090
  receipt = {
2404
3091
  kind: "refused",
2405
3092
  protocol_version: GATEWAY_PROTOCOL_VERSION,
2406
3093
  command_id: command.command_id,
2407
3094
  action_id: command.action_id,
2408
- reason: error.reason
3095
+ reason: refusal.reason
2409
3096
  };
2410
3097
  }
2411
3098
  const outcome = {
@@ -2422,8 +3109,9 @@ var Commands = class {
2422
3109
  return this.emit(receipt, update);
2423
3110
  }
2424
3111
  emit(receipt, update) {
2425
- this.lastUpdates.delete(receipt.action_id);
3112
+ this.activity.forget(receipt.action_id);
2426
3113
  if (update) {
3114
+ this.activity.noteSent(update);
2427
3115
  const binding = this.bindings.get(update.action_id);
2428
3116
  if (binding) binding.state = update.state;
2429
3117
  }
@@ -2446,13 +3134,13 @@ var Commands = class {
2446
3134
  binding.harness,
2447
3135
  entry.command.action_id,
2448
3136
  prior.session_ref,
2449
- row?.state ?? "unknown",
3137
+ row?.state ?? unreadState(binding),
2450
3138
  binding.ref
2451
3139
  ) : this.update(
2452
3140
  binding.harness,
2453
3141
  entry.command.action_id,
2454
3142
  binding.ref,
2455
- row?.state ?? "unknown"
3143
+ row?.state ?? unreadState(binding)
2456
3144
  );
2457
3145
  update.waiting_for = row?.waitingFor ?? null;
2458
3146
  return this.emit(entry.receipt, update);
@@ -2557,10 +3245,10 @@ var Commands = class {
2557
3245
  }
2558
3246
  await this.journal.retire(actionId);
2559
3247
  this.bindings.delete(actionId);
2560
- this.lastUpdates.delete(actionId);
3248
+ this.activity.release(actionId);
2561
3249
  }
2562
3250
  resetObservations() {
2563
- this.lastUpdates.clear();
3251
+ this.activity.clear();
2564
3252
  }
2565
3253
  /** Replay every binding's latest receipt before polling, including terminal sessions. */
2566
3254
  durableReceipts() {
@@ -2589,64 +3277,74 @@ var Commands = class {
2589
3277
  async poll() {
2590
3278
  if (this.bindings.size === 0) return [];
2591
3279
  const repositories = await this.repositories();
3280
+ const activity = await this.activity.enabled();
2592
3281
  const observations = await observeSessions(
2593
3282
  this.drivers,
2594
3283
  [...this.bindings.values()].map((binding) => ({
2595
3284
  harness: binding.harness,
2596
3285
  folder: repositories[binding.repository],
2597
3286
  ref: binding.ref
2598
- }))
3287
+ })),
3288
+ activity
2599
3289
  );
2600
3290
  const updates = [];
2601
3291
  for (const [action, binding] of this.bindings) {
2602
3292
  const { sessions, listed } = observations.get(binding.harness).get(repositories[binding.repository]);
2603
3293
  const row = sessions.find((session) => session.id === binding.ref);
2604
3294
  binding.missingPolls = row || !listed ? 0 : binding.missingPolls + 1;
2605
- const state = row?.state ?? (binding.state === "ended" || binding.missingPolls >= MISSING_SESSION_POLLS ? "ended" : "unknown");
3295
+ binding.unreadablePolls = listed ? 0 : binding.unreadablePolls + 1;
3296
+ const state = row?.state ?? unobservedState(binding);
3297
+ if (state === null) continue;
2606
3298
  const update = this.update(binding.harness, action, binding.ref, state);
2607
3299
  update.waiting_for = row?.waitingFor ?? null;
2608
3300
  binding.state = update.state;
2609
- const encoded = JSON.stringify(update);
2610
- if (this.lastUpdates.get(action) !== encoded) {
2611
- updates.push(update);
2612
- this.lastUpdates.set(action, encoded);
2613
- }
3301
+ const frame = this.activity.frame(update, row?.activity ?? null, activity);
3302
+ if (frame) updates.push(frame);
2614
3303
  }
2615
3304
  return updates;
2616
3305
  }
2617
3306
  };
2618
3307
 
2619
3308
  // src/config-watch.ts
2620
- import { unwatchFile, watch, watchFile } from "node:fs";
3309
+ import { statSync, watch } from "node:fs";
2621
3310
  import { basename as basename4, dirname as dirname4 } from "node:path";
2622
- function watchConfig(path, changed) {
3311
+ var watchDirectory = (directory, listener) => watch(directory, (_, filename) => listener(filename));
3312
+ function watchConfig(path, changed, options = {}) {
3313
+ let reported = identity(path);
2623
3314
  let pending;
2624
3315
  let watcher;
2625
- let fallback = false;
2626
- const notify = () => {
2627
- clearTimeout(pending);
2628
- pending = setTimeout(changed, 150);
3316
+ const report = () => {
3317
+ pending = void 0;
3318
+ const current = identity(path);
3319
+ if (current === reported) return;
3320
+ reported = current;
3321
+ changed();
2629
3322
  };
2630
- const poll = () => {
2631
- watcher?.close();
2632
- if (fallback) return;
2633
- fallback = true;
2634
- watchFile(path, { interval: 1e3 }, notify);
3323
+ const settle = () => {
3324
+ clearTimeout(pending);
3325
+ pending = setTimeout(report, 150);
2635
3326
  };
3327
+ const poll = setInterval(() => {
3328
+ if (pending === void 0 && identity(path) !== reported) settle();
3329
+ }, options.pollMs ?? 1e3);
2636
3330
  try {
2637
- watcher = watch(dirname4(path), (_, filename) => {
2638
- if (filename === null || filename === basename4(path)) notify();
3331
+ watcher = (options.watchDirectory ?? watchDirectory)(dirname4(path), (filename) => {
3332
+ if (filename === null || filename === basename4(path)) settle();
2639
3333
  });
2640
- watcher.on("error", poll);
3334
+ watcher.on("error", () => watcher?.close());
2641
3335
  } catch {
2642
- poll();
3336
+ watcher = void 0;
2643
3337
  }
2644
3338
  return () => {
2645
3339
  watcher?.close();
2646
- if (fallback) unwatchFile(path, notify);
3340
+ clearInterval(poll);
2647
3341
  clearTimeout(pending);
2648
3342
  };
2649
3343
  }
3344
+ function identity(path) {
3345
+ const stat4 = statSync(path, { bigint: true, throwIfNoEntry: false });
3346
+ return stat4 === void 0 ? "absent" : `${stat4.ino}:${stat4.mtimeNs}:${stat4.size}`;
3347
+ }
2650
3348
 
2651
3349
  // src/launch-permits.ts
2652
3350
  var LaunchPermits = class {
@@ -2719,9 +3417,9 @@ async function json(url, init) {
2719
3417
  return await response.json();
2720
3418
  }
2721
3419
  function requiredText(value, key) {
2722
- const text2 = isObject(value) ? field(value, key) : null;
2723
- if (typeof text2 !== "string" || !text2) throw new Error("Invalid OAuth response");
2724
- return text2;
3420
+ const text3 = isObject(value) ? field(value, key) : null;
3421
+ if (typeof text3 !== "string" || !text3) throw new Error("Invalid OAuth response");
3422
+ return text3;
2725
3423
  }
2726
3424
  async function discover(origin) {
2727
3425
  const value = await json(`${validateOrigin(origin)}/.well-known/oauth-authorization-server`);
@@ -3310,7 +4008,7 @@ import { lstatSync, unlinkSync } from "node:fs";
3310
4008
  import { realpath as realpath5 } from "node:fs/promises";
3311
4009
  import { createConnection, createServer as createServer2 } from "node:net";
3312
4010
  import { tmpdir as tmpdir2 } from "node:os";
3313
- import { join as join5, resolve as resolve5 } from "node:path";
4011
+ import { join as join7, resolve as resolve5 } from "node:path";
3314
4012
  function hasCode(error, code) {
3315
4013
  return isObject(error) && field(error, "code") === code;
3316
4014
  }
@@ -3319,13 +4017,13 @@ async function lockEndpoint(state) {
3319
4017
  const absolute = await realpath5(state);
3320
4018
  const hash = createHash3("sha256").update(absolute).digest("hex");
3321
4019
  if (process.platform === "win32") return `\\\\.\\pipe\\tsp-gateway-${hash}`;
3322
- const local = join5(absolute, "daemon.sock");
4020
+ const local = join7(absolute, "daemon.sock");
3323
4021
  if (Buffer.byteLength(local) <= 103) return local;
3324
4022
  const name = `tsp-gateway-${hash.slice(0, 24)}`;
3325
- let directory = join5(tmpdir2(), name);
3326
- if (Buffer.byteLength(join5(directory, "lock.sock")) > 103) directory = join5("/tmp", name);
4023
+ let directory = join7(tmpdir2(), name);
4024
+ if (Buffer.byteLength(join7(directory, "lock.sock")) > 103) directory = join7("/tmp", name);
3327
4025
  await privateDirectory(directory);
3328
- return join5(directory, "lock.sock");
4026
+ return join7(directory, "lock.sock");
3329
4027
  }
3330
4028
  function listen(server, path) {
3331
4029
  return new Promise((resolve6, reject) => {
@@ -3397,7 +4095,7 @@ async function daemonLock(state) {
3397
4095
  }
3398
4096
 
3399
4097
  // src/gateway-status.ts
3400
- import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
4098
+ import { readFile as readFile3, stat as stat3 } from "node:fs/promises";
3401
4099
  var GatewayStatus = class {
3402
4100
  constructor(path, executor) {
3403
4101
  this.path = path;
@@ -3427,9 +4125,9 @@ var GatewayStatus = class {
3427
4125
  };
3428
4126
  async function daemonConnection(statusPath, since = 0) {
3429
4127
  try {
3430
- const [text2, info] = await Promise.all([readFile3(statusPath, "utf8"), stat2(statusPath)]);
4128
+ const [text3, info] = await Promise.all([readFile3(statusPath, "utf8"), stat3(statusPath)]);
3431
4129
  if (info.mtimeMs < since) return null;
3432
- const status = parseJson(text2);
4130
+ const status = parseJson(text3);
3433
4131
  if (!isObject(status)) return null;
3434
4132
  const pid = field(status, "pid"), message = field(status, "message");
3435
4133
  return typeof pid === "number" && pidAlive(pid) && typeof message === "string" ? message : null;
@@ -3471,8 +4169,8 @@ function keychain(account) {
3471
4169
 
3472
4170
  // src/installer.ts
3473
4171
  import { readFile as readFile4, rm as rm2 } from "node:fs/promises";
3474
- import { homedir as homedir5, userInfo as userInfo2 } from "node:os";
3475
- import { dirname as dirname5, isAbsolute as isAbsolute5, join as join6, win32 } from "node:path";
4172
+ import { homedir as homedir6, userInfo as userInfo2 } from "node:os";
4173
+ import { dirname as dirname5, isAbsolute as isAbsolute6, join as join8, win32 } from "node:path";
3476
4174
  var label = "com.treestructuredplanning.tsp-gateway";
3477
4175
  function xml(value) {
3478
4176
  return value.replace(
@@ -3489,7 +4187,7 @@ function quoted(value) {
3489
4187
  }
3490
4188
  function installDefinition(platform, spec) {
3491
4189
  if (![spec.node, spec.entry, spec.config, spec.state].every(
3492
- platform === "win32" ? (value) => win32.isAbsolute(value) || isAbsolute5(value) : isAbsolute5
4190
+ platform === "win32" ? (value) => win32.isAbsolute(value) || isAbsolute6(value) : isAbsolute6
3493
4191
  ) || /[\r\n\0]/.test(Object.values(spec).join("")))
3494
4192
  throw new Error("Installer requires absolute paths and single-line values");
3495
4193
  const args = [
@@ -3512,8 +4210,8 @@ function installDefinition(platform, spec) {
3512
4210
  <key>ProgramArguments</key><array>${args.map((arg) => `<string>${xml(arg)}</string>`).join("")}</array>
3513
4211
  <key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
3514
4212
  <key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(spec.path)}</string></dict>
3515
- <key>StandardOutPath</key><string>${xml(join6(spec.state, "stdout.log"))}</string>
3516
- <key>StandardErrorPath</key><string>${xml(join6(spec.state, "stderr.log"))}</string>
4213
+ <key>StandardOutPath</key><string>${xml(join8(spec.state, "stdout.log"))}</string>
4214
+ <key>StandardErrorPath</key><string>${xml(join8(spec.state, "stderr.log"))}</string>
3517
4215
  </dict></plist>
3518
4216
  `;
3519
4217
  if (platform === "linux")
@@ -3526,8 +4224,8 @@ Environment=${systemd(`PATH=${spec.path}`, false)}
3526
4224
  Restart=on-failure
3527
4225
  RestartSec=5
3528
4226
  UMask=0077
3529
- StandardOutput=append:${join6(spec.state, "stdout.log").replace(/%/g, "%%")}
3530
- StandardError=append:${join6(spec.state, "stderr.log").replace(/%/g, "%%")}
4227
+ StandardOutput=append:${join8(spec.state, "stdout.log").replace(/%/g, "%%")}
4228
+ StandardError=append:${join8(spec.state, "stderr.log").replace(/%/g, "%%")}
3531
4229
  [Install]
3532
4230
  WantedBy=default.target
3533
4231
  `;
@@ -3553,11 +4251,11 @@ async function captureLoginPath(env = process.env, platform = process.platform,
3553
4251
  if (!path || /[\r\n\0]/.test(path)) throw new Error("Could not capture login-shell PATH");
3554
4252
  return path;
3555
4253
  }
3556
- function installPath(platform, state, home = homedir5()) {
3557
- if (platform === "darwin") return join6(home, "Library", "LaunchAgents", `${label}.plist`);
4254
+ function installPath(platform, state, home = homedir6()) {
4255
+ if (platform === "darwin") return join8(home, "Library", "LaunchAgents", `${label}.plist`);
3558
4256
  if (platform === "linux")
3559
- return join6(home, ".config", "systemd", "user", "tsp-gateway.service");
3560
- if (platform === "win32") return join6(state, "tsp-gateway.xml");
4257
+ return join8(home, ".config", "systemd", "user", "tsp-gateway.service");
4258
+ if (platform === "win32") return join8(state, "tsp-gateway.xml");
3561
4259
  throw new Error("Unsupported platform");
3562
4260
  }
3563
4261
  function launchdDomain() {
@@ -3590,7 +4288,7 @@ async function systemCommand(file, args) {
3590
4288
  if (result.code !== 0)
3591
4289
  throw new Error(`Could not update login item (${file}, exit ${result.code})`);
3592
4290
  }
3593
- async function install(spec, platform = process.platform, home = homedir5()) {
4291
+ async function install(spec, platform = process.platform, home = homedir6()) {
3594
4292
  const destination = installPath(platform, spec.state, home);
3595
4293
  await privateDirectory(spec.state);
3596
4294
  await import("node:fs/promises").then(
@@ -3617,9 +4315,9 @@ async function install(spec, platform = process.platform, home = homedir5()) {
3617
4315
  await systemCommand("systemctl", ["--user", "restart", "tsp-gateway.service"]);
3618
4316
  }
3619
4317
  }
3620
- await privateWrite(join6(spec.state, "installation.json"), JSON.stringify(spec));
4318
+ await privateWrite(join8(spec.state, "installation.json"), JSON.stringify(spec));
3621
4319
  }
3622
- async function uninstall(state, platform = process.platform, home = homedir5()) {
4320
+ async function uninstall(state, platform = process.platform, home = homedir6()) {
3623
4321
  const destination = installPath(platform, state, home);
3624
4322
  try {
3625
4323
  await readFile4(destination);
@@ -3636,12 +4334,12 @@ async function uninstall(state, platform = process.platform, home = homedir5())
3636
4334
  }
3637
4335
  await rm2(destination, { force: true });
3638
4336
  if (platform === "linux") await systemCommand("systemctl", ["--user", "daemon-reload"]);
3639
- await rm2(join6(state, "installation.json"), { force: true });
4337
+ await rm2(join8(state, "installation.json"), { force: true });
3640
4338
  return true;
3641
4339
  }
3642
- async function loginItemCurrent(spec, platform = process.platform, home = homedir5()) {
4340
+ async function loginItemCurrent(spec, platform = process.platform, home = homedir6()) {
3643
4341
  try {
3644
- const recorded = parseJson(await readFile4(join6(spec.state, "installation.json"), "utf8"));
4342
+ const recorded = parseJson(await readFile4(join8(spec.state, "installation.json"), "utf8"));
3645
4343
  await readFile4(installPath(platform, spec.state, home));
3646
4344
  const keys = Object.keys(spec);
3647
4345
  if (!isObject(recorded) || Object.keys(recorded).length !== keys.length || keys.some((key) => field(recorded, key) !== spec[key]))
@@ -3739,7 +4437,7 @@ async function disconnect(host, config) {
3739
4437
  const loginItem = await removeLoginItem(host);
3740
4438
  return { loginItem, pairing: await unpairMachine(host, config) };
3741
4439
  }
3742
- async function remainingSteps(drivers, config, repository) {
4440
+ async function folderSetups(drivers, config, repository) {
3743
4441
  const folders = repository ? { [repository.slug]: repository.folder } : { ...config.repositories };
3744
4442
  const rows = Object.keys(folders).length > 0 ? await drivers.repositories(folders) : (await drivers.detect()).map((row) => ({
3745
4443
  slug: "",
@@ -3748,34 +4446,109 @@ async function remainingSteps(drivers, config, repository) {
3748
4446
  signed_in: row.signed_in ?? null,
3749
4447
  trust: "trusted"
3750
4448
  }));
3751
- const steps = [];
4449
+ const setups = [];
3752
4450
  for (const slug of new Set(rows.map((row) => row.slug))) {
3753
4451
  const here = rows.filter((row) => row.slug === slug);
3754
- const prefix = slug ? `${slug}: ` : "";
3755
4452
  const found = here.filter((row) => row.available);
3756
4453
  if (found.length === 0) {
3757
- steps.push(...here.map((row) => prefix + drivers.get(row.harness).installInstruction));
4454
+ const required = here.map((row) => ({
4455
+ harness: row.harness,
4456
+ instruction: drivers.get(row.harness).installInstruction
4457
+ }));
4458
+ setups.push({ slug, ready: [], required, optional: [] });
3758
4459
  continue;
3759
4460
  }
4461
+ const ready = [];
4462
+ const steps = [];
3760
4463
  for (const row of found) {
3761
4464
  const driver = drivers.get(row.harness);
3762
- if (row.signed_in !== true) steps.push(prefix + driver.signInInstruction);
3763
- if (trustIsStep(row.trust, driver))
3764
- steps.push(prefix + driver.repositorySetupInstruction);
4465
+ const own = [];
4466
+ if (row.signed_in !== true) own.push(driver.signInInstruction);
4467
+ if (trustIsStep(row.trust, driver)) own.push(driver.repositorySetupInstruction);
4468
+ if (own.length === 0) ready.push(row.harness);
4469
+ steps.push(...own.map((instruction) => ({ harness: row.harness, instruction })));
3765
4470
  }
4471
+ setups.push(
4472
+ ready.length > 0 ? { slug, ready, required: [], optional: steps } : { slug, ready, required: steps, optional: [] }
4473
+ );
3766
4474
  }
3767
- return steps;
4475
+ return setups;
3768
4476
  }
3769
4477
  function trustIsStep(trust, driver) {
3770
4478
  return trust === "untrusted" || trust === "unknown" && !driver.unknownTrustAdmits;
3771
4479
  }
3772
4480
 
4481
+ // src/setup-summary.ts
4482
+ var REASONS = {
4483
+ SHELL: "named by your SHELL setting",
4484
+ "account login shell": "your account's login shell",
4485
+ "launch.shell override": "chosen in your launch settings",
4486
+ "configured direct": "chosen in your launch settings",
4487
+ "Windows uses direct spawn": "as Windows does"
4488
+ };
4489
+ function list(names) {
4490
+ return names.length < 3 ? names.join(" and ") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
4491
+ }
4492
+ function lowerFirst(text3) {
4493
+ return text3.charAt(0).toLowerCase() + text3.slice(1);
4494
+ }
4495
+ function sentence(text3) {
4496
+ return text3.replace(/\.+$/, "") + ".";
4497
+ }
4498
+ function stepLines(steps, lead, name) {
4499
+ return steps.map((step) => ` ${lead(name(step.harness))}: ${lowerFirst(step.instruction)}`);
4500
+ }
4501
+ function setupLines(setups, name) {
4502
+ return setups.flatMap((setup) => {
4503
+ const label2 = setup.slug || "This computer";
4504
+ return [
4505
+ setup.ready.length > 0 ? `${label2}: ready to build with ${list(setup.ready.map(name))}.` : `${label2}: not ready to build yet.`,
4506
+ ...stepLines(setup.required, (harness) => `To build with ${harness}`, name),
4507
+ ...stepLines(
4508
+ setup.optional,
4509
+ (harness) => `Optional, to also build with ${harness}`,
4510
+ name
4511
+ )
4512
+ ];
4513
+ });
4514
+ }
4515
+ function allSet(setups) {
4516
+ return setups.every(
4517
+ (setup) => setup.ready.length > 0 && setup.required.length === 0 && setup.optional.length === 0
4518
+ );
4519
+ }
4520
+ function pairedLine(view) {
4521
+ return view.machineId === null ? "Not paired. Run tsp-gateway connect to set up this computer." : `Paired as ${view.machineId}. ${sentence(view.connection)}`;
4522
+ }
4523
+ function connectLines(view, setups, name) {
4524
+ return [
4525
+ pairedLine(view),
4526
+ ...allSet(setups) ? ["This computer is ready to build."] : setupLines(setups, name)
4527
+ ];
4528
+ }
4529
+ function statusLines(view, setups, name) {
4530
+ const reason = REASONS[view.launch.reason] ?? view.launch.reason;
4531
+ const how = view.launch.effective_mode === "login-shell" && view.launch.shell !== null ? `Sessions start through your login shell, ${view.launch.shell} (${reason}).` : `Sessions start without a login shell (${reason}).`;
4532
+ return [
4533
+ pairedLine(view),
4534
+ ...view.lastMessage !== null && view.lastMessage !== view.connection ? [`Last message from the gateway: ${sentence(view.lastMessage)}`] : [],
4535
+ ...setupLines(setups, name),
4536
+ view.launch.wrapper === null ? how : `${how} Wrapper: ${view.launch.wrapper}.`,
4537
+ view.reporting === "off" ? "Activity reporting is off: TSP sees only each session's state." : "TSP sees what each session is doing, never file names, commands or text."
4538
+ ];
4539
+ }
4540
+
3773
4541
  export {
3774
4542
  GATEWAY_CLOSE_DISPOSITION,
4543
+ decodeReporting,
4544
+ toWire,
4545
+ ActivityCoalescer,
4546
+ ActivityReporter,
3775
4547
  isObject,
3776
4548
  field,
3777
4549
  decodeHub,
3778
4550
  parseJson,
4551
+ ClaudeTranscripts,
3779
4552
  ClaudeTrust,
3780
4553
  HarnessRefusal,
3781
4554
  defaultLaunchConfig,
@@ -3785,6 +4558,7 @@ export {
3785
4558
  HarnessExecutor,
3786
4559
  sanitizeWaiting,
3787
4560
  ClaudeDriver,
4561
+ CodexActivity,
3788
4562
  CodexTrust,
3789
4563
  CodexDriver,
3790
4564
  HarnessRegistry,
@@ -3799,6 +4573,8 @@ export {
3799
4573
  githubSlug,
3800
4574
  registerFolder,
3801
4575
  Journal,
4576
+ MISSING_SESSION_POLLS,
4577
+ UNREADABLE_SESSION_POLLS,
3802
4578
  Commands,
3803
4579
  watchConfig,
3804
4580
  LaunchPermits,
@@ -3827,6 +4603,9 @@ export {
3827
4603
  unpairMachine,
3828
4604
  connect,
3829
4605
  disconnect,
3830
- remainingSteps
4606
+ folderSetups,
4607
+ setupLines,
4608
+ connectLines,
4609
+ statusLines
3831
4610
  };
3832
- //# sourceMappingURL=shared-3OFEPCJI.js.map
4611
+ //# sourceMappingURL=shared-M7CEELPK.js.map