@treestructuredplanning/gateway 0.0.0-stage → 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.
@@ -0,0 +1,4611 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+
3
+ // ../tsp-shared/src/generated/constants.ts
4
+ var GATEWAY_PACKAGE_VERSION = "0.1.2";
5
+ var GATEWAY_PROTOCOL_VERSION = 1;
6
+ var SESSION_ACTIVITY_COUNT_MAX = 1e6;
7
+ var AGENT_SESSION_STATE = {
8
+ STARTING: "starting",
9
+ WORKING: "working",
10
+ NEEDS_INPUT: "needs_input",
11
+ DONE: "done",
12
+ FAILED: "failed",
13
+ STOPPED: "stopped",
14
+ ENDED: "ended",
15
+ UNKNOWN: "unknown"
16
+ };
17
+ var GATEWAY_CLOSE_DISPOSITION = {
18
+ TERMINAL: "terminal",
19
+ TOKEN: "token",
20
+ OUTDATED: "outdated",
21
+ RECONNECTABLE: "reconnectable"
22
+ };
23
+ var HARNESS_KIND = {
24
+ CLAUDE_CODE: "claude_code",
25
+ CODEX: "codex"
26
+ };
27
+ var LAUNCH_REFUSAL_REASON = {
28
+ WORKSPACE_UNTRUSTED: "workspace_untrusted",
29
+ NOT_SIGNED_IN: "not_signed_in",
30
+ REPOSITORY_NOT_REGISTERED: "repository_not_registered",
31
+ HARNESS_UNAVAILABLE: "harness_unavailable",
32
+ UNSUPPORTED_COMMAND: "unsupported_command",
33
+ REQUESTER_MISMATCH: "requester_mismatch",
34
+ PROTOCOL_OUTDATED: "protocol_outdated",
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",
41
+ STOP_FAILED: "stop_failed",
42
+ SESSION_NOT_FOUND: "session_not_found",
43
+ MACHINE_OFFLINE: "machine_offline",
44
+ MACHINE_REVOKED: "machine_revoked",
45
+ CONTROL_IN_FLIGHT: "control_in_flight",
46
+ AWAITING_OBSERVATION: "awaiting_observation",
47
+ ALREADY_RUNNING: "already_running",
48
+ NOT_RUNNING: "not_running",
49
+ LAUNCH_EXPIRED: "launch_expired",
50
+ LAUNCH_WITHDRAWN: "launch_withdrawn",
51
+ CONTROL_EXPIRED: "control_expired",
52
+ CONTROL_WITHDRAWN: "control_withdrawn"
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
+ };
70
+ var GATEWAY_CLOSE_DISPOSITION_BY_CODE = {
71
+ "1006": "reconnectable",
72
+ "4501": "terminal",
73
+ "4502": "terminal",
74
+ "4503": "outdated",
75
+ "4504": "terminal",
76
+ "4505": "token",
77
+ "4506": "reconnectable",
78
+ "4507": "reconnectable",
79
+ "4508": "reconnectable"
80
+ };
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
+
250
+ // src/protocol.ts
251
+ import { readFileSync } from "node:fs";
252
+ var schemas = JSON.parse(
253
+ readFileSync(new URL("./gateway-schema.json", import.meta.url), "utf8")
254
+ );
255
+ function isObject(value) {
256
+ return typeof value === "object" && value !== null && !Array.isArray(value);
257
+ }
258
+ function field(value, key) {
259
+ return Reflect.get(value, key);
260
+ }
261
+ function matchesObject(schema, value) {
262
+ if (!isObject(value)) return false;
263
+ const properties = schema.properties ?? {};
264
+ if (schema.required?.some((key) => !Object.hasOwn(value, key))) return false;
265
+ return Object.keys(value).every((key) => {
266
+ const child = properties[key];
267
+ return child ? matches(child, field(value, key)) : schema.additionalProperties !== false;
268
+ });
269
+ }
270
+ function matchesString(schema, value) {
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)));
272
+ }
273
+ function matchesInteger(schema, value) {
274
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= (schema.minimum ?? -Infinity) && value <= (schema.maximum ?? Infinity);
275
+ }
276
+ function matches(schema, value) {
277
+ if (schema.$ref) return matches(requiredSchema(schema.$ref.split("/").at(-1) ?? ""), value);
278
+ if (schema.oneOf) return schema.oneOf.filter((item) => matches(item, value)).length === 1;
279
+ if (schema.anyOf) return schema.anyOf.some((item) => matches(item, value));
280
+ if (schema.const !== void 0 && value !== schema.const) return false;
281
+ if (schema.enum && !schema.enum.some((item) => item === value)) return false;
282
+ switch (schema.type) {
283
+ case "object":
284
+ return matchesObject(schema, value);
285
+ case "string":
286
+ return matchesString(schema, value);
287
+ case "integer":
288
+ return matchesInteger(schema, value);
289
+ case "boolean":
290
+ return typeof value === "boolean";
291
+ case "null":
292
+ return value === null;
293
+ case "array":
294
+ return Array.isArray(value) && schema.items !== void 0 && value.every((item) => matches(schema.items, item));
295
+ case void 0:
296
+ default:
297
+ return false;
298
+ }
299
+ }
300
+ function requiredSchema(name) {
301
+ const schema = schemas[name];
302
+ if (!schema) throw new Error("Missing gateway contract");
303
+ return schema;
304
+ }
305
+ function decodeHub(value) {
306
+ if (!matches(requiredSchema("HubToGateway"), value) || !isObject(value) || field(value, "protocol_version") !== GATEWAY_PROTOCOL_VERSION || typeof field(value, "kind") !== "string")
307
+ throw new Error("Invalid hub frame");
308
+ const message = value;
309
+ if (message.kind === "launch" && message.session_name !== `tsp-${message.action_id.slice(3)}`)
310
+ throw new Error("Invalid launch identity");
311
+ if (message.kind === "permit") {
312
+ const receipt = message.receipt;
313
+ if (message.allowed !== (receipt == null) || receipt && (receipt.command_id !== message.command_id || receipt.action_id !== message.action_id))
314
+ throw new Error("Invalid permit outcome");
315
+ }
316
+ return message;
317
+ }
318
+ function decodeRegistration(value) {
319
+ if (!matches(requiredSchema("GatewayMachineRegistered"), value))
320
+ throw new Error("Invalid registration");
321
+ const registration = value;
322
+ if (registration.hub_path !== `/api/v1/gateway/machines/${registration.machine_id}/hub`)
323
+ throw new Error("Invalid machine hub path");
324
+ return registration;
325
+ }
326
+ function parseJson(text3) {
327
+ return JSON.parse(text3);
328
+ }
329
+ function decodeHubText(data) {
330
+ if (typeof data !== "string" || data.length > 131072) throw new Error("Invalid frame");
331
+ return decodeHub(parseJson(data));
332
+ }
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
+
533
+ // src/claude-trust.ts
534
+ import { open as open2 } from "node:fs/promises";
535
+ import { homedir } from "node:os";
536
+ import { join as join2 } from "node:path";
537
+ var MAX_CONFIG_BYTES = 4 * 1024 * 1024;
538
+ var ClaudeTrust = class {
539
+ constructor(environment = process.env, home = homedir()) {
540
+ this.environment = environment;
541
+ this.home = home;
542
+ }
543
+ observed = /* @__PURE__ */ new Map();
544
+ paths = /* @__PURE__ */ new Map();
545
+ mark(folder, trust) {
546
+ this.observed.set(folder, trust);
547
+ }
548
+ async projects(folder) {
549
+ try {
550
+ const env = typeof this.environment === "function" ? await this.environment(folder) : this.environment;
551
+ const path = join2(env["CLAUDE_CONFIG_DIR"] ?? env["HOME"] ?? this.home, ".claude.json");
552
+ const previous = this.paths.get(folder);
553
+ if (previous !== void 0 && path !== previous) this.observed.delete(folder);
554
+ this.paths.set(folder, path);
555
+ const handle = await open2(path, "r");
556
+ try {
557
+ const info = await handle.stat();
558
+ if (!info.isFile() || info.size > MAX_CONFIG_BYTES) return null;
559
+ const buffer = Buffer.alloc(MAX_CONFIG_BYTES + 1);
560
+ let total = 0;
561
+ while (total < buffer.length) {
562
+ const { bytesRead } = await handle.read(
563
+ buffer,
564
+ total,
565
+ buffer.length - total,
566
+ null
567
+ );
568
+ if (bytesRead === 0) break;
569
+ total += bytesRead;
570
+ }
571
+ if (total > MAX_CONFIG_BYTES) return null;
572
+ const value = parseJson(buffer.subarray(0, total).toString("utf8"));
573
+ const projects = isObject(value) ? field(value, "projects") : null;
574
+ return isObject(projects) ? projects : null;
575
+ } finally {
576
+ await handle.close();
577
+ }
578
+ } catch {
579
+ return null;
580
+ }
581
+ }
582
+ async repositories(registry) {
583
+ return Promise.all(
584
+ Object.entries(registry).sort(([a], [b]) => a.localeCompare(b)).map(async ([slug, folder]) => {
585
+ const projects = await this.projects(folder);
586
+ const project = projects && Object.hasOwn(projects, folder) ? field(projects, folder) : null;
587
+ const accepted = isObject(project) ? field(project, "hasTrustDialogAccepted") : null;
588
+ if (typeof accepted === "boolean") this.observed.delete(folder);
589
+ const trust = this.observed.get(folder) ?? (accepted === true ? "trusted" : accepted === false ? "untrusted" : "unknown");
590
+ return { harness: HARNESS_KIND.CLAUDE_CODE, slug, trust };
591
+ })
592
+ );
593
+ }
594
+ };
595
+
596
+ // src/harness.ts
597
+ function isTerminalSessionState(state) {
598
+ return state === AGENT_SESSION_STATE.DONE || state === AGENT_SESSION_STATE.STOPPED || state === AGENT_SESSION_STATE.ENDED || state === AGENT_SESSION_STATE.FAILED;
599
+ }
600
+ function wantsActivity(query, id) {
601
+ return query !== void 0 && "refs" in query && query.activity === true && query.refs.includes(id);
602
+ }
603
+ var HarnessRefusal = class extends Error {
604
+ constructor(reason) {
605
+ super(reason);
606
+ this.reason = reason;
607
+ }
608
+ };
609
+ var RESUME_CONTINUATION = "Continue where you left off.";
610
+
611
+ // src/launch-config.ts
612
+ import { isAbsolute } from "node:path";
613
+ function defaultLaunchConfig() {
614
+ return { mode: "login-shell", wrapper: [], env: {} };
615
+ }
616
+ function text2(value) {
617
+ return typeof value === "string" && !value.includes("\0");
618
+ }
619
+ function decodeLaunchConfig(value) {
620
+ if (!isObject(value) || Object.keys(value).some((key) => !["mode", "shell", "wrapper", "env"].includes(key)))
621
+ throw new Error("Invalid launch config fields");
622
+ const mode = Object.hasOwn(value, "mode") ? field(value, "mode") : "login-shell";
623
+ const shell = field(value, "shell");
624
+ const wrapper = Object.hasOwn(value, "wrapper") ? field(value, "wrapper") : [];
625
+ const env = Object.hasOwn(value, "env") ? field(value, "env") : {};
626
+ if (mode !== "login-shell" && mode !== "direct") throw new Error("Invalid launch.mode");
627
+ if (shell !== void 0 && (!text2(shell) || !isAbsolute(shell)))
628
+ throw new Error("launch.shell must be an absolute executable path");
629
+ return {
630
+ mode,
631
+ ...shell === void 0 ? {} : { shell },
632
+ wrapper: decodeWrapper(wrapper),
633
+ env: decodeVariables(env)
634
+ };
635
+ }
636
+ function decodeWrapper(wrapper) {
637
+ if (!Array.isArray(wrapper) || !wrapper.every(text2) || wrapper.length > 0 && !wrapper[0])
638
+ throw new Error("launch.wrapper must be an argv array with a nonempty executable");
639
+ const executable2 = wrapper[0];
640
+ if (executable2 !== void 0 && !isAbsolute(executable2) && !/^[A-Za-z0-9_][A-Za-z0-9_.+-]*$/.test(executable2))
641
+ throw new Error(
642
+ "launch.wrapper executable must be an absolute path or a bare command name"
643
+ );
644
+ return [...wrapper];
645
+ }
646
+ function decodeVariables(env) {
647
+ if (!isObject(env)) throw new Error("launch.env must contain string variables");
648
+ const variables = {};
649
+ for (const name of Object.keys(env)) {
650
+ const entry = field(env, name);
651
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || !text2(entry))
652
+ throw new Error("launch.env must contain valid names and NUL-free string values");
653
+ Object.defineProperty(variables, name, { value: entry, enumerable: true });
654
+ }
655
+ return variables;
656
+ }
657
+
658
+ // src/process.ts
659
+ import { spawn } from "node:child_process";
660
+ function execute(file, args, env, cwd) {
661
+ return new Promise((resolve6, reject) => {
662
+ const child = spawn(file, args, {
663
+ env,
664
+ ...cwd ? { cwd } : {},
665
+ stdio: ["ignore", "pipe", "pipe"],
666
+ windowsHide: true
667
+ });
668
+ let stdout = "", stderr = "";
669
+ const timer = setTimeout(() => {
670
+ child.kill();
671
+ reject(new Error("Local command timed out"));
672
+ }, 3e4);
673
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
674
+ stdout += chunk;
675
+ if (stdout.length > 4e6) {
676
+ child.kill();
677
+ reject(new Error("Local output exceeded limit"));
678
+ }
679
+ });
680
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
681
+ stderr = (stderr + chunk).slice(-16e3);
682
+ });
683
+ child.once("error", (error) => {
684
+ clearTimeout(timer);
685
+ reject(error);
686
+ });
687
+ child.once("close", (code) => {
688
+ clearTimeout(timer);
689
+ resolve6({ code: code ?? 1, stdout, stderr });
690
+ });
691
+ });
692
+ }
693
+ function pidAlive(pid) {
694
+ try {
695
+ process.kill(pid, 0);
696
+ return true;
697
+ } catch (error) {
698
+ return !(error instanceof Error && "code" in error && error.code === "ESRCH");
699
+ }
700
+ }
701
+
702
+ // src/shell-strategy.ts
703
+ import { constants } from "node:fs";
704
+ import { access, stat as stat2 } from "node:fs/promises";
705
+ import { userInfo } from "node:os";
706
+ import { basename, isAbsolute as isAbsolute2 } from "node:path";
707
+ var posix = {
708
+ flags: ["-l", "-i", "-c"],
709
+ command: 'cd /; cd -- "$5" || { "$1" -e "$6" "$3" "$5"; exit 125; }; "$1" -e "$2" "$3" "$4" || exit; cd /; cd -- "$5" || { "$1" -e "$6" "" "$5"; exit 125; }; shift 6; exec "$@"',
710
+ positionalZero: true
711
+ };
712
+ var csh = {
713
+ flags: ["-i", "-c"],
714
+ command: (argv) => 'cd /; cd "$argv[5]"; if ( $status != 0 ) exec "$argv[1]" -e "$argv[6]" "$argv[3]" "$argv[5]"; "$argv[1]" -e "$argv[2]" "$argv[3]" "$argv[4]"; if ( $status != 0 ) exit 125; cd /; cd "$argv[5]"; if ( $status != 0 ) exec "$argv[1]" -e "$argv[6]" "" "$argv[5]"; exec ' + argv.map((arg, index) => arg === "" ? '""' : `$argv[${index + 7}]:q`).join(" "),
715
+ loginArgv0: true
716
+ };
717
+ var strategies = /* @__PURE__ */ new Map([
718
+ ["bash", posix],
719
+ ["zsh", posix],
720
+ ["ksh", posix],
721
+ ["sh", { ...posix, flags: ["-l", "-c"] }],
722
+ [
723
+ "fish",
724
+ {
725
+ flags: ["-l", "-i", "-c"],
726
+ command: 'cd /; cd -- "$argv[5]"; or begin; command $argv[1] -e $argv[6] $argv[3] "$argv[5]"; exit 125; end; command $argv[1] -e $argv[2] $argv[3] "$argv[4]"; or exit; cd /; cd -- "$argv[5]"; or begin; command $argv[1] -e $argv[6] "" "$argv[5]"; exit 125; end; exec $argv[7..-1]'
727
+ }
728
+ ],
729
+ ["tcsh", csh],
730
+ ["csh", csh],
731
+ ["nu", null],
732
+ ["elvish", null],
733
+ ["xonsh", null]
734
+ ]);
735
+ async function executable(path) {
736
+ if (!isAbsolute2(path)) return false;
737
+ try {
738
+ await access(path, constants.X_OK);
739
+ return (await stat2(path)).isFile();
740
+ } catch {
741
+ return false;
742
+ }
743
+ }
744
+ async function fallbackShell(reason) {
745
+ return await executable("/bin/sh") ? { mode: "login-shell", shell: "/bin/sh", strategy: strategies.get("sh"), reason } : { mode: "direct", shell: null, reason: `${reason}; /bin/sh unavailable` };
746
+ }
747
+ async function resolveLaunchPath(config, env, platform = process.platform, accountShell = () => userInfo().shell) {
748
+ if (config.mode === "direct" || platform === "win32")
749
+ return {
750
+ mode: "direct",
751
+ shell: null,
752
+ reason: platform === "win32" ? "Windows uses direct spawn" : "configured direct"
753
+ };
754
+ let shell = config.shell || env["SHELL"];
755
+ let reason = config.shell ? "launch.shell override" : "SHELL";
756
+ if (!shell) {
757
+ reason = "account login shell";
758
+ try {
759
+ shell = accountShell() ?? void 0;
760
+ } catch {
761
+ return fallbackShell("SHELL unset; account login shell lookup failed");
762
+ }
763
+ }
764
+ if (!shell) return fallbackShell("SHELL unset; account login shell unavailable");
765
+ if (!await executable(shell))
766
+ return fallbackShell(`${reason}: requested shell is not an absolute executable file`);
767
+ const strategy = strategies.get(basename(shell));
768
+ if (!strategy)
769
+ return fallbackShell(`${reason}: requested shell has no supported login command strategy`);
770
+ return {
771
+ mode: "login-shell",
772
+ shell,
773
+ strategy,
774
+ reason
775
+ };
776
+ }
777
+ function shellArguments(path, capture, argv) {
778
+ const strategy = path.strategy;
779
+ return [
780
+ ...strategy.flags,
781
+ typeof strategy.command === "string" ? strategy.command : strategy.command(argv),
782
+ ...strategy.positionalZero ? ["tsp-gateway"] : [],
783
+ ...capture,
784
+ ...argv
785
+ ];
786
+ }
787
+
788
+ // src/harness-executor.ts
789
+ import { spawn as spawn3 } from "node:child_process";
790
+ import { homedir as homedir2 } from "node:os";
791
+ import { resolve } from "node:path";
792
+
793
+ // src/shell-process.ts
794
+ import { spawn as spawn2 } from "node:child_process";
795
+ import { randomUUID } from "node:crypto";
796
+ import { existsSync } from "node:fs";
797
+ import { basename as basename2, resolve as resolvePath } from "node:path";
798
+
799
+ // src/shell-output.ts
800
+ var CWD_ERROR_PREFIX = "Requested working directory unavailable: ";
801
+ var REPORT_CWD_ERROR = `require("node:fs").writeSync(2,process.argv[1]+${JSON.stringify(CWD_ERROR_PREFIX)}+process.argv[2]+"\\n");process.exit(125);`;
802
+ var ShellOutput = class {
803
+ constructor(sentinel) {
804
+ this.sentinel = sentinel;
805
+ }
806
+ pending = "";
807
+ ready = false;
808
+ read(chunk) {
809
+ if (this.ready) return chunk;
810
+ this.pending += chunk;
811
+ const index = this.pending.indexOf(this.sentinel);
812
+ if (index < 0) {
813
+ this.pending = this.pending.slice(-this.sentinel.length);
814
+ return "";
815
+ }
816
+ this.ready = true;
817
+ const output = this.pending.slice(index + this.sentinel.length);
818
+ this.pending = "";
819
+ return output;
820
+ }
821
+ };
822
+ function decodeEnvironment(text3) {
823
+ const value = parseJson(text3);
824
+ if (!isObject(value)) throw new Error("Invalid shell environment capture");
825
+ const env = {};
826
+ for (const name of Object.keys(value)) {
827
+ const item = field(value, name);
828
+ if (typeof item !== "string" || item.includes("\0"))
829
+ throw new Error("Invalid shell environment capture");
830
+ Object.defineProperty(env, name, {
831
+ value: item,
832
+ enumerable: true,
833
+ writable: true,
834
+ configurable: true
835
+ });
836
+ }
837
+ return env;
838
+ }
839
+ var ShellEnvironmentOutput = class {
840
+ constructor(sentinel) {
841
+ this.sentinel = sentinel;
842
+ this.prefix = new ShellOutput(sentinel);
843
+ }
844
+ prefix;
845
+ header = "";
846
+ environment;
847
+ get ready() {
848
+ return this.environment !== void 0;
849
+ }
850
+ read(chunk) {
851
+ if (this.ready) return chunk;
852
+ this.header += this.prefix.read(chunk);
853
+ const end = this.header.indexOf(this.sentinel);
854
+ if (end < 0) {
855
+ if (this.header.length > 4e6) throw new Error("Shell environment exceeded limit");
856
+ return "";
857
+ }
858
+ this.environment = decodeEnvironment(this.header.slice(0, end));
859
+ const output = this.header.slice(end + this.sentinel.length);
860
+ this.header = "";
861
+ return output;
862
+ }
863
+ };
864
+ var CAPTURE_ENVIRONMENT = 'const fs=require("node:fs"),s=process.argv[1];if(!fs.fstatSync(1).isSocket()||!fs.fstatSync(2).isSocket())process.exit(125);fs.writeSync(1,s+JSON.stringify(process.env)+s);fs.writeSync(2,s);if(process.argv[2]){const fd=fs.openSync(process.argv[2],"r"),line=Buffer.alloc(3);const n=fs.readSync(fd,line,0,3,null);fs.closeSync(fd);if(n!==3||line.toString()!=="go\\n")process.exit(125);}';
865
+
866
+ // src/shell-release.ts
867
+ import { closeSync, constants as constants2, openSync, writeSync } from "node:fs";
868
+ import { mkdtemp, rm } from "node:fs/promises";
869
+ import { tmpdir } from "node:os";
870
+ import { join as join3 } from "node:path";
871
+ var ShellRelease = class _ShellRelease {
872
+ constructor(path, directory, fd) {
873
+ this.path = path;
874
+ this.directory = directory;
875
+ this.fd = fd;
876
+ }
877
+ static async create() {
878
+ const directory = await mkdtemp(join3(tmpdir(), "tsp-shell-"));
879
+ const path = join3(directory, "release");
880
+ try {
881
+ const result = await execute("/usr/bin/mkfifo", ["-m", "600", path], {});
882
+ if (result.code !== 0) throw new Error("Could not create login-shell release FIFO");
883
+ const fd = openSync(path, constants2.O_RDWR | constants2.O_NONBLOCK);
884
+ return new _ShellRelease(path, directory, fd);
885
+ } catch (error) {
886
+ await rm(directory, { recursive: true, force: true });
887
+ throw error;
888
+ }
889
+ }
890
+ release(requireLive) {
891
+ requireLive();
892
+ writeSync(this.fd, "go\n");
893
+ }
894
+ async dispose() {
895
+ try {
896
+ closeSync(this.fd);
897
+ } finally {
898
+ await rm(this.directory, { recursive: true, force: true });
899
+ }
900
+ }
901
+ };
902
+
903
+ // src/shell-process.ts
904
+ var ShellStartupError = class extends Error {
905
+ constructor(problem, message) {
906
+ super(message);
907
+ this.problem = problem;
908
+ }
909
+ };
910
+ async function executeShell(path, argv, env, options) {
911
+ const release = options.requireLive ? await ShellRelease.create() : void 0;
912
+ try {
913
+ return await runShell(path, argv, env, { ...options, release });
914
+ } finally {
915
+ await release?.dispose();
916
+ }
917
+ }
918
+ function runShell(path, argv, env, options) {
919
+ const { cwd, startupMs, requireLive, release } = options;
920
+ return new Promise((resolve6, reject) => {
921
+ const sentinel = `TSP_${randomUUID()}`;
922
+ const out = new ShellEnvironmentOutput(sentinel), err = new ShellOutput(sentinel);
923
+ const child = spawn2(
924
+ path.shell,
925
+ shellArguments(
926
+ path,
927
+ [
928
+ process.execPath,
929
+ CAPTURE_ENVIRONMENT,
930
+ sentinel,
931
+ release?.path ?? "",
932
+ resolvePath(cwd ?? process.cwd()),
933
+ REPORT_CWD_ERROR
934
+ ],
935
+ argv
936
+ ),
937
+ {
938
+ env,
939
+ ...cwd ? { cwd } : {},
940
+ ...path.strategy?.loginArgv0 ? { argv0: `-${basename2(path.shell)}` } : {},
941
+ stdio: ["ignore", "pipe", "pipe"],
942
+ detached: true
943
+ }
944
+ );
945
+ let stdout = "", stderr = "";
946
+ let started = false, settled = false;
947
+ let failure;
948
+ const fail = (error) => {
949
+ if (settled || failure) return;
950
+ failure = error;
951
+ clearTimeout(timer);
952
+ if (!started && child.pid) {
953
+ try {
954
+ process.kill(-child.pid, "SIGKILL");
955
+ } catch {
956
+ }
957
+ } else child.kill("SIGKILL");
958
+ child.stdout.destroy();
959
+ child.stderr.destroy();
960
+ };
961
+ let timer = setTimeout(
962
+ () => fail(
963
+ new ShellStartupError(
964
+ "timed_out",
965
+ `Login shell startup timed out after ${startupMs}ms before harness exec (${path.shell})`
966
+ )
967
+ ),
968
+ startupMs
969
+ );
970
+ const ready = () => {
971
+ if (started || failure || !out.ready || !err.ready) return;
972
+ try {
973
+ if (requireLive) release.release(requireLive);
974
+ } catch (error) {
975
+ fail(error instanceof Error ? error : new Error("Shell release failed"));
976
+ return;
977
+ }
978
+ started = true;
979
+ clearTimeout(timer);
980
+ timer = setTimeout(() => fail(new Error("Local command timed out")), 3e4);
981
+ };
982
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
983
+ try {
984
+ stdout += out.read(chunk);
985
+ } catch {
986
+ fail(new Error("Invalid shell environment capture"));
987
+ return;
988
+ }
989
+ ready();
990
+ if (stdout.length > 4e6) fail(new Error("Local output exceeded limit"));
991
+ });
992
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
993
+ stderr = (stderr + err.read(chunk)).slice(-16e3);
994
+ ready();
995
+ });
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
+ );
1002
+ child.once("close", (code) => {
1003
+ if (settled) return;
1004
+ clearTimeout(timer);
1005
+ const exitError = shellExitError({ path, code, started, stderr, cwd });
1006
+ if (exitError) fail(exitError);
1007
+ settled = true;
1008
+ if (failure) {
1009
+ reject(failure);
1010
+ return;
1011
+ }
1012
+ resolve6({ code: code ?? 1, stdout, stderr, environment: out.environment });
1013
+ });
1014
+ });
1015
+ }
1016
+ function shellExitError(options) {
1017
+ const { path, code, started, stderr, cwd } = options;
1018
+ if (code === 125 && stderr.includes(CWD_ERROR_PREFIX))
1019
+ return new ShellStartupError(
1020
+ "folder_unavailable",
1021
+ CWD_ERROR_PREFIX + (cwd ?? process.cwd())
1022
+ );
1023
+ if (!started)
1024
+ return new ShellStartupError(
1025
+ "exited",
1026
+ `Login shell exited before harness exec (${path.shell}, exit ${code})`
1027
+ );
1028
+ return void 0;
1029
+ }
1030
+
1031
+ // src/harness-executor.ts
1032
+ var HarnessExecutor = class {
1033
+ constructor(env, options = {}) {
1034
+ this.env = env;
1035
+ this.options = options;
1036
+ this.home = env["HOME"] ?? env["USERPROFILE"] ?? homedir2();
1037
+ }
1038
+ home;
1039
+ captures = /* @__PURE__ */ new Map();
1040
+ revision;
1041
+ lastPath;
1042
+ /** The most recent successful capture in any folder, for a folder with none of its own. */
1043
+ latest;
1044
+ invalidate() {
1045
+ this.captures.clear();
1046
+ this.latest = void 0;
1047
+ this.revision = void 0;
1048
+ this.lastPath = void 0;
1049
+ }
1050
+ async configuration() {
1051
+ const config = await this.options.config?.() ?? defaultLaunchConfig();
1052
+ const revision = JSON.stringify(config);
1053
+ if (revision !== this.revision) {
1054
+ this.invalidate();
1055
+ this.revision = revision;
1056
+ }
1057
+ return config;
1058
+ }
1059
+ async status() {
1060
+ const config = await this.configuration();
1061
+ const path = this.lastPath ?? await resolveLaunchPath(
1062
+ config,
1063
+ this.env,
1064
+ this.options.platform,
1065
+ this.options.accountShell
1066
+ );
1067
+ return {
1068
+ mode: config.mode,
1069
+ effective_mode: path.mode,
1070
+ shell: path.shell,
1071
+ reason: path.reason,
1072
+ wrapper: config.wrapper[0] ?? null,
1073
+ wrapper_arguments: Math.max(0, config.wrapper.length - 1),
1074
+ env_names: Object.keys(config.env),
1075
+ environment_cached: this.latest !== void 0
1076
+ };
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
+ }
1095
+ record(path) {
1096
+ const changed = JSON.stringify(path) !== JSON.stringify(this.lastPath);
1097
+ this.lastPath = path;
1098
+ if (changed) {
1099
+ this.log(
1100
+ `TSP gateway launch path: ${path.mode} shell=${JSON.stringify(path.shell)} reason=${path.reason}`
1101
+ );
1102
+ this.options.changed?.();
1103
+ }
1104
+ }
1105
+ async shell(path, argv, config, capture, requireLive) {
1106
+ const { cwd } = capture;
1107
+ const generation = capture.generation;
1108
+ this.record(path);
1109
+ if (path.mode === "direct") {
1110
+ requireLive?.();
1111
+ return execute(argv[0], argv.slice(1), { ...this.env, ...config.env }, cwd);
1112
+ }
1113
+ const overlaid = Object.entries(config.env).map(([name, value]) => `${name}=${value}`);
1114
+ try {
1115
+ const result = await executeShell(
1116
+ path,
1117
+ overlaid.length ? ["/usr/bin/env", ...overlaid, ...argv] : argv,
1118
+ this.env,
1119
+ { cwd, startupMs: this.startupMs(cwd), requireLive }
1120
+ );
1121
+ if (result.code === 0 && this.captures.get(cwd) === capture && generation === capture.generation) {
1122
+ const environment = { ...result.environment, ...config.env };
1123
+ capture.environment = capture.captured = environment;
1124
+ capture.standIn = false;
1125
+ this.latest = { cwd, environment };
1126
+ this.options.changed?.();
1127
+ }
1128
+ return { code: result.code, stdout: result.stdout, stderr: result.stderr };
1129
+ } catch (error) {
1130
+ if (error instanceof Error && "code" in error && ["ENOENT", "EACCES", "ENOEXEC"].includes(String(error.code)) && path.shell !== "/bin/sh")
1131
+ return this.shell(
1132
+ await fallbackShell("requested shell could not be spawned"),
1133
+ argv,
1134
+ config,
1135
+ capture,
1136
+ requireLive
1137
+ );
1138
+ this.log(error instanceof Error ? error.message : "Login shell startup failed");
1139
+ throw error;
1140
+ }
1141
+ }
1142
+ capture(cwd) {
1143
+ let capture = this.captures.get(cwd);
1144
+ if (!capture) {
1145
+ capture = {
1146
+ cwd,
1147
+ generation: 0,
1148
+ environment: void 0,
1149
+ captured: void 0,
1150
+ standIn: false,
1151
+ initialization: void 0
1152
+ };
1153
+ this.captures.set(cwd, capture);
1154
+ }
1155
+ return capture;
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
+ }
1179
+ /** Read/control calls share a cold capture per cwd; repository-free calls use home. */
1180
+ async execute(file, args, purpose = "read", cwd = this.home, requireLive) {
1181
+ cwd = resolve(cwd);
1182
+ const config = await this.configuration();
1183
+ const capture = this.capture(cwd);
1184
+ const path = await resolveLaunchPath(
1185
+ config,
1186
+ this.env,
1187
+ this.options.platform,
1188
+ this.options.accountShell
1189
+ );
1190
+ const argv = [...config.wrapper, file, ...args];
1191
+ if (path.mode === "direct") {
1192
+ this.record(path);
1193
+ requireLive?.();
1194
+ return execute(argv[0], argv.slice(1), { ...this.env, ...config.env }, cwd);
1195
+ }
1196
+ if (purpose === "launch") return this.launch(path, argv, config, capture, requireLive);
1197
+ const environment = await this.environment(false, cwd);
1198
+ requireLive?.();
1199
+ return execute(argv[0], argv.slice(1), environment, cwd);
1200
+ }
1201
+ async environment(fresh = false, cwd = this.home) {
1202
+ cwd = resolve(cwd);
1203
+ const config = await this.configuration();
1204
+ const capture = this.capture(cwd);
1205
+ if (fresh) {
1206
+ capture.generation++;
1207
+ capture.environment = void 0;
1208
+ capture.standIn = false;
1209
+ capture.initialization = void 0;
1210
+ }
1211
+ const generation = capture.generation;
1212
+ const path = await resolveLaunchPath(
1213
+ config,
1214
+ this.env,
1215
+ this.options.platform,
1216
+ this.options.accountShell
1217
+ );
1218
+ if (path.mode === "direct") return { ...this.env, ...config.env };
1219
+ if (!capture.environment) {
1220
+ const initialization = capture.initialization ??= this.shell(
1221
+ path,
1222
+ [process.execPath, "-e", ""],
1223
+ config,
1224
+ capture
1225
+ ).then((result) => {
1226
+ if (result.code !== 0)
1227
+ throw new Error("Could not initialize login-shell environment");
1228
+ });
1229
+ try {
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;
1240
+ } finally {
1241
+ if (capture.initialization === initialization) capture.initialization = void 0;
1242
+ }
1243
+ }
1244
+ if (this.captures.get(cwd) !== capture || generation !== capture.generation)
1245
+ return this.environment(false, cwd);
1246
+ return capture.environment ?? { ...this.env, ...config.env };
1247
+ }
1248
+ /** A protocol child uses the same wrapper and captured environment as read/control calls. */
1249
+ async spawn(file, args, cwd, requireLive) {
1250
+ const config = await this.configuration();
1251
+ const env = await this.environment(false, cwd);
1252
+ const argv = [...config.wrapper, file, ...args];
1253
+ requireLive?.();
1254
+ return spawn3(argv[0], argv.slice(1), { cwd, env, stdio: "pipe", windowsHide: true });
1255
+ }
1256
+ };
1257
+ function slowShell(error) {
1258
+ return error instanceof ShellStartupError && error.problem === "timed_out";
1259
+ }
1260
+
1261
+ // src/claude-driver.ts
1262
+ import { homedir as homedir3 } from "node:os";
1263
+ import { isAbsolute as isAbsolute3, join as join4 } from "node:path";
1264
+ import { setTimeout as delay } from "node:timers/promises";
1265
+ function opaque(value) {
1266
+ if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value))
1267
+ throw new Error("Invalid local session id");
1268
+ return value;
1269
+ }
1270
+ function sanitizeWaiting(text3) {
1271
+ return [
1272
+ ...text3.replace(
1273
+ /(?:\\\\[?.]\\|\\\?\?\\|\\\\|[A-Za-z]:[\\/]|~?\/|\.\.?\/)[^\s"'<>]+/g,
1274
+ "[local path]"
1275
+ ).split("").map((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127 ? " " : char).join("")
1276
+ ].slice(0, 240).join("");
1277
+ }
1278
+ var STARTUP_GRACE_MS = 1e4;
1279
+ function backgroundSession(row) {
1280
+ if (!isObject(row) || field(row, "kind") !== "background") return null;
1281
+ let id, conversationId;
1282
+ try {
1283
+ id = opaque(field(row, "id"));
1284
+ conversationId = opaque(field(row, "sessionId"));
1285
+ } catch {
1286
+ return null;
1287
+ }
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");
1289
+ if (typeof name !== "string" || typeof state !== "string" || !(pid === void 0 || typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0))
1290
+ return null;
1291
+ return {
1292
+ id,
1293
+ conversationId,
1294
+ name,
1295
+ pid: pid ?? null,
1296
+ state,
1297
+ waiting,
1298
+ idle: field(row, "status") === "idle",
1299
+ startedAt: typeof startedAt === "number" ? startedAt : null,
1300
+ cwd: typeof cwd === "string" && isAbsolute3(cwd) ? cwd : null
1301
+ };
1302
+ }
1303
+ var ClaudeDriver = class {
1304
+ constructor(env, executable2 = "claude", trust = void 0, executor = new HarnessExecutor(env), transcripts = new ClaudeTranscripts()) {
1305
+ this.executable = executable2;
1306
+ this.executor = executor;
1307
+ this.transcripts = transcripts;
1308
+ this.trust = trust ?? new ClaudeTrust((folder) => this.executor.environment(false, folder));
1309
+ }
1310
+ trust;
1311
+ repositorySetupInstruction = "Run claude in that folder once and accept its trust prompt.";
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.";
1315
+ unknownTrustAdmits = true;
1316
+ capabilities = {
1317
+ start: true,
1318
+ stop: true,
1319
+ resume: true,
1320
+ attach_hint: true,
1321
+ answer_input: false
1322
+ };
1323
+ call(args, folder, purpose = "read", requireLive) {
1324
+ return this.executor.execute(this.executable, args, purpose, folder, requireLive);
1325
+ }
1326
+ async signedIn(folder) {
1327
+ try {
1328
+ const result = await this.call(["auth", "status"], folder);
1329
+ const value = parseJson(result.stdout);
1330
+ return isObject(value) && typeof field(value, "loggedIn") === "boolean" ? field(value, "loggedIn") : null;
1331
+ } catch {
1332
+ return null;
1333
+ }
1334
+ }
1335
+ async detect(folder) {
1336
+ if (folder) await this.executor.environment(true, folder);
1337
+ return this.probe(folder);
1338
+ }
1339
+ /** Reads the harness in the folder's cached environment; only a launch re-reads it fresh. */
1340
+ async probe(folder) {
1341
+ try {
1342
+ const version = await this.call(["--version"], folder);
1343
+ return {
1344
+ harness: HARNESS_KIND.CLAUDE_CODE,
1345
+ available: version.code === 0,
1346
+ harness_version: version.stdout.match(/\b\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?/)?.[0]?.slice(0, 80) ?? null,
1347
+ signed_in: await this.signedIn(folder),
1348
+ operations: this.capabilities
1349
+ };
1350
+ } catch {
1351
+ return {
1352
+ harness: HARNESS_KIND.CLAUDE_CODE,
1353
+ available: false,
1354
+ harness_version: null,
1355
+ signed_in: null,
1356
+ operations: this.capabilities
1357
+ };
1358
+ }
1359
+ }
1360
+ async start(command, folder, requireLive) {
1361
+ requireLive();
1362
+ const result = await this.call(
1363
+ ["--bg", "--name", command.session_name, "--", command.seed],
1364
+ folder,
1365
+ "launch",
1366
+ requireLive
1367
+ );
1368
+ if (result.code !== 0) {
1369
+ if (/Workspace not trusted/i.test(result.stdout + result.stderr)) {
1370
+ this.trust.mark(folder, "untrusted");
1371
+ throw new HarnessRefusal("workspace_untrusted");
1372
+ }
1373
+ if (await this.signedIn(folder) === false) throw new HarnessRefusal("not_signed_in");
1374
+ throw new HarnessRefusal("harness_exited");
1375
+ }
1376
+ const id = /backgrounded\s*·\s*([A-Za-z0-9_-]+)(?=\s*(?:·|$))/m.exec(result.stdout)?.[1];
1377
+ if (!id) throw new Error("Uncertain launch result; inspect local harness");
1378
+ const sessionId = opaque(id);
1379
+ this.trust.mark(folder, "trusted");
1380
+ return sessionId;
1381
+ }
1382
+ async list(folder, _requireLive, query) {
1383
+ const result = await this.call(["agents", "--json", "--all"], folder);
1384
+ if (result.code !== 0) throw new Error("Cannot list local sessions");
1385
+ const rows = parseJson(result.stdout);
1386
+ if (!Array.isArray(rows)) throw new Error("Invalid local session list");
1387
+ const sessions = [];
1388
+ let signedIn;
1389
+ for (const row of rows) {
1390
+ const session = backgroundSession(row);
1391
+ if (!session) continue;
1392
+ const { id, conversationId, name, pid, state, waiting, idle, startedAt, cwd } = session;
1393
+ let mapped = "unknown";
1394
+ let waitingFor = null;
1395
+ if (state === "working")
1396
+ mapped = idle && startedAt !== null && Date.now() - startedAt > STARTUP_GRACE_MS ? "needs_input" : "working";
1397
+ else if (state === "done") mapped = "done";
1398
+ else if (state === "stopped") mapped = "stopped";
1399
+ else if (state === "failed") mapped = "failed";
1400
+ else if (state === "blocked") {
1401
+ if (typeof waiting === "string" && waiting.trim()) {
1402
+ mapped = "needs_input";
1403
+ waitingFor = sanitizeWaiting(waiting);
1404
+ } else if (await (signedIn ??= this.signedIn(folder)) === false) {
1405
+ mapped = "failed";
1406
+ waitingFor = "Claude Code is not signed in. Run claude auth login.";
1407
+ } else mapped = "needs_input";
1408
+ }
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
+ });
1418
+ }
1419
+ return sessions;
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
+ }
1432
+ async stop(session, folder, requireLive) {
1433
+ requireLive();
1434
+ const result = await this.call(
1435
+ ["stop", opaque(session.id)],
1436
+ folder,
1437
+ "control",
1438
+ requireLive
1439
+ );
1440
+ if (result.code !== 0) throw new HarnessRefusal("stop_failed");
1441
+ }
1442
+ async resume(session, text3, folder, requireLive) {
1443
+ if (session.state === "working" || session.state === "needs_input")
1444
+ throw new HarnessRefusal("unsupported_command");
1445
+ if (session.pid !== null) {
1446
+ await this.stop(session, folder, requireLive);
1447
+ const until = performance.now() + 1e4;
1448
+ while (pidAlive(session.pid)) {
1449
+ requireLive();
1450
+ if (performance.now() >= until) throw new HarnessRefusal("stop_failed");
1451
+ await delay(50);
1452
+ }
1453
+ }
1454
+ await this.executor.environment(true, folder);
1455
+ if (await this.signedIn(folder) === false) throw new HarnessRefusal("not_signed_in");
1456
+ const prompt = text3 ?? (session.state === "stopped" ? RESUME_CONTINUATION : null);
1457
+ requireLive();
1458
+ const result = await this.call(
1459
+ [
1460
+ "--resume",
1461
+ opaque(session.conversationId),
1462
+ "--bg",
1463
+ ...prompt === null ? [] : ["--", prompt]
1464
+ ],
1465
+ folder,
1466
+ "launch",
1467
+ requireLive
1468
+ );
1469
+ if (result.code !== 0) throw new HarnessRefusal("harness_exited");
1470
+ const copy = /started a copy as\s+([A-Za-z0-9_-]+)/.exec(result.stdout)?.[1];
1471
+ const background = /backgrounded\s*·\s*([A-Za-z0-9_-]+)(?=\s*(?:·|$))/m.exec(
1472
+ result.stdout
1473
+ )?.[1];
1474
+ if (!copy && !background) throw new Error("Uncertain resume result; inspect local harness");
1475
+ return opaque(background ?? copy);
1476
+ }
1477
+ attachHint(id) {
1478
+ return { harness: HARNESS_KIND.CLAUDE_CODE, session_ref: opaque(id) };
1479
+ }
1480
+ async repositories(folders) {
1481
+ const readiness = new Map(
1482
+ await Promise.all(
1483
+ [...new Set(Object.values(folders))].map(async (folder) => {
1484
+ try {
1485
+ const detection = await this.probe(folder);
1486
+ return [
1487
+ folder,
1488
+ {
1489
+ available: detection.available,
1490
+ signed_in: detection.signed_in ?? null
1491
+ }
1492
+ ];
1493
+ } catch {
1494
+ return [folder, { available: false, signed_in: null }];
1495
+ }
1496
+ })
1497
+ )
1498
+ );
1499
+ return (await this.trust.repositories(folders)).map((row) => {
1500
+ const detection = readiness.get(folders[row.slug]);
1501
+ return {
1502
+ ...row,
1503
+ available: detection.available,
1504
+ signed_in: detection.signed_in ?? null
1505
+ };
1506
+ });
1507
+ }
1508
+ };
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
+
1741
+ // src/codex-trust.ts
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";
1745
+ import { parseToml } from "./vendor.js";
1746
+ var MAX_CONFIG_BYTES2 = 4 * 1024 * 1024;
1747
+ var CodexTrust = class {
1748
+ constructor(executor) {
1749
+ this.executor = executor;
1750
+ }
1751
+ async read(folder) {
1752
+ try {
1753
+ const env = await this.executor.environment(false, folder);
1754
+ const root = await this.executor.execute(
1755
+ "git",
1756
+ ["rev-parse", "--show-toplevel"],
1757
+ "read",
1758
+ folder
1759
+ );
1760
+ const prefix = await this.executor.execute(
1761
+ "git",
1762
+ ["rev-parse", "--show-prefix"],
1763
+ "read",
1764
+ folder
1765
+ );
1766
+ const common = await this.executor.execute(
1767
+ "git",
1768
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
1769
+ "read",
1770
+ folder
1771
+ );
1772
+ if (root.code !== 0 || prefix.code !== 0) return "unknown";
1773
+ const canonical2 = await realpath(root.stdout.trim());
1774
+ const commonDir = common.code === 0 ? common.stdout.trim() : "";
1775
+ const main = basename3(commonDir) === ".git" ? await realpath(dirname(commonDir)) : canonical2;
1776
+ let given = resolve2(folder);
1777
+ for (const part of prefix.stdout.trim().split("/").filter(Boolean)) {
1778
+ if (part) given = dirname(given);
1779
+ }
1780
+ const path = join5(
1781
+ env["CODEX_HOME"] ?? join5(env["HOME"] ?? homedir4(), ".codex"),
1782
+ "config.toml"
1783
+ );
1784
+ const file = await open3(path, "r");
1785
+ let contents;
1786
+ try {
1787
+ if (!(await file.stat()).isFile()) return "unknown";
1788
+ const buffer = Buffer.alloc(MAX_CONFIG_BYTES2 + 1);
1789
+ let total = 0;
1790
+ while (total < buffer.length) {
1791
+ const { bytesRead } = await file.read(
1792
+ buffer,
1793
+ total,
1794
+ buffer.length - total,
1795
+ null
1796
+ );
1797
+ if (!bytesRead) break;
1798
+ total += bytesRead;
1799
+ }
1800
+ if (total > MAX_CONFIG_BYTES2) return "unknown";
1801
+ contents = buffer.subarray(0, total).toString("utf8");
1802
+ } finally {
1803
+ await file.close();
1804
+ }
1805
+ const projects = parseToml(contents)["projects"];
1806
+ if (!isObject(projects)) return "unknown";
1807
+ for (const spelling of /* @__PURE__ */ new Set([canonical2, given, main])) {
1808
+ const project = Object.hasOwn(projects, spelling) ? field(projects, spelling) : null;
1809
+ const trust = isObject(project) ? field(project, "trust_level") : null;
1810
+ if (trust === "trusted" || trust === "untrusted") return trust;
1811
+ }
1812
+ return "unknown";
1813
+ } catch {
1814
+ return "unknown";
1815
+ }
1816
+ }
1817
+ };
1818
+
1819
+ // src/codex-driver.ts
1820
+ import { realpath as realpath3 } from "node:fs/promises";
1821
+
1822
+ // src/codex-app-server.ts
1823
+ import { Duplex } from "node:stream";
1824
+ import { WebSocket as WebSocket2 } from "./vendor.js";
1825
+ var CodexThreadMissing = class extends Error {
1826
+ };
1827
+ var CodexAppServer = class _CodexAppServer {
1828
+ constructor(child, timeouts) {
1829
+ this.child = child;
1830
+ this.timeouts = timeouts;
1831
+ this.exited = new Promise((resolve6) => child.once("close", resolve6));
1832
+ this.stream = new Duplex({
1833
+ read() {
1834
+ },
1835
+ final: (callback) => child.stdin.end(callback),
1836
+ write: (chunk, _encoding, callback) => {
1837
+ child.stdin.write(chunk, callback);
1838
+ }
1839
+ });
1840
+ child.stdout.on("data", (chunk) => this.stream.push(chunk));
1841
+ child.stdout.on("end", () => this.stream.push(null));
1842
+ child.stderr.resume();
1843
+ child.stdin.on("error", (error) => this.stream.destroy(error));
1844
+ child.stdout.on("error", (error) => this.stream.destroy(error));
1845
+ child.once("error", (error) => this.fail(error));
1846
+ child.once("close", () => this.fail(new Error("Codex proxy closed")));
1847
+ this.socket = new WebSocket2("ws://localhost/", {
1848
+ createConnection: () => this.stream,
1849
+ handshakeTimeout: timeouts.startupMs,
1850
+ maxPayload: 4 * 1024 * 1024,
1851
+ perMessageDeflate: false
1852
+ });
1853
+ this.socket.on("error", () => this.fail(new Error("Codex connection failed")));
1854
+ this.socket.on("close", () => this.fail(new Error("Codex connection closed")));
1855
+ this.socket.on("message", (bytes) => {
1856
+ try {
1857
+ const message = parseJson(
1858
+ Buffer.isBuffer(bytes) ? bytes.toString("utf8") : Buffer.from(bytes).toString("utf8")
1859
+ );
1860
+ if (!isObject(message) || typeof field(message, "method") === "string") return;
1861
+ const id = field(message, "id");
1862
+ const request = typeof id === "number" ? this.pending.get(id) : void 0;
1863
+ if (!request) return;
1864
+ this.pending.delete(id);
1865
+ clearTimeout(request.timer);
1866
+ const error = field(message, "error");
1867
+ if (error !== void 0) {
1868
+ const missing = isObject(error) && field(error, "code") === -32600 && request.method === "thread/read" && field(error, "message") === `thread not loaded: ${request.threadId}`;
1869
+ request.reject(
1870
+ missing ? new CodexThreadMissing("Codex thread missing") : new Error("Codex request failed")
1871
+ );
1872
+ } else request.resolve(field(message, "result"));
1873
+ } catch {
1874
+ this.fail(new Error("Invalid Codex response"));
1875
+ }
1876
+ });
1877
+ }
1878
+ pending = /* @__PURE__ */ new Map();
1879
+ nextId = 1;
1880
+ socket;
1881
+ stream;
1882
+ exited;
1883
+ closed = false;
1884
+ failure;
1885
+ get usable() {
1886
+ return !this.closed && !this.failure;
1887
+ }
1888
+ fail(error) {
1889
+ this.failure ??= error;
1890
+ for (const request of this.pending.values()) {
1891
+ clearTimeout(request.timer);
1892
+ request.reject(error);
1893
+ }
1894
+ this.pending.clear();
1895
+ }
1896
+ static async connect(executor, executable2, folder, timeouts, requireLive) {
1897
+ const timeout = new Error("Codex connection timed out");
1898
+ let expired = false;
1899
+ let connection2;
1900
+ let timer;
1901
+ const deadline = new Promise((_resolve, reject) => {
1902
+ timer = setTimeout(() => {
1903
+ expired = true;
1904
+ reject(timeout);
1905
+ }, timeouts.startupMs);
1906
+ });
1907
+ const startup = async () => {
1908
+ const child = await executor.spawn(executable2, ["app-server", "proxy"], folder, () => {
1909
+ if (expired) throw timeout;
1910
+ requireLive?.();
1911
+ });
1912
+ const server = new _CodexAppServer(child, timeouts);
1913
+ connection2 = server;
1914
+ if (expired) {
1915
+ await server.close();
1916
+ throw timeout;
1917
+ }
1918
+ await new Promise((resolve6, reject) => {
1919
+ const opened = () => finish();
1920
+ const failed = () => finish(new Error("Cannot connect to Codex"));
1921
+ function finish(error) {
1922
+ server.socket.off("open", opened).off("error", failed).off("close", failed);
1923
+ child.off("error", failed).off("close", failed);
1924
+ if (error) reject(error);
1925
+ else resolve6();
1926
+ }
1927
+ server.socket.once("open", opened).once("error", failed).once("close", failed);
1928
+ child.once("error", failed).once("close", failed);
1929
+ });
1930
+ await server.sendRequest(
1931
+ "initialize",
1932
+ {
1933
+ clientInfo: { name: "tsp_gateway", version: GATEWAY_PACKAGE_VERSION },
1934
+ capabilities: { experimentalApi: true }
1935
+ },
1936
+ void 0,
1937
+ timeouts.startupMs
1938
+ );
1939
+ server.socket.send(JSON.stringify({ method: "initialized" }));
1940
+ return server;
1941
+ };
1942
+ try {
1943
+ return await Promise.race([startup(), deadline]);
1944
+ } catch (error) {
1945
+ await connection2?.close();
1946
+ throw error;
1947
+ } finally {
1948
+ clearTimeout(timer);
1949
+ }
1950
+ }
1951
+ request(method, params, requireLive) {
1952
+ return this.sendRequest(
1953
+ method,
1954
+ params,
1955
+ requireLive,
1956
+ method === "thread/start" ? this.timeouts.threadStartMs : this.timeouts.requestMs
1957
+ );
1958
+ }
1959
+ sendRequest(method, params, requireLive, timeoutMs) {
1960
+ if (this.closed || this.failure)
1961
+ return Promise.reject(this.failure ?? new Error("Codex connection closed"));
1962
+ requireLive?.();
1963
+ const id = this.nextId++;
1964
+ return new Promise((resolve6, reject) => {
1965
+ const timer = setTimeout(() => {
1966
+ this.fail(new Error(`Codex ${method} timed out`));
1967
+ }, timeoutMs);
1968
+ this.pending.set(id, {
1969
+ resolve: resolve6,
1970
+ reject,
1971
+ timer,
1972
+ method,
1973
+ threadId: "threadId" in params ? params.threadId : void 0
1974
+ });
1975
+ this.socket.send(JSON.stringify({ id, method, params }), (error) => {
1976
+ if (error) this.fail(new Error("Codex write failed"));
1977
+ });
1978
+ });
1979
+ }
1980
+ async close() {
1981
+ if (this.closed) return this.exited;
1982
+ this.closed = true;
1983
+ this.fail(new Error("Codex connection closed"));
1984
+ if (this.socket.readyState === WebSocket2.OPEN) {
1985
+ let timer;
1986
+ let onClose = () => {
1987
+ };
1988
+ const closed = new Promise((resolve6) => {
1989
+ onClose = resolve6;
1990
+ this.socket.once("close", onClose);
1991
+ timer = setTimeout(resolve6, 250);
1992
+ });
1993
+ this.socket.close(1e3);
1994
+ try {
1995
+ await Promise.race([closed, this.exited]);
1996
+ } finally {
1997
+ clearTimeout(timer);
1998
+ this.socket.off("close", onClose);
1999
+ }
2000
+ }
2001
+ if (this.socket.readyState !== WebSocket2.CLOSED) this.socket.terminate();
2002
+ this.stream.destroy();
2003
+ if (this.child.exitCode === null && this.child.signalCode === null) {
2004
+ this.child.kill("SIGTERM");
2005
+ const timer = setTimeout(() => this.child.kill("SIGKILL"), 250);
2006
+ try {
2007
+ await this.exited;
2008
+ } finally {
2009
+ clearTimeout(timer);
2010
+ }
2011
+ } else await this.exited;
2012
+ }
2013
+ };
2014
+
2015
+ // src/codex-sessions.ts
2016
+ import { realpath as realpath2 } from "node:fs/promises";
2017
+ import { isAbsolute as isAbsolute4, relative, resolve as resolve3, sep } from "node:path";
2018
+ async function inside(folder, cwd) {
2019
+ if (!isAbsolute4(cwd)) return false;
2020
+ const path = await realpath2(cwd).catch(() => resolve3(cwd));
2021
+ const child = relative(folder, path);
2022
+ return child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute4(child);
2023
+ }
2024
+ async function lastTurn(server, id) {
2025
+ return latestTurn(
2026
+ await server.request("thread/turns/list", {
2027
+ threadId: codexId(id),
2028
+ limit: 1,
2029
+ sortDirection: "desc",
2030
+ itemsView: "notLoaded"
2031
+ })
2032
+ );
2033
+ }
2034
+ async function* threads(server, folder, query) {
2035
+ if (query && "refs" in query) {
2036
+ for (const id of new Set(query.refs)) {
2037
+ try {
2038
+ yield threadResult(
2039
+ await server.request("thread/read", {
2040
+ threadId: codexId(id),
2041
+ includeTurns: false
2042
+ })
2043
+ );
2044
+ } catch (error) {
2045
+ if (error instanceof CodexThreadMissing) continue;
2046
+ yield { id, cwd: folder, name: "", status: "unknown", activeFlags: [], turns: [] };
2047
+ }
2048
+ }
2049
+ return;
2050
+ }
2051
+ const seen = /* @__PURE__ */ new Set();
2052
+ for (const method of ["thread/list", "thread/loaded/list"]) {
2053
+ const cursors = /* @__PURE__ */ new Set();
2054
+ let cursor = null;
2055
+ do {
2056
+ const page2 = method === "thread/list" ? threadPage(
2057
+ await server.request(method, {
2058
+ cursor,
2059
+ limit: 100,
2060
+ // cwd is exact-match only; keep descendant/symlink sessions visible.
2061
+ // Skip rollout repair scans while enumerating metadata.
2062
+ useStateDbOnly: true,
2063
+ sourceKinds: ["cli", "vscode", "appServer"]
2064
+ })
2065
+ ) : loadedThreadPage(await server.request(method, { cursor, limit: 100 }));
2066
+ for (const entry of page2.threads) {
2067
+ const id = typeof entry === "string" ? entry : entry.id;
2068
+ if (seen.has(id)) continue;
2069
+ seen.add(id);
2070
+ if (typeof entry !== "string") {
2071
+ yield entry;
2072
+ continue;
2073
+ }
2074
+ try {
2075
+ yield threadResult(
2076
+ await server.request("thread/read", {
2077
+ threadId: id,
2078
+ includeTurns: false
2079
+ })
2080
+ );
2081
+ } catch {
2082
+ }
2083
+ }
2084
+ cursor = page2.cursor;
2085
+ if (cursor && cursors.has(cursor))
2086
+ throw new Error("Codex repeated a pagination cursor");
2087
+ if (cursor) cursors.add(cursor);
2088
+ } while (cursor);
2089
+ }
2090
+ }
2091
+ async function listCodexSessions(server, folder, query, activity) {
2092
+ const root = await realpath2(folder);
2093
+ const sessions = [];
2094
+ for await (let thread of threads(server, folder, query)) {
2095
+ if (!await inside(root, thread.cwd)) continue;
2096
+ if (query && "name" in query && thread.name !== query.name) continue;
2097
+ if (thread.status === "idle" || thread.status === "notLoaded") {
2098
+ try {
2099
+ const turn = await lastTurn(server, thread.id);
2100
+ thread = { ...thread, turns: turn ? [turn] : [] };
2101
+ } catch {
2102
+ thread = { ...thread, status: "unknown" };
2103
+ }
2104
+ }
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);
2109
+ }
2110
+ return sessions;
2111
+ }
2112
+
2113
+ // src/codex-driver.ts
2114
+ var MINIMUM_CODEX_VERSION = "0.162.1";
2115
+ function supportedCodexVersion(version) {
2116
+ const parts = (text3) => (text3.split(/[-+]/)[0] ?? "").split(".").map(Number);
2117
+ if (!version) return true;
2118
+ const found = parts(version), minimum = parts(MINIMUM_CODEX_VERSION);
2119
+ for (const [index, part] of minimum.entries()) {
2120
+ const value = found[index] ?? 0;
2121
+ if (value !== part) return value > part;
2122
+ }
2123
+ return true;
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
+ }
2137
+ var CodexDriver = class {
2138
+ constructor(env, executable2 = "codex", executor = new HarnessExecutor(env), timeouts = {}) {
2139
+ this.executable = executable2;
2140
+ this.executor = executor;
2141
+ this.trust = new CodexTrust(executor);
2142
+ this.timeouts = { ...CODEX_TIMEOUTS, ...timeouts };
2143
+ }
2144
+ repositorySetupInstruction = "Run codex in that folder once and accept its trust prompt.";
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.`;
2148
+ /** Codex refuses a folder it has no trust record for, so unknown trust is a step to take. */
2149
+ unknownTrustAdmits = false;
2150
+ capabilities = {
2151
+ start: true,
2152
+ stop: true,
2153
+ resume: true,
2154
+ attach_hint: true,
2155
+ answer_input: false
2156
+ };
2157
+ trust;
2158
+ activity = new CodexActivity();
2159
+ timeouts;
2160
+ async detect(folder) {
2161
+ if (folder) await this.executor.environment(true, folder);
2162
+ return this.probe(folder);
2163
+ }
2164
+ async probe(folder) {
2165
+ const detection = {
2166
+ harness: HARNESS_KIND.CODEX,
2167
+ available: false,
2168
+ harness_version: null,
2169
+ signed_in: null,
2170
+ operations: this.capabilities
2171
+ };
2172
+ try {
2173
+ const version = await this.executor.execute(
2174
+ this.executable,
2175
+ ["--version"],
2176
+ "read",
2177
+ folder
2178
+ );
2179
+ detection.harness_version = version.stdout.match(/\b\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?/)?.[0]?.slice(0, 80) ?? null;
2180
+ detection.available = version.code === 0 && supportedCodexVersion(detection.harness_version);
2181
+ if (detection.available) {
2182
+ const login = await this.executor.execute(
2183
+ this.executable,
2184
+ ["login", "status"],
2185
+ "read",
2186
+ folder
2187
+ );
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;
2190
+ }
2191
+ } catch {
2192
+ }
2193
+ return detection;
2194
+ }
2195
+ async requireTrusted(folder) {
2196
+ if (await this.trust.read(folder) !== "trusted")
2197
+ throw new HarnessRefusal("workspace_untrusted");
2198
+ }
2199
+ async open(folder, requireLive) {
2200
+ try {
2201
+ return await CodexAppServer.connect(
2202
+ this.executor,
2203
+ this.executable,
2204
+ folder,
2205
+ this.timeouts
2206
+ );
2207
+ } catch (error) {
2208
+ if (!requireLive) throw error;
2209
+ await this.requireTrusted(folder);
2210
+ const result = await this.executor.execute(
2211
+ this.executable,
2212
+ ["app-server", "daemon", "start"],
2213
+ "control",
2214
+ folder,
2215
+ requireLive
2216
+ );
2217
+ if (result.code !== 0) throw new Error("Cannot start Codex daemon");
2218
+ return CodexAppServer.connect(
2219
+ this.executor,
2220
+ this.executable,
2221
+ folder,
2222
+ this.timeouts,
2223
+ requireLive
2224
+ );
2225
+ }
2226
+ }
2227
+ async connection(folder, operation, requireLive) {
2228
+ let server = await this.open(folder, requireLive);
2229
+ const reader = {
2230
+ request: async (method, params, guard) => {
2231
+ if (!server.usable) {
2232
+ await server.close();
2233
+ server = await this.open(folder, requireLive);
2234
+ }
2235
+ return server.request(method, params, guard);
2236
+ }
2237
+ };
2238
+ try {
2239
+ return await operation(reader);
2240
+ } finally {
2241
+ await server.close();
2242
+ }
2243
+ }
2244
+ async start(command, folder, requireLive, checkpoint) {
2245
+ await this.requireTrusted(folder);
2246
+ return this.connection(
2247
+ folder,
2248
+ async (server) => {
2249
+ await this.requireTrusted(folder);
2250
+ const thread = threadResult(
2251
+ await server.request("thread/start", { cwd: folder }, requireLive)
2252
+ );
2253
+ await checkpoint?.(thread.id);
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
+ }
2272
+ return thread.id;
2273
+ },
2274
+ requireLive
2275
+ );
2276
+ }
2277
+ async reconcileLaunch(ref, command, folder, requireLive) {
2278
+ return this.connection(
2279
+ folder,
2280
+ async (server) => {
2281
+ let thread;
2282
+ try {
2283
+ thread = threadResult(
2284
+ await server.request("thread/read", {
2285
+ threadId: codexId(ref),
2286
+ includeTurns: false
2287
+ })
2288
+ );
2289
+ } catch (error) {
2290
+ if (error instanceof CodexThreadMissing) return void 0;
2291
+ throw error;
2292
+ }
2293
+ if (!await inside(await realpath3(folder), thread.cwd))
2294
+ throw new HarnessRefusal("start_uncertain");
2295
+ const turn = await lastTurn(server, thread.id);
2296
+ if (turn) return sessionFromThread({ ...thread, turns: [turn] });
2297
+ await this.requireTrusted(folder);
2298
+ if (thread.status === "notLoaded") {
2299
+ await server.request(
2300
+ "thread/resume",
2301
+ { threadId: thread.id, excludeTurns: true },
2302
+ requireLive
2303
+ );
2304
+ const loadedTurn = await lastTurn(server, thread.id);
2305
+ if (loadedTurn) return sessionFromThread({ ...thread, turns: [loadedTurn] });
2306
+ }
2307
+ if (thread.name !== command.session_name)
2308
+ await server.request(
2309
+ "thread/name/set",
2310
+ { threadId: thread.id, name: command.session_name },
2311
+ requireLive
2312
+ );
2313
+ await server.request(
2314
+ "turn/start",
2315
+ {
2316
+ threadId: thread.id,
2317
+ input: [{ type: "text", text: command.seed, text_elements: [] }]
2318
+ },
2319
+ requireLive
2320
+ );
2321
+ return { ...sessionFromThread(thread), state: "starting", waitingFor: null };
2322
+ },
2323
+ requireLive
2324
+ );
2325
+ }
2326
+ resumeRecovery = {
2327
+ observe: async (session, folder) => {
2328
+ const turn = await this.connection(folder, (server) => lastTurn(server, session.id));
2329
+ return turn ? [turn.id] : [];
2330
+ },
2331
+ reconcile: async (session, text3, observedRefs, folder, requireLive) => {
2332
+ const turn = await this.connection(folder, (server) => lastTurn(server, session.id));
2333
+ if (turn && !observedRefs.includes(turn.id)) return session.id;
2334
+ return this.resume(session, text3, folder, requireLive);
2335
+ }
2336
+ };
2337
+ async list(folder, requireLive, query) {
2338
+ return this.connection(
2339
+ folder,
2340
+ (server) => listCodexSessions(server, folder, query, this.activity),
2341
+ requireLive
2342
+ );
2343
+ }
2344
+ async stop(session, folder, requireLive) {
2345
+ await this.connection(
2346
+ folder,
2347
+ async (server) => {
2348
+ const turn = await lastTurn(server, session.id);
2349
+ if (turn?.status === "inProgress")
2350
+ await server.request(
2351
+ "turn/interrupt",
2352
+ { threadId: session.id, turnId: turn.id },
2353
+ requireLive
2354
+ );
2355
+ },
2356
+ requireLive
2357
+ );
2358
+ }
2359
+ async resume(session, text3, folder, requireLive) {
2360
+ if (session.state === "working" || session.state === "needs_input")
2361
+ throw new HarnessRefusal("unsupported_command");
2362
+ const detected = await this.detect(folder);
2363
+ if (!detected.available) throw new HarnessRefusal("harness_unavailable");
2364
+ if (detected.signed_in === false) throw new HarnessRefusal("not_signed_in");
2365
+ await this.requireTrusted(folder);
2366
+ const id = codexId(session.id);
2367
+ return this.connection(
2368
+ folder,
2369
+ async (server) => {
2370
+ await server.request(
2371
+ "thread/resume",
2372
+ { threadId: id, excludeTurns: true },
2373
+ requireLive
2374
+ );
2375
+ const turn = text3 === null ? await lastTurn(server, id) : null;
2376
+ const prompt = text3 ?? (turn?.status === "interrupted" ? RESUME_CONTINUATION : null);
2377
+ if (prompt !== null)
2378
+ await server.request(
2379
+ "turn/start",
2380
+ {
2381
+ threadId: id,
2382
+ input: [{ type: "text", text: prompt, text_elements: [] }]
2383
+ },
2384
+ requireLive
2385
+ );
2386
+ return id;
2387
+ },
2388
+ requireLive
2389
+ );
2390
+ }
2391
+ attachHint(id) {
2392
+ return { harness: HARNESS_KIND.CODEX, session_ref: codexId(id) };
2393
+ }
2394
+ async repositories(folders) {
2395
+ return Promise.all(
2396
+ Object.entries(folders).sort(([a], [b]) => a.localeCompare(b)).map(async ([slug, folder]) => {
2397
+ const detection = await this.probe(folder);
2398
+ return {
2399
+ harness: HARNESS_KIND.CODEX,
2400
+ slug,
2401
+ trust: await this.trust.read(folder),
2402
+ available: detection.available,
2403
+ signed_in: detection.signed_in ?? null
2404
+ };
2405
+ })
2406
+ );
2407
+ }
2408
+ };
2409
+
2410
+ // src/harness-registry.ts
2411
+ var HarnessRegistry = class {
2412
+ constructor(drivers) {
2413
+ this.drivers = drivers;
2414
+ }
2415
+ get(harness) {
2416
+ const driver = this.drivers[harness];
2417
+ if (!driver) throw new HarnessRefusal("harness_unavailable");
2418
+ return driver;
2419
+ }
2420
+ /**
2421
+ * The driver for a launch in `folder`, refused unless its harness is installed and
2422
+ * signed in as the user's current environment there says, never a cached one.
2423
+ */
2424
+ async ready(harness, folder) {
2425
+ const driver = this.get(harness);
2426
+ const detection = await driver.detect(folder);
2427
+ if (harness !== detection.harness || !detection.available)
2428
+ throw new HarnessRefusal("harness_unavailable");
2429
+ if (detection.signed_in === false) throw new HarnessRefusal("not_signed_in");
2430
+ return driver;
2431
+ }
2432
+ setupInstructions() {
2433
+ return Object.values(this.drivers).map((driver) => driver.repositorySetupInstruction);
2434
+ }
2435
+ async detect() {
2436
+ return Promise.all(Object.values(this.drivers).map((driver) => driver.detect()));
2437
+ }
2438
+ async repositories(folders) {
2439
+ return (await Promise.all(
2440
+ Object.values(this.drivers).map((driver) => driver.repositories(folders))
2441
+ )).flat();
2442
+ }
2443
+ };
2444
+
2445
+ // src/builtin-harnesses.ts
2446
+ function builtinHarnesses(environment, executor = new HarnessExecutor(environment)) {
2447
+ return new HarnessRegistry({
2448
+ [HARNESS_KIND.CLAUDE_CODE]: new ClaudeDriver(environment, "claude", void 0, executor),
2449
+ [HARNESS_KIND.CODEX]: new CodexDriver(environment, "codex", executor)
2450
+ });
2451
+ }
2452
+
2453
+ // src/command-lifetime.ts
2454
+ var lifetimeClock = {
2455
+ monotonic: () => performance.now(),
2456
+ wall: () => Date.now()
2457
+ };
2458
+ var CommandLifetime = class {
2459
+ constructor(ttlMs, clock = lifetimeClock, stored) {
2460
+ this.clock = clock;
2461
+ const downtime = stored ? clock.wall() - stored.savedAtMs : 0;
2462
+ const remaining = stored ? downtime < 0 ? 0 : Math.max(0, Math.min(ttlMs, stored.remainingMs - downtime)) : ttlMs;
2463
+ this.deadline = clock.monotonic() + remaining;
2464
+ }
2465
+ deadline;
2466
+ remaining() {
2467
+ return Math.max(0, this.deadline - this.clock.monotonic());
2468
+ }
2469
+ checkpoint() {
2470
+ return { remainingMs: this.remaining(), savedAtMs: this.clock.wall() };
2471
+ }
2472
+ requireLive(command) {
2473
+ if (this.remaining() <= 0)
2474
+ throw new HarnessRefusal(
2475
+ command.kind === "launch" ? "launch_expired" : "control_expired"
2476
+ );
2477
+ }
2478
+ };
2479
+
2480
+ // src/local-store.ts
2481
+ import { randomUUID as randomUUID2 } from "node:crypto";
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");
2488
+ return {
2489
+ config: resolve4(configRoot, "tsp-gateway", "config.json"),
2490
+ state: resolve4(stateRoot, "tsp-gateway")
2491
+ };
2492
+ }
2493
+ async function privateDirectory(path) {
2494
+ await mkdir(path, { recursive: true, mode: 448 });
2495
+ await chmod(path, 448);
2496
+ }
2497
+ async function privateWrite(path, value) {
2498
+ await privateDirectory(dirname2(path));
2499
+ const temporary = `${path}.${randomUUID2()}.tmp`;
2500
+ const handle = await open4(temporary, "wx", 384);
2501
+ try {
2502
+ await handle.writeFile(value);
2503
+ await handle.sync();
2504
+ } finally {
2505
+ await handle.close();
2506
+ }
2507
+ await rename(temporary, path);
2508
+ }
2509
+ async function readConfig(path) {
2510
+ let text3;
2511
+ try {
2512
+ text3 = await readFile(path, "utf8");
2513
+ } catch (error) {
2514
+ if (isObject(error) && field(error, "code") === "ENOENT")
2515
+ return {
2516
+ repositories: {},
2517
+ pairing: null,
2518
+ loginPath: null,
2519
+ launch: defaultLaunchConfig(),
2520
+ reporting: DEFAULT_REPORTING
2521
+ };
2522
+ throw error;
2523
+ }
2524
+ const value = parseJson(text3);
2525
+ if (!isObject(value) || Object.keys(value).some(
2526
+ (key) => !["repositories", "pairing", "loginPath", "launch", "reporting"].includes(key)
2527
+ ))
2528
+ throw new Error("Invalid gateway config");
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;
2531
+ const repositories = field(value, "repositories"), pairing = field(value, "pairing"), loginPath = field(value, "loginPath");
2532
+ if (!isObject(repositories) || !(loginPath === null || typeof loginPath === "string"))
2533
+ throw new Error("Invalid gateway config");
2534
+ const map = {};
2535
+ for (const slug of Object.keys(repositories)) {
2536
+ const folder = field(repositories, slug);
2537
+ if (!validSlug(slug) || typeof folder !== "string" || !isAbsolute5(folder))
2538
+ throw new Error("Invalid repository registry");
2539
+ map[slug] = folder;
2540
+ }
2541
+ let paired = null;
2542
+ if (pairing !== null) {
2543
+ if (!isObject(pairing)) throw new Error("Invalid pairing");
2544
+ const origin = field(pairing, "origin"), clientId = field(pairing, "clientId");
2545
+ if (typeof origin !== "string" || typeof clientId !== "string")
2546
+ throw new Error("Invalid pairing");
2547
+ validateOrigin(origin);
2548
+ paired = {
2549
+ ...decodeRegistration({
2550
+ machine_id: field(pairing, "machine_id"),
2551
+ hub_path: field(pairing, "hub_path")
2552
+ }),
2553
+ origin,
2554
+ clientId
2555
+ };
2556
+ }
2557
+ return { repositories: map, pairing: paired, loginPath, launch, reporting };
2558
+ }
2559
+ function saveConfig(path, config) {
2560
+ return privateWrite(path, JSON.stringify(config, null, 2) + "\n");
2561
+ }
2562
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
2563
+ function validateOrigin(input) {
2564
+ const url = new URL(input);
2565
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname)))
2566
+ throw new Error(
2567
+ "TSP requires HTTPS (HTTP is allowed only on a loopback host for local tests)"
2568
+ );
2569
+ if (url.username || url.password || url.pathname !== "/" || url.search || url.hash)
2570
+ throw new Error("Use the TSP API origin without a path");
2571
+ return url.origin;
2572
+ }
2573
+ function validSlug(slug) {
2574
+ return slug.length >= 3 && slug.length <= 201 && /^[a-z0-9][a-z0-9_-]*\/[a-z0-9][a-z0-9_.-]*$/.test(slug);
2575
+ }
2576
+ function githubSlug(remote) {
2577
+ const match = /^(?:git@github\.com:|https:\/\/github\.com\/|ssh:\/\/git@github\.com\/)([^\s?#]+?)\/?$/.exec(
2578
+ remote.trim()
2579
+ );
2580
+ const slug = match?.[1]?.replace(/\.git$/, "").toLowerCase();
2581
+ return slug && validSlug(slug) ? slug : null;
2582
+ }
2583
+ async function registerFolder(folder, env = process.env) {
2584
+ const absolute = await realpath4(folder);
2585
+ const remotes = await execute("git", ["remote"], env, absolute);
2586
+ if (remotes.code !== 0) throw new Error("Folder is not a Git repository");
2587
+ const names = remotes.stdout.trim().split(/\r?\n/).filter(Boolean).sort((a, b) => Number(b === "origin") - Number(a === "origin"));
2588
+ for (const name of names) {
2589
+ const remote = await execute("git", ["remote", "get-url", name], env, absolute);
2590
+ const slug = remote.code === 0 ? githubSlug(remote.stdout) : null;
2591
+ if (slug) return { slug, folder: absolute };
2592
+ }
2593
+ throw new Error("Folder has no GitHub remote");
2594
+ }
2595
+
2596
+ // src/journal.ts
2597
+ import { createHash } from "node:crypto";
2598
+ import { open as open5, readFile as readFile2, truncate } from "node:fs/promises";
2599
+ import { dirname as dirname3 } from "node:path";
2600
+
2601
+ // src/journal-codec.ts
2602
+ function object(value) {
2603
+ if (!isObject(value)) throw new Error("Invalid stored object");
2604
+ return value;
2605
+ }
2606
+ function string(value) {
2607
+ if (typeof value !== "string") throw new Error("Invalid stored string");
2608
+ return value;
2609
+ }
2610
+ function nullable(value) {
2611
+ return value == null ? null : string(value);
2612
+ }
2613
+ function nonnegative(value) {
2614
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
2615
+ throw new Error("Invalid stored lifetime");
2616
+ return value;
2617
+ }
2618
+ function member2(value, choices) {
2619
+ const found = choices.find((choice) => choice === value);
2620
+ if (found === void 0) throw new Error("Invalid stored enum");
2621
+ return found;
2622
+ }
2623
+ function readCommand(value) {
2624
+ const row = object(value);
2625
+ const command_id = string(field(row, "command_id")), action_id = string(field(row, "action_id"));
2626
+ if (!/^lc_[a-f0-9]{12}$/.test(command_id) || !/^la_[a-f0-9]{12}$/.test(action_id))
2627
+ throw new Error("Invalid stored identity");
2628
+ const ttl_ms = nonnegative(field(row, "ttl_ms"));
2629
+ if (!Number.isSafeInteger(ttl_ms)) throw new Error("Invalid stored lifetime");
2630
+ const identity2 = { command_id, action_id, ttl_ms };
2631
+ switch (field(row, "kind")) {
2632
+ case "launch": {
2633
+ const session_name = string(field(row, "session_name"));
2634
+ if (session_name !== `tsp-${action_id.slice(3)}`)
2635
+ throw new Error("Invalid stored session name");
2636
+ return {
2637
+ ...identity2,
2638
+ kind: "launch",
2639
+ session_name,
2640
+ harness: member2(field(row, "harness"), Object.values(HARNESS_KIND)),
2641
+ repository: string(field(row, "repository")),
2642
+ seed: string(field(row, "seed"))
2643
+ };
2644
+ }
2645
+ case "stop":
2646
+ return { ...identity2, kind: "stop", session_ref: string(field(row, "session_ref")) };
2647
+ case "resume":
2648
+ return {
2649
+ ...identity2,
2650
+ kind: "resume",
2651
+ session_ref: string(field(row, "session_ref")),
2652
+ text: nullable(field(row, "text"))
2653
+ };
2654
+ default:
2655
+ throw new Error("Invalid stored operation");
2656
+ }
2657
+ }
2658
+ function checkIdentity(row, command) {
2659
+ for (const key of ["action_id", "command_id"]) {
2660
+ const value = field(row, key);
2661
+ if (value !== void 0 && value !== command[key])
2662
+ throw new Error("Invalid stored identity");
2663
+ }
2664
+ }
2665
+ function readReceipt(value, command) {
2666
+ if (value === null) return null;
2667
+ const row = object(value);
2668
+ checkIdentity(row, command);
2669
+ switch (field(row, "kind")) {
2670
+ case "ack":
2671
+ return { kind: "ack" };
2672
+ case "refused":
2673
+ return {
2674
+ kind: "refused",
2675
+ reason: member2(field(row, "reason"), Object.values(LAUNCH_REFUSAL_REASON))
2676
+ };
2677
+ default:
2678
+ throw new Error("Invalid stored receipt");
2679
+ }
2680
+ }
2681
+ function readAttachHint(value) {
2682
+ if (value == null) return null;
2683
+ const row = object(value);
2684
+ const session_ref = string(field(row, "session_ref"));
2685
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(session_ref))
2686
+ throw new Error("Invalid attach session reference");
2687
+ return { harness: member2(field(row, "harness"), Object.values(HARNESS_KIND)), session_ref };
2688
+ }
2689
+ function readObservation(value, command) {
2690
+ if (value === null) return null;
2691
+ const row = object(value);
2692
+ checkIdentity(row, command);
2693
+ return {
2694
+ session_ref: string(field(row, "session_ref")),
2695
+ state: member2(field(row, "state"), Object.values(AGENT_SESSION_STATE)),
2696
+ waiting_for: nullable(field(row, "waiting_for")),
2697
+ attach_hint: readAttachHint(field(row, "attach_hint")),
2698
+ resumed_as: nullable(field(row, "resumed_as"))
2699
+ };
2700
+ }
2701
+ function readJournalEntry(value) {
2702
+ const row = object(value), version = field(row, "format_version");
2703
+ if (version !== void 0 && version !== 1) throw new Error("Unsupported journal format");
2704
+ const command = readCommand(field(row, "command"));
2705
+ const lifetime = object(field(row, "lifetime"));
2706
+ const receipt = readReceipt(field(row, "receipt"), command);
2707
+ const update = readObservation(field(row, "update"), command);
2708
+ const rawRefs = field(row, "observedRefs");
2709
+ if (!Array.isArray(rawRefs)) throw new Error("Invalid stored observations");
2710
+ const observedRefs = rawRefs.map((ref) => string(ref));
2711
+ const attempts = field(row, "attempts") ?? 0;
2712
+ if (typeof attempts !== "number" || !Number.isSafeInteger(attempts) || attempts < 0)
2713
+ throw new Error("Invalid stored attempts");
2714
+ const envelope = {
2715
+ protocol_version: GATEWAY_PROTOCOL_VERSION,
2716
+ action_id: command.action_id
2717
+ };
2718
+ return {
2719
+ lifetime: {
2720
+ remainingMs: nonnegative(field(lifetime, "remainingMs")),
2721
+ savedAtMs: nonnegative(field(lifetime, "savedAtMs"))
2722
+ },
2723
+ command: { ...command, protocol_version: GATEWAY_PROTOCOL_VERSION },
2724
+ receipt: receipt && { ...receipt, ...envelope, command_id: command.command_id },
2725
+ update: update && { ...update, ...envelope, kind: "session_update" },
2726
+ conversationId: nullable(field(row, "conversationId")),
2727
+ observedRefs,
2728
+ attempts
2729
+ };
2730
+ }
2731
+ function storeJournalEntry(entry) {
2732
+ const { protocol_version: _version, ...command } = entry.command;
2733
+ const receipt = entry.receipt;
2734
+ const update = entry.update;
2735
+ return {
2736
+ format_version: 1,
2737
+ lifetime: entry.lifetime,
2738
+ command,
2739
+ receipt: receipt === null ? null : receipt.kind === "refused" ? { kind: "refused", reason: receipt.reason } : { kind: "ack" },
2740
+ update: update && {
2741
+ session_ref: update.session_ref,
2742
+ state: update.state,
2743
+ waiting_for: update.waiting_for ?? null,
2744
+ attach_hint: update.attach_hint ?? null,
2745
+ resumed_as: update.resumed_as ?? null
2746
+ },
2747
+ conversationId: entry.conversationId,
2748
+ observedRefs: entry.observedRefs,
2749
+ attempts: entry.attempts
2750
+ };
2751
+ }
2752
+
2753
+ // src/journal.ts
2754
+ function canonical(value) {
2755
+ if (Array.isArray(value)) return `[${value.map((item) => canonical(item)).join(",")}]`;
2756
+ if (isObject(value))
2757
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(field(value, key))}`).join(",")}}`;
2758
+ return JSON.stringify(value);
2759
+ }
2760
+ function commandDigest(command) {
2761
+ const identity2 = {
2762
+ ...command,
2763
+ ttl_ms: null,
2764
+ ...command.kind === "resume" ? { text: command.text ?? null } : {}
2765
+ };
2766
+ return createHash("sha256").update(canonical(identity2)).digest("hex");
2767
+ }
2768
+ var Journal = class {
2769
+ constructor(path) {
2770
+ this.path = path;
2771
+ }
2772
+ entries = /* @__PURE__ */ new Map();
2773
+ unreadableCommandIds = /* @__PURE__ */ new Set();
2774
+ unreadableRows = [];
2775
+ async load() {
2776
+ await privateDirectory(dirname3(this.path));
2777
+ let bytes;
2778
+ try {
2779
+ bytes = await readFile2(this.path);
2780
+ } catch (error) {
2781
+ if (isObject(error) && field(error, "code") === "ENOENT") return;
2782
+ throw error;
2783
+ }
2784
+ const end = bytes.lastIndexOf(10) + 1;
2785
+ if (end !== bytes.length) await truncate(this.path, end);
2786
+ for (const line of bytes.subarray(0, end).toString("utf8").split("\n").filter(Boolean)) {
2787
+ let value;
2788
+ try {
2789
+ value = parseJson(line);
2790
+ const entry = readJournalEntry(value);
2791
+ this.entries.set(entry.command.command_id, entry);
2792
+ } catch {
2793
+ this.quarantine(line, value);
2794
+ console.error("TSP gateway skipped an unreadable journal entry.");
2795
+ }
2796
+ }
2797
+ }
2798
+ quarantine(line, value) {
2799
+ const command = isObject(value) ? field(value, "command") : null;
2800
+ const id = isObject(command) ? field(command, "command_id") : null;
2801
+ const action = isObject(command) ? field(command, "action_id") : null;
2802
+ if (typeof id === "string") this.unreadableCommandIds.add(id);
2803
+ this.unreadableRows.push({ line, actionId: typeof action === "string" ? action : null });
2804
+ }
2805
+ async retire(actionId) {
2806
+ const retained = [...this.entries.values()].filter(
2807
+ (entry) => entry.command.action_id !== actionId
2808
+ );
2809
+ const unreadable = this.unreadableRows.filter((row) => row.actionId !== actionId);
2810
+ await privateWrite(
2811
+ this.path,
2812
+ retained.map((entry) => JSON.stringify(storeJournalEntry(entry)) + "\n").join("") + unreadable.map((row) => row.line + "\n").join("")
2813
+ );
2814
+ this.unreadableRows = unreadable;
2815
+ for (const [id, entry] of this.entries) {
2816
+ if (entry.command.action_id === actionId) this.entries.delete(id);
2817
+ }
2818
+ }
2819
+ async append(entry) {
2820
+ const handle = await open5(this.path, "a", 384);
2821
+ try {
2822
+ await handle.chmod(384);
2823
+ await handle.writeFile(JSON.stringify(storeJournalEntry(entry)) + "\n");
2824
+ await handle.sync();
2825
+ } finally {
2826
+ await handle.close();
2827
+ }
2828
+ this.entries.set(entry.command.command_id, entry);
2829
+ }
2830
+ };
2831
+
2832
+ // src/session-control.ts
2833
+ import { setTimeout as delay2 } from "node:timers/promises";
2834
+ async function stateAfterStop(driver, id, folder, settleMs) {
2835
+ const deadline = performance.now() + settleMs;
2836
+ for (; ; ) {
2837
+ const row = (await driver.list(folder, void 0, { refs: [id] })).find(
2838
+ (candidate) => candidate.id === id
2839
+ );
2840
+ if (row && row.state !== "working" && row.state !== "needs_input") return row.state;
2841
+ if (performance.now() >= deadline) return "unknown";
2842
+ await delay2(200);
2843
+ }
2844
+ }
2845
+ async function findSession(driver, ref, folder, requireLive) {
2846
+ const session = (await driver.list(folder, requireLive, { refs: [ref] })).find(
2847
+ (row) => row.id === ref
2848
+ );
2849
+ if (!session) throw new HarnessRefusal("session_not_found");
2850
+ return session;
2851
+ }
2852
+ async function launchSession(journal, request) {
2853
+ const { driver, intent, folder, retry, knownRef, requireLive } = request;
2854
+ const command = intent.command;
2855
+ if (command.kind !== "launch") throw new HarnessRefusal("unsupported_command");
2856
+ if (driver.reconcileLaunch) {
2857
+ for (const entry of journal.entries.values()) {
2858
+ if (entry.command.kind === "launch" && entry.command.action_id === command.action_id && entry.observedRefs.length > intent.observedRefs.length)
2859
+ intent.observedRefs = [...entry.observedRefs];
2860
+ }
2861
+ await journal.append(intent);
2862
+ }
2863
+ const checkpoint = async (ref2) => {
2864
+ if (intent.observedRefs.at(-1) !== ref2) intent.observedRefs = [...intent.observedRefs, ref2];
2865
+ await journal.append(intent);
2866
+ };
2867
+ const saved = driver.reconcileLaunch ? intent.observedRefs.at(-1) : void 0;
2868
+ let session;
2869
+ if (saved && !knownRef) {
2870
+ session = await driver.reconcileLaunch(saved, command, folder, requireLive);
2871
+ } else {
2872
+ const sessions = await driver.list(
2873
+ folder,
2874
+ requireLive,
2875
+ knownRef ? { refs: [knownRef] } : { name: command.session_name }
2876
+ );
2877
+ const matching = sessions.filter(
2878
+ (row) => knownRef ? row.id === knownRef : row.name === command.session_name
2879
+ );
2880
+ if (matching.length > 1) throw new HarnessRefusal("start_uncertain");
2881
+ session = matching[0];
2882
+ if (knownRef && !session) throw new HarnessRefusal("session_not_found");
2883
+ if (session && driver.reconcileLaunch) {
2884
+ await checkpoint(session.id);
2885
+ session = await driver.reconcileLaunch(session.id, command, folder, requireLive);
2886
+ }
2887
+ }
2888
+ if (session) return { ref: session.id, session };
2889
+ if (retry && !driver.reconcileLaunch) throw new HarnessRefusal("start_uncertain");
2890
+ requireLive();
2891
+ const ref = await driver.start(command, folder, requireLive, checkpoint);
2892
+ return { ref };
2893
+ }
2894
+ async function resumeSession(journal, request) {
2895
+ const { driver, intent, session, folder, retry, requireLive } = request;
2896
+ const command = intent.command;
2897
+ if (command.kind !== "resume") throw new HarnessRefusal("unsupported_command");
2898
+ if (driver.resumeRecovery) {
2899
+ if (retry && intent.conversationId !== null)
2900
+ return driver.resumeRecovery.reconcile(
2901
+ session,
2902
+ command.text ?? null,
2903
+ intent.observedRefs,
2904
+ folder,
2905
+ requireLive
2906
+ );
2907
+ intent.observedRefs = await driver.resumeRecovery.observe(session, folder);
2908
+ intent.conversationId = session.conversationId;
2909
+ await journal.append(intent);
2910
+ requireLive();
2911
+ return driver.resume(session, command.text ?? null, folder, requireLive);
2912
+ }
2913
+ const sessions = await driver.list(folder);
2914
+ if (retry) {
2915
+ const candidates = sessions.filter(
2916
+ (row) => row.conversationId === intent.conversationId && !intent.observedRefs.includes(row.id)
2917
+ );
2918
+ if (!intent.conversationId || candidates.length !== 1)
2919
+ throw new HarnessRefusal("start_uncertain");
2920
+ return candidates[0].id;
2921
+ }
2922
+ intent.observedRefs = sessions.filter((row) => row.conversationId === session.conversationId).map((row) => row.id);
2923
+ await journal.append({ ...intent, conversationId: session.conversationId });
2924
+ requireLive();
2925
+ return await driver.resume(session, command.text ?? null, folder, requireLive);
2926
+ }
2927
+ async function observeSessions(drivers, contexts, activity = false) {
2928
+ const contextList = [...contexts];
2929
+ const observations = /* @__PURE__ */ new Map();
2930
+ for (const { harness, folder } of contextList) {
2931
+ let folders = observations.get(harness);
2932
+ if (!folders) {
2933
+ folders = /* @__PURE__ */ new Map();
2934
+ observations.set(harness, folders);
2935
+ }
2936
+ if (folders.has(folder)) continue;
2937
+ try {
2938
+ folders.set(folder, {
2939
+ sessions: folder ? await drivers.get(harness).list(folder, void 0, {
2940
+ refs: contextList.filter(
2941
+ (context) => context.harness === harness && context.folder === folder
2942
+ ).map((context) => context.ref),
2943
+ activity
2944
+ }) : [],
2945
+ listed: Boolean(folder)
2946
+ });
2947
+ } catch {
2948
+ folders.set(folder, { sessions: [], listed: false });
2949
+ }
2950
+ }
2951
+ return observations;
2952
+ }
2953
+ var MISSING_SESSION_POLLS = 3;
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;
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
2980
+ var Commands = class {
2981
+ constructor(journal, drivers, repositories, options = {}) {
2982
+ this.journal = journal;
2983
+ this.drivers = drivers;
2984
+ this.repositories = repositories;
2985
+ this.stopSettleMs = options.stopSettleMs ?? 5e3;
2986
+ this.clock = options.clock ?? lifetimeClock;
2987
+ this.activity = options.activity ?? new ActivityReporter();
2988
+ for (const entry of journal.entries.values()) {
2989
+ this.remember(entry);
2990
+ this.lifetimes.set(
2991
+ entry.command.command_id,
2992
+ new CommandLifetime(entry.command.ttl_ms, this.clock, entry.lifetime)
2993
+ );
2994
+ }
2995
+ }
2996
+ stopSettleMs;
2997
+ clock;
2998
+ activity;
2999
+ bindings = /* @__PURE__ */ new Map();
3000
+ lifetimes = /* @__PURE__ */ new Map();
3001
+ resolutions = /* @__PURE__ */ new Map();
3002
+ /** Called at socket receipt, before joining the serial work queue. */
3003
+ receive(command) {
3004
+ let lifetime = this.lifetimes.get(command.command_id);
3005
+ if (!lifetime) {
3006
+ lifetime = new CommandLifetime(command.ttl_ms, this.clock);
3007
+ this.lifetimes.set(command.command_id, lifetime);
3008
+ }
3009
+ return lifetime;
3010
+ }
3011
+ remember(entry) {
3012
+ const { command, update } = entry;
3013
+ const previous = this.bindings.get(command.action_id);
3014
+ if (update && (command.kind === "launch" || previous))
3015
+ this.bindings.set(command.action_id, {
3016
+ harness: command.kind === "launch" ? command.harness : previous.harness,
3017
+ state: update.state,
3018
+ missingPolls: 0,
3019
+ unreadablePolls: 0,
3020
+ repository: command.kind === "launch" ? command.repository.toLowerCase() : previous.repository,
3021
+ ref: update.resumed_as ?? update.session_ref,
3022
+ conversationId: entry.conversationId
3023
+ });
3024
+ }
3025
+ update(harness, action, ref, state, resumedAs) {
3026
+ return {
3027
+ kind: "session_update",
3028
+ protocol_version: GATEWAY_PROTOCOL_VERSION,
3029
+ action_id: action,
3030
+ session_ref: ref,
3031
+ state,
3032
+ waiting_for: null,
3033
+ attach_hint: this.drivers.get(harness).attachHint(resumedAs ?? ref),
3034
+ resumed_as: resumedAs ?? null
3035
+ };
3036
+ }
3037
+ async process(command, accept) {
3038
+ const previous = this.journal.entries.get(command.command_id);
3039
+ if (previous && commandDigest(previous.command) !== commandDigest(command))
3040
+ throw new Error("Command identity conflict");
3041
+ if (previous?.receipt && !this.resolutions.has(command.command_id))
3042
+ return await this.replay(previous);
3043
+ const lifetime = this.receive(command);
3044
+ const decision = this.resolutions.get(command.command_id) ?? (lifetime.remaining() > 0 ? await accept(command, lifetime.remaining()) : true);
3045
+ if (decision === false) return [];
3046
+ const intent = {
3047
+ ...previous ?? {
3048
+ command,
3049
+ receipt: null,
3050
+ update: null,
3051
+ conversationId: null,
3052
+ observedRefs: []
3053
+ },
3054
+ attempts: (previous?.attempts ?? 0) + 1,
3055
+ lifetime: lifetime.checkpoint()
3056
+ };
3057
+ if (decision !== true) {
3058
+ this.resolutions.set(command.command_id, decision);
3059
+ await this.journal.append({ ...intent, receipt: decision });
3060
+ this.resolutions.delete(command.command_id);
3061
+ return [];
3062
+ }
3063
+ await this.journal.append(intent);
3064
+ let update = null, conversationId = intent.conversationId;
3065
+ let receipt;
3066
+ try {
3067
+ if (!previous) lifetime.requireLive(command);
3068
+ if (this.journal.unreadableCommandIds.has(command.command_id))
3069
+ throw unreadableCommandRefusal(command);
3070
+ const result = command.kind === "launch" ? await this.launch(
3071
+ intent,
3072
+ Boolean(previous),
3073
+ () => lifetime.requireLive(command)
3074
+ ) : await this.control(
3075
+ intent,
3076
+ Boolean(previous),
3077
+ () => lifetime.requireLive(command)
3078
+ );
3079
+ update = result.update;
3080
+ conversationId = result.conversationId;
3081
+ receipt = {
3082
+ kind: "ack",
3083
+ protocol_version: GATEWAY_PROTOCOL_VERSION,
3084
+ command_id: command.command_id,
3085
+ action_id: command.action_id
3086
+ };
3087
+ } catch (error) {
3088
+ const refusal = provenRefusal(error, Boolean(previous));
3089
+ if (!refusal) throw error;
3090
+ receipt = {
3091
+ kind: "refused",
3092
+ protocol_version: GATEWAY_PROTOCOL_VERSION,
3093
+ command_id: command.command_id,
3094
+ action_id: command.action_id,
3095
+ reason: refusal.reason
3096
+ };
3097
+ }
3098
+ const outcome = {
3099
+ command,
3100
+ receipt,
3101
+ update,
3102
+ conversationId,
3103
+ observedRefs: intent.observedRefs,
3104
+ attempts: intent.attempts,
3105
+ lifetime: lifetime.checkpoint()
3106
+ };
3107
+ await this.journal.append(outcome);
3108
+ this.remember(outcome);
3109
+ return this.emit(receipt, update);
3110
+ }
3111
+ emit(receipt, update) {
3112
+ this.activity.forget(receipt.action_id);
3113
+ if (update) {
3114
+ this.activity.noteSent(update);
3115
+ const binding = this.bindings.get(update.action_id);
3116
+ if (binding) binding.state = update.state;
3117
+ }
3118
+ return [receipt, ...update ? [update] : []];
3119
+ }
3120
+ async replay(entry) {
3121
+ if (!entry.receipt) throw new Error("Cannot replay an unfinished command");
3122
+ const binding = this.bindings.get(entry.command.action_id);
3123
+ if (entry.receipt.kind === "refused" || !binding) return [entry.receipt];
3124
+ let rows;
3125
+ try {
3126
+ const folder = (await this.repositories())[binding.repository];
3127
+ rows = folder ? await this.drivers.get(binding.harness).list(folder, void 0, { refs: [binding.ref] }) : [];
3128
+ } catch {
3129
+ rows = [];
3130
+ }
3131
+ const row = rows.find((session) => session.id === binding.ref);
3132
+ const prior = entry.update;
3133
+ const update = prior?.resumed_as === binding.ref ? this.update(
3134
+ binding.harness,
3135
+ entry.command.action_id,
3136
+ prior.session_ref,
3137
+ row?.state ?? unreadState(binding),
3138
+ binding.ref
3139
+ ) : this.update(
3140
+ binding.harness,
3141
+ entry.command.action_id,
3142
+ binding.ref,
3143
+ row?.state ?? unreadState(binding)
3144
+ );
3145
+ update.waiting_for = row?.waitingFor ?? null;
3146
+ return this.emit(entry.receipt, update);
3147
+ }
3148
+ hasUncertainLaunch(command) {
3149
+ const earlier = [...this.journal.entries.values()].filter(
3150
+ (entry) => entry.command.action_id === command.action_id && entry.command.command_id !== command.command_id && entry.command.kind === "launch"
3151
+ );
3152
+ for (const entry of earlier) {
3153
+ if (entry.command.kind === "launch" && (entry.command.seed !== command.seed || entry.command.harness !== command.harness || entry.command.repository.toLowerCase() !== command.repository.toLowerCase()))
3154
+ throw new Error("Action identity conflict");
3155
+ }
3156
+ return earlier.some((entry) => entry.receipt === null);
3157
+ }
3158
+ async launch(intent, retry, requireLive) {
3159
+ const command = intent.command;
3160
+ if (command.kind !== "launch") throw new HarnessRefusal("unsupported_command");
3161
+ const folder = (await this.repositories())[command.repository.toLowerCase()];
3162
+ if (!folder) throw new HarnessRefusal("repository_not_registered");
3163
+ const driver = await this.drivers.ready(command.harness, folder);
3164
+ retry ||= this.hasUncertainLaunch(command);
3165
+ const known = this.bindings.get(command.action_id);
3166
+ if (known && (known.repository !== command.repository.toLowerCase() || known.harness !== command.harness))
3167
+ throw new Error("Action identity conflict");
3168
+ const { ref, session } = await launchSession(this.journal, {
3169
+ driver,
3170
+ intent,
3171
+ folder,
3172
+ retry,
3173
+ knownRef: known?.ref,
3174
+ requireLive
3175
+ });
3176
+ const update = this.update(
3177
+ command.harness,
3178
+ command.action_id,
3179
+ ref,
3180
+ session?.state ?? "starting"
3181
+ );
3182
+ update.waiting_for = session?.waitingFor ?? null;
3183
+ return { update, conversationId: session?.conversationId ?? null };
3184
+ }
3185
+ async control(intent, retry, requireLive) {
3186
+ const command = intent.command;
3187
+ if (command.kind !== "stop" && command.kind !== "resume")
3188
+ throw new HarnessRefusal("unsupported_command");
3189
+ const binding = this.bindings.get(command.action_id);
3190
+ if (!binding || binding.ref !== command.session_ref)
3191
+ throw new HarnessRefusal("session_not_found");
3192
+ const folder = (await this.repositories())[binding.repository];
3193
+ if (!folder) throw new HarnessRefusal("repository_not_registered");
3194
+ const driver = this.drivers.get(binding.harness);
3195
+ const session = await findSession(driver, binding.ref, folder, requireLive);
3196
+ if (command.kind === "stop") {
3197
+ if (session.state !== "stopped") {
3198
+ requireLive();
3199
+ await driver.stop(session, folder, requireLive);
3200
+ }
3201
+ return {
3202
+ update: this.update(
3203
+ binding.harness,
3204
+ command.action_id,
3205
+ session.id,
3206
+ await stateAfterStop(driver, session.id, folder, this.stopSettleMs)
3207
+ ),
3208
+ conversationId: session.conversationId
3209
+ };
3210
+ }
3211
+ const ref = await resumeSession(this.journal, {
3212
+ driver,
3213
+ intent,
3214
+ session,
3215
+ folder,
3216
+ retry,
3217
+ requireLive
3218
+ });
3219
+ return {
3220
+ update: this.update(
3221
+ binding.harness,
3222
+ command.action_id,
3223
+ session.id,
3224
+ "starting",
3225
+ ref === session.id ? void 0 : ref
3226
+ ),
3227
+ conversationId: session.conversationId
3228
+ };
3229
+ }
3230
+ /** A hub reconciliation also repairs receipts persisted by an older gateway. */
3231
+ async reconcile(receipt) {
3232
+ const entry = this.journal.entries.get(receipt.command_id);
3233
+ if (!entry) return;
3234
+ if (entry.command.action_id !== receipt.action_id)
3235
+ throw new Error("Receipt identity conflict");
3236
+ this.resolutions.set(receipt.command_id, receipt);
3237
+ await this.journal.append({ ...entry, receipt });
3238
+ this.resolutions.delete(receipt.command_id);
3239
+ }
3240
+ async retire(actionId) {
3241
+ for (const entry of this.journal.entries.values())
3242
+ if (entry.command.action_id === actionId) {
3243
+ this.lifetimes.delete(entry.command.command_id);
3244
+ this.resolutions.delete(entry.command.command_id);
3245
+ }
3246
+ await this.journal.retire(actionId);
3247
+ this.bindings.delete(actionId);
3248
+ this.activity.release(actionId);
3249
+ }
3250
+ resetObservations() {
3251
+ this.activity.clear();
3252
+ }
3253
+ /** Replay every binding's latest receipt before polling, including terminal sessions. */
3254
+ durableReceipts() {
3255
+ const latest = /* @__PURE__ */ new Map();
3256
+ for (const entry of this.journal.entries.values())
3257
+ latest.set(entry.command.action_id, entry);
3258
+ const receipts = [];
3259
+ for (const action of this.bindings.keys()) {
3260
+ const receipt = latest.get(action)?.receipt;
3261
+ if (receipt) receipts.push(receipt);
3262
+ }
3263
+ return receipts;
3264
+ }
3265
+ journalEntry(commandId) {
3266
+ return this.journal.entries.get(commandId);
3267
+ }
3268
+ /** Unfinished durable operations are retried locally, even without hub redelivery. */
3269
+ get pendingIntents() {
3270
+ return [...this.journal.entries.values()].filter((entry) => entry.receipt === null);
3271
+ }
3272
+ get hasLiveBindings() {
3273
+ return [...this.bindings.values()].some(
3274
+ (binding) => !isTerminalSessionState(binding.state)
3275
+ );
3276
+ }
3277
+ async poll() {
3278
+ if (this.bindings.size === 0) return [];
3279
+ const repositories = await this.repositories();
3280
+ const activity = await this.activity.enabled();
3281
+ const observations = await observeSessions(
3282
+ this.drivers,
3283
+ [...this.bindings.values()].map((binding) => ({
3284
+ harness: binding.harness,
3285
+ folder: repositories[binding.repository],
3286
+ ref: binding.ref
3287
+ })),
3288
+ activity
3289
+ );
3290
+ const updates = [];
3291
+ for (const [action, binding] of this.bindings) {
3292
+ const { sessions, listed } = observations.get(binding.harness).get(repositories[binding.repository]);
3293
+ const row = sessions.find((session) => session.id === binding.ref);
3294
+ binding.missingPolls = row || !listed ? 0 : binding.missingPolls + 1;
3295
+ binding.unreadablePolls = listed ? 0 : binding.unreadablePolls + 1;
3296
+ const state = row?.state ?? unobservedState(binding);
3297
+ if (state === null) continue;
3298
+ const update = this.update(binding.harness, action, binding.ref, state);
3299
+ update.waiting_for = row?.waitingFor ?? null;
3300
+ binding.state = update.state;
3301
+ const frame = this.activity.frame(update, row?.activity ?? null, activity);
3302
+ if (frame) updates.push(frame);
3303
+ }
3304
+ return updates;
3305
+ }
3306
+ };
3307
+
3308
+ // src/config-watch.ts
3309
+ import { statSync, watch } from "node:fs";
3310
+ import { basename as basename4, dirname as dirname4 } from "node:path";
3311
+ var watchDirectory = (directory, listener) => watch(directory, (_, filename) => listener(filename));
3312
+ function watchConfig(path, changed, options = {}) {
3313
+ let reported = identity(path);
3314
+ let pending;
3315
+ let watcher;
3316
+ const report = () => {
3317
+ pending = void 0;
3318
+ const current = identity(path);
3319
+ if (current === reported) return;
3320
+ reported = current;
3321
+ changed();
3322
+ };
3323
+ const settle = () => {
3324
+ clearTimeout(pending);
3325
+ pending = setTimeout(report, 150);
3326
+ };
3327
+ const poll = setInterval(() => {
3328
+ if (pending === void 0 && identity(path) !== reported) settle();
3329
+ }, options.pollMs ?? 1e3);
3330
+ try {
3331
+ watcher = (options.watchDirectory ?? watchDirectory)(dirname4(path), (filename) => {
3332
+ if (filename === null || filename === basename4(path)) settle();
3333
+ });
3334
+ watcher.on("error", () => watcher?.close());
3335
+ } catch {
3336
+ watcher = void 0;
3337
+ }
3338
+ return () => {
3339
+ watcher?.close();
3340
+ clearInterval(poll);
3341
+ clearTimeout(pending);
3342
+ };
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
+ }
3348
+
3349
+ // src/launch-permits.ts
3350
+ var LaunchPermits = class {
3351
+ constructor(send, active, timeout) {
3352
+ this.send = send;
3353
+ this.active = active;
3354
+ this.timeout = timeout;
3355
+ }
3356
+ pending = null;
3357
+ accept(command, remainingMs) {
3358
+ return new Promise((resolve6) => {
3359
+ if (!this.active() || remainingMs <= 0) {
3360
+ resolve6(false);
3361
+ return;
3362
+ }
3363
+ const timer = setTimeout(
3364
+ () => {
3365
+ this.cancel();
3366
+ this.timeout();
3367
+ },
3368
+ Math.max(1, Math.min(2e4, remainingMs))
3369
+ );
3370
+ this.pending = {
3371
+ action: command.action_id,
3372
+ command: command.command_id,
3373
+ resolve: (decision) => {
3374
+ clearTimeout(timer);
3375
+ this.pending = null;
3376
+ resolve6(decision === true ? this.active() : decision);
3377
+ }
3378
+ };
3379
+ this.send({
3380
+ kind: "claim",
3381
+ protocol_version: GATEWAY_PROTOCOL_VERSION,
3382
+ command_id: command.command_id,
3383
+ action_id: command.action_id
3384
+ });
3385
+ });
3386
+ }
3387
+ receive(message) {
3388
+ if (this.pending?.action === message.action_id && (message.kind === "retire" || this.pending.command === message.command_id))
3389
+ this.pending.resolve(
3390
+ message.kind === "permit" ? message.receipt ?? message.allowed : false
3391
+ );
3392
+ }
3393
+ cancel() {
3394
+ this.pending?.resolve(false);
3395
+ }
3396
+ };
3397
+
3398
+ // src/oauth.ts
3399
+ import { createHash as createHash2, randomBytes } from "node:crypto";
3400
+ import { createServer } from "node:http";
3401
+ import { hostname } from "node:os";
3402
+ var TokenAccessDenied = class extends Error {
3403
+ };
3404
+ var TspRequestRejected = class extends Error {
3405
+ constructor(status) {
3406
+ super(`TSP request rejected (${status})`);
3407
+ this.status = status;
3408
+ }
3409
+ };
3410
+ async function json(url, init) {
3411
+ const response = await fetch(url, {
3412
+ ...init,
3413
+ redirect: "error",
3414
+ signal: AbortSignal.timeout(2e4)
3415
+ });
3416
+ if (!response.ok) throw new TspRequestRejected(response.status);
3417
+ return await response.json();
3418
+ }
3419
+ function requiredText(value, key) {
3420
+ const text3 = isObject(value) ? field(value, key) : null;
3421
+ if (typeof text3 !== "string" || !text3) throw new Error("Invalid OAuth response");
3422
+ return text3;
3423
+ }
3424
+ async function discover(origin) {
3425
+ const value = await json(`${validateOrigin(origin)}/.well-known/oauth-authorization-server`);
3426
+ const endpoint = (key) => {
3427
+ const url = new URL(requiredText(value, key));
3428
+ if (url.origin !== origin || url.username || url.password)
3429
+ throw new Error("OAuth endpoint must belong to the configured TSP origin");
3430
+ return url.href;
3431
+ };
3432
+ return {
3433
+ authorization: endpoint("authorization_endpoint"),
3434
+ token: endpoint("token_endpoint"),
3435
+ revocation: endpoint("revocation_endpoint")
3436
+ };
3437
+ }
3438
+ async function tokenExchange(endpoint, form) {
3439
+ let value;
3440
+ try {
3441
+ value = await json(endpoint, { method: "POST", body: form });
3442
+ } catch (error) {
3443
+ if (error instanceof TspRequestRejected && (error.status === 400 || error.status === 401))
3444
+ throw new TokenAccessDenied(error.message);
3445
+ throw error;
3446
+ }
3447
+ const access2 = requiredText(value, "access_token");
3448
+ if (!isObject(value)) throw new Error("Invalid OAuth token");
3449
+ const expiry = field(value, "expires_in"), refresh = field(value, "refresh_token");
3450
+ if (typeof expiry !== "number" || !Number.isFinite(expiry) || expiry <= 0 || !(refresh === void 0 || typeof refresh === "string"))
3451
+ throw new Error("Invalid OAuth token lifetime");
3452
+ return { access: access2, refresh: refresh ?? null, expires: Date.now() + expiry * 1e3 };
3453
+ }
3454
+ var OAuthTokens = class {
3455
+ constructor(pairing, store) {
3456
+ this.pairing = pairing;
3457
+ this.store = store;
3458
+ }
3459
+ current = null;
3460
+ async access(force = false) {
3461
+ if (!force && this.current && this.current.expiresAt > Date.now() + 3e4)
3462
+ return this.current;
3463
+ const refresh = await this.store.get();
3464
+ if (!refresh) throw new TokenAccessDenied("No gateway token. Run tsp-gateway pair.");
3465
+ const endpoints = await discover(this.pairing.origin);
3466
+ const tokens = await tokenExchange(
3467
+ endpoints.token,
3468
+ new URLSearchParams({
3469
+ grant_type: "refresh_token",
3470
+ client_id: this.pairing.clientId,
3471
+ refresh_token: refresh
3472
+ })
3473
+ );
3474
+ if (tokens.refresh) await this.store.set(tokens.refresh);
3475
+ this.current = { token: tokens.access, expiresAt: tokens.expires };
3476
+ return this.current;
3477
+ }
3478
+ };
3479
+ async function pair(origin, store, openBrowser, report = () => {
3480
+ }, displayName = hostname()) {
3481
+ origin = validateOrigin(origin);
3482
+ const endpoints = await discover(origin);
3483
+ const verifier = randomBytes(32).toString("base64url"), state = randomBytes(32).toString("base64url");
3484
+ let acceptCode = () => {
3485
+ };
3486
+ let rejectCode = () => {
3487
+ };
3488
+ const code = new Promise((resolve6, reject) => {
3489
+ acceptCode = resolve6;
3490
+ rejectCode = reject;
3491
+ });
3492
+ void code.catch(() => {
3493
+ });
3494
+ const server = createServer((request, response) => {
3495
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
3496
+ if (request.method !== "GET" || url.pathname !== "/callback" || url.searchParams.get("state") !== state) {
3497
+ response.writeHead(400).end("Invalid callback.");
3498
+ return;
3499
+ }
3500
+ const authorizationCode = url.searchParams.get("code");
3501
+ if (!authorizationCode || url.searchParams.has("error")) {
3502
+ response.writeHead(400).end("Authorization was not completed.");
3503
+ rejectCode(new Error("Authorization was not completed"));
3504
+ return;
3505
+ }
3506
+ response.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" }).end("TSP gateway authorized. You can close this tab.");
3507
+ acceptCode(authorizationCode);
3508
+ });
3509
+ await new Promise((resolve6, reject) => {
3510
+ server.once("error", reject);
3511
+ server.listen(0, "127.0.0.1", resolve6);
3512
+ });
3513
+ const timer = setTimeout(() => rejectCode(new Error("Pairing timed out")), 18e4);
3514
+ try {
3515
+ const address = server.address();
3516
+ if (!address || typeof address === "string") throw new Error("No loopback listener");
3517
+ const redirect = `http://127.0.0.1:${address.port}/callback`;
3518
+ const clientId = "tsp-gateway";
3519
+ const url = new URL(endpoints.authorization);
3520
+ url.search = new URLSearchParams({
3521
+ client_id: clientId,
3522
+ response_type: "code",
3523
+ redirect_uri: redirect,
3524
+ scope: "agent_launch",
3525
+ state,
3526
+ code_challenge: createHash2("sha256").update(verifier).digest("base64url"),
3527
+ code_challenge_method: "S256"
3528
+ }).toString();
3529
+ report(`Approve pairing in your browser. If it doesn't open, visit:
3530
+ ${url.href}`);
3531
+ await openBrowser(url.href);
3532
+ report("Waiting for approval (up to 3 minutes)\u2026");
3533
+ const tokens = await tokenExchange(
3534
+ endpoints.token,
3535
+ new URLSearchParams({
3536
+ grant_type: "authorization_code",
3537
+ client_id: clientId,
3538
+ code: await code,
3539
+ redirect_uri: redirect,
3540
+ code_verifier: verifier
3541
+ })
3542
+ );
3543
+ if (!tokens.refresh) throw new Error("TSP did not issue a refresh token");
3544
+ const machine = decodeRegistration(
3545
+ await json(`${origin}/api/v1/gateway/machines`, {
3546
+ method: "POST",
3547
+ headers: {
3548
+ Authorization: `Bearer ${tokens.access}`,
3549
+ "Content-Type": "application/json"
3550
+ },
3551
+ body: JSON.stringify({ display_name: displayName.slice(0, 80) })
3552
+ })
3553
+ );
3554
+ try {
3555
+ await store.set(tokens.refresh);
3556
+ } catch (error) {
3557
+ try {
3558
+ const cleanup = await fetch(
3559
+ `${origin}/api/v1/gateway/machines/${machine.machine_id}`,
3560
+ {
3561
+ method: "DELETE",
3562
+ headers: { Authorization: `Bearer ${tokens.access}` },
3563
+ redirect: "error",
3564
+ signal: AbortSignal.timeout(2e4)
3565
+ }
3566
+ );
3567
+ if (!cleanup.ok && cleanup.status !== 404)
3568
+ throw new Error(`Could not unregister new machine (${cleanup.status})`);
3569
+ } catch (cleanupError) {
3570
+ if (error instanceof Error) error.cause = cleanupError;
3571
+ }
3572
+ throw error;
3573
+ }
3574
+ return { ...machine, origin, clientId };
3575
+ } finally {
3576
+ clearTimeout(timer);
3577
+ server.closeAllConnections();
3578
+ await new Promise((resolve6) => server.close(() => resolve6()));
3579
+ }
3580
+ }
3581
+ async function unpair(pairing, store) {
3582
+ const tokens = new OAuthTokens(pairing, store);
3583
+ let access2;
3584
+ try {
3585
+ access2 = await tokens.access();
3586
+ } catch (error) {
3587
+ if (!(error instanceof TokenAccessDenied))
3588
+ throw new Error("Could not access TSP; pairing retained for retry", { cause: error });
3589
+ await store.delete();
3590
+ return "Unpaired locally. This machine may still be listed in TSP and can be disconnected from Settings.";
3591
+ }
3592
+ const response = await fetch(
3593
+ `${pairing.origin}/api/v1/gateway/machines/${pairing.machine_id}`,
3594
+ {
3595
+ method: "DELETE",
3596
+ headers: { Authorization: `Bearer ${access2.token}` },
3597
+ redirect: "error",
3598
+ signal: AbortSignal.timeout(2e4)
3599
+ }
3600
+ );
3601
+ if (!response.ok && response.status !== 404)
3602
+ throw new Error("Could not revoke machine; pairing retained for retry");
3603
+ const endpoints = await discover(pairing.origin);
3604
+ const refresh = await store.get();
3605
+ if (refresh) {
3606
+ const revoked = await fetch(endpoints.revocation, {
3607
+ method: "POST",
3608
+ body: new URLSearchParams({
3609
+ token: refresh,
3610
+ token_type_hint: "refresh_token",
3611
+ client_id: pairing.clientId
3612
+ }),
3613
+ redirect: "error",
3614
+ signal: AbortSignal.timeout(2e4)
3615
+ });
3616
+ if (!revoked.ok) throw new Error("Could not revoke token; pairing retained for retry");
3617
+ }
3618
+ await store.delete();
3619
+ return "Unpaired.";
3620
+ }
3621
+
3622
+ // src/daemon.ts
3623
+ import { setTimeout as delay3 } from "node:timers/promises";
3624
+
3625
+ // src/intent-retries.ts
3626
+ var BASE_INTENT_RETRY_MS = 2e3;
3627
+ var MAX_INTENT_RETRY_MS = 5 * 6e4;
3628
+ var IntentRetries = class {
3629
+ constructor(commands, now, random) {
3630
+ this.commands = commands;
3631
+ this.now = now;
3632
+ this.random = random;
3633
+ for (const entry of commands.pendingIntents)
3634
+ this.schedule(entry.command.command_id, entry.attempts);
3635
+ }
3636
+ retryAt = /* @__PURE__ */ new Map();
3637
+ unjournaled = /* @__PURE__ */ new Map();
3638
+ schedule(commandId, attempts) {
3639
+ const delay4 = Math.min(
3640
+ MAX_INTENT_RETRY_MS,
3641
+ BASE_INTENT_RETRY_MS * 2 ** Math.max(0, attempts - 1)
3642
+ );
3643
+ this.retryAt.set(commandId, this.now() + Math.floor(delay4 * (0.5 + this.random() * 0.5)));
3644
+ }
3645
+ get hasPending() {
3646
+ return this.unjournaled.size > 0 || this.commands.pendingIntents.length > 0;
3647
+ }
3648
+ ready(commandId) {
3649
+ return this.now() >= (this.retryAt.get(commandId) ?? -Infinity);
3650
+ }
3651
+ defer(command) {
3652
+ const id = command.command_id;
3653
+ const entry = this.commands.journalEntry(id);
3654
+ if (entry) {
3655
+ this.unjournaled.delete(id);
3656
+ if (entry.receipt === null) this.schedule(id, entry.attempts);
3657
+ else this.retryAt.delete(id);
3658
+ return;
3659
+ }
3660
+ const attempts = (this.unjournaled.get(id)?.attempts ?? 0) + 1;
3661
+ this.unjournaled.set(id, { command, attempts });
3662
+ this.schedule(id, attempts);
3663
+ }
3664
+ /** A retired action is withdrawn by the hub: its unjournaled commands must never run. */
3665
+ retire(actionId) {
3666
+ for (const [id, held] of this.unjournaled)
3667
+ if (held.command.action_id === actionId) {
3668
+ this.unjournaled.delete(id);
3669
+ this.retryAt.delete(id);
3670
+ }
3671
+ }
3672
+ async retryPending(process2, isActive) {
3673
+ for (const command of this.pending) {
3674
+ if (!isActive()) break;
3675
+ await process2(command);
3676
+ }
3677
+ }
3678
+ get pending() {
3679
+ const commands = [
3680
+ ...this.commands.pendingIntents.map((entry) => entry.command),
3681
+ ...[...this.unjournaled.values()].map((held) => held.command)
3682
+ ];
3683
+ const ids = new Set(commands.map((command) => command.command_id));
3684
+ for (const id of this.retryAt.keys()) if (!ids.has(id)) this.retryAt.delete(id);
3685
+ return commands;
3686
+ }
3687
+ };
3688
+
3689
+ // src/daemon.ts
3690
+ var STABLE_CONNECTION_MS = 3e4;
3691
+ var OUTDATED_RETRY_MS = 60 * 60 * 1e3;
3692
+ function authenticatedSocket(pairing, token) {
3693
+ const url = new URL(pairing.hub_path, pairing.origin);
3694
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
3695
+ const NodeWebSocket = WebSocket;
3696
+ return new NodeWebSocket(url, { headers: { Authorization: `Bearer ${token}` } });
3697
+ }
3698
+ function reconnectDelay(attempt, random = Math.random) {
3699
+ return Math.floor(Math.min(3e4, 500 * 2 ** Math.min(attempt, 6)) * (0.5 + random() * 0.5));
3700
+ }
3701
+ function disposition(code) {
3702
+ for (const [key, value] of Object.entries(GATEWAY_CLOSE_DISPOSITION_BY_CODE))
3703
+ if (Number(key) === code) return value;
3704
+ return "reconnectable";
3705
+ }
3706
+ async function runDaemon(options) {
3707
+ const retries = new IntentRetries(
3708
+ options.commands,
3709
+ options.now ?? (() => performance.now()),
3710
+ options.random ?? Math.random
3711
+ );
3712
+ let attempt = 0, force = false, rejectedToken = false;
3713
+ let closeCode = null;
3714
+ let closeDisposition = null;
3715
+ const status = (connected, message) => options.status({
3716
+ connected,
3717
+ message,
3718
+ close_code: closeCode,
3719
+ close_disposition: closeDisposition
3720
+ });
3721
+ const wait = options.wait ?? (async (ms, signal) => {
3722
+ await delay3(ms, void 0, { signal });
3723
+ });
3724
+ const pause = async (ms) => {
3725
+ try {
3726
+ await wait(ms, options.signal);
3727
+ } catch {
3728
+ if (!options.signal.aborted) throw new Error("Reconnect wait failed");
3729
+ }
3730
+ };
3731
+ while (!options.signal.aborted) {
3732
+ let token;
3733
+ try {
3734
+ token = await options.tokens.access(force);
3735
+ } catch (error) {
3736
+ if (options.signal.aborted) break;
3737
+ if (error instanceof TokenAccessDenied) {
3738
+ await status(false, "Token refresh failed. Run tsp-gateway pair again.");
3739
+ return;
3740
+ }
3741
+ await status(false, "Waiting for the network or TSP. Retrying\u2026");
3742
+ await pause(reconnectDelay(attempt++, options.random));
3743
+ continue;
3744
+ }
3745
+ force = false;
3746
+ const result = await connection(options, token.token, token.expiresAt, status, retries);
3747
+ if (result.stable) attempt = 0;
3748
+ if (result.receivedFrame) rejectedToken = false;
3749
+ const recovery = disposition(result.code);
3750
+ closeCode = result.code;
3751
+ closeDisposition = recovery;
3752
+ const reconnect = !options.signal.aborted && recovery !== "terminal" && !(recovery === "token" && rejectedToken);
3753
+ console.error(
3754
+ `TSP gateway socket closed: code=${result.code} disposition=${recovery} reconnect=${reconnect}`
3755
+ );
3756
+ if (options.signal.aborted) break;
3757
+ if (recovery === "outdated") {
3758
+ await status(
3759
+ false,
3760
+ "This gateway is outdated. Run npm install --global @treestructuredplanning/gateway@latest, then tsp-gateway install."
3761
+ );
3762
+ await pause(OUTDATED_RETRY_MS);
3763
+ continue;
3764
+ }
3765
+ if (recovery === "terminal") {
3766
+ await status(
3767
+ false,
3768
+ result.code === 4504 ? "Agent work is disabled. Restart manually after it is enabled." : "Machine access ended. Run tsp-gateway pair again."
3769
+ );
3770
+ return;
3771
+ }
3772
+ if (recovery === "token") {
3773
+ if (rejectedToken) {
3774
+ await status(false, "Token rejected after refresh. Run tsp-gateway pair again.");
3775
+ return;
3776
+ }
3777
+ rejectedToken = true;
3778
+ force = true;
3779
+ }
3780
+ if (result.code === 4e3) force = true;
3781
+ await status(false, "Reconnecting");
3782
+ await pause(reconnectDelay(attempt++, options.random));
3783
+ }
3784
+ await status(false, "Stopped");
3785
+ }
3786
+ function sessionPolling(options, enqueue, send, isReady, pending) {
3787
+ let polling = false;
3788
+ let pollTimer;
3789
+ const schedulePoll = () => {
3790
+ if (!isReady()) return;
3791
+ pollTimer = setTimeout(
3792
+ () => {
3793
+ pollTimer = void 0;
3794
+ enqueue(async () => {
3795
+ if (pollTimer === void 0) await poll();
3796
+ });
3797
+ },
3798
+ options.commands.hasLiveBindings || pending.exists() ? options.pollMs ?? 2e3 : options.idlePollMs ?? 3e4
3799
+ );
3800
+ };
3801
+ const poll = async () => {
3802
+ if (!isReady() || polling) return;
3803
+ clearTimeout(pollTimer);
3804
+ pollTimer = void 0;
3805
+ polling = true;
3806
+ try {
3807
+ await pending.retry();
3808
+ for (const update of await options.commands.poll()) send(update);
3809
+ } finally {
3810
+ polling = false;
3811
+ schedulePoll();
3812
+ }
3813
+ };
3814
+ return { poll, stop: () => clearTimeout(pollTimer) };
3815
+ }
3816
+ function transportSender(socket, isActive) {
3817
+ return (message) => {
3818
+ if (!isActive() || socket.readyState !== WebSocket.OPEN) return;
3819
+ try {
3820
+ socket.send(JSON.stringify(message));
3821
+ } catch {
3822
+ socket.close(4001, "Transport send failed");
3823
+ }
3824
+ };
3825
+ }
3826
+ function commandProcessor(commands, permits, retries, send) {
3827
+ return async (command) => {
3828
+ if (!retries.ready(command.command_id)) return;
3829
+ let results;
3830
+ try {
3831
+ results = await commands.process(
3832
+ command,
3833
+ (operation, remainingMs) => permits.accept(operation, remainingMs)
3834
+ );
3835
+ } catch {
3836
+ console.error(
3837
+ `TSP gateway command pending: kind=${command.kind} command_id=${command.command_id} action_id=${command.action_id}`
3838
+ );
3839
+ return;
3840
+ } finally {
3841
+ retries.defer(command);
3842
+ }
3843
+ for (const result of results) send(result);
3844
+ };
3845
+ }
3846
+ function machineFacts(options, send, enqueue, state) {
3847
+ let lastAdvertisement;
3848
+ const advertise = async (kind) => {
3849
+ const advertisement = {
3850
+ protocol_version: GATEWAY_PROTOCOL_VERSION,
3851
+ gateway_version: options.version,
3852
+ harnesses: await options.drivers.detect(),
3853
+ repositories: await options.repositories()
3854
+ };
3855
+ const encoded = JSON.stringify(advertisement);
3856
+ if (kind === "hello" || encoded !== lastAdvertisement) {
3857
+ send({ ...advertisement, protocol_version: GATEWAY_PROTOCOL_VERSION, kind });
3858
+ lastAdvertisement = encoded;
3859
+ }
3860
+ };
3861
+ let refreshing = false;
3862
+ let refreshPending = false;
3863
+ const refresh = () => {
3864
+ if (!state.ready()) return;
3865
+ refreshPending = true;
3866
+ if (refreshing) return;
3867
+ refreshing = true;
3868
+ enqueue(async () => {
3869
+ try {
3870
+ refreshPending = false;
3871
+ await advertise("advertise");
3872
+ } finally {
3873
+ refreshing = false;
3874
+ if (refreshPending && state.live()) refresh();
3875
+ }
3876
+ });
3877
+ };
3878
+ return { advertise, refresh };
3879
+ }
3880
+ async function connection(options, token, expiresAt, status, retries) {
3881
+ const socket = authenticatedSocket(options.pairing, token);
3882
+ let active = true, ready = false;
3883
+ const now = options.now ?? (() => performance.now());
3884
+ let readyAt = null;
3885
+ let stable = false;
3886
+ let receivedFrame = false;
3887
+ let queue = Promise.resolve();
3888
+ const send = transportSender(socket, () => active);
3889
+ const permits = new LaunchPermits(
3890
+ send,
3891
+ () => active && !options.signal.aborted,
3892
+ () => socket.close(4001, "Acceptance timeout")
3893
+ );
3894
+ const enqueue = (task) => {
3895
+ queue = queue.then(async () => {
3896
+ if (active && !options.signal.aborted) await task();
3897
+ }).catch(() => {
3898
+ console.error("TSP gateway local queue task failed.");
3899
+ });
3900
+ };
3901
+ const processCommand = commandProcessor(options.commands, permits, retries, send);
3902
+ const { advertise, refresh } = machineFacts(options, send, enqueue, {
3903
+ ready: () => ready,
3904
+ live: () => active && !options.signal.aborted
3905
+ });
3906
+ const factsInterval = setInterval(refresh, options.advertiseMs ?? 3e4);
3907
+ const unwatch = options.watchFacts?.(refresh);
3908
+ const polling = sessionPolling(
3909
+ options,
3910
+ enqueue,
3911
+ send,
3912
+ () => ready && active && !options.signal.aborted,
3913
+ {
3914
+ retry: () => retries.retryPending(processCommand, () => active && !options.signal.aborted),
3915
+ exists: () => retries.hasPending
3916
+ }
3917
+ );
3918
+ const expiry = setTimeout(
3919
+ () => socket.close(4e3, "Refresh access token"),
3920
+ Math.max(100, expiresAt - Date.now() - 15e3)
3921
+ );
3922
+ const timeout = setTimeout(() => socket.close(4001, "Connection timeout"), 2e4);
3923
+ const abort = () => {
3924
+ active = false;
3925
+ permits.cancel();
3926
+ socket.close(1e3, "Gateway stopped");
3927
+ };
3928
+ options.signal.addEventListener("abort", abort, { once: true });
3929
+ if (options.signal.aborted) abort();
3930
+ socket.addEventListener("open", () => {
3931
+ enqueue(async () => {
3932
+ await advertise("hello");
3933
+ clearTimeout(timeout);
3934
+ for (const receipt of options.commands.durableReceipts()) send(receipt);
3935
+ options.commands.resetObservations();
3936
+ ready = true;
3937
+ readyAt = now();
3938
+ await polling.poll();
3939
+ await status(true, "Connected");
3940
+ });
3941
+ });
3942
+ socket.addEventListener("message", (event) => {
3943
+ if (!active || options.signal.aborted) return;
3944
+ let message;
3945
+ try {
3946
+ message = decodeHubText(event.data);
3947
+ } catch {
3948
+ socket.close(4002, "Invalid frame");
3949
+ return;
3950
+ }
3951
+ receivedFrame = true;
3952
+ if (message.kind === "ping") {
3953
+ send({
3954
+ kind: "pong",
3955
+ protocol_version: GATEWAY_PROTOCOL_VERSION,
3956
+ nonce: message.nonce
3957
+ });
3958
+ return;
3959
+ }
3960
+ if (message.kind === "permit" || message.kind === "retire") {
3961
+ permits.receive(message);
3962
+ if (message.kind === "permit") {
3963
+ const receipt = message.receipt;
3964
+ if (receipt)
3965
+ enqueue(async () => {
3966
+ await options.commands.reconcile(receipt);
3967
+ });
3968
+ return;
3969
+ }
3970
+ }
3971
+ if (message.kind !== "retire") options.commands.receive(message);
3972
+ enqueue(async () => {
3973
+ if (message.kind === "retire") {
3974
+ retries.retire(message.action_id);
3975
+ await options.commands.retire(message.action_id);
3976
+ } else await processCommand(message);
3977
+ await polling.poll();
3978
+ await advertise("advertise");
3979
+ });
3980
+ });
3981
+ socket.addEventListener("error", () => {
3982
+ });
3983
+ const code = await new Promise(
3984
+ (resolve6) => socket.addEventListener(
3985
+ "close",
3986
+ (event) => {
3987
+ stable = readyAt !== null && now() - readyAt >= STABLE_CONNECTION_MS;
3988
+ active = false;
3989
+ permits.cancel();
3990
+ resolve6(event.code);
3991
+ },
3992
+ { once: true }
3993
+ )
3994
+ );
3995
+ polling.stop();
3996
+ clearInterval(factsInterval);
3997
+ unwatch?.();
3998
+ clearTimeout(expiry);
3999
+ clearTimeout(timeout);
4000
+ options.signal.removeEventListener("abort", abort);
4001
+ await queue;
4002
+ return { code, stable, receivedFrame };
4003
+ }
4004
+
4005
+ // src/daemon-lock.ts
4006
+ import { createHash as createHash3 } from "node:crypto";
4007
+ import { lstatSync, unlinkSync } from "node:fs";
4008
+ import { realpath as realpath5 } from "node:fs/promises";
4009
+ import { createConnection, createServer as createServer2 } from "node:net";
4010
+ import { tmpdir as tmpdir2 } from "node:os";
4011
+ import { join as join7, resolve as resolve5 } from "node:path";
4012
+ function hasCode(error, code) {
4013
+ return isObject(error) && field(error, "code") === code;
4014
+ }
4015
+ async function lockEndpoint(state) {
4016
+ await privateDirectory(resolve5(state));
4017
+ const absolute = await realpath5(state);
4018
+ const hash = createHash3("sha256").update(absolute).digest("hex");
4019
+ if (process.platform === "win32") return `\\\\.\\pipe\\tsp-gateway-${hash}`;
4020
+ const local = join7(absolute, "daemon.sock");
4021
+ if (Buffer.byteLength(local) <= 103) return local;
4022
+ const name = `tsp-gateway-${hash.slice(0, 24)}`;
4023
+ let directory = join7(tmpdir2(), name);
4024
+ if (Buffer.byteLength(join7(directory, "lock.sock")) > 103) directory = join7("/tmp", name);
4025
+ await privateDirectory(directory);
4026
+ return join7(directory, "lock.sock");
4027
+ }
4028
+ function listen(server, path) {
4029
+ return new Promise((resolve6, reject) => {
4030
+ const failed = (error) => {
4031
+ server.removeListener("listening", ready);
4032
+ reject(error);
4033
+ };
4034
+ const ready = () => {
4035
+ server.removeListener("error", failed);
4036
+ resolve6();
4037
+ };
4038
+ server.once("error", failed);
4039
+ server.once("listening", ready);
4040
+ server.listen({ path, exclusive: true });
4041
+ });
4042
+ }
4043
+ function owned(path) {
4044
+ return new Promise((resolve6, reject) => {
4045
+ const socket = createConnection(path);
4046
+ socket.once("connect", () => {
4047
+ socket.destroy();
4048
+ resolve6(true);
4049
+ });
4050
+ socket.once("error", (error) => {
4051
+ socket.destroy();
4052
+ if (hasCode(error, "ECONNREFUSED") || hasCode(error, "ENOENT")) resolve6(false);
4053
+ else reject(error);
4054
+ });
4055
+ socket.setTimeout(2e3, () => {
4056
+ socket.destroy();
4057
+ reject(new Error("Timed out checking the gateway process lock"));
4058
+ });
4059
+ });
4060
+ }
4061
+ async function recoverSocket(path) {
4062
+ const previous = process.platform === "win32" ? void 0 : lstatSync(path, { throwIfNoEntry: false });
4063
+ if (await owned(path)) throw new Error("A gateway is already running");
4064
+ if (!previous?.isSocket()) return;
4065
+ const current = lstatSync(path, { throwIfNoEntry: false });
4066
+ if (current?.dev !== previous.dev || current.ino !== previous.ino) return;
4067
+ try {
4068
+ unlinkSync(path);
4069
+ } catch (error) {
4070
+ if (!hasCode(error, "ENOENT")) throw error;
4071
+ }
4072
+ }
4073
+ async function daemonLock(state) {
4074
+ const path = await lockEndpoint(state);
4075
+ const server = createServer2((socket) => socket.destroy());
4076
+ try {
4077
+ await listen(server, path);
4078
+ } catch (error) {
4079
+ if (!hasCode(error, "EADDRINUSE")) throw error;
4080
+ await recoverSocket(path);
4081
+ try {
4082
+ await listen(server, path);
4083
+ } catch (retryError) {
4084
+ if (hasCode(retryError, "EADDRINUSE")) throw new Error("A gateway is already running");
4085
+ throw retryError;
4086
+ }
4087
+ }
4088
+ let releasing;
4089
+ return () => {
4090
+ releasing ??= new Promise((resolve6, reject) => {
4091
+ server.close((error) => error ? reject(error) : resolve6());
4092
+ });
4093
+ return releasing;
4094
+ };
4095
+ }
4096
+
4097
+ // src/gateway-status.ts
4098
+ import { readFile as readFile3, stat as stat3 } from "node:fs/promises";
4099
+ var GatewayStatus = class {
4100
+ constructor(path, executor) {
4101
+ this.path = path;
4102
+ this.executor = executor;
4103
+ }
4104
+ current;
4105
+ pending = Promise.resolve();
4106
+ update(status) {
4107
+ this.current = status;
4108
+ return this.refresh();
4109
+ }
4110
+ refresh() {
4111
+ this.pending = this.pending.catch(() => {
4112
+ }).then(async () => {
4113
+ if (!this.current) return;
4114
+ await privateWrite(
4115
+ this.path,
4116
+ JSON.stringify({
4117
+ pid: process.pid,
4118
+ ...this.current,
4119
+ launch: await this.executor.status()
4120
+ })
4121
+ );
4122
+ });
4123
+ return this.pending;
4124
+ }
4125
+ };
4126
+ async function daemonConnection(statusPath, since = 0) {
4127
+ try {
4128
+ const [text3, info] = await Promise.all([readFile3(statusPath, "utf8"), stat3(statusPath)]);
4129
+ if (info.mtimeMs < since) return null;
4130
+ const status = parseJson(text3);
4131
+ if (!isObject(status)) return null;
4132
+ const pid = field(status, "pid"), message = field(status, "message");
4133
+ return typeof pid === "number" && pidAlive(pid) && typeof message === "string" ? message : null;
4134
+ } catch {
4135
+ return null;
4136
+ }
4137
+ }
4138
+ async function awaitDaemonConnection(statusPath, since, timeoutMs = 8e3, intervalMs = 250) {
4139
+ const deadline = Date.now() + timeoutMs;
4140
+ for (; ; ) {
4141
+ const message = await daemonConnection(statusPath, since);
4142
+ if (message !== null || Date.now() >= deadline) return message;
4143
+ await new Promise((resolve6) => setTimeout(resolve6, intervalMs));
4144
+ }
4145
+ }
4146
+ function readLaunchObservation(value) {
4147
+ if (!isObject(value)) return null;
4148
+ const mode = field(value, "effective_mode"), shell = field(value, "shell"), reason = field(value, "reason");
4149
+ if (mode !== "direct" && mode !== "login-shell" || !(shell === null || typeof shell === "string") || typeof reason !== "string")
4150
+ return null;
4151
+ return { effective_mode: mode, shell, reason };
4152
+ }
4153
+
4154
+ // src/keychain.ts
4155
+ import { AsyncEntry } from "@napi-rs/keyring";
4156
+ function keychainOptions(platform = process.platform) {
4157
+ return platform === "linux" ? { linux: { store: "secret-service" } } : {};
4158
+ }
4159
+ function keychain(account) {
4160
+ const entry = new AsyncEntry("com.treestructuredplanning.gateway", account, keychainOptions());
4161
+ return {
4162
+ get: () => entry.getPassword(),
4163
+ set: (token) => entry.setPassword(token),
4164
+ delete: async () => {
4165
+ await entry.deletePassword();
4166
+ }
4167
+ };
4168
+ }
4169
+
4170
+ // src/installer.ts
4171
+ import { readFile as readFile4, rm as rm2 } from "node:fs/promises";
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";
4174
+ var label = "com.treestructuredplanning.tsp-gateway";
4175
+ function xml(value) {
4176
+ return value.replace(
4177
+ /[<>&"']/g,
4178
+ (ch) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&apos;" })[ch]
4179
+ );
4180
+ }
4181
+ function systemd(value, expandDollar = true) {
4182
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%");
4183
+ return '"' + (expandDollar ? escaped.replace(/\$/g, () => "$$") : escaped) + '"';
4184
+ }
4185
+ function quoted(value) {
4186
+ return '"' + value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1") + '"';
4187
+ }
4188
+ function installDefinition(platform, spec) {
4189
+ if (![spec.node, spec.entry, spec.config, spec.state].every(
4190
+ platform === "win32" ? (value) => win32.isAbsolute(value) || isAbsolute6(value) : isAbsolute6
4191
+ ) || /[\r\n\0]/.test(Object.values(spec).join("")))
4192
+ throw new Error("Installer requires absolute paths and single-line values");
4193
+ const args = [
4194
+ spec.node,
4195
+ spec.entry,
4196
+ "start",
4197
+ "--expected-version",
4198
+ spec.version,
4199
+ "--config-file",
4200
+ spec.config,
4201
+ "--state-dir",
4202
+ spec.state
4203
+ ];
4204
+ if (platform === "win32") args.push("--login-path", spec.path);
4205
+ if (platform === "darwin")
4206
+ return `<?xml version="1.0" encoding="UTF-8"?>
4207
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4208
+ <plist version="1.0"><dict>
4209
+ <key>Label</key><string>${label}</string>
4210
+ <key>ProgramArguments</key><array>${args.map((arg) => `<string>${xml(arg)}</string>`).join("")}</array>
4211
+ <key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
4212
+ <key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(spec.path)}</string></dict>
4213
+ <key>StandardOutPath</key><string>${xml(join8(spec.state, "stdout.log"))}</string>
4214
+ <key>StandardErrorPath</key><string>${xml(join8(spec.state, "stderr.log"))}</string>
4215
+ </dict></plist>
4216
+ `;
4217
+ if (platform === "linux")
4218
+ return `[Unit]
4219
+ Description=TSP gateway ${spec.version}
4220
+ [Service]
4221
+ Type=simple
4222
+ ExecStart=${args.map((arg) => systemd(arg)).join(" ")}
4223
+ Environment=${systemd(`PATH=${spec.path}`, false)}
4224
+ Restart=on-failure
4225
+ RestartSec=5
4226
+ UMask=0077
4227
+ StandardOutput=append:${join8(spec.state, "stdout.log").replace(/%/g, "%%")}
4228
+ StandardError=append:${join8(spec.state, "stderr.log").replace(/%/g, "%%")}
4229
+ [Install]
4230
+ WantedBy=default.target
4231
+ `;
4232
+ if (platform === "win32")
4233
+ return `<?xml version="1.0" encoding="UTF-16"?>
4234
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><RegistrationInfo><Description>TSP gateway ${xml(spec.version)}</Description></RegistrationInfo><Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${xml(spec.user ?? userInfo2().username)}</UserId></LogonTrigger></Triggers><Principals><Principal id="Author"><UserId>${xml(spec.user ?? userInfo2().username)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure></Settings><Actions Context="Author"><Exec><Command>${xml(spec.node)}</Command><Arguments>${xml(args.slice(1).map(quoted).join(" "))}</Arguments><WorkingDirectory>${xml(win32.isAbsolute(spec.entry) ? win32.dirname(spec.entry) : dirname5(spec.entry))}</WorkingDirectory></Exec></Actions></Task>
4235
+ `;
4236
+ throw new Error("Login items support macOS, Linux and Windows");
4237
+ }
4238
+ async function captureLoginPath(env = process.env, platform = process.platform, launch = defaultLaunchConfig()) {
4239
+ if (platform === "win32") {
4240
+ const path2 = env["PATH"] ?? env["Path"];
4241
+ if (!path2) throw new Error("PATH is unavailable");
4242
+ return path2;
4243
+ }
4244
+ const captured = await new HarnessExecutor(env, {
4245
+ config: async () => launch,
4246
+ platform,
4247
+ log: () => {
4248
+ }
4249
+ }).environment();
4250
+ const path = captured["PATH"];
4251
+ if (!path || /[\r\n\0]/.test(path)) throw new Error("Could not capture login-shell PATH");
4252
+ return path;
4253
+ }
4254
+ function installPath(platform, state, home = homedir6()) {
4255
+ if (platform === "darwin") return join8(home, "Library", "LaunchAgents", `${label}.plist`);
4256
+ if (platform === "linux")
4257
+ return join8(home, ".config", "systemd", "user", "tsp-gateway.service");
4258
+ if (platform === "win32") return join8(state, "tsp-gateway.xml");
4259
+ throw new Error("Unsupported platform");
4260
+ }
4261
+ function launchdDomain() {
4262
+ return `gui/${process.getuid?.()}`;
4263
+ }
4264
+ function launchdService() {
4265
+ return `${launchdDomain()}/${label}`;
4266
+ }
4267
+ async function registered(platform) {
4268
+ const [file, args] = platform === "darwin" ? ["launchctl", ["print", launchdService()]] : platform === "linux" ? ["systemctl", ["--user", "is-active", "--quiet", "tsp-gateway.service"]] : ["schtasks.exe", ["/Query", "/TN", label]];
4269
+ return (await execute(file, args, process.env)).code === 0;
4270
+ }
4271
+ async function running(platform) {
4272
+ if (platform === "linux") return registered(platform);
4273
+ const [file, args, pattern] = platform === "darwin" ? ["launchctl", ["print", launchdService()], /^\s*state = running$/m] : ["schtasks.exe", ["/Query", "/TN", label, "/FO", "LIST"], /^Status:\s+Running\s*$/m];
4274
+ const result = await execute(file, args, process.env);
4275
+ return result.code === 0 && pattern.test(result.stdout);
4276
+ }
4277
+ async function bootout(timeoutMs = 1e4, intervalMs = 100) {
4278
+ await systemCommand("launchctl", ["bootout", launchdService()]);
4279
+ const deadline = Date.now() + timeoutMs;
4280
+ while (await registered("darwin")) {
4281
+ if (Date.now() >= deadline)
4282
+ throw new Error("Could not update login item (launchd still lists the old one)");
4283
+ await new Promise((resolve6) => setTimeout(resolve6, intervalMs));
4284
+ }
4285
+ }
4286
+ async function systemCommand(file, args) {
4287
+ const result = await execute(file, args, process.env);
4288
+ if (result.code !== 0)
4289
+ throw new Error(`Could not update login item (${file}, exit ${result.code})`);
4290
+ }
4291
+ async function install(spec, platform = process.platform, home = homedir6()) {
4292
+ const destination = installPath(platform, spec.state, home);
4293
+ await privateDirectory(spec.state);
4294
+ await import("node:fs/promises").then(
4295
+ (fs) => fs.mkdir(dirname5(destination), { recursive: true })
4296
+ );
4297
+ const definition = installDefinition(platform, spec);
4298
+ if (platform === "win32") {
4299
+ await import("node:fs/promises").then(
4300
+ (fs) => fs.writeFile(destination, "\uFEFF" + definition, { encoding: "utf16le", mode: 384 })
4301
+ );
4302
+ if (await registered(platform)) await systemCommand("schtasks.exe", ["/End", "/TN", label]);
4303
+ await systemCommand("schtasks.exe", ["/Create", "/TN", label, "/XML", destination, "/F"]);
4304
+ await systemCommand("schtasks.exe", ["/Run", "/TN", label]);
4305
+ } else {
4306
+ await import("node:fs/promises").then(
4307
+ (fs) => fs.writeFile(destination, definition, { mode: 384 })
4308
+ );
4309
+ if (platform === "darwin") {
4310
+ if (await registered(platform)) await bootout();
4311
+ await systemCommand("launchctl", ["bootstrap", launchdDomain(), destination]);
4312
+ } else {
4313
+ await systemCommand("systemctl", ["--user", "daemon-reload"]);
4314
+ await systemCommand("systemctl", ["--user", "enable", "tsp-gateway.service"]);
4315
+ await systemCommand("systemctl", ["--user", "restart", "tsp-gateway.service"]);
4316
+ }
4317
+ }
4318
+ await privateWrite(join8(spec.state, "installation.json"), JSON.stringify(spec));
4319
+ }
4320
+ async function uninstall(state, platform = process.platform, home = homedir6()) {
4321
+ const destination = installPath(platform, state, home);
4322
+ try {
4323
+ await readFile4(destination);
4324
+ } catch {
4325
+ return false;
4326
+ }
4327
+ if (platform === "darwin") {
4328
+ if (await registered(platform)) await bootout();
4329
+ } else if (platform === "linux")
4330
+ await systemCommand("systemctl", ["--user", "disable", "--now", "tsp-gateway.service"]);
4331
+ else if (platform === "win32") {
4332
+ await systemCommand("schtasks.exe", ["/End", "/TN", label]);
4333
+ await systemCommand("schtasks.exe", ["/Delete", "/TN", label, "/F"]);
4334
+ }
4335
+ await rm2(destination, { force: true });
4336
+ if (platform === "linux") await systemCommand("systemctl", ["--user", "daemon-reload"]);
4337
+ await rm2(join8(state, "installation.json"), { force: true });
4338
+ return true;
4339
+ }
4340
+ async function loginItemCurrent(spec, platform = process.platform, home = homedir6()) {
4341
+ try {
4342
+ const recorded = parseJson(await readFile4(join8(spec.state, "installation.json"), "utf8"));
4343
+ await readFile4(installPath(platform, spec.state, home));
4344
+ const keys = Object.keys(spec);
4345
+ if (!isObject(recorded) || Object.keys(recorded).length !== keys.length || keys.some((key) => field(recorded, key) !== spec[key]))
4346
+ return false;
4347
+ } catch {
4348
+ return false;
4349
+ }
4350
+ return running(platform);
4351
+ }
4352
+
4353
+ // src/setup.ts
4354
+ async function pairMachine(host, config) {
4355
+ const pairing = await pair(
4356
+ host.origin,
4357
+ host.tokens(host.origin),
4358
+ host.openBrowser,
4359
+ host.report
4360
+ );
4361
+ config.pairing = pairing;
4362
+ await saveConfig(host.paths.config, config);
4363
+ return pairing;
4364
+ }
4365
+ async function saveRepository(host, config, registered2) {
4366
+ const previous = config.repositories[registered2.slug];
4367
+ if (previous === registered2.folder) return { ...registered2, change: "unchanged" };
4368
+ config.repositories[registered2.slug] = registered2.folder;
4369
+ await saveConfig(host.paths.config, config);
4370
+ return { ...registered2, change: previous === void 0 ? "registered" : "moved" };
4371
+ }
4372
+ async function addRepository(host, config, folder) {
4373
+ return saveRepository(host, config, await registerFolder(folder, host.env));
4374
+ }
4375
+ async function installLoginItem(host, config, refresh = "always") {
4376
+ if (!config.pairing) throw new Error("Run tsp-gateway pair first.");
4377
+ const path = await captureLoginPath(host.env, host.platform, config.launch);
4378
+ const spec = {
4379
+ node: host.node,
4380
+ entry: host.entry,
4381
+ path,
4382
+ config: host.paths.config,
4383
+ state: host.paths.state,
4384
+ version: host.version
4385
+ };
4386
+ if (refresh === "when-changed" && await loginItemCurrent(spec, host.platform, host.home))
4387
+ return "current";
4388
+ config.loginPath = path;
4389
+ await saveConfig(host.paths.config, config);
4390
+ await install(spec, host.platform, host.home);
4391
+ return "installed";
4392
+ }
4393
+ async function removeLoginItem(host) {
4394
+ return await uninstall(host.paths.state, host.platform, host.home) ? "removed" : "absent";
4395
+ }
4396
+ async function unpairMachine(host, config) {
4397
+ if (!config.pairing) return "Not paired; nothing to revoke.";
4398
+ const message = await unpair(config.pairing, host.tokens(config.pairing.origin));
4399
+ config.pairing = null;
4400
+ await saveConfig(host.paths.config, config);
4401
+ return message;
4402
+ }
4403
+ async function pairingUsable(host, pairing) {
4404
+ if (pairing.origin !== host.origin) return false;
4405
+ try {
4406
+ await new OAuthTokens(pairing, host.tokens(pairing.origin)).access();
4407
+ return true;
4408
+ } catch (error) {
4409
+ if (error instanceof TokenAccessDenied) return false;
4410
+ throw new Error(
4411
+ "Could not reach TSP to check this computer's pairing. Nothing was changed; try again.",
4412
+ { cause: error }
4413
+ );
4414
+ }
4415
+ }
4416
+ async function connectFolder(host, config, folder) {
4417
+ if (folder !== void 0) return registerFolder(folder, host.env);
4418
+ try {
4419
+ return await registerFolder(host.cwd, host.env);
4420
+ } catch (error) {
4421
+ if (Object.keys(config.repositories).length > 0) return null;
4422
+ throw new Error(
4423
+ "Run tsp-gateway connect inside a clone of a GitHub repository, or pass its folder.",
4424
+ { cause: error }
4425
+ );
4426
+ }
4427
+ }
4428
+ async function connect(host, config, folder) {
4429
+ const target = await connectFolder(host, config, folder);
4430
+ const kept = config.pairing !== null && await pairingUsable(host, config.pairing);
4431
+ if (!kept) await pairMachine(host, config);
4432
+ const repository = target ? await saveRepository(host, config, target) : null;
4433
+ const loginItem = await installLoginItem(host, config, kept ? "when-changed" : "always");
4434
+ return { pairing: kept ? "kept" : "paired", repository, loginItem };
4435
+ }
4436
+ async function disconnect(host, config) {
4437
+ const loginItem = await removeLoginItem(host);
4438
+ return { loginItem, pairing: await unpairMachine(host, config) };
4439
+ }
4440
+ async function folderSetups(drivers, config, repository) {
4441
+ const folders = repository ? { [repository.slug]: repository.folder } : { ...config.repositories };
4442
+ const rows = Object.keys(folders).length > 0 ? await drivers.repositories(folders) : (await drivers.detect()).map((row) => ({
4443
+ slug: "",
4444
+ harness: row.harness,
4445
+ available: row.available,
4446
+ signed_in: row.signed_in ?? null,
4447
+ trust: "trusted"
4448
+ }));
4449
+ const setups = [];
4450
+ for (const slug of new Set(rows.map((row) => row.slug))) {
4451
+ const here = rows.filter((row) => row.slug === slug);
4452
+ const found = here.filter((row) => row.available);
4453
+ if (found.length === 0) {
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: [] });
4459
+ continue;
4460
+ }
4461
+ const ready = [];
4462
+ const steps = [];
4463
+ for (const row of found) {
4464
+ const driver = drivers.get(row.harness);
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 })));
4470
+ }
4471
+ setups.push(
4472
+ ready.length > 0 ? { slug, ready, required: [], optional: steps } : { slug, ready, required: steps, optional: [] }
4473
+ );
4474
+ }
4475
+ return setups;
4476
+ }
4477
+ function trustIsStep(trust, driver) {
4478
+ return trust === "untrusted" || trust === "unknown" && !driver.unknownTrustAdmits;
4479
+ }
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
+
4541
+ export {
4542
+ GATEWAY_CLOSE_DISPOSITION,
4543
+ decodeReporting,
4544
+ toWire,
4545
+ ActivityCoalescer,
4546
+ ActivityReporter,
4547
+ isObject,
4548
+ field,
4549
+ decodeHub,
4550
+ parseJson,
4551
+ ClaudeTranscripts,
4552
+ ClaudeTrust,
4553
+ HarnessRefusal,
4554
+ defaultLaunchConfig,
4555
+ decodeLaunchConfig,
4556
+ execute,
4557
+ resolveLaunchPath,
4558
+ HarnessExecutor,
4559
+ sanitizeWaiting,
4560
+ ClaudeDriver,
4561
+ CodexActivity,
4562
+ CodexTrust,
4563
+ CodexDriver,
4564
+ HarnessRegistry,
4565
+ builtinHarnesses,
4566
+ CommandLifetime,
4567
+ locations,
4568
+ privateDirectory,
4569
+ readConfig,
4570
+ saveConfig,
4571
+ validateOrigin,
4572
+ validSlug,
4573
+ githubSlug,
4574
+ registerFolder,
4575
+ Journal,
4576
+ MISSING_SESSION_POLLS,
4577
+ UNREADABLE_SESSION_POLLS,
4578
+ Commands,
4579
+ watchConfig,
4580
+ LaunchPermits,
4581
+ OAuthTokens,
4582
+ pair,
4583
+ unpair,
4584
+ reconnectDelay,
4585
+ runDaemon,
4586
+ daemonLock,
4587
+ GatewayStatus,
4588
+ daemonConnection,
4589
+ awaitDaemonConnection,
4590
+ readLaunchObservation,
4591
+ keychainOptions,
4592
+ keychain,
4593
+ installDefinition,
4594
+ captureLoginPath,
4595
+ installPath,
4596
+ install,
4597
+ uninstall,
4598
+ loginItemCurrent,
4599
+ pairMachine,
4600
+ addRepository,
4601
+ installLoginItem,
4602
+ removeLoginItem,
4603
+ unpairMachine,
4604
+ connect,
4605
+ disconnect,
4606
+ folderSetups,
4607
+ setupLines,
4608
+ connectLines,
4609
+ statusLines
4610
+ };
4611
+ //# sourceMappingURL=shared-M7CEELPK.js.map