@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.
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,44 +25,51 @@ 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
- pairMachine,
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,
37
48
  recordConnectRoot,
49
+ registeredLines,
38
50
  removeLoginItem,
39
51
  repositoryFolders,
40
52
  repositoryKey,
41
53
  runDaemon,
42
54
  saveConfig,
43
55
  statusLines,
44
- unpairMachine,
56
+ text,
57
+ updateGateway,
45
58
  validateOrigin,
46
59
  watchConfig,
47
- worktreesCommand
48
- } from "./shared-IOW65S5G.js";
60
+ worktreesCommand,
61
+ writeLines
62
+ } from "./shared-SSP3A5QQ.js";
49
63
 
50
64
  // src/cli.ts
51
- import { readFile } from "node:fs/promises";
52
- import { homedir } from "node:os";
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.2.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 pair 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,63 +311,8 @@ 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
- }
182
- return {
183
- paired: config.pairing !== null,
184
- machine_id: config.pairing?.machine_id ?? null,
185
- connection,
186
- last_message: lastMessage,
187
- close_code: closeCode,
188
- close_disposition: closeDisposition,
189
- harnesses: await drivers.detect(),
190
- launch: await executor.status(),
191
- launch_source: "status-probe",
192
- last_daemon_launch: daemonLaunch,
193
- repositories: Object.keys(config.repositories),
194
- reporting: config.reporting
195
- };
196
- }
197
- function harnessName(drivers) {
198
- return (harness) => drivers.get(harness).displayName;
199
- }
200
- async function printStatus(paths, config, drivers, executor, json) {
201
- const status = await readStatus(paths, config, drivers, executor);
202
- if (json) {
203
- console.log(JSON.stringify(status, null, 2));
204
- return;
205
- }
206
- const view = machineView(status);
207
- const setups = await folderSetups(drivers, config, null, executor);
208
- for (const line of statusLines(view, setups, harnessName(drivers))) console.log(line);
209
- }
210
- function machineView(status) {
211
- return {
212
- machineId: status.machine_id,
213
- connection: status.connection,
214
- lastMessage: status.last_message,
215
- launch: status.launch,
216
- reporting: status.reporting
217
- };
218
- }
219
314
  function startupOptions(args, version) {
220
- const options = args[0] === "start" ? parseArgs({
315
+ const options = args[0] === "run" ? parseArgs({
221
316
  args: args.slice(1),
222
317
  options: {
223
318
  "expected-version": { type: "string" },
@@ -227,7 +322,10 @@ function startupOptions(args, version) {
227
322
  }
228
323
  }).values : void 0;
229
324
  if (options?.["expected-version"] !== void 0 && options["expected-version"] !== version)
230
- throw new Error("Installed gateway version changed. Run tsp-gateway install again.");
325
+ throw new ActionableError(
326
+ "The installed gateway version changed.",
327
+ CONNECTION.outdated.next
328
+ );
231
329
  const defaults = locations();
232
330
  const paths = {
233
331
  config: options?.["config-file"] ?? defaults.config,
@@ -250,103 +348,131 @@ 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, harnessName(drivers)))
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.`
292
- );
293
- },
294
- pair: async ({ host, config }) => {
295
- await pairMachine(host, config);
296
- console.log("Paired. Use tsp-gateway add <folder>, then tsp-gateway install.");
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
+ ]);
297
407
  },
298
408
  add: async ({ args, argument, host, config, drivers }) => {
299
- if (!argument || args.length !== 2) throw new Error("Usage: tsp-gateway add <folder>");
300
- const registered = await addRepository(host, config, argument);
301
- console.log(
302
- `Registered ${registered.slug}. ${drivers.setupInstructions().join(" ")} The running gateway picks up the change automatically.`
303
- );
409
+ if (!argument || args.length !== 2) throw new UsageError("tsp-gateway add <folder>");
410
+ writeLines(registeredLines(await addRepository(host, config, argument), drivers));
304
411
  },
305
412
  remove: async ({ argument, config, paths }) => {
306
413
  const repository = argument ? parseRepositoryRemote(argument) : null;
307
- if (!repository) throw new Error("Usage: tsp-gateway remove <host/owner/name>");
414
+ if (!repository) throw new UsageError("tsp-gateway remove <host/owner/name>");
308
415
  delete config.repositories[repositoryKey(repository)];
309
416
  await saveConfig(paths.config, config);
310
- console.log("Repository removed. The running gateway picks up the change automatically.");
417
+ writeLines([marked("pass", `Removed ${repositoryKey(repository)}`), PICKED_UP]);
311
418
  },
312
419
  "configure-launch": ({ args, config, paths }) => configureLaunch(args, config, paths.config),
313
420
  "configure-reporting": ({ args, config, paths }) => configureReporting(args, config, paths.config),
314
- status: ({ args, paths, config, drivers, executor }) => {
421
+ status: (context) => {
422
+ const { args } = context;
315
423
  const json = args[1] === "--json";
316
424
  if (args.length > 2 || args.length === 2 && !json)
317
- throw new Error("Usage: tsp-gateway status [--json]");
318
- return printStatus(paths, config, drivers, executor, json);
425
+ throw new UsageError("tsp-gateway status [--json]");
426
+ return printStatus(context, json);
319
427
  },
320
- install: async ({ host, config, version }) => {
428
+ start: async ({ args, host, config, version }) => {
429
+ if (args.length !== 1) throw new UsageError("tsp-gateway start");
321
430
  await installLoginItem(host, config);
322
- console.log(`Installed tsp-gateway ${version} as a login item.`);
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
+ ]);
323
435
  },
324
- uninstall: async ({ host }) => {
325
- console.log(
326
- `${await removeLoginItem(host) === "removed" ? "Login item removed." : "No login item was installed."} Pairing and folders are retained.`
327
- );
436
+ stop: async ({ args, host }) => {
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
+ ]);
328
447
  },
329
- unpair: async ({ host, config }) => {
330
- console.log(await unpairMachine(host, config));
448
+ update: async ({ args, host, config }) => {
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
+ ]);
331
455
  },
332
- start: ({ loginPath, paths, config, version }) => runLocal(loginPath, paths, config, version)
456
+ run: ({ loginPath, paths, config, version }) => runLocal(loginPath, paths, config, version)
333
457
  };
334
458
  function isVerbName(name) {
335
459
  return Object.hasOwn(VERBS, name);
336
460
  }
337
- function verbNamed(name) {
338
- return name !== void 0 && isVerbName(name) ? VERBS[name] : null;
339
- }
340
461
  async function main(args) {
341
- const [command, argument] = args;
342
- const verb = verbNamed(command);
462
+ const [command2, argument] = args;
463
+ const verb = command2 !== void 0 && isVerbName(command2) ? VERBS[command2] : null;
464
+ const version = package_default.version;
343
465
  if (!verb) {
344
- console.log(
345
- "Usage: tsp-gateway connect [folder] | disconnect | pair | add <folder> | remove <slug> | configure-launch <json> | configure-reporting <activity|off> | status [--json] | worktrees | start | install | uninstall | unpair"
346
- );
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
+ }
347
474
  return;
348
475
  }
349
- const version = package_default.version;
350
476
  const { paths, loginPath } = startupOptions(args, version);
351
477
  const config = await readConfig(paths.config);
352
478
  const environment = { ...process.env, PATH: config.loginPath ?? process.env["PATH"] };
@@ -372,18 +498,16 @@ async function main(args) {
372
498
  entry: fileURLToPath(import.meta.url),
373
499
  env: process.env,
374
500
  platform: process.platform,
375
- home: homedir(),
501
+ home: loginItemHome(),
376
502
  cwd: process.cwd(),
377
503
  tokens: keychain,
378
504
  openBrowser: openAuthorization,
379
- report: (line) => console.log(line)
505
+ report: (lines) => writeLines(lines)
380
506
  }
381
507
  });
382
508
  }
383
509
  void main(process.argv.slice(2)).catch((error) => {
384
- console.error(
385
- error instanceof Error ? error.message : "Gateway could not complete the command"
386
- );
510
+ writeLines(errorLines(error), process.stderr);
387
511
  process.exitCode = 1;
388
512
  });
389
513
  //# sourceMappingURL=cli.js.map