@treestructuredplanning/gateway 0.2.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
2
 
3
3
  // ../tsp-shared/src/generated/constants.ts
4
- var GATEWAY_PACKAGE_VERSION = "0.2.0";
4
+ var GATEWAY_PACKAGE_VERSION = "0.3.2";
5
5
  var GATEWAY_PROTOCOL_VERSION = 3;
6
6
  var SESSION_ACTIVITY_COUNT_MAX = 1e6;
7
7
  var AGENT_SESSION_STATE = {
@@ -381,8 +381,8 @@ function decodeRegistration(value) {
381
381
  throw new Error("Invalid machine hub path");
382
382
  return registration;
383
383
  }
384
- function parseJson(text4) {
385
- return JSON.parse(text4);
384
+ function parseJson(text5) {
385
+ return JSON.parse(text5);
386
386
  }
387
387
  function decodeHubText(data) {
388
388
  if (typeof data !== "string" || data.length > 131072) throw new Error("Invalid frame");
@@ -430,19 +430,19 @@ function opaque(value) {
430
430
  }
431
431
  var WAITING_FOR_MAX_LENGTH = 4e3;
432
432
  var LAST_MESSAGE_MAX_LENGTH = 240;
433
- function sanitizeWords(text4, maxLength) {
433
+ function sanitizeWords(text5, maxLength) {
434
434
  return [
435
- ...text4.replace(
435
+ ...text5.replace(
436
436
  /(?:\\\\[?.]\\|\\\?\?\\|\\\\|[A-Za-z]:[\\/]|~?\/|\.\.?\/)[^\s"'<>]+/g,
437
437
  "[local path]"
438
438
  ).split("").map((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127 ? " " : char).join("")
439
439
  ].slice(0, maxLength).join("");
440
440
  }
441
- function sanitizeWaiting(text4) {
442
- return sanitizeWords(text4, WAITING_FOR_MAX_LENGTH);
441
+ function sanitizeWaiting(text5) {
442
+ return sanitizeWords(text5, WAITING_FOR_MAX_LENGTH);
443
443
  }
444
- function sanitizeLastMessage(text4) {
445
- return sanitizeWords(text4, LAST_MESSAGE_MAX_LENGTH);
444
+ function sanitizeLastMessage(text5) {
445
+ return sanitizeWords(text5, LAST_MESSAGE_MAX_LENGTH);
446
446
  }
447
447
  var STARTUP_GRACE_MS = 1e4;
448
448
  function backgroundSession(row) {
@@ -544,7 +544,7 @@ function excludeLine(clone, root) {
544
544
 
545
545
  // src/process.ts
546
546
  import { spawn } from "node:child_process";
547
- function execute(file, args, env, cwd) {
547
+ function execute(file, args, env, cwd, { timeoutMs = 3e4 } = {}) {
548
548
  return new Promise((resolve13, reject) => {
549
549
  const child = spawn(file, args, {
550
550
  env,
@@ -556,7 +556,7 @@ function execute(file, args, env, cwd) {
556
556
  const timer = setTimeout(() => {
557
557
  child.kill();
558
558
  reject(new Error("Local command timed out"));
559
- }, 3e4);
559
+ }, timeoutMs);
560
560
  child.stdout.setEncoding("utf8").on("data", (chunk) => {
561
561
  stdout += chunk;
562
562
  if (stdout.length > 4e6) {
@@ -701,8 +701,8 @@ var ShellOutput = class {
701
701
  return output;
702
702
  }
703
703
  };
704
- function decodeEnvironment(text4) {
705
- const value = parseJson(text4);
704
+ function decodeEnvironment(text5) {
705
+ const value = parseJson(text5);
706
706
  if (!isObject(value)) throw new Error("Invalid shell environment capture");
707
707
  const env = {};
708
708
  for (const name of Object.keys(value)) {
@@ -1073,11 +1073,11 @@ function decodeStoredSessions(result) {
1073
1073
  function heldRequestText(params) {
1074
1074
  if (!isObject(params)) return null;
1075
1075
  const toolCall = field(params, "toolCall");
1076
- for (const source2 of [isObject(toolCall) ? toolCall : null, params]) {
1077
- if (!source2) continue;
1076
+ for (const source of [isObject(toolCall) ? toolCall : null, params]) {
1077
+ if (!source) continue;
1078
1078
  for (const key of ["title", "question", "name"]) {
1079
- const text4 = field(source2, key);
1080
- if (typeof text4 === "string" && text4.trim()) return text4.trim();
1079
+ const text5 = field(source, key);
1080
+ if (typeof text5 === "string" && text5.trim()) return text5.trim();
1081
1081
  }
1082
1082
  }
1083
1083
  return null;
@@ -1252,11 +1252,11 @@ var AcpConnection = class _AcpConnection {
1252
1252
  const error = field(message, "error");
1253
1253
  if (isObject(error)) {
1254
1254
  const code = field(error, "code");
1255
- const text4 = field(error, "message");
1255
+ const text5 = field(error, "message");
1256
1256
  request.reject(
1257
1257
  new AcpRpcError(
1258
1258
  typeof code === "number" ? code : -32603,
1259
- typeof text4 === "string" ? text4 : "ACP request failed"
1259
+ typeof text5 === "string" ? text5 : "ACP request failed"
1260
1260
  )
1261
1261
  );
1262
1262
  } else request.resolve(field(message, "result"));
@@ -1353,8 +1353,8 @@ var BETWEEN_UPDATES = /* @__PURE__ */ new Set([
1353
1353
  ]);
1354
1354
  function messageText(update) {
1355
1355
  const content = field(update, "content");
1356
- const text4 = isObject(content) && field(content, "type") === "text" ? field(content, "text") : null;
1357
- return typeof text4 === "string" ? text4 : "";
1356
+ const text5 = isObject(content) && field(content, "type") === "text" ? field(content, "text") : null;
1357
+ return typeof text5 === "string" ? text5 : "";
1358
1358
  }
1359
1359
  var AcpSession = class {
1360
1360
  constructor(id, name, folder) {
@@ -1449,8 +1449,8 @@ var AcpSession = class {
1449
1449
  }
1450
1450
  /** The turn's last words, only for a finished turn, as the owner's canvas shows them. */
1451
1451
  lastMessage() {
1452
- const text4 = sanitizeLastMessage(this.said.replace(/\s+/g, " ").trim());
1453
- return this.state === "done" && text4 ? text4 : void 0;
1452
+ const text5 = sanitizeLastMessage(this.said.replace(/\s+/g, " ").trim());
1453
+ return this.state === "done" && text5 ? text5 : void 0;
1454
1454
  }
1455
1455
  async snapshot(activityRoot) {
1456
1456
  return {
@@ -1484,17 +1484,17 @@ var AcpDriver = class {
1484
1484
  this.timeouts = timeouts;
1485
1485
  this.groups = groups;
1486
1486
  this.displayName = agent.displayName;
1487
- this.signInInstruction = agent.signInInstruction;
1488
- this.installInstruction = agent.installInstruction;
1489
- this.repositorySetupInstruction = agent.repositorySetupInstruction;
1487
+ this.signInStep = agent.signInStep;
1488
+ this.installStep = agent.installStep;
1490
1489
  this.unknownTrustAdmits = agent.unknownTrustAdmits;
1490
+ this.repositorySetup = (folder) => agent.repositorySetup(folder);
1491
1491
  this.hold = /* @__PURE__ */ new Set([ACP_PERMISSION_METHOD, ...agent.holdMethods]);
1492
1492
  }
1493
1493
  displayName;
1494
- signInInstruction;
1495
- installInstruction;
1496
- repositorySetupInstruction;
1494
+ signInStep;
1495
+ installStep;
1497
1496
  unknownTrustAdmits;
1497
+ repositorySetup;
1498
1498
  sessions = /* @__PURE__ */ new Map();
1499
1499
  stored = /* @__PURE__ */ new Map();
1500
1500
  hold;
@@ -1566,14 +1566,14 @@ var AcpDriver = class {
1566
1566
  return session;
1567
1567
  }
1568
1568
  /** Sends one prompt without waiting for its turn, which ends through `settle`. */
1569
- beginTurn(session, connection, text4, check) {
1569
+ beginTurn(session, connection, text5, check) {
1570
1570
  check();
1571
1571
  session.beginTurn(connection);
1572
1572
  connection.onUpdate = (params) => session.observe(params);
1573
1573
  connection.onHeldChange = () => session.holding(connection.held);
1574
1574
  void connection.request(
1575
1575
  "session/prompt",
1576
- { sessionId: session.id, prompt: [{ type: "text", text: text4 }] },
1576
+ { sessionId: session.id, prompt: [{ type: "text", text: text5 }] },
1577
1577
  { timeoutMs: null }
1578
1578
  ).then((result) => decodeStopReason(result)).then(
1579
1579
  (reason) => this.settle(session, connection, reason),
@@ -1597,7 +1597,7 @@ var AcpDriver = class {
1597
1597
  );
1598
1598
  await connection.close();
1599
1599
  }
1600
- async start(command, folder, requireLive, checkpoint) {
1600
+ async start(command2, folder, requireLive, checkpoint) {
1601
1601
  await this.requireTrusted(folder);
1602
1602
  const connection = await this.connect(folder, requireLive);
1603
1603
  try {
@@ -1609,21 +1609,21 @@ var AcpDriver = class {
1609
1609
  )
1610
1610
  );
1611
1611
  await checkpoint?.(id);
1612
- const session = this.register(id, command.session_name, folder);
1613
- this.beginTurn(session, connection, command.seed, promptCheck(requireLive));
1612
+ const session = this.register(id, command2.session_name, folder);
1613
+ this.beginTurn(session, connection, command2.seed, promptCheck(requireLive));
1614
1614
  return id;
1615
1615
  } catch (error) {
1616
1616
  await connection.close();
1617
1617
  throw error;
1618
1618
  }
1619
1619
  }
1620
- async reconcileLaunch(ref, command, folder, requireLive, beforeSeed) {
1620
+ async reconcileLaunch(ref, command2, folder, requireLive, beforeSeed) {
1621
1621
  const known = this.sessions.get(ref);
1622
1622
  if (known?.seeded) return known.snapshot();
1623
1623
  const connection = await this.connect(folder, requireLive);
1624
1624
  try {
1625
1625
  if (!connection.capabilities.loadSession) throw new HarnessRefusal("start_uncertain");
1626
- const session = known ?? this.register(ref, command.session_name, folder);
1626
+ const session = known ?? this.register(ref, command2.session_name, folder);
1627
1627
  const seeded = await this.load(session, connection, folder, requireLive);
1628
1628
  if (seeded !== false) {
1629
1629
  if (seeded) session.endedWithGateway();
@@ -1634,7 +1634,7 @@ var AcpDriver = class {
1634
1634
  await this.requireTrusted(folder);
1635
1635
  if (!inside(await realpath2(await beforeSeed()), await realpath2(folder)))
1636
1636
  throw new HarnessRefusal("start_uncertain");
1637
- this.beginTurn(session, connection, command.seed, promptCheck(requireLive));
1637
+ this.beginTurn(session, connection, command2.seed, promptCheck(requireLive));
1638
1638
  return session.snapshot();
1639
1639
  } catch (error) {
1640
1640
  await connection.close();
@@ -1726,7 +1726,7 @@ var AcpDriver = class {
1726
1726
  if (ended === false && running3.connection === connection) running3.finish("stopped");
1727
1727
  await connection.close();
1728
1728
  }
1729
- async resume(session, text4, folder, requireLive) {
1729
+ async resume(session, text5, folder, requireLive) {
1730
1730
  if (session.state === "working" || session.state === "needs_input")
1731
1731
  throw new HarnessRefusal("already_running");
1732
1732
  const detected = await this.detect(folder);
@@ -1736,7 +1736,7 @@ var AcpDriver = class {
1736
1736
  if (!this.loadSession) throw new HarnessRefusal("unsupported_command");
1737
1737
  const record = this.register(session.id, session.name, folder);
1738
1738
  if (record.connection) throw new HarnessRefusal("unsupported_command");
1739
- const prompt = text4 ?? (session.state === "stopped" ? RESUME_CONTINUATION : null);
1739
+ const prompt = text5 ?? (session.state === "stopped" ? RESUME_CONTINUATION : null);
1740
1740
  const connection = await this.connect(folder, requireLive);
1741
1741
  try {
1742
1742
  if (await this.load(record, connection, folder, requireLive) === void 0)
@@ -1819,10 +1819,10 @@ function decodeVariables(env) {
1819
1819
  if (!isObject(env)) throw new Error("launch.env must contain string variables");
1820
1820
  const variables = {};
1821
1821
  for (const name of Object.keys(env)) {
1822
- const entry = field(env, name);
1823
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || !text(entry))
1822
+ const entry2 = field(env, name);
1823
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || !text(entry2))
1824
1824
  throw new Error("launch.env must contain valid names and NUL-free string values");
1825
- Object.defineProperty(variables, name, { value: entry, enumerable: true });
1825
+ Object.defineProperty(variables, name, { value: entry2, enumerable: true });
1826
1826
  }
1827
1827
  return variables;
1828
1828
  }
@@ -1857,9 +1857,9 @@ async function privateWrite(path, value) {
1857
1857
  await rename(temporary, path);
1858
1858
  }
1859
1859
  async function readConfig(path) {
1860
- let text4;
1860
+ let text5;
1861
1861
  try {
1862
- text4 = await readFile(path, "utf8");
1862
+ text5 = await readFile(path, "utf8");
1863
1863
  } catch (error) {
1864
1864
  if (isObject(error) && field(error, "code") === "ENOENT")
1865
1865
  return {
@@ -1872,7 +1872,7 @@ async function readConfig(path) {
1872
1872
  };
1873
1873
  throw error;
1874
1874
  }
1875
- const value = parseJson(text4);
1875
+ const value = parseJson(text5);
1876
1876
  if (!isObject(value) || Object.keys(value).some(
1877
1877
  (key) => ![
1878
1878
  "repositories",
@@ -1948,7 +1948,7 @@ async function registerFolder(folder, env = process.env) {
1948
1948
  }
1949
1949
  function repositoryFolders(config) {
1950
1950
  return Object.fromEntries(
1951
- Object.entries(config.repositories).map(([key, entry]) => [key, entry.folder])
1951
+ Object.entries(config.repositories).map(([key, entry2]) => [key, entry2.folder])
1952
1952
  );
1953
1953
  }
1954
1954
  function decodeRepositories(value, repositories) {
@@ -1959,18 +1959,18 @@ function decodeRepositories(value, repositories) {
1959
1959
  const map = {};
1960
1960
  let upgraded = worktrees === void 0;
1961
1961
  for (const slug of Object.keys(repositories)) {
1962
- const entry = field(repositories, slug);
1963
- const folder = typeof entry === "string" ? entry : isObject(entry) ? field(entry, "folder") : null;
1964
- if (isObject(entry) && Object.keys(entry).some((key) => !["folder", "worktreeRoot"].includes(key)))
1962
+ const entry2 = field(repositories, slug);
1963
+ const folder = typeof entry2 === "string" ? entry2 : isObject(entry2) ? field(entry2, "folder") : null;
1964
+ if (isObject(entry2) && Object.keys(entry2).some((key) => !["folder", "worktreeRoot"].includes(key)))
1965
1965
  throw new Error("Invalid repository registry");
1966
- upgraded ||= typeof entry === "string";
1966
+ upgraded ||= typeof entry2 === "string";
1967
1967
  if (typeof folder !== "string" || !isAbsolute6(folder))
1968
1968
  throw new Error("Invalid repository registry");
1969
1969
  decodeWorktreeRoot(root, folder);
1970
1970
  map[repositoryKey(storedRepository(slug))] = {
1971
1971
  folder,
1972
1972
  worktreeRoot: decodeWorktreeRoot(
1973
- isObject(entry) ? field(entry, "worktreeRoot") : null,
1973
+ isObject(entry2) ? field(entry2, "worktreeRoot") : null,
1974
1974
  folder
1975
1975
  )
1976
1976
  };
@@ -2147,9 +2147,9 @@ var ClaudeTranscripts = class {
2147
2147
  if (await exists(expected)) return expected;
2148
2148
  if (this.now() - cursor.searchedAt < SEARCH_INTERVAL_MS) return null;
2149
2149
  cursor.searchedAt = this.now();
2150
- for (const entry of await readdir(projects, { withFileTypes: true })) {
2151
- if (!entry.isDirectory()) continue;
2152
- const candidate = join4(projects, entry.name, file);
2150
+ for (const entry2 of await readdir(projects, { withFileTypes: true })) {
2151
+ if (!entry2.isDirectory()) continue;
2152
+ const candidate = join4(projects, entry2.name, file);
2153
2153
  if (await exists(candidate)) return candidate;
2154
2154
  }
2155
2155
  return null;
@@ -2177,9 +2177,9 @@ var ClaudeTranscripts = class {
2177
2177
  cursor.remainder = data.length > LINE_LIMIT_BYTES ? Buffer.alloc(0) : Buffer.from(data);
2178
2178
  }
2179
2179
  entry(conversationId, tally, line) {
2180
- const entry = parseEntry(line);
2181
- if (!entry) return;
2182
- const { role, content, at } = entry;
2180
+ const entry2 = parseEntry(line);
2181
+ if (!entry2) return;
2182
+ const { role, content, at } = entry2;
2183
2183
  if (typeof content === "string") {
2184
2184
  if (role === "user") {
2185
2185
  tally.stepped(at);
@@ -2324,6 +2324,11 @@ var ClaudeTrust = class {
2324
2324
  }
2325
2325
  };
2326
2326
 
2327
+ // src/folder-command.ts
2328
+ function inFolder(folder, program, platform = process.platform) {
2329
+ return platform === "win32" ? `Set-Location -LiteralPath '${folder.replace(/'/g, "''")}'; ${program}` : `cd '${folder.replace(/'/g, "'\\''")}' && ${program}`;
2330
+ }
2331
+
2327
2332
  // src/harness-executor.ts
2328
2333
  import { spawn as spawn3 } from "node:child_process";
2329
2334
  import { homedir as homedir5 } from "node:os";
@@ -2596,10 +2601,18 @@ var ClaudeDriver = class {
2596
2601
  this.trust = trust ?? new ClaudeTrust((folder) => this.executor.environment(false, folder));
2597
2602
  }
2598
2603
  trust;
2599
- repositorySetupInstruction = "Run claude in that folder once and accept its trust prompt.";
2604
+ repositorySetup(folder) {
2605
+ return {
2606
+ instruction: "Run claude in the repository's folder once and accept its trust prompt.",
2607
+ command: inFolder(folder, "claude")
2608
+ };
2609
+ }
2600
2610
  displayName = "Claude Code";
2601
- signInInstruction = "Run claude and sign in.";
2602
- installInstruction = "Install it with npm install --global @anthropic-ai/claude-code, then run connect again.";
2611
+ signInStep = { instruction: "Run claude and sign in.", command: "claude" };
2612
+ installStep = {
2613
+ instruction: "Install it, then run connect again.",
2614
+ link: "https://code.claude.com/docs/en/setup"
2615
+ };
2603
2616
  unknownTrustAdmits = true;
2604
2617
  capabilities = {
2605
2618
  start: true,
@@ -2646,11 +2659,11 @@ var ClaudeDriver = class {
2646
2659
  };
2647
2660
  }
2648
2661
  }
2649
- async start(command, folder, requireLive) {
2662
+ async start(command2, folder, requireLive) {
2650
2663
  const seeding = promptCheck(requireLive);
2651
2664
  seeding();
2652
2665
  const result = await this.call(
2653
- ["--bg", "--name", command.session_name, "--", command.seed],
2666
+ ["--bg", "--name", command2.session_name, "--", command2.seed],
2654
2667
  folder,
2655
2668
  "launch",
2656
2669
  seeding
@@ -2779,7 +2792,7 @@ var ClaudeDriver = class {
2779
2792
  );
2780
2793
  if (result.code !== 0) throw new HarnessRefusal("stop_failed");
2781
2794
  }
2782
- async resume(session, text4, folder, requireLive) {
2795
+ async resume(session, text5, folder, requireLive) {
2783
2796
  if (session.state === "working" || session.state === "needs_input")
2784
2797
  throw new HarnessRefusal("already_running");
2785
2798
  if (session.pid !== null) {
@@ -2793,7 +2806,7 @@ var ClaudeDriver = class {
2793
2806
  }
2794
2807
  await this.executor.environment(true, folder);
2795
2808
  if (await this.signedIn(folder) === false) throw new HarnessRefusal("not_signed_in");
2796
- const prompt = text4 ?? (session.state === "stopped" ? RESUME_CONTINUATION : null);
2809
+ const prompt = text5 ?? (session.state === "stopped" ? RESUME_CONTINUATION : null);
2797
2810
  const resuming = promptCheck(requireLive);
2798
2811
  resuming();
2799
2812
  const result = await this.call(
@@ -2952,8 +2965,8 @@ function requestWords(params) {
2952
2965
  function lastAgentMessage(page2) {
2953
2966
  const data = isObject(page2) ? field(page2, "data") : null;
2954
2967
  if (!Array.isArray(data)) return null;
2955
- for (const entry of data) {
2956
- const item = isObject(entry) ? field(entry, "item") : null;
2968
+ for (const entry2 of data) {
2969
+ const item = isObject(entry2) ? field(entry2, "item") : null;
2957
2970
  if (isObject(item) && field(item, "type") === "agentMessage") {
2958
2971
  const said2 = text3(field(item, "text"));
2959
2972
  if (said2) return said2;
@@ -3050,14 +3063,14 @@ var CodexActivity = class {
3050
3063
  throw new Error("Unrecognised Codex item page");
3051
3064
  let reachedSettled = false;
3052
3065
  for (const raw of field(response, "data")) {
3053
- const entry = entryOf(raw);
3054
- if (!entry) continue;
3055
- if (thread.settled.has(entry.id)) {
3066
+ const entry2 = entryOf(raw);
3067
+ if (!entry2) continue;
3068
+ if (thread.settled.has(entry2.id)) {
3056
3069
  reachedSettled = true;
3057
3070
  continue;
3058
3071
  }
3059
- unseen.delete(entry.id);
3060
- entries.push(entry);
3072
+ unseen.delete(entry2.id);
3073
+ entries.push(entry2);
3061
3074
  }
3062
3075
  const next = field(response, "nextCursor");
3063
3076
  cursor = typeof next === "string" && next ? next : null;
@@ -3068,7 +3081,7 @@ var CodexActivity = class {
3068
3081
  thread.commands.delete(id);
3069
3082
  thread.tally.finished(id);
3070
3083
  }
3071
- for (const entry of entries.reverse()) this.apply(thread, entry);
3084
+ for (const entry2 of entries.reverse()) this.apply(thread, entry2);
3072
3085
  return thread.tally.snapshot(root);
3073
3086
  }
3074
3087
  apply(thread, { id, item, status, at, completed }) {
@@ -3451,12 +3464,12 @@ async function* threads(server, folder, query) {
3451
3464
  sourceKinds: ["cli", "vscode", "appServer"]
3452
3465
  })
3453
3466
  ) : loadedThreadPage(await server.request(method, { cursor, limit: 100 }));
3454
- for (const entry of page2.threads) {
3455
- const id = typeof entry === "string" ? entry : entry.id;
3467
+ for (const entry2 of page2.threads) {
3468
+ const id = typeof entry2 === "string" ? entry2 : entry2.id;
3456
3469
  if (seen.has(id)) continue;
3457
3470
  seen.add(id);
3458
- if (typeof entry !== "string") {
3459
- yield entry;
3471
+ if (typeof entry2 !== "string") {
3472
+ yield entry2;
3460
3473
  continue;
3461
3474
  }
3462
3475
  try {
@@ -3526,7 +3539,7 @@ async function listCodexSessions(server, folder, query, activity) {
3526
3539
  // src/codex-driver.ts
3527
3540
  var MINIMUM_CODEX_VERSION = "0.162.1";
3528
3541
  function supportedCodexVersion(version) {
3529
- const parts = (text4) => (text4.split(/[-+]/)[0] ?? "").split(".").map(Number);
3542
+ const parts = (text5) => (text5.split(/[-+]/)[0] ?? "").split(".").map(Number);
3530
3543
  if (!version) return true;
3531
3544
  const found = parts(version), minimum = parts(MINIMUM_CODEX_VERSION);
3532
3545
  for (const [index, part] of minimum.entries()) {
@@ -3547,18 +3560,18 @@ async function discardThread(server, threadId) {
3547
3560
  } catch {
3548
3561
  }
3549
3562
  }
3550
- async function seedThread(server, thread, command, requireLive) {
3551
- if (thread.name !== command.session_name)
3563
+ async function seedThread(server, thread, command2, requireLive) {
3564
+ if (thread.name !== command2.session_name)
3552
3565
  await server.request(
3553
3566
  "thread/name/set",
3554
- { threadId: thread.id, name: command.session_name },
3567
+ { threadId: thread.id, name: command2.session_name },
3555
3568
  requireLive
3556
3569
  );
3557
3570
  await server.request(
3558
3571
  "turn/start",
3559
3572
  {
3560
3573
  threadId: thread.id,
3561
- input: [{ type: "text", text: command.seed, text_elements: [] }]
3574
+ input: [{ type: "text", text: command2.seed, text_elements: [] }]
3562
3575
  },
3563
3576
  promptCheck(requireLive)
3564
3577
  );
@@ -3570,10 +3583,18 @@ var CodexDriver = class {
3570
3583
  this.trust = new CodexTrust(executor);
3571
3584
  this.timeouts = { ...CODEX_TIMEOUTS, ...timeouts };
3572
3585
  }
3573
- repositorySetupInstruction = "Run codex in that folder once and accept its trust prompt.";
3586
+ repositorySetup(folder) {
3587
+ return {
3588
+ instruction: "Run codex in the repository's folder once and accept its trust prompt.",
3589
+ command: inFolder(folder, "codex")
3590
+ };
3591
+ }
3574
3592
  displayName = "Codex";
3575
- signInInstruction = "Run codex login and sign in.";
3576
- installInstruction = `Install Codex ${MINIMUM_CODEX_VERSION} or newer with npm install --global @openai/codex, then run connect again.`;
3593
+ signInStep = { instruction: "Run codex login and sign in.", command: "codex login" };
3594
+ installStep = {
3595
+ instruction: `Install Codex ${MINIMUM_CODEX_VERSION} or newer, then run connect again.`,
3596
+ link: "https://developers.openai.com/codex/cli"
3597
+ };
3577
3598
  /** Codex refuses a folder it has no trust record for, so unknown trust is a step to take. */
3578
3599
  unknownTrustAdmits = false;
3579
3600
  capabilities = {
@@ -3615,8 +3636,8 @@ var CodexDriver = class {
3615
3636
  "read",
3616
3637
  folder
3617
3638
  );
3618
- const text4 = login.stdout + login.stderr;
3619
- detection.signed_in = /not logged in/i.test(text4) ? false : login.code === 0 && /logged in/i.test(text4) ? true : null;
3639
+ const text5 = login.stdout + login.stderr;
3640
+ detection.signed_in = /not logged in/i.test(text5) ? false : login.code === 0 && /logged in/i.test(text5) ? true : null;
3620
3641
  }
3621
3642
  } catch {
3622
3643
  }
@@ -3673,7 +3694,7 @@ var CodexDriver = class {
3673
3694
  await server.close();
3674
3695
  }
3675
3696
  }
3676
- async start(command, folder, requireLive, checkpoint) {
3697
+ async start(command2, folder, requireLive, checkpoint) {
3677
3698
  await this.requireTrusted(folder);
3678
3699
  return this.connection(
3679
3700
  folder,
@@ -3684,7 +3705,7 @@ var CodexDriver = class {
3684
3705
  );
3685
3706
  await checkpoint?.(thread.id);
3686
3707
  try {
3687
- await seedThread(server, thread, command, requireLive);
3708
+ await seedThread(server, thread, command2, requireLive);
3688
3709
  } catch (error) {
3689
3710
  if (error instanceof HarnessRefusal) await discardThread(server, thread.id);
3690
3711
  throw error;
@@ -3694,7 +3715,7 @@ var CodexDriver = class {
3694
3715
  requireLive
3695
3716
  );
3696
3717
  }
3697
- async reconcileLaunch(ref, command, folder, requireLive, beforeSeed) {
3718
+ async reconcileLaunch(ref, command2, folder, requireLive, beforeSeed) {
3698
3719
  return this.connection(
3699
3720
  folder,
3700
3721
  async (server) => {
@@ -3727,7 +3748,7 @@ var CodexDriver = class {
3727
3748
  requireLive.prompt?.();
3728
3749
  if (!await inside2(await realpath6(await beforeSeed()), thread.cwd))
3729
3750
  throw new HarnessRefusal("start_uncertain");
3730
- await seedThread(server, thread, command, requireLive);
3751
+ await seedThread(server, thread, command2, requireLive);
3731
3752
  return { ...sessionFromThread(thread), state: "starting", waitingFor: null };
3732
3753
  },
3733
3754
  requireLive
@@ -3738,10 +3759,10 @@ var CodexDriver = class {
3738
3759
  const turn = await this.connection(folder, (server) => lastTurn(server, session.id));
3739
3760
  return turn ? [turn.id] : [];
3740
3761
  },
3741
- reconcile: async (session, text4, observedRefs, folder, requireLive) => {
3762
+ reconcile: async (session, text5, observedRefs, folder, requireLive) => {
3742
3763
  const turn = await this.connection(folder, (server) => lastTurn(server, session.id));
3743
3764
  if (turn && !observedRefs.includes(turn.id)) return session.id;
3744
- return this.resume(session, text4, folder, requireLive);
3765
+ return this.resume(session, text5, folder, requireLive);
3745
3766
  }
3746
3767
  };
3747
3768
  async list(folder, requireLive, query) {
@@ -3766,7 +3787,7 @@ var CodexDriver = class {
3766
3787
  requireLive
3767
3788
  );
3768
3789
  }
3769
- async resume(session, text4, folder, requireLive) {
3790
+ async resume(session, text5, folder, requireLive) {
3770
3791
  if (session.state === "working" || session.state === "needs_input")
3771
3792
  throw new HarnessRefusal("already_running");
3772
3793
  const detected = await this.detect(folder);
@@ -3782,8 +3803,8 @@ var CodexDriver = class {
3782
3803
  { threadId: id, excludeTurns: true },
3783
3804
  requireLive
3784
3805
  );
3785
- const turn = text4 === null ? await lastTurn(server, id) : null;
3786
- const prompt = text4 ?? (turn?.status === "interrupted" ? RESUME_CONTINUATION : null);
3806
+ const turn = text5 === null ? await lastTurn(server, id) : null;
3807
+ const prompt = text5 ?? (turn?.status === "interrupted" ? RESUME_CONTINUATION : null);
3787
3808
  if (prompt !== null)
3788
3809
  await server.request(
3789
3810
  "turn/start",
@@ -3820,11 +3841,11 @@ var CodexDriver = class {
3820
3841
  // src/cursor-agent.ts
3821
3842
  import { open as open5, realpath as realpath7 } from "node:fs/promises";
3822
3843
  import { homedir as homedir8 } from "node:os";
3823
- import { join as join8 } from "node:path";
3844
+ import { basename as basename4, dirname as dirname4, join as join8 } from "node:path";
3824
3845
  var MINIMUM_CURSOR_VERSION = "2026.10.19";
3825
3846
  var MAX_RECORD_BYTES = 64 * 1024;
3826
3847
  function supportedVersion(version) {
3827
- const parts = (text4) => (text4.split(/[-+]/)[0] ?? "").split(".").map(Number);
3848
+ const parts = (text5) => (text5.split(/[-+]/)[0] ?? "").split(".").map(Number);
3828
3849
  if (!version) return true;
3829
3850
  const found = parts(version), minimum = parts(MINIMUM_CURSOR_VERSION);
3830
3851
  for (const [index, part] of minimum.entries()) {
@@ -3842,9 +3863,17 @@ var CursorAgent = class {
3842
3863
  executable = "agent";
3843
3864
  args = ["acp"];
3844
3865
  holdMethods = ["cursor/ask_question", "cursor/create_plan"];
3845
- repositorySetupInstruction = "Run agent in that folder once and trust the workspace when it asks.";
3846
- signInInstruction = "Run agent login and sign in.";
3847
- installInstruction = `Install the Cursor CLI ${MINIMUM_CURSOR_VERSION} or newer with curl https://cursor.com/install -fsS | bash, then run connect again.`;
3866
+ repositorySetup(folder) {
3867
+ return {
3868
+ instruction: "Run agent in the repository's folder once and trust the workspace when it asks.",
3869
+ command: inFolder(folder, "agent")
3870
+ };
3871
+ }
3872
+ signInStep = { instruction: "Run agent login and sign in.", command: "agent login" };
3873
+ installStep = {
3874
+ instruction: `Install the Cursor CLI ${MINIMUM_CURSOR_VERSION} or newer, then run connect again.`,
3875
+ link: "https://cursor.com/docs/cli/installation"
3876
+ };
3848
3877
  /** ACP has no trust gate of its own, so an undecided folder is a step to take, not a launch to admit. */
3849
3878
  unknownTrustAdmits = false;
3850
3879
  async probe(executor, folder) {
@@ -3854,28 +3883,45 @@ var CursorAgent = class {
3854
3883
  probe.available = version.code === 0 && probe.version !== null && supportedVersion(probe.version);
3855
3884
  if (!probe.available) return probe;
3856
3885
  const status = await executor.execute(this.executable, ["status"], "read", folder);
3857
- const text4 = status.stdout + status.stderr;
3858
- probe.signedIn = /not logged in|not authenticated|login required/i.test(text4) ? false : status.code === 0 && /logged in/i.test(text4) ? true : null;
3886
+ const text5 = status.stdout + status.stderr;
3887
+ probe.signedIn = /not logged in|not authenticated|login required/i.test(text5) ? false : status.code === 0 && /logged in/i.test(text5) ? true : null;
3859
3888
  return probe;
3860
3889
  }
3890
+ /**
3891
+ * The folder's own record, then, for a linked worktree, its main repository's: the
3892
+ * gateway's attempt worktrees are new folders no one can have trusted ahead of time.
3893
+ */
3861
3894
  async trust(executor, folder) {
3862
3895
  try {
3863
3896
  const env = await executor.environment(false, folder);
3864
3897
  const root = env["CURSOR_CONFIG_DIR"] ?? join8(env["HOME"] ?? homedir8(), ".cursor");
3865
- const canonical2 = await realpath7(folder);
3866
- for (const spelling of /* @__PURE__ */ new Set([canonical2, folder])) {
3898
+ const trusted = async (spelling) => {
3867
3899
  const record = await readRecord(
3868
3900
  join8(root, "projects", cursorProjectKey(spelling), ".workspace-trusted")
3869
3901
  );
3870
- if (isObject(record) && field(record, "workspacePath") === spelling)
3871
- return "trusted";
3872
- }
3873
- return "unknown";
3902
+ return isObject(record) && field(record, "workspacePath") === spelling;
3903
+ };
3904
+ for (const spelling of /* @__PURE__ */ new Set([await realpath7(folder), folder]))
3905
+ if (await trusted(spelling)) return "trusted";
3906
+ const main = await mainRepository(executor, folder);
3907
+ return main && await trusted(main) ? "trusted" : "unknown";
3874
3908
  } catch {
3875
3909
  return "unknown";
3876
3910
  }
3877
3911
  }
3878
3912
  };
3913
+ async function mainRepository(executor, folder) {
3914
+ const common = await executor.execute(
3915
+ "git",
3916
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
3917
+ "read",
3918
+ folder
3919
+ );
3920
+ const commonDir = common.code === 0 ? common.stdout.trim() : "";
3921
+ if (basename4(commonDir) !== ".git") return null;
3922
+ const main = await realpath7(dirname4(commonDir));
3923
+ return main === await realpath7(folder) ? null : main;
3924
+ }
3879
3925
  async function readRecord(path) {
3880
3926
  try {
3881
3927
  const file = await open5(path, "r");
@@ -3914,8 +3960,13 @@ var HarnessRegistry = class {
3914
3960
  if (detection.signed_in === false) throw new HarnessRefusal("not_signed_in");
3915
3961
  return driver;
3916
3962
  }
3917
- setupInstructions() {
3918
- return Object.values(this.drivers).map((driver) => driver.repositorySetupInstruction);
3963
+ /** A harness's name as a person knows it, such as "Claude Code". */
3964
+ displayName = (harness) => this.get(harness).displayName;
3965
+ /** Every harness's one-time step for a newly registered folder. */
3966
+ repositorySetups(folder) {
3967
+ return Object.entries(this.drivers).map(
3968
+ ([harness, driver]) => ({ harness, ...driver.repositorySetup(folder) })
3969
+ );
3919
3970
  }
3920
3971
  async detect() {
3921
3972
  return Promise.all(Object.values(this.drivers).map((driver) => driver.detect()));
@@ -4068,12 +4119,12 @@ function fetchFailureCause(stderr) {
4068
4119
 
4069
4120
  // src/checkout.ts
4070
4121
  import { access as access2, appendFile as appendFile2, constants as constants4, mkdir as mkdir3, readFile as readFile4, realpath as realpath11 } from "node:fs/promises";
4071
- import { dirname as dirname5, resolve as resolve10 } from "node:path";
4122
+ import { dirname as dirname6, resolve as resolve10 } from "node:path";
4072
4123
 
4073
4124
  // src/checkout-includes.ts
4074
4125
  import { constants as constants3 } from "node:fs";
4075
4126
  import { appendFile, copyFile, lstat, mkdir as mkdir2, readFile as readFile3, realpath as realpath9 } from "node:fs/promises";
4076
- import { dirname as dirname4, posix as posix2, resolve as resolve8 } from "node:path";
4127
+ import { dirname as dirname5, posix as posix2, resolve as resolve8 } from "node:path";
4077
4128
  async function copyIncluded(git, folder, requireLive, prefix = "") {
4078
4129
  const include = resolve8(git.clone, ".worktreeinclude");
4079
4130
  try {
@@ -4097,11 +4148,11 @@ async function copyIncluded(git, folder, requireLive, prefix = "") {
4097
4148
  const clone = await realpath9(git.clone);
4098
4149
  const destinationRoot = await realpath9(folder);
4099
4150
  for (const name of result.stdout.split("\0").filter(Boolean)) {
4100
- const source2 = resolve8(clone, name);
4151
+ const source = resolve8(clone, name);
4101
4152
  const destinationName = posix2.join(prefix, name);
4102
4153
  const destination = resolve8(destinationRoot, destinationName);
4103
- if (!inside(clone, source2) || !inside(destinationRoot, destination)) continue;
4104
- if (!(await lstat(source2)).isFile() || !inside(clone, await realpath9(source2))) continue;
4154
+ if (!inside(clone, source) || !inside(destinationRoot, destination)) continue;
4155
+ if (!(await lstat(source)).isFile() || !inside(clone, await realpath9(source))) continue;
4105
4156
  if (await checkDestination(destinationRoot, destination)) continue;
4106
4157
  const tracked = await git.run(
4107
4158
  ["--literal-pathspecs", "ls-files", "--error-unmatch", "--", destinationName],
@@ -4112,16 +4163,16 @@ async function copyIncluded(git, folder, requireLive, prefix = "") {
4112
4163
  if (tracked.code !== 1) throw new Error("Cannot check included destination index");
4113
4164
  await ensureIgnored(git, folder, destinationName, requireLive);
4114
4165
  requireLive();
4115
- await mkdir2(dirname4(destination), { recursive: true });
4166
+ await mkdir2(dirname5(destination), { recursive: true });
4116
4167
  requireLive();
4117
- await copyFile(source2, destination, constants3.COPYFILE_EXCL).catch((error) => {
4168
+ await copyFile(source, destination, constants3.COPYFILE_EXCL).catch((error) => {
4118
4169
  if (!(error instanceof Error && "code" in error && error.code === "EEXIST"))
4119
4170
  throw error;
4120
4171
  });
4121
4172
  }
4122
4173
  }
4123
4174
  async function checkDestination(destinationRoot, destination) {
4124
- let parent = dirname4(destination);
4175
+ let parent = dirname5(destination);
4125
4176
  while (parent !== destinationRoot) {
4126
4177
  try {
4127
4178
  if (!inside(destinationRoot, await realpath9(parent)))
@@ -4131,7 +4182,7 @@ async function checkDestination(destinationRoot, destination) {
4131
4182
  if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
4132
4183
  throw error;
4133
4184
  }
4134
- parent = dirname4(parent);
4185
+ parent = dirname5(parent);
4135
4186
  }
4136
4187
  try {
4137
4188
  if ((await lstat(destination)).isSymbolicLink())
@@ -4153,7 +4204,7 @@ async function ensureIgnored(git, folder, name, requireLive) {
4153
4204
  const line = `/${name.replace(/[\\*?[\] ]/g, "\\$&")}`;
4154
4205
  if (!contents.split(/\r?\n/).includes(line)) {
4155
4206
  requireLive();
4156
- await mkdir2(dirname4(exclude), { recursive: true });
4207
+ await mkdir2(dirname5(exclude), { recursive: true });
4157
4208
  requireLive();
4158
4209
  await appendFile(exclude, `${contents && !contents.endsWith("\n") ? "\n" : ""}${line}
4159
4210
  `);
@@ -4301,7 +4352,7 @@ var CheckoutPreparer = class {
4301
4352
  if (!previous.worktreeFolder) throw new Error("Missing worktree root");
4302
4353
  const location = previous.location ?? "in_clone";
4303
4354
  root = {
4304
- folder: dirname5(previous.worktreeFolder),
4355
+ folder: dirname6(previous.worktreeFolder),
4305
4356
  location,
4306
4357
  setting: await this.previousSetting(clone, location)
4307
4358
  };
@@ -4461,7 +4512,7 @@ async function prepareRoot(git, root, top, requireLive) {
4461
4512
  });
4462
4513
  if (contents.split(/\r?\n/).includes(line)) return;
4463
4514
  requireLive();
4464
- await mkdir3(dirname5(exclude), { recursive: true });
4515
+ await mkdir3(dirname6(exclude), { recursive: true });
4465
4516
  requireLive();
4466
4517
  await appendFile2(exclude, `${contents.endsWith("\n") || !contents ? "" : "\n"}${line}
4467
4518
  `);
@@ -4523,14 +4574,110 @@ async function createBranch(git, context, requireLive) {
4523
4574
  return !local && !prior;
4524
4575
  }
4525
4576
 
4577
+ // src/cli-output.ts
4578
+ import { styleText } from "node:util";
4579
+ var MARKS = {
4580
+ pass: { glyph: "\u2713", format: "green" },
4581
+ fail: { glyph: "\u2717", format: "red" },
4582
+ wait: { glyph: "\u25CB", format: "yellow" },
4583
+ next: { glyph: "\u2192", format: "cyan" }
4584
+ };
4585
+ var heading = (text5) => ({ kind: "heading", text: text5 });
4586
+ var marked = (mark, text5, depth = 0) => ({
4587
+ kind: "marked",
4588
+ mark,
4589
+ text: text5,
4590
+ depth
4591
+ });
4592
+ var text4 = (value, depth = 0) => ({
4593
+ kind: "text",
4594
+ text: value,
4595
+ depth,
4596
+ muted: false
4597
+ });
4598
+ var note = (value, depth = 0) => ({
4599
+ kind: "text",
4600
+ text: value,
4601
+ depth,
4602
+ muted: true
4603
+ });
4604
+ var command = (value, depth = 0) => ({
4605
+ kind: "command",
4606
+ text: value,
4607
+ depth
4608
+ });
4609
+ var entry = (name, summary, width, depth = 0) => ({
4610
+ kind: "entry",
4611
+ name,
4612
+ summary,
4613
+ width,
4614
+ depth
4615
+ });
4616
+ var blank = { kind: "blank" };
4617
+ function nextLines(action, depth = 0) {
4618
+ return [marked("next", `${action.instruction}:`, depth), command(action.command, depth + 2)];
4619
+ }
4620
+ function colorEnabled(stream, env) {
4621
+ if (env["NO_COLOR"]) return false;
4622
+ const force = env["FORCE_COLOR"];
4623
+ if (force !== void 0) return force !== "0" && force !== "false";
4624
+ return stream.isTTY === true && stream.hasColors() === true;
4625
+ }
4626
+ function renderLines(lines, color) {
4627
+ const style = (format, value) => color ? styleText(format, value, { validateStream: false }) : value;
4628
+ return lines.map((line) => {
4629
+ if (line.kind === "blank") return "";
4630
+ if (line.kind === "heading") return style("bold", line.text);
4631
+ const indent = " ".repeat(line.depth);
4632
+ if (line.kind === "command") return indent + style("cyan", line.text);
4633
+ if (line.kind === "entry")
4634
+ return `${indent}${style("cyan", line.name.padEnd(line.width))} ${line.summary}`;
4635
+ if (line.kind === "text")
4636
+ return indent + (line.muted ? style("dim", line.text) : line.text);
4637
+ const mark = MARKS[line.mark];
4638
+ return `${indent}${style(mark.format, mark.glyph)} ${line.text}`;
4639
+ });
4640
+ }
4641
+ function writeLines(lines, stream = process.stdout, env = process.env) {
4642
+ if (lines.length === 0) return;
4643
+ stream.write(renderLines(lines, colorEnabled(stream, env)).join("\n") + "\n");
4644
+ }
4645
+ var ActionableError = class extends Error {
4646
+ constructor(message, next) {
4647
+ super(message);
4648
+ this.next = next;
4649
+ this.name = "ActionableError";
4650
+ }
4651
+ };
4652
+ var UsageError = class extends Error {
4653
+ constructor(usage) {
4654
+ super(`Usage: ${usage}`);
4655
+ this.usage = usage;
4656
+ this.name = "UsageError";
4657
+ }
4658
+ };
4659
+ function errorLines(error) {
4660
+ if (error instanceof UsageError)
4661
+ return [
4662
+ marked("fail", "That command takes different arguments. Usage:"),
4663
+ command(error.usage, 2),
4664
+ note("tsp-gateway --help lists every command.", 1)
4665
+ ];
4666
+ const message = error instanceof Error ? error.message : "Gateway could not complete the command";
4667
+ return [
4668
+ marked("fail", message),
4669
+ ...error instanceof ActionableError ? nextLines(error.next, 1) : []
4670
+ ];
4671
+ }
4672
+
4526
4673
  // src/checkout-config.ts
4527
4674
  import { realpath as realpath12 } from "node:fs/promises";
4528
4675
  import { resolve as resolve11 } from "node:path";
4529
4676
  async function configureWorktrees(config, path) {
4530
4677
  decodeWorktreeRoot(config.worktrees.root);
4531
- for (const entry of Object.values(config.repositories)) {
4532
- decodeWorktreeRoot(config.worktrees.root, entry.folder);
4533
- decodeWorktreeRoot(entry.worktreeRoot, entry.folder);
4678
+ for (const entry2 of Object.values(config.repositories)) {
4679
+ decodeWorktreeRoot(config.worktrees.root, entry2.folder);
4680
+ decodeWorktreeRoot(entry2.worktreeRoot, entry2.folder);
4534
4681
  }
4535
4682
  await saveConfig(path, config);
4536
4683
  }
@@ -4538,46 +4685,59 @@ var SETTING_SOURCE = {
4538
4685
  repository: "set for this repository with --repo",
4539
4686
  machine: "set for this machine"
4540
4687
  };
4541
- function source(root) {
4542
- return root?.setting ? SETTING_SOURCE[root.setting] : "the default inside the repository";
4688
+ function worktreeView(clone, root) {
4689
+ return {
4690
+ folder: root?.folder ?? UNRESOLVED_WORKTREE_ROOT,
4691
+ source: root?.setting ? SETTING_SOURCE[root.setting] : "the default inside the repository",
4692
+ outsideClone: root !== null && !inside(clone, root.folder)
4693
+ };
4694
+ }
4695
+ function worktreeLines(view, depth) {
4696
+ return [
4697
+ text4(`Worktrees: ${view.folder} (${view.source})`, depth),
4698
+ ...view.outsideClone ? [
4699
+ note(
4700
+ "Codex: trust the registered clone; linked worktrees inherit that trust.",
4701
+ depth
4702
+ )
4703
+ ] : []
4704
+ ];
4543
4705
  }
4544
- async function printWorktreeRoots(config, executor) {
4706
+ async function printWorktreeRoots(config, executor, print = (lines) => writeLines(lines)) {
4707
+ const lines = [];
4545
4708
  if (Object.keys(config.repositories).length === 0)
4546
- console.log(
4547
- `Worktree root for future clones: ${config.worktrees.root ?? UNRESOLVED_WORKTREE_ROOT}`
4548
- );
4549
- for (const entry of Object.values(config.repositories)) {
4550
- const root = await previewWorktreeRoot(executor, entry.folder, config);
4551
- console.log(
4552
- `Worktrees for ${entry.folder}: ${root?.folder ?? UNRESOLVED_WORKTREE_ROOT} (${source(root)})`
4709
+ lines.push(
4710
+ text4(
4711
+ `Worktrees for future clones: ${config.worktrees.root ?? UNRESOLVED_WORKTREE_ROOT}`
4712
+ )
4553
4713
  );
4554
- if (root && !inside(entry.folder, root.folder))
4555
- console.log("Codex: trust the registered clone; linked worktrees inherit that trust.");
4714
+ for (const entry2 of Object.values(config.repositories)) {
4715
+ const root = await previewWorktreeRoot(executor, entry2.folder, config);
4716
+ lines.push(heading(entry2.folder), ...worktreeLines(worktreeView(entry2.folder, root), 1));
4556
4717
  }
4718
+ print(lines);
4557
4719
  }
4558
4720
  function connectWorktreeArgs(args) {
4559
4721
  if (args.length <= 2) return args[1] ? { folder: args[1] } : {};
4560
4722
  if (args.length !== 4 || args[2] !== "--worktrees-root")
4561
- throw new Error("Usage: tsp-gateway connect [folder] [--worktrees-root <path>]");
4723
+ throw new UsageError("tsp-gateway connect [folder] [--worktrees-root <path>]");
4562
4724
  const root = decodeWorktreeRoot(args[3], resolve11(args[1]));
4563
4725
  if (root === null) throw new Error("A worktree root is required");
4564
4726
  return { folder: args[1], root };
4565
4727
  }
4566
4728
  async function setWorktreeRoot(config, path, args) {
4567
4729
  if (args[1] !== "worktrees-root" || !(args.length === 3 && !args[2].startsWith("--repo") || args.length === 5 && args[2] === "--repo"))
4568
- throw new Error(
4569
- "Usage: tsp-gateway config worktrees-root [--repo <folder>] <path|--reset>"
4570
- );
4730
+ throw new UsageError("tsp-gateway config worktrees-root [--repo <folder>] <path|--reset>");
4571
4731
  const value = args.at(-1);
4572
4732
  const root = value === "--reset" ? null : value;
4573
4733
  if (args.length === 5) {
4574
4734
  const folder = await realpath12(args[3]);
4575
- const entry = Object.values(config.repositories).find((entry2) => entry2.folder === folder);
4576
- if (!entry)
4735
+ const entry2 = Object.values(config.repositories).find((entry3) => entry3.folder === folder);
4736
+ if (!entry2)
4577
4737
  throw new Error(
4578
4738
  "Repository folder is not registered. Run tsp-gateway add <folder> first."
4579
4739
  );
4580
- entry.worktreeRoot = decodeWorktreeRoot(root, folder);
4740
+ entry2.worktreeRoot = decodeWorktreeRoot(root, folder);
4581
4741
  } else config.worktrees.root = decodeWorktreeRoot(root);
4582
4742
  await configureWorktrees(config, path);
4583
4743
  }
@@ -4593,13 +4753,13 @@ async function worktreesCommand({
4593
4753
  args
4594
4754
  }) {
4595
4755
  if (args[0] === "config") await setWorktreeRoot(config, paths.config, args);
4596
- else if (args.length !== 1) throw new Error("Usage: tsp-gateway worktrees");
4756
+ else if (args.length !== 1) throw new UsageError("tsp-gateway worktrees");
4597
4757
  await printWorktreeRoots(config, executor);
4598
4758
  }
4599
4759
 
4600
4760
  // src/command-lifetime.ts
4601
- function withdrawnReason(command) {
4602
- return command.kind === "launch" ? "launch_withdrawn" : "control_withdrawn";
4761
+ function withdrawnReason(command2) {
4762
+ return command2.kind === "launch" ? "launch_withdrawn" : "control_withdrawn";
4603
4763
  }
4604
4764
  var lifetimeClock = {
4605
4765
  monotonic: () => performance.now(),
@@ -4636,28 +4796,28 @@ var CommandLifetime = class {
4636
4796
  * Aborts `signal` and fails every later check of this launch or resume, or only holds an
4637
4797
  * uncertain one. Repeating it changes nothing.
4638
4798
  */
4639
- withdraw(command) {
4640
- if (command.kind === "stop" || this.held || this.withdrawal.signal.aborted) return;
4799
+ withdraw(command2) {
4800
+ if (command2.kind === "stop" || this.held || this.withdrawal.signal.aborted) return;
4641
4801
  if (this.uncertain) {
4642
4802
  this.held = true;
4643
4803
  return;
4644
4804
  }
4645
- this.withdrawal.abort(new HarnessRefusal(withdrawnReason(command)));
4805
+ this.withdrawal.abort(new HarnessRefusal(withdrawnReason(command2)));
4646
4806
  }
4647
- requireLive(command) {
4807
+ requireLive(command2) {
4648
4808
  if (this.withdrawal.signal.aborted) throw this.withdrawal.signal.reason;
4649
4809
  if (this.remaining() <= 0)
4650
4810
  throw new HarnessRefusal(
4651
- command.kind === "launch" ? "launch_expired" : "control_expired"
4811
+ command2.kind === "launch" ? "launch_expired" : "control_expired"
4652
4812
  );
4653
4813
  }
4654
4814
  /** The checks a command's harness effects run, carrying the withdrawal signal with them. */
4655
- check(command) {
4656
- return Object.assign(() => this.requireLive(command), {
4815
+ check(command2) {
4816
+ return Object.assign(() => this.requireLive(command2), {
4657
4817
  signal: this.withdrawal.signal,
4658
4818
  prompt: () => {
4659
- this.requireLive(command);
4660
- if (this.held) throw new HarnessRefusal(withdrawnReason(command));
4819
+ this.requireLive(command2);
4820
+ if (this.held) throw new HarnessRefusal(withdrawnReason(command2));
4661
4821
  }
4662
4822
  });
4663
4823
  }
@@ -4687,27 +4847,27 @@ var CommandLifetimes = class {
4687
4847
  constructor(journal, clock) {
4688
4848
  this.journal = journal;
4689
4849
  this.clock = clock;
4690
- for (const entry of journal.entries.values()) {
4691
- const { command } = entry;
4692
- const lifetime = new CommandLifetime(command.ttl_ms, clock, entry.lifetime);
4693
- this.lifetimes.set(command.command_id, lifetime);
4694
- if (entry.receipt === null && command.kind !== "stop") lifetime.uncertainStart();
4695
- if (command.kind === "stop") this.withdrawStarts(command);
4850
+ for (const entry2 of journal.entries.values()) {
4851
+ const { command: command2 } = entry2;
4852
+ const lifetime = new CommandLifetime(command2.ttl_ms, clock, entry2.lifetime);
4853
+ this.lifetimes.set(command2.command_id, lifetime);
4854
+ if (entry2.receipt === null && command2.kind !== "stop") lifetime.uncertainStart();
4855
+ if (command2.kind === "stop") this.withdrawStarts(command2);
4696
4856
  }
4697
4857
  }
4698
4858
  lifetimes = /* @__PURE__ */ new Map();
4699
4859
  /** Commands received but not journaled yet, so a Stop can withdraw a start still queued. */
4700
4860
  queued = /* @__PURE__ */ new Map();
4701
- receive(command) {
4702
- let lifetime = this.lifetimes.get(command.command_id);
4861
+ receive(command2) {
4862
+ let lifetime = this.lifetimes.get(command2.command_id);
4703
4863
  if (!lifetime) {
4704
- lifetime = new CommandLifetime(command.ttl_ms, this.clock);
4705
- this.lifetimes.set(command.command_id, lifetime);
4706
- if (!this.journal.entries.has(command.command_id))
4707
- this.queued.set(command.command_id, command);
4864
+ lifetime = new CommandLifetime(command2.ttl_ms, this.clock);
4865
+ this.lifetimes.set(command2.command_id, lifetime);
4866
+ if (!this.journal.entries.has(command2.command_id))
4867
+ this.queued.set(command2.command_id, command2);
4708
4868
  }
4709
- if (command.kind === "stop" && !this.journal.entries.get(command.command_id)?.receipt)
4710
- this.withdrawStarts(command);
4869
+ if (command2.kind === "stop" && !this.journal.entries.get(command2.command_id)?.receipt)
4870
+ this.withdrawStarts(command2);
4711
4871
  return lifetime;
4712
4872
  }
4713
4873
  /** The command left the queue; the journal holds it from here on. */
@@ -4715,10 +4875,10 @@ var CommandLifetimes = class {
4715
4875
  this.queued.delete(commandId);
4716
4876
  }
4717
4877
  retire(actionId) {
4718
- for (const { command } of this.journal.entries.values())
4719
- if (command.action_id === actionId) this.lifetimes.delete(command.command_id);
4720
- for (const [id, command] of this.queued)
4721
- if (command.action_id === actionId) {
4878
+ for (const { command: command2 } of this.journal.entries.values())
4879
+ if (command2.action_id === actionId) this.lifetimes.delete(command2.command_id);
4880
+ for (const [id, command2] of this.queued)
4881
+ if (command2.action_id === actionId) {
4722
4882
  this.queued.delete(id);
4723
4883
  this.lifetimes.delete(id);
4724
4884
  }
@@ -4726,10 +4886,10 @@ var CommandLifetimes = class {
4726
4886
  /** Withdraws every unfinished launch or resume of the Stop's action received before it. */
4727
4887
  withdrawStarts(stop) {
4728
4888
  for (const [id, lifetime] of this.lifetimes) {
4729
- const entry = this.journal.entries.get(id);
4730
- const command = entry?.command ?? this.queued.get(id);
4731
- if (command && command.kind !== "stop" && command.action_id === stop.action_id && !entry?.receipt)
4732
- lifetime.withdraw(command);
4889
+ const entry2 = this.journal.entries.get(id);
4890
+ const command2 = entry2?.command ?? this.queued.get(id);
4891
+ if (command2 && command2.kind !== "stop" && command2.action_id === stop.action_id && !entry2?.receipt)
4892
+ lifetime.withdraw(command2);
4733
4893
  }
4734
4894
  }
4735
4895
  };
@@ -4737,7 +4897,7 @@ var CommandLifetimes = class {
4737
4897
  // src/journal.ts
4738
4898
  import { createHash } from "node:crypto";
4739
4899
  import { open as open6, readFile as readFile5, truncate } from "node:fs/promises";
4740
- import { dirname as dirname6 } from "node:path";
4900
+ import { dirname as dirname7 } from "node:path";
4741
4901
 
4742
4902
  // src/journal-codec.ts
4743
4903
  import { isAbsolute as isAbsolute9 } from "node:path";
@@ -4798,17 +4958,17 @@ function readCommand(value, version) {
4798
4958
  throw new Error("Invalid stored operation");
4799
4959
  }
4800
4960
  }
4801
- function checkIdentity(row, command) {
4961
+ function checkIdentity(row, command2) {
4802
4962
  for (const key of ["action_id", "command_id"]) {
4803
4963
  const value = field(row, key);
4804
- if (value !== void 0 && value !== command[key])
4964
+ if (value !== void 0 && value !== command2[key])
4805
4965
  throw new Error("Invalid stored identity");
4806
4966
  }
4807
4967
  }
4808
- function readReceipt(value, command) {
4968
+ function readReceipt(value, command2) {
4809
4969
  if (value === null) return null;
4810
4970
  const row = object(value);
4811
- checkIdentity(row, command);
4971
+ checkIdentity(row, command2);
4812
4972
  switch (field(row, "kind")) {
4813
4973
  case "ack":
4814
4974
  return { kind: "ack" };
@@ -4830,10 +4990,10 @@ function readAttachHint(value) {
4830
4990
  throw new Error("Invalid attach session reference");
4831
4991
  return { harness: member2(field(row, "harness"), Object.values(HARNESS_KIND)), session_ref };
4832
4992
  }
4833
- function readObservation(value, command) {
4993
+ function readObservation(value, command2) {
4834
4994
  if (value === null) return null;
4835
4995
  const row = object(value);
4836
- checkIdentity(row, command);
4996
+ checkIdentity(row, command2);
4837
4997
  return {
4838
4998
  checkout: decodeCheckoutReport(field(row, "checkout")),
4839
4999
  session_ref: string(field(row, "session_ref")),
@@ -4848,11 +5008,11 @@ function readJournalEntry(value, folders = {}) {
4848
5008
  const row = object(value), version = field(row, "format_version");
4849
5009
  if (version !== void 0 && version !== 1 && version !== 2 && version !== 3)
4850
5010
  throw new Error("Unsupported journal format");
4851
- const command = readCommand(field(row, "command"), version);
5011
+ const command2 = readCommand(field(row, "command"), version);
4852
5012
  const lifetime = object(field(row, "lifetime"));
4853
- const receipt = readReceipt(field(row, "receipt"), command);
5013
+ const receipt = readReceipt(field(row, "receipt"), command2);
4854
5014
  if (receipt?.kind === "refused") validateRefusalDetail(receipt.reason, receipt.detail);
4855
- const update = readObservation(field(row, "update"), command);
5015
+ const update = readObservation(field(row, "update"), command2);
4856
5016
  const rawRefs = field(row, "observedRefs");
4857
5017
  if (!Array.isArray(rawRefs)) throw new Error("Invalid stored observations");
4858
5018
  const observedRefs = rawRefs.map((ref) => string(ref));
@@ -4861,16 +5021,16 @@ function readJournalEntry(value, folders = {}) {
4861
5021
  throw new Error("Invalid stored attempts");
4862
5022
  const envelope = {
4863
5023
  protocol_version: GATEWAY_PROTOCOL_VERSION,
4864
- action_id: command.action_id
5024
+ action_id: command2.action_id
4865
5025
  };
4866
5026
  return {
4867
- checkout: version === 3 ? readPrepared(field(row, "checkout")) : legacyPrepared(command, folders),
5027
+ checkout: version === 3 ? readPrepared(field(row, "checkout")) : legacyPrepared(command2, folders),
4868
5028
  lifetime: {
4869
5029
  remainingMs: nonnegative(field(lifetime, "remainingMs")),
4870
5030
  savedAtMs: nonnegative(field(lifetime, "savedAtMs"))
4871
5031
  },
4872
- command: { ...command, protocol_version: GATEWAY_PROTOCOL_VERSION },
4873
- receipt: receipt && { ...receipt, ...envelope, command_id: command.command_id },
5032
+ command: { ...command2, protocol_version: GATEWAY_PROTOCOL_VERSION },
5033
+ receipt: receipt && { ...receipt, ...envelope, command_id: command2.command_id },
4874
5034
  update: update && {
4875
5035
  ...update,
4876
5036
  ...envelope,
@@ -4881,15 +5041,15 @@ function readJournalEntry(value, folders = {}) {
4881
5041
  attempts
4882
5042
  };
4883
5043
  }
4884
- function storeJournalEntry(entry) {
4885
- const { protocol_version: _version, ...command } = entry.command;
4886
- const receipt = entry.receipt;
4887
- const update = entry.update;
5044
+ function storeJournalEntry(entry2) {
5045
+ const { protocol_version: _version, ...command2 } = entry2.command;
5046
+ const receipt = entry2.receipt;
5047
+ const update = entry2.update;
4888
5048
  return {
4889
5049
  format_version: 3,
4890
- checkout: entry.checkout,
4891
- lifetime: entry.lifetime,
4892
- command,
5050
+ checkout: entry2.checkout,
5051
+ lifetime: entry2.lifetime,
5052
+ command: command2,
4893
5053
  receipt: receipt === null ? null : receipt.kind === "refused" ? { kind: "refused", reason: receipt.reason, detail: receipt.detail ?? null } : { kind: "ack" },
4894
5054
  update: update && {
4895
5055
  checkout: update.checkout ?? null,
@@ -4900,9 +5060,9 @@ function storeJournalEntry(entry) {
4900
5060
  attach_hint: update.attach_hint ?? null,
4901
5061
  resumed_as: update.resumed_as ?? null
4902
5062
  },
4903
- conversationId: entry.conversationId,
4904
- observedRefs: entry.observedRefs,
4905
- attempts: entry.attempts
5063
+ conversationId: entry2.conversationId,
5064
+ observedRefs: entry2.observedRefs,
5065
+ attempts: entry2.attempts
4906
5066
  };
4907
5067
  }
4908
5068
  function readPrepared(value) {
@@ -4929,9 +5089,9 @@ function readPrepared(value) {
4929
5089
  sharesCheckout: boolean("sharesCheckout")
4930
5090
  };
4931
5091
  }
4932
- function legacyPrepared(command, folders) {
4933
- if (command.kind !== "launch") return null;
4934
- const folder = folders[repositoryKey(command.repository)];
5092
+ function legacyPrepared(command2, folders) {
5093
+ if (command2.kind !== "launch") return null;
5094
+ const folder = folders[repositoryKey(command2.repository)];
4935
5095
  if (!folder) return null;
4936
5096
  return {
4937
5097
  folder,
@@ -4960,11 +5120,11 @@ function canonical(value) {
4960
5120
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(field(value, key))}`).join(",")}}`;
4961
5121
  return JSON.stringify(value);
4962
5122
  }
4963
- function commandDigest(command) {
5123
+ function commandDigest(command2) {
4964
5124
  const identity2 = {
4965
- ...command,
5125
+ ...command2,
4966
5126
  ttl_ms: null,
4967
- ...command.kind === "resume" ? { text: command.text ?? null } : {}
5127
+ ...command2.kind === "resume" ? { text: command2.text ?? null } : {}
4968
5128
  };
4969
5129
  return createHash("sha256").update(canonical(identity2)).digest("hex");
4970
5130
  }
@@ -4976,7 +5136,7 @@ var Journal = class {
4976
5136
  unreadableCommandIds = /* @__PURE__ */ new Set();
4977
5137
  unreadableRows = [];
4978
5138
  async load(folders = {}) {
4979
- await privateDirectory(dirname6(this.path));
5139
+ await privateDirectory(dirname7(this.path));
4980
5140
  let bytes;
4981
5141
  try {
4982
5142
  bytes = await readFile5(this.path);
@@ -4991,9 +5151,9 @@ var Journal = class {
4991
5151
  let value;
4992
5152
  try {
4993
5153
  value = parseJson(line);
4994
- const entry = readJournalEntry(value, folders);
5154
+ const entry2 = readJournalEntry(value, folders);
4995
5155
  upgrade ||= isObject(value) && field(value, "format_version") !== 3;
4996
- this.entries.set(entry.command.command_id, entry);
5156
+ this.entries.set(entry2.command.command_id, entry2);
4997
5157
  } catch {
4998
5158
  this.quarantine(line, value);
4999
5159
  console.error("TSP gateway skipped an unreadable journal entry.");
@@ -5002,40 +5162,40 @@ var Journal = class {
5002
5162
  if (!upgrade) return;
5003
5163
  await privateWrite(
5004
5164
  this.path,
5005
- [...this.entries.values()].map((entry) => JSON.stringify(storeJournalEntry(entry)) + "\n").join("") + this.unreadableRows.map((row) => row.line + "\n").join("")
5165
+ [...this.entries.values()].map((entry2) => JSON.stringify(storeJournalEntry(entry2)) + "\n").join("") + this.unreadableRows.map((row) => row.line + "\n").join("")
5006
5166
  );
5007
5167
  }
5008
5168
  quarantine(line, value) {
5009
- const command = isObject(value) ? field(value, "command") : null;
5010
- const id = isObject(command) ? field(command, "command_id") : null;
5011
- const action = isObject(command) ? field(command, "action_id") : null;
5169
+ const command2 = isObject(value) ? field(value, "command") : null;
5170
+ const id = isObject(command2) ? field(command2, "command_id") : null;
5171
+ const action = isObject(command2) ? field(command2, "action_id") : null;
5012
5172
  if (typeof id === "string") this.unreadableCommandIds.add(id);
5013
5173
  this.unreadableRows.push({ line, actionId: typeof action === "string" ? action : null });
5014
5174
  }
5015
5175
  async retire(actionId) {
5016
5176
  const retained = [...this.entries.values()].filter(
5017
- (entry) => entry.command.action_id !== actionId
5177
+ (entry2) => entry2.command.action_id !== actionId
5018
5178
  );
5019
5179
  const unreadable = this.unreadableRows.filter((row) => row.actionId !== actionId);
5020
5180
  await privateWrite(
5021
5181
  this.path,
5022
- retained.map((entry) => JSON.stringify(storeJournalEntry(entry)) + "\n").join("") + unreadable.map((row) => row.line + "\n").join("")
5182
+ retained.map((entry2) => JSON.stringify(storeJournalEntry(entry2)) + "\n").join("") + unreadable.map((row) => row.line + "\n").join("")
5023
5183
  );
5024
5184
  this.unreadableRows = unreadable;
5025
- for (const [id, entry] of this.entries) {
5026
- if (entry.command.action_id === actionId) this.entries.delete(id);
5185
+ for (const [id, entry2] of this.entries) {
5186
+ if (entry2.command.action_id === actionId) this.entries.delete(id);
5027
5187
  }
5028
5188
  }
5029
- async append(entry) {
5189
+ async append(entry2) {
5030
5190
  const handle = await open6(this.path, "a", 384);
5031
5191
  try {
5032
5192
  await handle.chmod(384);
5033
- await handle.writeFile(JSON.stringify(storeJournalEntry(entry)) + "\n");
5193
+ await handle.writeFile(JSON.stringify(storeJournalEntry(entry2)) + "\n");
5034
5194
  await handle.sync();
5035
5195
  } finally {
5036
5196
  await handle.close();
5037
5197
  }
5038
- this.entries.set(entry.command.command_id, entry);
5198
+ this.entries.set(entry2.command.command_id, entry2);
5039
5199
  }
5040
5200
  };
5041
5201
 
@@ -5075,12 +5235,12 @@ async function stopUntilSettled(driver, session, folder, requireLive, settleMs)
5075
5235
  await delay3(STOP_POLL_MS);
5076
5236
  }
5077
5237
  }
5078
- function stopUnstarted(journal, command) {
5238
+ function stopUnstarted(journal, command2) {
5079
5239
  const launches = [...journal.entries.values()].filter(
5080
- (entry) => entry.command.action_id === command.action_id && entry.command.kind === "launch"
5240
+ (entry2) => entry2.command.action_id === command2.action_id && entry2.command.kind === "launch"
5081
5241
  );
5082
5242
  if (launches.length === 0) throw new HarnessRefusal("session_not_found");
5083
- if (launches.some((entry) => entry.receipt === null))
5243
+ if (launches.some((entry2) => entry2.receipt === null))
5084
5244
  throw new Error("The launch this Stop withdrew is still settling");
5085
5245
  return { update: null, conversationId: null };
5086
5246
  }
@@ -5093,12 +5253,12 @@ async function findSession(driver, ref, folder, requireLive) {
5093
5253
  }
5094
5254
  async function launchSession(journal, request) {
5095
5255
  const { driver, intent, folder, retry, knownRef, requireLive } = request;
5096
- const command = intent.command;
5097
- if (command.kind !== "launch") throw new HarnessRefusal("unsupported_command");
5256
+ const command2 = intent.command;
5257
+ if (command2.kind !== "launch") throw new HarnessRefusal("unsupported_command");
5098
5258
  if (driver.reconcileLaunch) {
5099
- for (const entry of journal.entries.values()) {
5100
- if (entry.command.kind === "launch" && entry.command.action_id === command.action_id && entry.observedRefs.length > intent.observedRefs.length)
5101
- intent.observedRefs = [...entry.observedRefs];
5259
+ for (const entry2 of journal.entries.values()) {
5260
+ if (entry2.command.kind === "launch" && entry2.command.action_id === command2.action_id && entry2.observedRefs.length > intent.observedRefs.length)
5261
+ intent.observedRefs = [...entry2.observedRefs];
5102
5262
  }
5103
5263
  await journal.append(intent);
5104
5264
  }
@@ -5111,7 +5271,7 @@ async function launchSession(journal, request) {
5111
5271
  if (saved && !knownRef) {
5112
5272
  session = await driver.reconcileLaunch(
5113
5273
  saved,
5114
- command,
5274
+ command2,
5115
5275
  folder,
5116
5276
  requireLive,
5117
5277
  request.beforeStart
@@ -5120,10 +5280,10 @@ async function launchSession(journal, request) {
5120
5280
  const sessions = await driver.list(
5121
5281
  folder,
5122
5282
  requireLive,
5123
- knownRef ? { refs: [knownRef] } : { name: command.session_name }
5283
+ knownRef ? { refs: [knownRef] } : { name: command2.session_name }
5124
5284
  );
5125
5285
  const matching = sessions.filter(
5126
- (row) => knownRef ? row.id === knownRef : row.name === command.session_name
5286
+ (row) => knownRef ? row.id === knownRef : row.name === command2.session_name
5127
5287
  );
5128
5288
  if (matching.length > 1) throw new HarnessRefusal("start_uncertain");
5129
5289
  session = matching[0];
@@ -5132,7 +5292,7 @@ async function launchSession(journal, request) {
5132
5292
  await checkpoint(session.id);
5133
5293
  session = await driver.reconcileLaunch(
5134
5294
  session.id,
5135
- command,
5295
+ command2,
5136
5296
  folder,
5137
5297
  requireLive,
5138
5298
  request.beforeStart
@@ -5144,18 +5304,18 @@ async function launchSession(journal, request) {
5144
5304
  promptCheck(requireLive)();
5145
5305
  const preparedFolder = await request.beforeStart();
5146
5306
  promptCheck(requireLive)();
5147
- const ref = await driver.start(command, preparedFolder, requireLive, checkpoint);
5307
+ const ref = await driver.start(command2, preparedFolder, requireLive, checkpoint);
5148
5308
  return { ref };
5149
5309
  }
5150
5310
  async function resumeSession(journal, request) {
5151
5311
  const { driver, intent, session, folder, retry, requireLive } = request;
5152
- const command = intent.command;
5153
- if (command.kind !== "resume") throw new HarnessRefusal("unsupported_command");
5312
+ const command2 = intent.command;
5313
+ if (command2.kind !== "resume") throw new HarnessRefusal("unsupported_command");
5154
5314
  if (driver.resumeRecovery) {
5155
5315
  if (retry && intent.conversationId !== null)
5156
5316
  return driver.resumeRecovery.reconcile(
5157
5317
  session,
5158
- command.text ?? null,
5318
+ command2.text ?? null,
5159
5319
  intent.observedRefs,
5160
5320
  folder,
5161
5321
  requireLive
@@ -5164,7 +5324,7 @@ async function resumeSession(journal, request) {
5164
5324
  intent.conversationId = session.conversationId;
5165
5325
  await journal.append(intent);
5166
5326
  promptCheck(requireLive)();
5167
- return driver.resume(session, command.text ?? null, folder, requireLive);
5327
+ return driver.resume(session, command2.text ?? null, folder, requireLive);
5168
5328
  }
5169
5329
  const sessions = await driver.list(folder);
5170
5330
  if (retry) {
@@ -5178,7 +5338,7 @@ async function resumeSession(journal, request) {
5178
5338
  intent.observedRefs = sessions.filter((row) => row.conversationId === session.conversationId).map((row) => row.id);
5179
5339
  await journal.append({ ...intent, conversationId: session.conversationId });
5180
5340
  promptCheck(requireLive)();
5181
- return await driver.resume(session, command.text ?? null, folder, requireLive);
5341
+ return await driver.resume(session, command2.text ?? null, folder, requireLive);
5182
5342
  }
5183
5343
  async function observeSessions(drivers, contexts, activity = false) {
5184
5344
  const contextList = [...contexts];
@@ -5248,19 +5408,19 @@ function unreadState(binding) {
5248
5408
  }
5249
5409
 
5250
5410
  // src/command-bindings.ts
5251
- function rememberBinding(entry, previous) {
5252
- const { command, update } = entry;
5253
- if (!update || !entry.checkout && !previous) return void 0;
5411
+ function rememberBinding(entry2, previous) {
5412
+ const { command: command2, update } = entry2;
5413
+ if (!update || !entry2.checkout && !previous) return void 0;
5254
5414
  return {
5255
- harness: command.kind === "launch" ? command.harness : previous.harness,
5256
- folder: entry.checkout?.folder ?? previous.folder,
5257
- checkout: entry.checkout ? checkoutReport(entry.checkout) : previous?.checkout,
5415
+ harness: command2.kind === "launch" ? command2.harness : previous.harness,
5416
+ folder: entry2.checkout?.folder ?? previous.folder,
5417
+ checkout: entry2.checkout ? checkoutReport(entry2.checkout) : previous?.checkout,
5258
5418
  state: update.state,
5259
5419
  missingPolls: 0,
5260
5420
  unreadablePolls: 0,
5261
- repository: command.kind === "launch" ? repositoryKey(command.repository) : previous.repository,
5421
+ repository: command2.kind === "launch" ? repositoryKey(command2.repository) : previous.repository,
5262
5422
  ref: update.resumed_as ?? update.session_ref,
5263
- conversationId: entry.conversationId
5423
+ conversationId: entry2.conversationId
5264
5424
  };
5265
5425
  }
5266
5426
 
@@ -5276,29 +5436,29 @@ async function prepareLaunchCheckout({
5276
5436
  }) {
5277
5437
  const entries = [...journal.entries.values()];
5278
5438
  const launch = intent.command.kind === "resume" ? entries.find(
5279
- (entry) => entry.command.action_id === intent.command.action_id && entry.command.kind === "launch"
5439
+ (entry2) => entry2.command.action_id === intent.command.action_id && entry2.command.kind === "launch"
5280
5440
  ) : intent;
5281
- const command = launch?.command;
5282
- if (command?.kind !== "launch") throw new HarnessRefusal("unsupported_command");
5441
+ const command2 = launch?.command;
5442
+ if (command2?.kind !== "launch") throw new HarnessRefusal("unsupported_command");
5283
5443
  if (!intent.checkout) {
5284
- const previous = entries.reverse().find((entry) => entry.command.action_id === command.action_id && entry.checkout);
5444
+ const previous = entries.reverse().find((entry2) => entry2.command.action_id === command2.action_id && entry2.checkout);
5285
5445
  if (previous?.checkout) {
5286
5446
  intent.checkout = previous.checkout;
5287
5447
  await journal.append(intent);
5288
5448
  }
5289
5449
  }
5290
5450
  if (!intent.checkout || revalidate) {
5291
- const clone = intent.checkout?.clone ?? (await repositories())[launchRepositoryKey(command.repository)];
5451
+ const clone = intent.checkout?.clone ?? (await repositories())[launchRepositoryKey(command2.repository)];
5292
5452
  if (!clone) throw new HarnessRefusal("repository_not_registered");
5293
5453
  intent.checkout = await checkout.prepare({
5294
- checkout: command.checkout,
5295
- repository: command.repository,
5454
+ checkout: command2.checkout,
5455
+ repository: command2.repository,
5296
5456
  clone,
5297
5457
  live: {
5298
5458
  folders: () => [
5299
5459
  ...[...bindings.values()].filter((binding) => !isTerminalSessionState(binding.state)).map((binding) => binding.folder),
5300
5460
  ...[...journal.entries.values()].flatMap(
5301
- (entry) => (entry.command.kind === "launch" || entry.command.kind === "resume") && entry.command.command_id !== intent.command.command_id && entry.receipt === null && entry.checkout && (!entry.update || !isTerminalSessionState(entry.update.state)) ? [entry.checkout.folder] : []
5461
+ (entry2) => (entry2.command.kind === "launch" || entry2.command.kind === "resume") && entry2.command.command_id !== intent.command.command_id && entry2.receipt === null && entry2.checkout && (!entry2.update || !isTerminalSessionState(entry2.update.state)) ? [entry2.checkout.folder] : []
5302
5462
  )
5303
5463
  ]
5304
5464
  },
@@ -5311,18 +5471,18 @@ async function prepareLaunchCheckout({
5311
5471
  }
5312
5472
 
5313
5473
  // src/command-identity.ts
5314
- function hasUncertainLaunch(journal, command) {
5474
+ function hasUncertainLaunch(journal, command2) {
5315
5475
  const earlier = [...journal.entries.values()].filter(
5316
- (entry) => entry.command.action_id === command.action_id && entry.command.command_id !== command.command_id && entry.command.kind === "launch"
5476
+ (entry2) => entry2.command.action_id === command2.action_id && entry2.command.command_id !== command2.command_id && entry2.command.kind === "launch"
5317
5477
  );
5318
- for (const entry of earlier) {
5319
- if (entry.command.kind === "launch" && (entry.command.seed !== command.seed || entry.command.harness !== command.harness || repositoryKey(entry.command.repository) !== repositoryKey(command.repository) || JSON.stringify(entry.command.checkout) !== JSON.stringify(command.checkout)))
5478
+ for (const entry2 of earlier) {
5479
+ if (entry2.command.kind === "launch" && (entry2.command.seed !== command2.seed || entry2.command.harness !== command2.harness || repositoryKey(entry2.command.repository) !== repositoryKey(command2.repository) || JSON.stringify(entry2.command.checkout) !== JSON.stringify(command2.checkout)))
5320
5480
  throw new Error("Action identity conflict");
5321
5481
  }
5322
- return earlier.some((entry) => entry.receipt === null && entry.checkout !== null);
5482
+ return earlier.some((entry2) => entry2.receipt === null && entry2.checkout !== null);
5323
5483
  }
5324
- function startsAsRetry(journal, command, previous) {
5325
- return command.kind === "launch" ? Boolean(previous?.checkout) || hasUncertainLaunch(journal, command) : Boolean(previous);
5484
+ function startsAsRetry(journal, command2, previous) {
5485
+ return command2.kind === "launch" ? Boolean(previous?.checkout) || hasUncertainLaunch(journal, command2) : Boolean(previous);
5326
5486
  }
5327
5487
 
5328
5488
  // src/command-observation.ts
@@ -5351,8 +5511,8 @@ var STARTUP_REASONS = {
5351
5511
  exited: "shell_startup_failed",
5352
5512
  folder_unavailable: "repository_folder_unavailable"
5353
5513
  };
5354
- function unreadableCommandRefusal(command) {
5355
- return new HarnessRefusal(command.kind === "stop" ? "stop_failed" : "start_uncertain");
5514
+ function unreadableCommandRefusal(command2) {
5515
+ return new HarnessRefusal(command2.kind === "stop" ? "stop_failed" : "start_uncertain");
5356
5516
  }
5357
5517
  function provenRefusal(error, retry) {
5358
5518
  if (error instanceof HarnessRefusal) return error;
@@ -5377,7 +5537,7 @@ var Commands = class {
5377
5537
  })
5378
5538
  );
5379
5539
  this.lifetimes = new CommandLifetimes(journal, options.clock ?? lifetimeClock);
5380
- for (const entry of journal.entries.values()) this.remember(entry);
5540
+ for (const entry2 of journal.entries.values()) this.remember(entry2);
5381
5541
  }
5382
5542
  stopSettleMs;
5383
5543
  activity;
@@ -5386,12 +5546,12 @@ var Commands = class {
5386
5546
  lifetimes;
5387
5547
  resolutions = /* @__PURE__ */ new Map();
5388
5548
  /** Called at socket receipt, before joining the serial work queue. A Stop withdraws its action's start at once. */
5389
- receive(command) {
5390
- return this.lifetimes.receive(command);
5549
+ receive(command2) {
5550
+ return this.lifetimes.receive(command2);
5391
5551
  }
5392
- remember(entry) {
5393
- const action = entry.command.action_id;
5394
- const binding = rememberBinding(entry, this.bindings.get(action));
5552
+ remember(entry2) {
5553
+ const action = entry2.command.action_id;
5554
+ const binding = rememberBinding(entry2, this.bindings.get(action));
5395
5555
  if (binding) this.bindings.set(action, binding);
5396
5556
  }
5397
5557
  update(harness, action, ref, state, resumedAs) {
@@ -5400,18 +5560,18 @@ var Commands = class {
5400
5560
  checkout: this.bindings.get(action)?.checkout ?? null
5401
5561
  };
5402
5562
  }
5403
- async process(command, accept) {
5404
- const previous = this.journal.entries.get(command.command_id);
5405
- if (previous && commandDigest(previous.command) !== commandDigest(command))
5563
+ async process(command2, accept) {
5564
+ const previous = this.journal.entries.get(command2.command_id);
5565
+ if (previous && commandDigest(previous.command) !== commandDigest(command2))
5406
5566
  throw new Error("Command identity conflict");
5407
- if (previous?.receipt && !this.resolutions.has(command.command_id))
5567
+ if (previous?.receipt && !this.resolutions.has(command2.command_id))
5408
5568
  return await this.replay(previous);
5409
- const lifetime = this.receive(command);
5410
- const decision = this.resolutions.get(command.command_id) ?? (lifetime.remaining() > 0 ? await accept(command, lifetime.remaining()) : true);
5569
+ const lifetime = this.receive(command2);
5570
+ const decision = this.resolutions.get(command2.command_id) ?? (lifetime.remaining() > 0 ? await accept(command2, lifetime.remaining()) : true);
5411
5571
  if (decision === false) return [];
5412
5572
  const intent = {
5413
5573
  ...previous ?? {
5414
- command,
5574
+ command: command2,
5415
5575
  checkout: null,
5416
5576
  receipt: null,
5417
5577
  update: null,
@@ -5422,29 +5582,29 @@ var Commands = class {
5422
5582
  lifetime: lifetime.checkpoint()
5423
5583
  };
5424
5584
  if (decision !== true) {
5425
- this.resolutions.set(command.command_id, decision);
5585
+ this.resolutions.set(command2.command_id, decision);
5426
5586
  await this.journal.append({ ...intent, receipt: decision });
5427
- this.resolutions.delete(command.command_id);
5587
+ this.resolutions.delete(command2.command_id);
5428
5588
  return [];
5429
5589
  }
5430
5590
  await this.journal.append(intent);
5431
5591
  let update = null, conversationId = intent.conversationId;
5432
5592
  let receipt;
5433
- this.lifetimes.dequeued(command.command_id);
5593
+ this.lifetimes.dequeued(command2.command_id);
5434
5594
  try {
5435
- const retry = startsAsRetry(this.journal, command, previous);
5595
+ const retry = startsAsRetry(this.journal, command2, previous);
5436
5596
  if (retry) lifetime.uncertainStart();
5437
- else lifetime.requireLive(command);
5438
- if (this.journal.unreadableCommandIds.has(command.command_id))
5439
- throw unreadableCommandRefusal(command);
5440
- const result = command.kind === "launch" ? await this.launch(intent, retry, lifetime) : await this.control(intent, retry, lifetime);
5597
+ else lifetime.requireLive(command2);
5598
+ if (this.journal.unreadableCommandIds.has(command2.command_id))
5599
+ throw unreadableCommandRefusal(command2);
5600
+ const result = command2.kind === "launch" ? await this.launch(intent, retry, lifetime) : await this.control(intent, retry, lifetime);
5441
5601
  update = result.update;
5442
5602
  conversationId = result.conversationId;
5443
5603
  receipt = {
5444
5604
  kind: "ack",
5445
5605
  protocol_version: GATEWAY_PROTOCOL_VERSION,
5446
- command_id: command.command_id,
5447
- action_id: command.action_id
5606
+ command_id: command2.command_id,
5607
+ action_id: command2.action_id
5448
5608
  };
5449
5609
  } catch (error) {
5450
5610
  const refusal = provenRefusal(error, Boolean(previous));
@@ -5452,15 +5612,15 @@ var Commands = class {
5452
5612
  receipt = {
5453
5613
  kind: "refused",
5454
5614
  protocol_version: GATEWAY_PROTOCOL_VERSION,
5455
- command_id: command.command_id,
5456
- action_id: command.action_id,
5615
+ command_id: command2.command_id,
5616
+ action_id: command2.action_id,
5457
5617
  reason: refusal.reason,
5458
5618
  detail: refusalDetail(refusal, intent.checkout)
5459
5619
  };
5460
5620
  }
5461
5621
  const outcome = {
5462
5622
  checkout: intent.checkout,
5463
- command,
5623
+ command: command2,
5464
5624
  receipt,
5465
5625
  update,
5466
5626
  conversationId,
@@ -5481,10 +5641,10 @@ var Commands = class {
5481
5641
  }
5482
5642
  return [receipt, ...update ? [update] : []];
5483
5643
  }
5484
- async replay(entry) {
5485
- if (!entry.receipt) throw new Error("Cannot replay an unfinished command");
5486
- const binding = this.bindings.get(entry.command.action_id);
5487
- if (entry.receipt.kind === "refused" || !binding) return [entry.receipt];
5644
+ async replay(entry2) {
5645
+ if (!entry2.receipt) throw new Error("Cannot replay an unfinished command");
5646
+ const binding = this.bindings.get(entry2.command.action_id);
5647
+ if (entry2.receipt.kind === "refused" || !binding) return [entry2.receipt];
5488
5648
  let rows;
5489
5649
  try {
5490
5650
  const folder = binding.folder;
@@ -5493,26 +5653,26 @@ var Commands = class {
5493
5653
  rows = [];
5494
5654
  }
5495
5655
  const row = rows.find((session) => session.id === binding.ref);
5496
- const prior = entry.update;
5656
+ const prior = entry2.update;
5497
5657
  const update = prior?.resumed_as === binding.ref ? this.update(
5498
5658
  binding.harness,
5499
- entry.command.action_id,
5659
+ entry2.command.action_id,
5500
5660
  prior.session_ref,
5501
5661
  row?.state ?? unreadState(binding),
5502
5662
  binding.ref
5503
5663
  ) : this.update(
5504
5664
  binding.harness,
5505
- entry.command.action_id,
5665
+ entry2.command.action_id,
5506
5666
  binding.ref,
5507
5667
  row?.state ?? unreadState(binding)
5508
5668
  );
5509
5669
  update.waiting_for = row?.waitingFor ?? null;
5510
- return this.emit(entry.receipt, update);
5670
+ return this.emit(entry2.receipt, update);
5511
5671
  }
5512
5672
  async launch(intent, retry, lifetime) {
5513
- const command = intent.command;
5514
- if (command.kind !== "launch") throw new HarnessRefusal("unsupported_command");
5515
- const requireLive = lifetime.check(command);
5673
+ const command2 = intent.command;
5674
+ if (command2.kind !== "launch") throw new HarnessRefusal("unsupported_command");
5675
+ const requireLive = lifetime.check(command2);
5516
5676
  const preparation = {
5517
5677
  journal: this.journal,
5518
5678
  checkout: this.checkout,
@@ -5522,9 +5682,9 @@ var Commands = class {
5522
5682
  requireLive
5523
5683
  };
5524
5684
  const folder = await prepareLaunchCheckout(preparation);
5525
- const driver = await lifetime.unlessWithdrawn(this.drivers.ready(command.harness, folder));
5526
- const known = this.bindings.get(command.action_id);
5527
- if (known && (known.repository !== repositoryKey(command.repository) || known.harness !== command.harness))
5685
+ const driver = await lifetime.unlessWithdrawn(this.drivers.ready(command2.harness, folder));
5686
+ const known = this.bindings.get(command2.action_id);
5687
+ if (known && (known.repository !== repositoryKey(command2.repository) || known.harness !== command2.harness))
5528
5688
  throw new Error("Action identity conflict");
5529
5689
  const { ref, session } = await launchSession(this.journal, {
5530
5690
  driver,
@@ -5536,8 +5696,8 @@ var Commands = class {
5536
5696
  requireLive
5537
5697
  });
5538
5698
  const update = this.update(
5539
- command.harness,
5540
- command.action_id,
5699
+ command2.harness,
5700
+ command2.action_id,
5541
5701
  ref,
5542
5702
  session?.state ?? "starting"
5543
5703
  );
@@ -5546,24 +5706,24 @@ var Commands = class {
5546
5706
  return { update, conversationId: session?.conversationId ?? null };
5547
5707
  }
5548
5708
  async control(intent, retry, lifetime) {
5549
- const command = intent.command;
5550
- if (command.kind !== "stop" && command.kind !== "resume")
5709
+ const command2 = intent.command;
5710
+ if (command2.kind !== "stop" && command2.kind !== "resume")
5551
5711
  throw new HarnessRefusal("unsupported_command");
5552
- const requireLive = lifetime.check(command);
5553
- const binding = this.bindings.get(command.action_id);
5554
- if (command.kind === "stop" && !command.session_ref && !binding)
5555
- return stopUnstarted(this.journal, command);
5556
- if (!binding || (command.session_ref ?? binding.ref) !== binding.ref)
5712
+ const requireLive = lifetime.check(command2);
5713
+ const binding = this.bindings.get(command2.action_id);
5714
+ if (command2.kind === "stop" && !command2.session_ref && !binding)
5715
+ return stopUnstarted(this.journal, command2);
5716
+ if (!binding || (command2.session_ref ?? binding.ref) !== binding.ref)
5557
5717
  throw new HarnessRefusal("session_not_found");
5558
5718
  const folder = binding.folder;
5559
5719
  if (!folder) throw new HarnessRefusal("repository_not_registered");
5560
5720
  const driver = this.drivers.get(binding.harness);
5561
5721
  const session = await findSession(driver, binding.ref, folder, requireLive);
5562
- if (command.kind === "stop")
5722
+ if (command2.kind === "stop")
5563
5723
  return {
5564
5724
  update: this.update(
5565
5725
  binding.harness,
5566
- command.action_id,
5726
+ command2.action_id,
5567
5727
  session.id,
5568
5728
  await stopUntilSettled(driver, session, folder, requireLive, this.stopSettleMs)
5569
5729
  ),
@@ -5587,7 +5747,7 @@ var Commands = class {
5587
5747
  });
5588
5748
  const update = this.update(
5589
5749
  binding.harness,
5590
- command.action_id,
5750
+ command2.action_id,
5591
5751
  session.id,
5592
5752
  "starting",
5593
5753
  ref === session.id ? void 0 : ref
@@ -5600,18 +5760,18 @@ var Commands = class {
5600
5760
  }
5601
5761
  /** A hub reconciliation also repairs receipts persisted by an older gateway. */
5602
5762
  async reconcile(receipt) {
5603
- const entry = this.journal.entries.get(receipt.command_id);
5604
- if (!entry) return;
5605
- if (entry.command.action_id !== receipt.action_id)
5763
+ const entry2 = this.journal.entries.get(receipt.command_id);
5764
+ if (!entry2) return;
5765
+ if (entry2.command.action_id !== receipt.action_id)
5606
5766
  throw new Error("Receipt identity conflict");
5607
5767
  this.resolutions.set(receipt.command_id, receipt);
5608
- await this.journal.append({ ...entry, receipt });
5768
+ await this.journal.append({ ...entry2, receipt });
5609
5769
  this.resolutions.delete(receipt.command_id);
5610
5770
  }
5611
5771
  async retire(actionId) {
5612
- for (const entry of this.journal.entries.values())
5613
- if (entry.command.action_id === actionId)
5614
- this.resolutions.delete(entry.command.command_id);
5772
+ for (const entry2 of this.journal.entries.values())
5773
+ if (entry2.command.action_id === actionId)
5774
+ this.resolutions.delete(entry2.command.command_id);
5615
5775
  this.lifetimes.retire(actionId);
5616
5776
  await this.journal.retire(actionId);
5617
5777
  this.bindings.delete(actionId);
@@ -5623,8 +5783,8 @@ var Commands = class {
5623
5783
  /** Replay every binding's latest receipt before polling, including terminal sessions. */
5624
5784
  durableReceipts() {
5625
5785
  const latest = /* @__PURE__ */ new Map();
5626
- for (const entry of this.journal.entries.values())
5627
- latest.set(entry.command.action_id, entry);
5786
+ for (const entry2 of this.journal.entries.values())
5787
+ latest.set(entry2.command.action_id, entry2);
5628
5788
  const receipts = [];
5629
5789
  for (const action of this.bindings.keys()) {
5630
5790
  const receipt = latest.get(action)?.receipt;
@@ -5637,7 +5797,7 @@ var Commands = class {
5637
5797
  }
5638
5798
  /** Unfinished durable operations are retried locally, even without hub redelivery. */
5639
5799
  get pendingIntents() {
5640
- return [...this.journal.entries.values()].filter((entry) => entry.receipt === null);
5800
+ return [...this.journal.entries.values()].filter((entry2) => entry2.receipt === null);
5641
5801
  }
5642
5802
  get hasLiveBindings() {
5643
5803
  return [...this.bindings.values()].some(
@@ -5677,7 +5837,7 @@ var Commands = class {
5677
5837
 
5678
5838
  // src/config-watch.ts
5679
5839
  import { statSync, watch } from "node:fs";
5680
- import { basename as basename4, dirname as dirname7 } from "node:path";
5840
+ import { basename as basename5, dirname as dirname8 } from "node:path";
5681
5841
  var watchDirectory = (directory, listener) => watch(directory, (_, filename) => listener(filename));
5682
5842
  function watchConfig(path, changed, options = {}) {
5683
5843
  let reported = identity(path);
@@ -5698,8 +5858,8 @@ function watchConfig(path, changed, options = {}) {
5698
5858
  if (pending === void 0 && identity(path) !== reported) settle();
5699
5859
  }, options.pollMs ?? 1e3);
5700
5860
  try {
5701
- watcher = (options.watchDirectory ?? watchDirectory)(dirname7(path), (filename) => {
5702
- if (filename === null || filename === basename4(path)) settle();
5861
+ watcher = (options.watchDirectory ?? watchDirectory)(dirname8(path), (filename) => {
5862
+ if (filename === null || filename === basename5(path)) settle();
5703
5863
  });
5704
5864
  watcher.on("error", () => watcher?.close());
5705
5865
  } catch {
@@ -5716,6 +5876,62 @@ function identity(path) {
5716
5876
  return stat5 === void 0 ? "absent" : `${stat5.ino}:${stat5.mtimeNs}:${stat5.size}`;
5717
5877
  }
5718
5878
 
5879
+ // src/connection-state.ts
5880
+ var START = {
5881
+ instruction: "Start the gateway now and at login",
5882
+ command: "tsp-gateway start"
5883
+ };
5884
+ var CONNECT = {
5885
+ instruction: "Connect this computer again",
5886
+ command: "tsp-gateway connect"
5887
+ };
5888
+ var CONNECTION = {
5889
+ connected: { message: "Connected", text: "Connected to TSP", mark: "pass" },
5890
+ starting: { message: "Starting", text: "Starting", mark: "wait" },
5891
+ reconnecting: { message: "Reconnecting", text: "Reconnecting to TSP", mark: "wait" },
5892
+ waiting: {
5893
+ message: "Waiting for the network or TSP. Retrying\u2026",
5894
+ text: "Waiting for the network or TSP. Retrying\u2026",
5895
+ mark: "wait"
5896
+ },
5897
+ notRunning: { message: "Not running", text: "Not running", mark: "fail", next: START },
5898
+ stopped: { message: "Stopped", text: "Not running", mark: "fail", next: START },
5899
+ refreshFailed: {
5900
+ message: "Token refresh failed. Run tsp-gateway connect again.",
5901
+ text: "TSP no longer accepts this computer's credential",
5902
+ mark: "fail",
5903
+ next: CONNECT
5904
+ },
5905
+ tokenRejected: {
5906
+ message: "Token rejected after refresh. Run tsp-gateway connect again.",
5907
+ text: "TSP rejected this computer's credential",
5908
+ mark: "fail",
5909
+ next: CONNECT
5910
+ },
5911
+ accessEnded: {
5912
+ message: "Machine access ended. Run tsp-gateway connect again.",
5913
+ text: "This computer's access to TSP ended",
5914
+ mark: "fail",
5915
+ next: CONNECT
5916
+ },
5917
+ outdated: {
5918
+ message: "This gateway is outdated. Run npx @treestructuredplanning/gateway@latest update.",
5919
+ text: "This gateway is outdated",
5920
+ mark: "fail",
5921
+ next: {
5922
+ instruction: "Update it",
5923
+ command: "npx -y @treestructuredplanning/gateway@latest update"
5924
+ }
5925
+ }
5926
+ };
5927
+ function connectionState(message) {
5928
+ return Object.values(CONNECTION).find((state) => state.message === message) ?? {
5929
+ message,
5930
+ text: message.replace(/\.+$/, ""),
5931
+ mark: "fail"
5932
+ };
5933
+ }
5934
+
5719
5935
  // src/launch-permits.ts
5720
5936
  var LaunchPermits = class {
5721
5937
  constructor(send, active, timeout) {
@@ -5724,7 +5940,7 @@ var LaunchPermits = class {
5724
5940
  this.timeout = timeout;
5725
5941
  }
5726
5942
  pending = null;
5727
- accept(command, remainingMs) {
5943
+ accept(command2, remainingMs) {
5728
5944
  return new Promise((resolve13) => {
5729
5945
  if (!this.active() || remainingMs <= 0) {
5730
5946
  resolve13(false);
@@ -5738,8 +5954,8 @@ var LaunchPermits = class {
5738
5954
  Math.max(1, Math.min(2e4, remainingMs))
5739
5955
  );
5740
5956
  this.pending = {
5741
- action: command.action_id,
5742
- command: command.command_id,
5957
+ action: command2.action_id,
5958
+ command: command2.command_id,
5743
5959
  resolve: (decision) => {
5744
5960
  clearTimeout(timer);
5745
5961
  this.pending = null;
@@ -5749,8 +5965,8 @@ var LaunchPermits = class {
5749
5965
  this.send({
5750
5966
  kind: "claim",
5751
5967
  protocol_version: GATEWAY_PROTOCOL_VERSION,
5752
- command_id: command.command_id,
5753
- action_id: command.action_id
5968
+ command_id: command2.command_id,
5969
+ action_id: command2.action_id
5754
5970
  });
5755
5971
  });
5756
5972
  }
@@ -5816,21 +6032,21 @@ function transportSender(socket, isActive) {
5816
6032
  };
5817
6033
  }
5818
6034
  function commandProcessor(commands, permits, retries, send) {
5819
- return async (command) => {
5820
- if (!retries.ready(command.command_id)) return;
6035
+ return async (command2) => {
6036
+ if (!retries.ready(command2.command_id)) return;
5821
6037
  let results;
5822
6038
  try {
5823
6039
  results = await commands.process(
5824
- command,
6040
+ command2,
5825
6041
  (operation, remainingMs) => permits.accept(operation, remainingMs)
5826
6042
  );
5827
6043
  } catch {
5828
6044
  console.error(
5829
- `TSP gateway command pending: kind=${command.kind} command_id=${command.command_id} action_id=${command.action_id}`
6045
+ `TSP gateway command pending: kind=${command2.kind} command_id=${command2.command_id} action_id=${command2.action_id}`
5830
6046
  );
5831
6047
  return;
5832
6048
  } finally {
5833
- retries.defer(command);
6049
+ retries.defer(command2);
5834
6050
  }
5835
6051
  for (const result of results) send(result);
5836
6052
  };
@@ -5962,7 +6178,7 @@ async function serve(options, socket, setup, refreshDue) {
5962
6178
  ready = true;
5963
6179
  readyAt = now();
5964
6180
  await polling.poll();
5965
- await status(true, "Connected");
6181
+ await status(true, CONNECTION.connected.message);
5966
6182
  });
5967
6183
  });
5968
6184
  socket.addEventListener("message", (event) => {
@@ -6049,9 +6265,9 @@ async function json(url, init) {
6049
6265
  return await response.json();
6050
6266
  }
6051
6267
  function requiredText(value, key) {
6052
- const text4 = isObject(value) ? field(value, key) : null;
6053
- if (typeof text4 !== "string" || !text4) throw new Error("Invalid OAuth response");
6054
- return text4;
6268
+ const text5 = isObject(value) ? field(value, key) : null;
6269
+ if (typeof text5 !== "string" || !text5) throw new Error("Invalid OAuth response");
6270
+ return text5;
6055
6271
  }
6056
6272
  async function discover(origin) {
6057
6273
  const value = await json(`${validateOrigin(origin)}/.well-known/oauth-authorization-server`);
@@ -6093,7 +6309,7 @@ var OAuthTokens = class {
6093
6309
  if (!force && this.current && this.current.expiresAt > Date.now() + 3e4)
6094
6310
  return this.current;
6095
6311
  const refresh = await this.store.get();
6096
- if (!refresh) throw new TokenAccessDenied("No gateway token. Run tsp-gateway pair.");
6312
+ if (!refresh) throw new TokenAccessDenied("No gateway token. Run tsp-gateway connect.");
6097
6313
  const endpoints = await discover(this.pairing.origin);
6098
6314
  const tokens = await tokenExchange(
6099
6315
  endpoints.token,
@@ -6158,10 +6374,12 @@ async function pair(origin, store, openBrowser, report = () => {
6158
6374
  code_challenge: createHash2("sha256").update(verifier).digest("base64url"),
6159
6375
  code_challenge_method: "S256"
6160
6376
  }).toString();
6161
- report(`Approve pairing in your browser. If it doesn't open, visit:
6162
- ${url.href}`);
6377
+ report([
6378
+ marked("next", "Approve pairing in your browser. If it doesn't open, visit:"),
6379
+ command(url.href, 2)
6380
+ ]);
6163
6381
  await openBrowser(url.href);
6164
- report("Waiting for approval (up to 3 minutes)\u2026");
6382
+ report([marked("wait", "Waiting for approval (up to 3 minutes)\u2026")]);
6165
6383
  const tokens = await tokenExchange(
6166
6384
  endpoints.token,
6167
6385
  new URLSearchParams({
@@ -6262,8 +6480,8 @@ var IntentRetries = class {
6262
6480
  this.commands = commands;
6263
6481
  this.now = now;
6264
6482
  this.random = random;
6265
- for (const entry of commands.pendingIntents)
6266
- this.schedule(entry.command.command_id, entry.attempts);
6483
+ for (const entry2 of commands.pendingIntents)
6484
+ this.schedule(entry2.command.command_id, entry2.attempts);
6267
6485
  }
6268
6486
  retryAt = /* @__PURE__ */ new Map();
6269
6487
  unjournaled = /* @__PURE__ */ new Map();
@@ -6280,17 +6498,17 @@ var IntentRetries = class {
6280
6498
  ready(commandId) {
6281
6499
  return this.now() >= (this.retryAt.get(commandId) ?? -Infinity);
6282
6500
  }
6283
- defer(command) {
6284
- const id = command.command_id;
6285
- const entry = this.commands.journalEntry(id);
6286
- if (entry) {
6501
+ defer(command2) {
6502
+ const id = command2.command_id;
6503
+ const entry2 = this.commands.journalEntry(id);
6504
+ if (entry2) {
6287
6505
  this.unjournaled.delete(id);
6288
- if (entry.receipt === null) this.schedule(id, entry.attempts);
6506
+ if (entry2.receipt === null) this.schedule(id, entry2.attempts);
6289
6507
  else this.retryAt.delete(id);
6290
6508
  return;
6291
6509
  }
6292
6510
  const attempts = (this.unjournaled.get(id)?.attempts ?? 0) + 1;
6293
- this.unjournaled.set(id, { command, attempts });
6511
+ this.unjournaled.set(id, { command: command2, attempts });
6294
6512
  this.schedule(id, attempts);
6295
6513
  }
6296
6514
  /** A retired action is withdrawn by the hub: its unjournaled commands must never run. */
@@ -6302,17 +6520,17 @@ var IntentRetries = class {
6302
6520
  }
6303
6521
  }
6304
6522
  async retryPending(process2, isActive) {
6305
- for (const command of this.pending) {
6523
+ for (const command2 of this.pending) {
6306
6524
  if (!isActive()) break;
6307
- await process2(command);
6525
+ await process2(command2);
6308
6526
  }
6309
6527
  }
6310
6528
  get pending() {
6311
6529
  const commands = [
6312
- ...this.commands.pendingIntents.map((entry) => entry.command),
6530
+ ...this.commands.pendingIntents.map((entry2) => entry2.command),
6313
6531
  ...[...this.unjournaled.values()].map((held) => held.command)
6314
6532
  ];
6315
- const ids = new Set(commands.map((command) => command.command_id));
6533
+ const ids = new Set(commands.map((command2) => command2.command_id));
6316
6534
  for (const id of this.retryAt.keys()) if (!ids.has(id)) this.retryAt.delete(id);
6317
6535
  return commands;
6318
6536
  }
@@ -6398,7 +6616,7 @@ async function reconnectLoop(options, handover) {
6398
6616
  if (step === "halt") return;
6399
6617
  if (step === "exit") break;
6400
6618
  }
6401
- await state.status(false, "Stopped");
6619
+ await state.status(false, CONNECTION.stopped.message);
6402
6620
  }
6403
6621
  async function accessToken(options, state, handover) {
6404
6622
  try {
@@ -6407,11 +6625,10 @@ async function accessToken(options, state, handover) {
6407
6625
  if (options.signal.aborted) return "exit";
6408
6626
  if (error instanceof TokenAccessDenied) {
6409
6627
  await handover.predecessor?.retire();
6410
- await state.status(false, "Token refresh failed. Run tsp-gateway pair again.");
6628
+ await state.status(false, CONNECTION.refreshFailed.message);
6411
6629
  return "halt";
6412
6630
  }
6413
- if (!handover.predecessor)
6414
- await state.status(false, "Waiting for the network or TSP. Retrying\u2026");
6631
+ if (!handover.predecessor) await state.status(false, CONNECTION.waiting.message);
6415
6632
  await state.backoff();
6416
6633
  return "retry";
6417
6634
  }
@@ -6428,26 +6645,23 @@ async function afterClose(options, state, result, handover) {
6428
6645
  );
6429
6646
  if (options.signal.aborted) return "exit";
6430
6647
  if (recovery === "outdated") {
6431
- await state.status(
6432
- false,
6433
- "This gateway is outdated. Run npm install --global @treestructuredplanning/gateway@latest, then tsp-gateway install."
6434
- );
6648
+ await state.status(false, CONNECTION.outdated.message);
6435
6649
  await state.pause(OUTDATED_RETRY_MS);
6436
6650
  return "retry";
6437
6651
  }
6438
6652
  if (recovery === "terminal") {
6439
- await state.status(false, "Machine access ended. Run tsp-gateway pair again.");
6653
+ await state.status(false, CONNECTION.accessEnded.message);
6440
6654
  return "halt";
6441
6655
  }
6442
6656
  if (recovery === "token") {
6443
6657
  if (state.rejectedToken) {
6444
- await state.status(false, "Token rejected after refresh. Run tsp-gateway pair again.");
6658
+ await state.status(false, CONNECTION.tokenRejected.message);
6445
6659
  return "halt";
6446
6660
  }
6447
6661
  state.rejectedToken = true;
6448
6662
  state.force = true;
6449
6663
  }
6450
- if (!handover.predecessor?.open()) await state.status(false, "Reconnecting");
6664
+ if (!handover.predecessor?.open()) await state.status(false, CONNECTION.reconnecting.message);
6451
6665
  await state.backoff();
6452
6666
  return "retry";
6453
6667
  }
@@ -6575,9 +6789,9 @@ var GatewayStatus = class {
6575
6789
  };
6576
6790
  async function daemonConnection(statusPath, since = 0) {
6577
6791
  try {
6578
- const [text4, info] = await Promise.all([readFile6(statusPath, "utf8"), stat4(statusPath)]);
6792
+ const [text5, info] = await Promise.all([readFile6(statusPath, "utf8"), stat4(statusPath)]);
6579
6793
  if (info.mtimeMs < since) return null;
6580
- const status = parseJson(text4);
6794
+ const status = parseJson(text5);
6581
6795
  if (!isObject(status)) return null;
6582
6796
  const pid = field(status, "pid"), message = field(status, "message");
6583
6797
  return typeof pid === "number" && pidAlive(pid) && typeof message === "string" ? message : null;
@@ -6601,26 +6815,10 @@ function readLaunchObservation(value) {
6601
6815
  return { effective_mode: mode, shell, reason };
6602
6816
  }
6603
6817
 
6604
- // src/keychain.ts
6605
- import { AsyncEntry } from "@napi-rs/keyring";
6606
- function keychainOptions(platform = process.platform) {
6607
- return platform === "linux" ? { linux: { store: "secret-service" } } : {};
6608
- }
6609
- function keychain(account) {
6610
- const entry = new AsyncEntry("com.treestructuredplanning.gateway", account, keychainOptions());
6611
- return {
6612
- get: () => entry.getPassword(),
6613
- set: (token) => entry.setPassword(token),
6614
- delete: async () => {
6615
- await entry.deletePassword();
6616
- }
6617
- };
6618
- }
6619
-
6620
6818
  // src/installer.ts
6621
6819
  import { readFile as readFile7, rm as rm2 } from "node:fs/promises";
6622
6820
  import { homedir as homedir9, userInfo as userInfo2 } from "node:os";
6623
- import { dirname as dirname8, isAbsolute as isAbsolute10, join as join10, win32 } from "node:path";
6821
+ import { dirname as dirname9, isAbsolute as isAbsolute10, join as join10, win32 } from "node:path";
6624
6822
  var label = "com.treestructuredplanning.tsp-gateway";
6625
6823
  function xml(value) {
6626
6824
  return value.replace(
@@ -6643,7 +6841,7 @@ function installDefinition(platform, spec) {
6643
6841
  const args = [
6644
6842
  spec.node,
6645
6843
  spec.entry,
6646
- "start",
6844
+ "run",
6647
6845
  "--expected-version",
6648
6846
  spec.version,
6649
6847
  "--config-file",
@@ -6681,7 +6879,7 @@ WantedBy=default.target
6681
6879
  `;
6682
6880
  if (platform === "win32")
6683
6881
  return `<?xml version="1.0" encoding="UTF-16"?>
6684
- <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) : dirname8(spec.entry))}</WorkingDirectory></Exec></Actions></Task>
6882
+ <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) : dirname9(spec.entry))}</WorkingDirectory></Exec></Actions></Task>
6685
6883
  `;
6686
6884
  throw new Error("Login items support macOS, Linux and Windows");
6687
6885
  }
@@ -6701,7 +6899,10 @@ async function captureLoginPath(env = process.env, platform = process.platform,
6701
6899
  if (!path || /[\r\n\0]/.test(path)) throw new Error("Could not capture login-shell PATH");
6702
6900
  return path;
6703
6901
  }
6704
- function installPath(platform, state, home = homedir9()) {
6902
+ function loginItemHome(env = process.env, home = homedir9()) {
6903
+ return env["TSP_GATEWAY_LOGIN_ITEM_HOME"] || home;
6904
+ }
6905
+ function installPath(platform, state, home = loginItemHome()) {
6705
6906
  if (platform === "darwin") return join10(home, "Library", "LaunchAgents", `${label}.plist`);
6706
6907
  if (platform === "linux")
6707
6908
  return join10(home, ".config", "systemd", "user", "tsp-gateway.service");
@@ -6738,11 +6939,11 @@ async function systemCommand(file, args) {
6738
6939
  if (result.code !== 0)
6739
6940
  throw new Error(`Could not update login item (${file}, exit ${result.code})`);
6740
6941
  }
6741
- async function install(spec, platform = process.platform, home = homedir9()) {
6942
+ async function install(spec, platform = process.platform, home = loginItemHome()) {
6742
6943
  const destination = installPath(platform, spec.state, home);
6743
6944
  await privateDirectory(spec.state);
6744
6945
  await import("node:fs/promises").then(
6745
- (fs) => fs.mkdir(dirname8(destination), { recursive: true })
6946
+ (fs) => fs.mkdir(dirname9(destination), { recursive: true })
6746
6947
  );
6747
6948
  const definition = installDefinition(platform, spec);
6748
6949
  if (platform === "win32") {
@@ -6767,7 +6968,7 @@ async function install(spec, platform = process.platform, home = homedir9()) {
6767
6968
  }
6768
6969
  await privateWrite(join10(spec.state, "installation.json"), JSON.stringify(spec));
6769
6970
  }
6770
- async function uninstall(state, platform = process.platform, home = homedir9()) {
6971
+ async function uninstall(state, platform = process.platform, home = loginItemHome()) {
6771
6972
  const destination = installPath(platform, state, home);
6772
6973
  try {
6773
6974
  await readFile7(destination);
@@ -6787,7 +6988,7 @@ async function uninstall(state, platform = process.platform, home = homedir9())
6787
6988
  await rm2(join10(state, "installation.json"), { force: true });
6788
6989
  return true;
6789
6990
  }
6790
- async function loginItemCurrent(spec, platform = process.platform, home = homedir9()) {
6991
+ async function loginItemCurrent(spec, platform = process.platform, home = loginItemHome()) {
6791
6992
  try {
6792
6993
  const recorded = parseJson(await readFile7(join10(spec.state, "installation.json"), "utf8"));
6793
6994
  await readFile7(installPath(platform, spec.state, home));
@@ -6800,7 +7001,25 @@ async function loginItemCurrent(spec, platform = process.platform, home = homedi
6800
7001
  return running2(platform);
6801
7002
  }
6802
7003
 
7004
+ // src/keychain.ts
7005
+ import { AsyncEntry } from "@napi-rs/keyring";
7006
+ function keychainOptions(platform = process.platform) {
7007
+ return platform === "linux" ? { linux: { store: "secret-service" } } : {};
7008
+ }
7009
+ function keychain(account) {
7010
+ const entry2 = new AsyncEntry("com.treestructuredplanning.gateway", account, keychainOptions());
7011
+ return {
7012
+ get: () => entry2.getPassword(),
7013
+ set: (token) => entry2.setPassword(token),
7014
+ delete: async () => {
7015
+ await entry2.deletePassword();
7016
+ }
7017
+ };
7018
+ }
7019
+
6803
7020
  // src/setup.ts
7021
+ import { readFile as readFile8 } from "node:fs/promises";
7022
+ import { dirname as dirname10, join as join11 } from "node:path";
6804
7023
  async function pairMachine(host, config) {
6805
7024
  const pairing = await pair(
6806
7025
  host.origin,
@@ -6828,7 +7047,7 @@ async function addRepository(host, config, folder) {
6828
7047
  return saveRepository(host, config, await registerFolder(folder, host.env));
6829
7048
  }
6830
7049
  async function installLoginItem(host, config, refresh = "always") {
6831
- if (!config.pairing) throw new Error("Run tsp-gateway pair first.");
7050
+ if (!config.pairing) throw notConnected();
6832
7051
  const path = await captureLoginPath(host.env, host.platform, config.launch);
6833
7052
  const spec = {
6834
7053
  node: host.node,
@@ -6845,6 +7064,41 @@ async function installLoginItem(host, config, refresh = "always") {
6845
7064
  await install(spec, host.platform, host.home);
6846
7065
  return "installed";
6847
7066
  }
7067
+ function notConnected() {
7068
+ return new ActionableError("This computer isn't connected to TSP yet.", {
7069
+ instruction: "Connect it",
7070
+ command: "tsp-gateway connect"
7071
+ });
7072
+ }
7073
+ var PACKAGE_INSTALL_TIMEOUT_MS = 6e5;
7074
+ async function updateGateway(host, config, run2 = execute) {
7075
+ if (!config.pairing) throw notConnected();
7076
+ let latest = host;
7077
+ const npm = host.platform === "win32" ? host.node : "npm";
7078
+ const npmArgs = host.platform === "win32" ? [join11(dirname10(host.node), "node_modules", "npm", "bin", "npm-cli.js")] : [];
7079
+ if (!host.entry.split(/[\\/]/).includes("_npx")) {
7080
+ host.report([marked("wait", "Installing the latest gateway with npm\u2026")]);
7081
+ const installed = await run2(
7082
+ npm,
7083
+ [...npmArgs, "install", "--global", "@treestructuredplanning/gateway@latest"],
7084
+ host.env,
7085
+ void 0,
7086
+ { timeoutMs: PACKAGE_INSTALL_TIMEOUT_MS }
7087
+ );
7088
+ if (installed.code !== 0) throw new Error("Could not install the latest gateway.");
7089
+ const root = await run2(npm, [...npmArgs, "root", "--global"], host.env);
7090
+ if (root.code !== 0 || !root.stdout.trim())
7091
+ throw new Error("Could not locate the updated gateway.");
7092
+ const folder = join11(root.stdout.trim(), "@treestructuredplanning", "gateway");
7093
+ const manifest = parseJson(await readFile8(join11(folder, "package.json"), "utf8"));
7094
+ const version = isObject(manifest) ? field(manifest, "version") : null;
7095
+ if (typeof version !== "string" || !version)
7096
+ throw new Error("Updated gateway has no version.");
7097
+ latest = { ...host, entry: join11(folder, "dist", "cli.js"), version };
7098
+ }
7099
+ await installLoginItem(latest, config);
7100
+ return latest.version;
7101
+ }
6848
7102
  async function removeLoginItem(host) {
6849
7103
  return await uninstall(host.paths.state, host.platform, host.home) ? "removed" : "absent";
6850
7104
  }
@@ -6911,7 +7165,7 @@ async function folderSetups(drivers, config, repository, executor) {
6911
7165
  if (found.length === 0) {
6912
7166
  const required = here.map((row) => ({
6913
7167
  harness: row.harness,
6914
- instruction: drivers.get(row.harness).installInstruction
7168
+ ...drivers.get(row.harness).installStep
6915
7169
  }));
6916
7170
  setups.push({ slug, ready: [], required, optional: [] });
6917
7171
  continue;
@@ -6921,10 +7175,12 @@ async function folderSetups(drivers, config, repository, executor) {
6921
7175
  for (const row of found) {
6922
7176
  const driver = drivers.get(row.harness);
6923
7177
  const own = [];
6924
- if (row.signed_in !== true) own.push(driver.signInInstruction);
6925
- if (trustIsStep(row.trust, driver)) own.push(driver.repositorySetupInstruction);
7178
+ if (row.signed_in !== true) own.push({ harness: row.harness, ...driver.signInStep });
7179
+ const folder = folders[slug];
7180
+ if (folder && trustIsStep(row.trust, driver))
7181
+ own.push({ harness: row.harness, ...driver.repositorySetup(folder) });
6926
7182
  if (own.length === 0) ready.push(row.harness);
6927
- steps.push(...own.map((instruction) => ({ harness: row.harness, instruction })));
7183
+ steps.push(...own);
6928
7184
  }
6929
7185
  setups.push(
6930
7186
  ready.length > 0 ? { slug, ready, required: [], optional: steps } : { slug, ready, required: steps, optional: [] }
@@ -6935,7 +7191,7 @@ async function folderSetups(drivers, config, repository, executor) {
6935
7191
  const registered2 = config.repositories[setup.slug];
6936
7192
  if (!registered2) return setup;
6937
7193
  const root = await previewWorktreeRoot(executor, registered2.folder, config);
6938
- return { ...setup, worktreeRoot: root?.folder ?? UNRESOLVED_WORKTREE_ROOT };
7194
+ return { ...setup, worktree: worktreeView(registered2.folder, root) };
6939
7195
  })
6940
7196
  );
6941
7197
  }
@@ -6951,48 +7207,136 @@ var REASONS = {
6951
7207
  "configured direct": "chosen in your launch settings",
6952
7208
  "Windows uses direct spawn": "as Windows does"
6953
7209
  };
7210
+ var CONNECT_HERE = {
7211
+ instruction: "Run this inside a clone of a GitHub repository to register it",
7212
+ command: "tsp-gateway connect"
7213
+ };
6954
7214
  function list(names) {
6955
7215
  return names.length < 3 ? names.join(" and ") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
6956
7216
  }
6957
- function lowerFirst(text4) {
6958
- return text4.charAt(0).toLowerCase() + text4.slice(1);
7217
+ function lowerFirst(value) {
7218
+ return value.charAt(0).toLowerCase() + value.slice(1);
6959
7219
  }
6960
- function sentence(text4) {
6961
- return text4.replace(/\.+$/, "") + ".";
7220
+ function stepTarget(step) {
7221
+ return step.command ?? step.link;
6962
7222
  }
6963
- function stepLines(steps, lead, name) {
6964
- return steps.map((step) => ` ${lead(name(step.harness))}: ${lowerFirst(step.instruction)}`);
7223
+ function stepSentence(step, lead) {
7224
+ const sentence = `${lead}, ${lowerFirst(step.instruction)}`;
7225
+ return stepTarget(step) ? sentence.replace(/\.+$/, ":") : sentence;
6965
7226
  }
6966
- function setupLines(setups, name) {
7227
+ function stepLines(steps, kind, name, depth) {
7228
+ return steps.flatMap((step) => {
7229
+ const sentence = kind === "required" ? marked("next", stepSentence(step, `To build with ${name(step.harness)}`), depth) : note(
7230
+ stepSentence(step, `Optional: to also build with ${name(step.harness)}`),
7231
+ depth
7232
+ );
7233
+ const target = stepTarget(step);
7234
+ return target ? [sentence, command(target, depth + 2)] : [sentence];
7235
+ });
7236
+ }
7237
+ function setupLines(setups, name, depth = 1) {
6967
7238
  return setups.flatMap((setup) => {
6968
7239
  const label2 = setup.slug || "This computer";
6969
7240
  return [
6970
- setup.ready.length > 0 ? `${label2}: ready to build with ${list(setup.ready.map(name))}.` : `${label2}: not ready to build yet.`,
6971
- ...setup.worktreeRoot ? [` Worktrees: ${setup.worktreeRoot}`] : [],
6972
- ...stepLines(setup.required, (harness) => `To build with ${harness}`, name),
6973
- ...stepLines(
6974
- setup.optional,
6975
- (harness) => `Optional, to also build with ${harness}`,
6976
- name
6977
- )
7241
+ setup.ready.length > 0 ? marked(
7242
+ "pass",
7243
+ `${label2}: ready to build with ${list(setup.ready.map(name))}`,
7244
+ depth
7245
+ ) : marked("fail", `${label2}: not ready to build yet`, depth),
7246
+ ...setup.worktree ? worktreeLines(setup.worktree, depth + 1) : [],
7247
+ ...stepLines(setup.required, "required", name, depth + 1),
7248
+ ...stepLines(setup.optional, "optional", name, depth + 1)
6978
7249
  ];
6979
7250
  });
6980
7251
  }
6981
- function pairedLine(view) {
6982
- return view.machineId === null ? "Not paired. Run tsp-gateway connect to set up this computer." : `Paired as ${view.machineId}. ${sentence(view.connection)}`;
7252
+ function registeredLines(registered2, drivers) {
7253
+ return [
7254
+ marked("pass", `Registered ${registered2.slug}`),
7255
+ note("The running gateway picks up the change automatically.", 1),
7256
+ ...stepLines(
7257
+ drivers.repositorySetups(registered2.folder),
7258
+ "required",
7259
+ drivers.displayName,
7260
+ 1
7261
+ ),
7262
+ ...nextLines(
7263
+ { instruction: "Start the gateway now and at login", command: "tsp-gateway start" },
7264
+ 1
7265
+ )
7266
+ ];
7267
+ }
7268
+ function gatewayLines(view) {
7269
+ const lines = [heading(`Gateway ${view.version}`)];
7270
+ if (view.machineId === null)
7271
+ return [
7272
+ ...lines,
7273
+ marked("fail", "Not paired", 1),
7274
+ ...nextLines({ instruction: "Pair this computer", command: "tsp-gateway connect" }, 2)
7275
+ ];
7276
+ const current = connectionState(view.connection);
7277
+ const last = view.lastMessage !== null && view.lastMessage !== view.connection ? connectionState(view.lastMessage) : null;
7278
+ const next = current.mark === "fail" && last?.next ? last.next : current.next;
7279
+ return [
7280
+ ...lines,
7281
+ marked("pass", `Paired as ${view.machineId}`, 1),
7282
+ marked(current.mark, current.text, 1),
7283
+ ...last ? [note(`Last report: ${last.text}`, 2)] : [],
7284
+ ...next ? nextLines(next, 2) : []
7285
+ ];
7286
+ }
7287
+ function verdictLines(view, setups) {
7288
+ const connection = connectionState(view.connection).mark;
7289
+ const registered2 = setups.filter((setup) => setup.slug !== "");
7290
+ const ready = registered2.filter((setup) => setup.ready.length > 0).map((setup) => setup.slug);
7291
+ if (view.machineId === null || connection === "fail" || registered2.length > 0 && !ready.length)
7292
+ return [marked("fail", "Not ready to build yet. Follow the \u2192 steps above.")];
7293
+ if (registered2.length === 0)
7294
+ return [
7295
+ marked("fail", "No repository folder is registered yet."),
7296
+ ...nextLines(CONNECT_HERE, 1)
7297
+ ];
7298
+ if (connection === "wait")
7299
+ return [
7300
+ marked(
7301
+ "wait",
7302
+ `Ready to build in ${list(ready)} once the gateway connects. Check with:`
7303
+ ),
7304
+ command("tsp-gateway status", 2)
7305
+ ];
7306
+ return [marked("pass", `Ready to build in ${list(ready)}.`)];
7307
+ }
7308
+ function folderSection(setups, name) {
7309
+ return [blank, heading("Folders"), ...setupLines(setups, name)];
6983
7310
  }
6984
7311
  function connectLines(view, setups, name) {
6985
- return [pairedLine(view), ...setupLines(setups, name)];
7312
+ return [
7313
+ ...gatewayLines(view),
7314
+ ...folderSection(setups, name),
7315
+ blank,
7316
+ ...verdictLines(view, setups),
7317
+ note(
7318
+ "tsp-gateway stop, start and update manage the background gateway. Pairing and folders stay."
7319
+ )
7320
+ ];
6986
7321
  }
6987
7322
  function statusLines(view, setups, name) {
6988
7323
  const reason = REASONS[view.launch.reason] ?? view.launch.reason;
6989
- 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}).`;
6990
7324
  return [
6991
- pairedLine(view),
6992
- ...view.lastMessage !== null && view.lastMessage !== view.connection ? [`Last message from the gateway: ${sentence(view.lastMessage)}`] : [],
6993
- ...setupLines(setups, name),
6994
- view.launch.wrapper === null ? how : `${how} Wrapper: ${view.launch.wrapper}.`,
6995
- 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."
7325
+ ...gatewayLines(view),
7326
+ ...folderSection(setups, name),
7327
+ blank,
7328
+ heading("Sessions"),
7329
+ text4(
7330
+ view.launch.effective_mode === "login-shell" && view.launch.shell !== null ? `Start through your login shell, ${view.launch.shell} (${reason})` : `Start without a login shell (${reason})`,
7331
+ 1
7332
+ ),
7333
+ ...view.launch.wrapper === null ? [] : [text4(`Wrapper: ${view.launch.wrapper}`, 1)],
7334
+ text4(
7335
+ view.reporting === "off" ? "Activity reporting off: TSP sees only each session's state" : "Activity reporting on: TSP sees each session's kind of work and its counts of files edited and commands run",
7336
+ 1
7337
+ ),
7338
+ blank,
7339
+ ...verdictLines(view, setups)
6996
7340
  ];
6997
7341
  }
6998
7342
 
@@ -7028,6 +7372,7 @@ export {
7028
7372
  AcpGroupLedger,
7029
7373
  ClaudeTranscripts,
7030
7374
  ClaudeTrust,
7375
+ inFolder,
7031
7376
  HarnessExecutor,
7032
7377
  ClaudeDriver,
7033
7378
  CodexActivity,
@@ -7042,6 +7387,20 @@ export {
7042
7387
  CheckoutPreparer,
7043
7388
  previewWorktreeRoot,
7044
7389
  checkoutReport,
7390
+ heading,
7391
+ marked,
7392
+ text4 as text,
7393
+ note,
7394
+ command,
7395
+ entry,
7396
+ blank,
7397
+ nextLines,
7398
+ colorEnabled,
7399
+ renderLines,
7400
+ writeLines,
7401
+ ActionableError,
7402
+ UsageError,
7403
+ errorLines,
7045
7404
  printWorktreeRoots,
7046
7405
  connectWorktreeArgs,
7047
7406
  recordConnectRoot,
@@ -7052,6 +7411,8 @@ export {
7052
7411
  UNREADABLE_SESSION_POLLS,
7053
7412
  Commands,
7054
7413
  watchConfig,
7414
+ CONNECTION,
7415
+ connectionState,
7055
7416
  LaunchPermits,
7056
7417
  HANDOVER_MS,
7057
7418
  REFRESH_LEAD_MS,
@@ -7065,24 +7426,26 @@ export {
7065
7426
  daemonConnection,
7066
7427
  awaitDaemonConnection,
7067
7428
  readLaunchObservation,
7068
- keychainOptions,
7069
- keychain,
7070
7429
  installDefinition,
7071
7430
  captureLoginPath,
7431
+ loginItemHome,
7072
7432
  installPath,
7073
7433
  install,
7074
7434
  uninstall,
7075
7435
  loginItemCurrent,
7076
- pairMachine,
7436
+ keychainOptions,
7437
+ keychain,
7077
7438
  addRepository,
7078
7439
  installLoginItem,
7440
+ notConnected,
7441
+ updateGateway,
7079
7442
  removeLoginItem,
7080
- unpairMachine,
7081
7443
  connect,
7082
7444
  disconnect,
7083
7445
  folderSetups,
7084
7446
  setupLines,
7447
+ registeredLines,
7085
7448
  connectLines,
7086
7449
  statusLines
7087
7450
  };
7088
- //# sourceMappingURL=shared-IOW65S5G.js.map
7451
+ //# sourceMappingURL=shared-SSP3A5QQ.js.map