@treestructuredplanning/gateway 0.3.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.
package/dist/cli.js CHANGED
@@ -1,7 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
3
3
  import {
4
+ ActionableError,
4
5
  ActivityReporter,
6
+ CONNECTION,
5
7
  CheckoutPreparer,
6
8
  Commands,
7
9
  GATEWAY_CLOSE_DISPOSITION,
@@ -9,9 +11,12 @@ import {
9
11
  HarnessExecutor,
10
12
  Journal,
11
13
  OAuthTokens,
14
+ UsageError,
12
15
  addRepository,
13
16
  awaitDaemonConnection,
17
+ blank,
14
18
  builtinHarnesses,
19
+ command,
15
20
  connect,
16
21
  connectLines,
17
22
  connectWorktreeArgs,
@@ -20,17 +25,23 @@ import {
20
25
  decodeLaunchConfig,
21
26
  decodeReporting,
22
27
  disconnect,
28
+ entry,
29
+ errorLines,
23
30
  execute,
24
31
  field,
25
32
  folderSetups,
33
+ heading,
26
34
  installLoginItem,
27
35
  isObject,
28
36
  keychain,
29
37
  locations,
30
38
  loginItemHome,
39
+ marked,
40
+ nextLines,
41
+ notConnected,
42
+ note,
31
43
  parseJson,
32
44
  parseRepositoryRemote,
33
- printWorktreeRoots,
34
45
  privateDirectory,
35
46
  readConfig,
36
47
  readLaunchObservation,
@@ -42,22 +53,23 @@ import {
42
53
  runDaemon,
43
54
  saveConfig,
44
55
  statusLines,
56
+ text,
45
57
  updateGateway,
46
58
  validateOrigin,
47
59
  watchConfig,
48
- worktreesCommand
49
- } from "./shared-KRIZBGVD.js";
60
+ worktreesCommand,
61
+ writeLines
62
+ } from "./shared-SSP3A5QQ.js";
50
63
 
51
64
  // src/cli.ts
52
- import { readFile } from "node:fs/promises";
53
- import { isAbsolute, join } from "node:path";
65
+ import { isAbsolute, join as join2 } from "node:path";
54
66
  import { fileURLToPath } from "node:url";
55
67
  import { parseArgs } from "node:util";
56
68
 
57
69
  // package.json
58
70
  var package_default = {
59
71
  name: "@treestructuredplanning/gateway",
60
- version: "0.3.0",
72
+ version: "0.3.2",
61
73
  description: "Outbound local harness gateway for Tree-Structured Planning",
62
74
  type: "module",
63
75
  engines: {
@@ -106,10 +118,148 @@ var package_default = {
106
118
  }
107
119
  };
108
120
 
121
+ // src/cli-help.ts
122
+ var HELP = [
123
+ {
124
+ title: "Set up",
125
+ commands: [
126
+ ["connect [folder]", "Pair if needed, register the folder and start the gateway"],
127
+ ["disconnect", "Stop the gateway starting at login, then unpair"],
128
+ ["add <folder>", "Register a repository folder"],
129
+ ["remove <host/owner/name>", "Unregister a repository"]
130
+ ]
131
+ },
132
+ {
133
+ title: "Run",
134
+ commands: [
135
+ ["start", "Start the gateway in the background now and each time you log in"],
136
+ ["stop", "Stop the gateway and turn off its start at login"],
137
+ ["run", "Run the gateway in this terminal; Ctrl-C stops it"],
138
+ ["update", "Install the latest gateway and restart it"]
139
+ ]
140
+ },
141
+ {
142
+ title: "Check and configure",
143
+ commands: [
144
+ ["status [--json]", "Show pairing, connection and each folder's next steps"],
145
+ ["worktrees", "Show where each folder's agents get their own worktree"],
146
+ [
147
+ "config worktrees-root [--repo <folder>] <path|--reset>",
148
+ "Choose where those worktrees go"
149
+ ],
150
+ ["configure-launch '<json>'", "Set how agents start"],
151
+ ["configure-reporting <activity|off>", "Choose whether TSP sees what agents are doing"]
152
+ ]
153
+ }
154
+ ];
155
+ var ENTRY_WIDTH = 40;
156
+ function helpLines(version) {
157
+ const width = Math.max(
158
+ ...HELP.flatMap((group) => group.commands.map(([name]) => name.length)).filter(
159
+ (length) => length <= ENTRY_WIDTH
160
+ )
161
+ );
162
+ return [
163
+ heading(`TSP gateway ${version}`),
164
+ text("Lets the Tree-Structured Planning canvas start coding agents on this computer."),
165
+ blank,
166
+ text("Usage: tsp-gateway <command>"),
167
+ ...HELP.flatMap((group) => [
168
+ blank,
169
+ heading(group.title),
170
+ ...group.commands.flatMap(
171
+ ([name, summary]) => name.length > ENTRY_WIDTH ? [command(name, 1), text(summary, 3)] : [entry(name, summary, width, 1)]
172
+ )
173
+ ]),
174
+ blank,
175
+ note(
176
+ "Docs: https://treestructuredplanning.com/docs/drive-with-your-agent/build-on-your-machine"
177
+ )
178
+ ];
179
+ }
180
+ var HELP_FLAGS = /* @__PURE__ */ new Set(["--help", "-h", "help"]);
181
+
182
+ // src/status-report.ts
183
+ import { readFile } from "node:fs/promises";
184
+ import { join } from "node:path";
185
+ async function readStatus(paths, config, executor, idle = CONNECTION.notRunning.message) {
186
+ const connection = await daemonConnection(join(paths.state, "status.json")) ?? idle;
187
+ let daemonLaunch = null;
188
+ let lastMessage = null;
189
+ let closeCode = null;
190
+ let closeDisposition = null;
191
+ try {
192
+ const status = parseJson(await readFile(join(paths.state, "status.json"), "utf8"));
193
+ if (isObject(status)) {
194
+ daemonLaunch = readLaunchObservation(field(status, "launch"));
195
+ const code = field(status, "close_code"), recovery = field(status, "close_disposition");
196
+ if (typeof code === "number" && Number.isInteger(code)) closeCode = code;
197
+ closeDisposition = Object.values(GATEWAY_CLOSE_DISPOSITION).find((value) => value === recovery) ?? null;
198
+ }
199
+ if (isObject(status) && typeof field(status, "message") === "string")
200
+ lastMessage = field(status, "message");
201
+ } catch {
202
+ lastMessage = null;
203
+ }
204
+ return {
205
+ paired: config.pairing !== null,
206
+ machine_id: config.pairing?.machine_id ?? null,
207
+ connection,
208
+ last_message: lastMessage,
209
+ close_code: closeCode,
210
+ close_disposition: closeDisposition,
211
+ launch: await executor.status(),
212
+ launch_source: "status-probe",
213
+ last_daemon_launch: daemonLaunch,
214
+ repositories: Object.keys(config.repositories),
215
+ reporting: config.reporting
216
+ };
217
+ }
218
+ async function printStatus({ paths, config, drivers, executor, version }, json) {
219
+ if (json) {
220
+ const [status2, harnesses] = await Promise.all([
221
+ readStatus(paths, config, executor),
222
+ drivers.detect()
223
+ ]);
224
+ const { launch, launch_source, last_daemon_launch, repositories, reporting, ...daemon } = status2;
225
+ console.log(
226
+ JSON.stringify(
227
+ {
228
+ ...daemon,
229
+ harnesses,
230
+ launch,
231
+ launch_source,
232
+ last_daemon_launch,
233
+ repositories,
234
+ reporting
235
+ },
236
+ null,
237
+ 2
238
+ )
239
+ );
240
+ return;
241
+ }
242
+ const [status, setups] = await Promise.all([
243
+ readStatus(paths, config, executor),
244
+ folderSetups(drivers, config, null, executor)
245
+ ]);
246
+ writeLines(statusLines(machineView(status, version), setups, drivers.displayName));
247
+ }
248
+ function machineView(status, version) {
249
+ return {
250
+ version,
251
+ machineId: status.machine_id,
252
+ connection: status.connection,
253
+ lastMessage: status.last_message,
254
+ launch: status.launch,
255
+ reporting: status.reporting
256
+ };
257
+ }
258
+
109
259
  // src/cli.ts
110
260
  async function runLocal(loginPath, paths, config, version) {
111
261
  const pairing = config.pairing;
112
- if (!pairing) throw new Error("Run tsp-gateway connect first.");
262
+ if (!pairing) throw notConnected();
113
263
  await privateDirectory(paths.state);
114
264
  const release = await daemonLock(paths.state);
115
265
  const abort = new AbortController();
@@ -118,7 +268,7 @@ async function runLocal(loginPath, paths, config, version) {
118
268
  process.once("SIGTERM", stop);
119
269
  let drivers;
120
270
  try {
121
- const journal = new Journal(join(paths.state, `${pairing.machine_id}-receipts.jsonl`));
271
+ const journal = new Journal(join2(paths.state, `${pairing.machine_id}-receipts.jsonl`));
122
272
  await journal.load(repositoryFolders(config));
123
273
  const repositories = async () => repositoryFolders(await readConfig(paths.config));
124
274
  const environment = {
@@ -131,8 +281,8 @@ async function runLocal(loginPath, paths, config, version) {
131
281
  void status.refresh().catch(() => console.error("Could not update gateway launch status"));
132
282
  }
133
283
  });
134
- const status = new GatewayStatus(join(paths.state, "status.json"), executor);
135
- drivers = builtinHarnesses(environment, executor, join(paths.state, "acp-groups.json"));
284
+ const status = new GatewayStatus(join2(paths.state, "status.json"), executor);
285
+ drivers = builtinHarnesses(environment, executor, join2(paths.state, "acp-groups.json"));
136
286
  await drivers.reap();
137
287
  const registry = drivers;
138
288
  const commands = new Commands(journal, registry, repositories, {
@@ -161,59 +311,6 @@ async function runLocal(loginPath, paths, config, version) {
161
311
  await release();
162
312
  }
163
313
  }
164
- async function readStatus(paths, config, drivers, executor, idle = "Not running") {
165
- const connection = await daemonConnection(join(paths.state, "status.json")) ?? idle;
166
- let daemonLaunch = null;
167
- let lastMessage = null;
168
- let closeCode = null;
169
- let closeDisposition = null;
170
- try {
171
- const status = parseJson(await readFile(join(paths.state, "status.json"), "utf8"));
172
- if (isObject(status)) {
173
- daemonLaunch = readLaunchObservation(field(status, "launch"));
174
- const code = field(status, "close_code"), recovery = field(status, "close_disposition");
175
- if (typeof code === "number" && Number.isInteger(code)) closeCode = code;
176
- closeDisposition = Object.values(GATEWAY_CLOSE_DISPOSITION).find((value) => value === recovery) ?? null;
177
- }
178
- if (isObject(status) && typeof field(status, "message") === "string")
179
- lastMessage = field(status, "message");
180
- } catch {
181
- lastMessage = null;
182
- }
183
- return {
184
- paired: config.pairing !== null,
185
- machine_id: config.pairing?.machine_id ?? null,
186
- connection,
187
- last_message: lastMessage,
188
- close_code: closeCode,
189
- close_disposition: closeDisposition,
190
- harnesses: await drivers.detect(),
191
- launch: await executor.status(),
192
- launch_source: "status-probe",
193
- last_daemon_launch: daemonLaunch,
194
- repositories: Object.keys(config.repositories),
195
- reporting: config.reporting
196
- };
197
- }
198
- async function printStatus(paths, config, drivers, executor, json) {
199
- const status = await readStatus(paths, config, drivers, executor);
200
- if (json) {
201
- console.log(JSON.stringify(status, null, 2));
202
- return;
203
- }
204
- const view = machineView(status);
205
- const setups = await folderSetups(drivers, config, null, executor);
206
- for (const line of statusLines(view, setups, drivers.displayName)) console.log(line);
207
- }
208
- function machineView(status) {
209
- return {
210
- machineId: status.machine_id,
211
- connection: status.connection,
212
- lastMessage: status.last_message,
213
- launch: status.launch,
214
- reporting: status.reporting
215
- };
216
- }
217
314
  function startupOptions(args, version) {
218
315
  const options = args[0] === "run" ? parseArgs({
219
316
  args: args.slice(1),
@@ -225,8 +322,9 @@ function startupOptions(args, version) {
225
322
  }
226
323
  }).values : void 0;
227
324
  if (options?.["expected-version"] !== void 0 && options["expected-version"] !== version)
228
- throw new Error(
229
- "Installed gateway version changed. Run npx @treestructuredplanning/gateway@latest update."
325
+ throw new ActionableError(
326
+ "The installed gateway version changed.",
327
+ CONNECTION.outdated.next
230
328
  );
231
329
  const defaults = locations();
232
330
  const paths = {
@@ -250,82 +348,110 @@ function gatewayOrigin(config) {
250
348
  async function configureLaunch(args, config, path) {
251
349
  const json = args[1];
252
350
  if (!json || args.length !== 2)
253
- throw new Error("Usage: tsp-gateway configure-launch '<JSON object>'");
351
+ throw new UsageError("tsp-gateway configure-launch '<JSON object>'");
254
352
  config.launch = decodeLaunchConfig(parseJson(json));
255
353
  await saveConfig(path, config);
256
- console.log("Launch settings saved. The running gateway picks up the change automatically.");
354
+ writeLines([marked("pass", "Launch settings saved"), PICKED_UP]);
257
355
  }
258
356
  async function configureReporting(args, config, path) {
259
- if (args.length !== 2) throw new Error("Usage: tsp-gateway configure-reporting <activity|off>");
357
+ if (args.length !== 2) throw new UsageError("tsp-gateway configure-reporting <activity|off>");
260
358
  config.reporting = decodeReporting(args[1]);
261
359
  await saveConfig(path, config);
262
- console.log(
263
- config.reporting === "off" ? "Reporting off: TSP shows your sessions' state only. The running gateway picks up the change automatically." : "Reporting activity: TSP shows what your sessions are doing, without file names, commands or text. The running gateway picks up the change automatically."
264
- );
360
+ writeLines([
361
+ marked(
362
+ "pass",
363
+ config.reporting === "off" ? "Activity reporting off: TSP shows only your sessions' state" : "Activity reporting on: TSP shows each session's kind of work and its counts of files edited and commands run"
364
+ ),
365
+ PICKED_UP
366
+ ]);
265
367
  }
368
+ var PICKED_UP = note("The running gateway picks up the change automatically.", 1);
266
369
  var VERBS = {
267
- connect: async ({ args, config, host, paths, drivers, executor }) => {
370
+ connect: async ({ args, config, host, paths, drivers, executor, version }) => {
268
371
  const choice = connectWorktreeArgs(args);
269
372
  const since = Date.now();
270
373
  const outcome = await connect(host, config, choice.folder);
271
374
  await recordConnectRoot(config, paths.config, outcome.repository?.slug, choice.root);
272
- await printWorktreeRoots(config, executor);
273
- const reported = outcome.loginItem === "installed" ? await awaitDaemonConnection(join(paths.state, "status.json"), since) : null;
375
+ const [reported, setups] = await Promise.all([
376
+ outcome.loginItem === "installed" ? awaitDaemonConnection(join2(paths.state, "status.json"), since) : null,
377
+ folderSetups(drivers, config, outcome.repository, executor)
378
+ ]);
274
379
  const status = await readStatus(
275
380
  paths,
276
381
  config,
277
- drivers,
278
382
  executor,
279
- outcome.loginItem === "installed" && reported === null ? "Starting" : void 0
383
+ outcome.loginItem === "installed" && reported === null ? CONNECTION.starting.message : void 0
280
384
  );
281
- const setups = await folderSetups(drivers, config, outcome.repository, executor);
282
- for (const line of connectLines(machineView(status), setups, drivers.displayName))
283
- console.log(line);
385
+ writeLines([
386
+ ...outcome.pairing === "paired" ? [blank] : [],
387
+ ...connectLines(machineView(status, version), setups, drivers.displayName)
388
+ ]);
284
389
  },
285
390
  config: worktreesCommand,
286
391
  worktrees: worktreesCommand,
287
392
  disconnect: async ({ args, host, config }) => {
288
- if (args.length !== 1) throw new Error("Usage: tsp-gateway disconnect");
393
+ if (args.length !== 1) throw new UsageError("tsp-gateway disconnect");
289
394
  const outcome = await disconnect(host, config);
290
- console.log(
291
- `${outcome.loginItem === "removed" ? "Login item removed." : "No login item was installed."} ${outcome.pairing} Registered folders are kept. Run tsp-gateway connect to reconnect.`
292
- );
395
+ writeLines([
396
+ marked(
397
+ "pass",
398
+ outcome.loginItem === "removed" ? "Stopped the gateway and turned off its start at login" : "The gateway wasn't set to start at login"
399
+ ),
400
+ marked("pass", outcome.pairing.replace(/\.$/, "")),
401
+ note("Registered folders stay.", 1),
402
+ ...nextLines(
403
+ { instruction: "Connect this computer again", command: "tsp-gateway connect" },
404
+ 1
405
+ )
406
+ ]);
293
407
  },
294
408
  add: async ({ args, argument, host, config, drivers }) => {
295
- if (!argument || args.length !== 2) throw new Error("Usage: tsp-gateway add <folder>");
296
- const registered = await addRepository(host, config, argument);
297
- for (const line of registeredLines(registered, drivers)) console.log(line);
409
+ if (!argument || args.length !== 2) throw new UsageError("tsp-gateway add <folder>");
410
+ writeLines(registeredLines(await addRepository(host, config, argument), drivers));
298
411
  },
299
412
  remove: async ({ argument, config, paths }) => {
300
413
  const repository = argument ? parseRepositoryRemote(argument) : null;
301
- if (!repository) throw new Error("Usage: tsp-gateway remove <host/owner/name>");
414
+ if (!repository) throw new UsageError("tsp-gateway remove <host/owner/name>");
302
415
  delete config.repositories[repositoryKey(repository)];
303
416
  await saveConfig(paths.config, config);
304
- console.log("Repository removed. The running gateway picks up the change automatically.");
417
+ writeLines([marked("pass", `Removed ${repositoryKey(repository)}`), PICKED_UP]);
305
418
  },
306
419
  "configure-launch": ({ args, config, paths }) => configureLaunch(args, config, paths.config),
307
420
  "configure-reporting": ({ args, config, paths }) => configureReporting(args, config, paths.config),
308
- status: ({ args, paths, config, drivers, executor }) => {
421
+ status: (context) => {
422
+ const { args } = context;
309
423
  const json = args[1] === "--json";
310
424
  if (args.length > 2 || args.length === 2 && !json)
311
- throw new Error("Usage: tsp-gateway status [--json]");
312
- return printStatus(paths, config, drivers, executor, json);
425
+ throw new UsageError("tsp-gateway status [--json]");
426
+ return printStatus(context, json);
313
427
  },
314
428
  start: async ({ args, host, config, version }) => {
315
- if (args.length !== 1) throw new Error("Usage: tsp-gateway start");
429
+ if (args.length !== 1) throw new UsageError("tsp-gateway start");
316
430
  await installLoginItem(host, config);
317
- console.log(`Started tsp-gateway ${version} now and at login.`);
431
+ writeLines([
432
+ marked("pass", `Started tsp-gateway ${version}. It also starts each time you log in.`),
433
+ ...nextLines({ instruction: "Check its connection", command: "tsp-gateway status" }, 1)
434
+ ]);
318
435
  },
319
436
  stop: async ({ args, host }) => {
320
- if (args.length !== 1) throw new Error("Usage: tsp-gateway stop");
321
- console.log(
322
- `${await removeLoginItem(host) === "removed" ? "Login item removed." : "No login item was installed."} The link and registered folders are kept.`
323
- );
437
+ if (args.length !== 1) throw new UsageError("tsp-gateway stop");
438
+ const removed = await removeLoginItem(host) === "removed";
439
+ writeLines([
440
+ marked(
441
+ "pass",
442
+ removed ? "Stopped the gateway and turned off its start at login" : "The gateway wasn't set to start at login, so nothing changed"
443
+ ),
444
+ note("Pairing and registered folders stay.", 1),
445
+ ...nextLines({ instruction: "Start it again", command: "tsp-gateway start" }, 1)
446
+ ]);
324
447
  },
325
448
  update: async ({ args, host, config }) => {
326
- if (args.length !== 1) throw new Error("Usage: tsp-gateway update");
327
- await updateGateway(host, config);
328
- console.log("Gateway updated and restarted. The link and registered folders are kept.");
449
+ if (args.length !== 1) throw new UsageError("tsp-gateway update");
450
+ const version = await updateGateway(host, config);
451
+ writeLines([
452
+ marked("pass", `Updated to tsp-gateway ${version} and restarted it`),
453
+ note("Pairing and registered folders stay.", 1)
454
+ ]);
329
455
  },
330
456
  run: ({ loginPath, paths, config, version }) => runLocal(loginPath, paths, config, version)
331
457
  };
@@ -333,15 +459,20 @@ function isVerbName(name) {
333
459
  return Object.hasOwn(VERBS, name);
334
460
  }
335
461
  async function main(args) {
336
- const [command, argument] = args;
337
- const verb = command !== void 0 && isVerbName(command) ? VERBS[command] : null;
462
+ const [command2, argument] = args;
463
+ const verb = command2 !== void 0 && isVerbName(command2) ? VERBS[command2] : null;
464
+ const version = package_default.version;
338
465
  if (!verb) {
339
- console.log(
340
- "Usage: tsp-gateway connect [folder] | disconnect | add <folder> | remove <slug> | configure-launch <json> | configure-reporting <activity|off> | status [--json] | worktrees (config) | start | stop | run | update\n\nstart: Start the background gateway now and at login.\nstop: Stop it and disable login startup; keep the link and folders.\nrun: Run the gateway in the foreground.\nupdate: Install the latest version and restart; keep the link and folders."
341
- );
466
+ writeLines(helpLines(version));
467
+ if (command2 !== void 0 && !HELP_FLAGS.has(command2)) {
468
+ writeLines(
469
+ [blank, marked("fail", `tsp-gateway has no ${command2} command.`)],
470
+ process.stderr
471
+ );
472
+ process.exitCode = 1;
473
+ }
342
474
  return;
343
475
  }
344
- const version = package_default.version;
345
476
  const { paths, loginPath } = startupOptions(args, version);
346
477
  const config = await readConfig(paths.config);
347
478
  const environment = { ...process.env, PATH: config.loginPath ?? process.env["PATH"] };
@@ -371,14 +502,12 @@ async function main(args) {
371
502
  cwd: process.cwd(),
372
503
  tokens: keychain,
373
504
  openBrowser: openAuthorization,
374
- report: (line) => console.log(line)
505
+ report: (lines) => writeLines(lines)
375
506
  }
376
507
  });
377
508
  }
378
509
  void main(process.argv.slice(2)).catch((error) => {
379
- console.error(
380
- error instanceof Error ? error.message : "Gateway could not complete the command"
381
- );
510
+ writeLines(errorLines(error), process.stderr);
382
511
  process.exitCode = 1;
383
512
  });
384
513
  //# sourceMappingURL=cli.js.map