@treestructuredplanning/gateway 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Webify Services
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,207 @@
1
- # Temporary Holding Version
1
+ # TSP gateway
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The TSP gateway lets the [Tree-Structured Planning](https://treestructuredplanning.com)
4
+ (TSP) canvas start, stop and resume Claude Code and Codex sessions on your computer, in the
5
+ repository folders you register. It runs in the background under your own user account and
6
+ only connects outward to TSP.
7
+
8
+ ## Requirements
9
+
10
+ - Node.js **22 or newer**.
11
+ - Claude Code, or Codex **0.162.1 or newer**, installed separately and signed in with its
12
+ own login (`codex login` for Codex). The gateway never signs in for you.
13
+ - Each folder you register must be a local clone with a GitHub remote, and the harness must
14
+ trust it: run `claude` or `codex` in the folder once and accept its trust prompt. Codex
15
+ sessions never start in a folder Codex has not trusted, and trusting a parent folder does not
16
+ count for a repository inside it.
17
+ - On Linux, a running Secret Service such as GNOME Keyring or KWallet. The gateway will not
18
+ run without an OS credential store.
19
+ - Build must be available for your TSP account.
20
+
21
+ `connect` and `tsp-gateway status` say which harnesses can build in each folder and what is left to
22
+ you: installing or signing in to a harness, or accepting its trust prompt. Once one harness is ready
23
+ in a folder, steps for your other harnesses are optional.
24
+
25
+ ## Connect this computer
26
+
27
+ Run this inside the local clone of the repository you want TSP to build in:
28
+
29
+ ```sh
30
+ npx -y @treestructuredplanning/gateway@latest connect
31
+ ```
32
+
33
+ `connect [folder]` (the folder defaults to the current one) does the whole setup, and running
34
+ it again is safe:
35
+
36
+ 1. It checks that the folder is a clone with a GitHub remote, so a wrong folder fails before
37
+ anything changes.
38
+ 2. It pairs this computer with your TSP account, only after you approve in the browser window
39
+ it opens. It also prints the approval link in case no browser opens. A working pairing is
40
+ kept.
41
+ 3. It registers the folder.
42
+ 4. It installs a login item that starts the gateway when you log in.
43
+ 5. It prints a short summary: which harnesses are ready in each folder, and the steps only you can
44
+ take (install a harness, sign in, or run it there once to accept its trust prompt). They are
45
+ required until one harness is ready, and optional after that.
46
+
47
+ Run outside any clone, `connect` keeps the folders already registered and repairs the rest,
48
+ so it also fixes a stopped, outdated or revoked gateway. If TSP cannot be reached, nothing
49
+ changes; try again later. The login item runs the copy of the gateway that `connect` ran
50
+ from. With `npx` that is npm's cache, so if you clear that cache, run `connect` again.
51
+
52
+ ## Disconnect and uninstall
53
+
54
+ ```sh
55
+ npx -y @treestructuredplanning/gateway@latest disconnect
56
+ ```
57
+
58
+ `disconnect` removes the login item, then revokes this computer's pairing in TSP and deletes
59
+ its stored credential. Registered folders stay in the config file. If TSP cannot be reached,
60
+ the pairing is kept; run `disconnect` again. If the credential was already missing, the
61
+ computer may still be listed in TSP; remove it from Settings there.
62
+
63
+ To leave nothing behind, also delete the config and state folders listed under
64
+ [What it stores](#what-it-stores), and if you installed globally:
65
+
66
+ ```sh
67
+ npm uninstall --global @treestructuredplanning/gateway
68
+ ```
69
+
70
+ ## Commands
71
+
72
+ With a global install (`npm install --global @treestructuredplanning/gateway@latest`) the
73
+ command is `tsp-gateway`; with `npx`, use `npx -y @treestructuredplanning/gateway@latest`
74
+ in its place.
75
+
76
+ | Command | What it does |
77
+ | ----------------------------- | ------------------------------------------------------------------------------- |
78
+ | `connect [folder]` | Pair if needed, register the folder, install the login item, print a summary. |
79
+ | `disconnect` | Remove the login item, then unpair. |
80
+ | `pair` | Pair this computer with your TSP account (replaces any existing pairing). |
81
+ | `add <folder>` | Register a repository folder. |
82
+ | `remove <owner/name>` | Unregister a repository. |
83
+ | `configure-launch '<json>'` | Set how sessions get your shell environment (see below). |
84
+ | `configure-reporting <level>` | `activity` (default) or `off`: whether session activity is sent to TSP. |
85
+ | `status [--json]` | Show pairing, connection and each folder's next steps; `--json` is for scripts. |
86
+ | `start` | Run the gateway in the foreground. Ctrl-C stops it, not your sessions. |
87
+ | `install` | Install or refresh the login item. Run it again after upgrading the gateway. |
88
+ | `uninstall` | Remove the login item; keep the pairing and folders. |
89
+ | `unpair` | Revoke this computer's pairing in TSP and delete the stored credential. |
90
+
91
+ Registering or removing a folder takes effect in the running gateway without a restart.
92
+
93
+ ## What TSP can ask it to do
94
+
95
+ TSP can ask the gateway for exactly four things, and only in folders you registered:
96
+
97
+ - **Launch** a Claude Code or Codex session, with a prompt describing the TSP work you
98
+ started from the canvas.
99
+ - **Stop** that session.
100
+ - **Resume** that session, with the text you typed. With no text, a stopped session gets the
101
+ fixed prompt `Continue where you left off.`; a done or failed session reopens without a
102
+ prompt and waits for you.
103
+ - **Report status**: which harnesses are installed, signed in and trust each registered
104
+ folder, and how each launched session is doing.
105
+
106
+ Only your own clicks in TSP send a prompt. Sessions keep running if the gateway stops. A
107
+ session that finishes does not mean TSP has reviewed or accepted its work. Keep the
108
+ [TSP plugin](https://github.com/WebifyServices/tsp-plugin) installed so launched sessions
109
+ have TSP's tools.
110
+
111
+ The gateway never:
112
+
113
+ - changes your Claude Code or Codex settings, permissions or configuration, or passes any
114
+ flag that bypasses them. Your own settings govern every session.
115
+ - answers an approval prompt or question inside a session. When a session needs you, TSP
116
+ shows the command to open it yourself (`claude attach <id>` or `codex resume <id>`).
117
+ - signs in, accepts a trust prompt, or approves pairing for you.
118
+ - accepts a shell command, program, folder, file path or environment variable from TSP.
119
+ - runs anything in a folder you have not registered, or starts Codex in a folder Codex does
120
+ not trust.
121
+
122
+ For Codex, sessions run in Codex's own background service, which the gateway starts when
123
+ needed and never stops.
124
+
125
+ ## What leaves your computer
126
+
127
+ The gateway sends TSP only repository names (`owner/name`), which harnesses are available,
128
+ signed in and trusted per folder, and session status, including any waiting message with
129
+ folder paths removed. For each launched session it also sends what the session is doing
130
+ (reading, editing, running a command), when it was last active, and counts of files edited
131
+ and commands run; never file names, commands or transcript text. Folder paths, environment
132
+ variables, command lines, transcripts and raw error output stay on your computer. Run
133
+ `tsp-gateway configure-reporting off` to stop sending activity (`activity` turns it back on).
134
+
135
+ The gateway only connects outward, to TSP, and accepts no inbound connections. The only
136
+ exception is pairing: while you approve in the browser, it listens briefly on `127.0.0.1`
137
+ (your computer only) for the browser's reply, then stops.
138
+
139
+ ## How sessions get your environment
140
+
141
+ By default, Claude Code sessions start through your login shell, so variables your shell
142
+ startup files export reach the session: for example `CLAUDE_CONFIG_DIR`, `ANTHROPIC_*`,
143
+ `AWS_*`, proxy settings and version-manager `PATH` entries. Aliases and unexported shell
144
+ variables do not. Bash reads its login profile; source `.bashrc` from there if your terminal
145
+ relies on it. Codex's background service gets the same environment when the gateway starts
146
+ it, and keeps that environment until it restarts.
147
+
148
+ Supported shells are bash, zsh, ksh, fish, csh, tcsh and sh. With any other shell, or none,
149
+ the gateway falls back to `/bin/sh`, then to starting the harness directly. On Windows the
150
+ harness always starts directly and PowerShell or cmd profiles are not loaded. Your shell
151
+ startup must finish quickly, must not wait for input, and must not redirect its own output to
152
+ a file or terminal. If it takes longer than 10 seconds, for example on a busy computer, the
153
+ session starts with the environment your shell gave the gateway last time; the first time, the
154
+ gateway waits up to 30 seconds before it gives up.
155
+
156
+ Change this with `configure-launch`, which sets the `launch` section of the gateway's config
157
+ file. Omitted settings use defaults:
158
+
159
+ ```sh
160
+ # Restore the default login-shell behaviour.
161
+ tsp-gateway configure-launch '{}'
162
+
163
+ # Use the gateway's own environment directly.
164
+ tsp-gateway configure-launch '{"mode":"direct"}'
165
+
166
+ # Choose a shell, run through direnv in the session's folder, and add a nonsecret variable.
167
+ # Allow the repository's .envrc first; direnv exec . must also succeed from your home folder.
168
+ tsp-gateway configure-launch '{"shell":"/bin/zsh","wrapper":["direnv","exec","."],"env":{"AWS_PROFILE":"development"}}'
169
+
170
+ # Any program of yours can wrap the harness; give it as an argument list, not a command string.
171
+ tsp-gateway configure-launch '{"wrapper":["/absolute/path/to/company-launcher","--profile","development"]}'
172
+ tsp-gateway status
173
+ ```
174
+
175
+ - `mode`: `"login-shell"` (default) or `"direct"`.
176
+ - `shell`: an absolute path.
177
+ - `wrapper`: an argument list whose program is an absolute path or a command name. The harness
178
+ command is appended to it. It also runs for the gateway's status checks, sometimes from your
179
+ home folder, so keep it fast and noninteractive.
180
+ - `env`: variable names and plain string values, applied after your shell startup.
181
+
182
+ Unknown fields and command strings are rejected. **Keep secrets in your shell setup or
183
+ keychain, not in this file.** `status` shows the shell in use and why, the wrapper program and
184
+ the names of `env` variables, never their values.
185
+
186
+ If a session's environment differs from your terminal's, check the shell and reason in
187
+ `tsp-gateway status` and the gateway log, then check that your shell startup exports the
188
+ variables you need. Your terminal and the login item can have different `$SHELL` values. For a
189
+ slow or interactive startup, make its interactive parts depend on a terminal, use a wrapper,
190
+ or choose `direct`. Changes apply to sessions started afterwards, not to running ones.
191
+
192
+ ## What it stores
193
+
194
+ | What | Where |
195
+ | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
196
+ | Credential | One OS credential-store entry (Keychain, Credential Manager or Secret Service) named `com.treestructuredplanning.gateway`, holding the pairing's refresh token. |
197
+ | Config | `${XDG_CONFIG_HOME:-~/.config}/tsp-gateway/config.json` (mode 0600, folder 0700), or `%APPDATA%\tsp-gateway` on Windows: pairing identity, registered folders and their paths, captured `PATH`, launch settings. |
198
+ | State and logs | `${XDG_STATE_HOME:-~/.local/state}/tsp-gateway`, or `%LOCALAPPDATA%\tsp-gateway` on Windows: status, logs, and a private record of the commands it received, which can include launch prompts and your resume text. Never uploaded. |
199
+ | Login item | `~/Library/LaunchAgents/com.treestructuredplanning.tsp-gateway.plist` (macOS), `~/.config/systemd/user/tsp-gateway.service` (Linux), or the `com.treestructuredplanning.tsp-gateway` logon task (Windows). |
200
+
201
+ On Windows, access to these folders follows your user profile's permissions. Delete the state
202
+ folder only after `disconnect`, once no gateway is running.
203
+
204
+ ## Help
205
+
206
+ See the [TSP documentation](https://treestructuredplanning.com/docs) or email
207
+ `support@treestructuredplanning.com`.
package/dist/cli.js ADDED
@@ -0,0 +1,373 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
3
+ import {
4
+ ActivityReporter,
5
+ Commands,
6
+ GATEWAY_CLOSE_DISPOSITION,
7
+ GatewayStatus,
8
+ HarnessExecutor,
9
+ Journal,
10
+ OAuthTokens,
11
+ addRepository,
12
+ awaitDaemonConnection,
13
+ builtinHarnesses,
14
+ connect,
15
+ connectLines,
16
+ daemonConnection,
17
+ daemonLock,
18
+ decodeLaunchConfig,
19
+ decodeReporting,
20
+ disconnect,
21
+ execute,
22
+ field,
23
+ folderSetups,
24
+ installLoginItem,
25
+ isObject,
26
+ keychain,
27
+ locations,
28
+ pairMachine,
29
+ parseJson,
30
+ privateDirectory,
31
+ readConfig,
32
+ readLaunchObservation,
33
+ removeLoginItem,
34
+ runDaemon,
35
+ saveConfig,
36
+ statusLines,
37
+ unpairMachine,
38
+ validSlug,
39
+ validateOrigin,
40
+ watchConfig
41
+ } from "./shared-M7CEELPK.js";
42
+
43
+ // src/cli.ts
44
+ import { readFile } from "node:fs/promises";
45
+ import { homedir } from "node:os";
46
+ import { isAbsolute, join } from "node:path";
47
+ import { fileURLToPath } from "node:url";
48
+ import { parseArgs } from "node:util";
49
+
50
+ // package.json
51
+ var package_default = {
52
+ name: "@treestructuredplanning/gateway",
53
+ version: "0.1.2",
54
+ description: "Outbound local harness gateway for Tree-Structured Planning",
55
+ type: "module",
56
+ engines: {
57
+ node: ">=22"
58
+ },
59
+ bin: {
60
+ "tsp-gateway": "dist/cli.js"
61
+ },
62
+ files: [
63
+ "dist/cli.js",
64
+ "dist/shared-*.js",
65
+ "dist/vendor.js",
66
+ "dist/gateway-schema.json",
67
+ "README.md"
68
+ ],
69
+ scripts: {
70
+ build: "node scripts/build.mjs",
71
+ prepack: "pnpm build",
72
+ test: "pnpm build && node --test --test-concurrency=3 test/*.test.mjs",
73
+ "measure:launch": "pnpm build && node scripts/measure-launch.mjs",
74
+ typecheck: "tsc --noEmit",
75
+ lint: "eslint src --report-unused-disable-directives --max-warnings 0",
76
+ check: "pnpm typecheck && pnpm lint && pnpm format:check && pnpm test",
77
+ "format:check": 'prettier --check "src/**/*.ts" "test/*.mjs" "scripts/*.mjs" README.md package.json tsconfig.json',
78
+ "test:coverage": 'pnpm build && node --test-concurrency=3 --experimental-test-coverage --test-coverage-lines=80 --test --test-coverage-include="dist/*.js" --test-coverage-exclude="dist/vendor.js" test/*.test.mjs'
79
+ },
80
+ devDependencies: {
81
+ "@tsp/shared": "workspace:*",
82
+ "@types/node": "^24.10.9",
83
+ esbuild: "0.25.12",
84
+ typescript: "^5.7.2"
85
+ },
86
+ license: "MIT",
87
+ dependencies: {
88
+ "@napi-rs/keyring": "2.1.2",
89
+ "smol-toml": "1.6.0",
90
+ ws: "8.21.0"
91
+ },
92
+ publishConfig: {
93
+ access: "public"
94
+ },
95
+ repository: {
96
+ type: "git",
97
+ url: "git+https://github.com/WebifyServices/tsp.git",
98
+ directory: "packages/tsp-gateway"
99
+ }
100
+ };
101
+
102
+ // src/cli.ts
103
+ async function runLocal(loginPath, paths, config, version) {
104
+ const pairing = config.pairing;
105
+ if (!pairing) throw new Error("Run tsp-gateway pair first.");
106
+ await privateDirectory(paths.state);
107
+ const release = await daemonLock(paths.state);
108
+ const abort = new AbortController();
109
+ const stop = () => abort.abort();
110
+ process.once("SIGINT", stop);
111
+ process.once("SIGTERM", stop);
112
+ try {
113
+ const journal = new Journal(join(paths.state, `${pairing.machine_id}-receipts.jsonl`));
114
+ await journal.load();
115
+ const repositories = async () => (await readConfig(paths.config)).repositories;
116
+ const environment = {
117
+ ...process.env,
118
+ PATH: loginPath ?? config.loginPath ?? process.env["PATH"]
119
+ };
120
+ const executor = new HarnessExecutor(environment, {
121
+ config: async () => (await readConfig(paths.config)).launch,
122
+ changed: () => {
123
+ void status.refresh().catch(() => console.error("Could not update gateway launch status"));
124
+ }
125
+ });
126
+ const status = new GatewayStatus(join(paths.state, "status.json"), executor);
127
+ const drivers = builtinHarnesses(environment, executor);
128
+ const commands = new Commands(journal, drivers, repositories, {
129
+ activity: new ActivityReporter(async () => (await readConfig(paths.config)).reporting)
130
+ });
131
+ await runDaemon({
132
+ pairing,
133
+ version,
134
+ drivers,
135
+ commands,
136
+ tokens: new OAuthTokens(pairing, keychain(pairing.origin)),
137
+ repositories: async () => drivers.repositories(await repositories()),
138
+ watchFacts: (changed) => watchConfig(paths.config, () => {
139
+ executor.invalidate();
140
+ changed();
141
+ void status.refresh().catch(() => console.error("Could not update gateway launch status"));
142
+ }),
143
+ signal: abort.signal,
144
+ status: (current) => status.update(current)
145
+ });
146
+ } finally {
147
+ process.removeListener("SIGINT", stop);
148
+ process.removeListener("SIGTERM", stop);
149
+ await release();
150
+ }
151
+ }
152
+ async function readStatus(paths, config, drivers, executor, idle = "Not running") {
153
+ const connection = await daemonConnection(join(paths.state, "status.json")) ?? idle;
154
+ let daemonLaunch = null;
155
+ let lastMessage = null;
156
+ let closeCode = null;
157
+ let closeDisposition = null;
158
+ try {
159
+ const status = parseJson(await readFile(join(paths.state, "status.json"), "utf8"));
160
+ if (isObject(status)) {
161
+ daemonLaunch = readLaunchObservation(field(status, "launch"));
162
+ const code = field(status, "close_code"), recovery = field(status, "close_disposition");
163
+ if (typeof code === "number" && Number.isInteger(code)) closeCode = code;
164
+ closeDisposition = Object.values(GATEWAY_CLOSE_DISPOSITION).find((value) => value === recovery) ?? null;
165
+ }
166
+ if (isObject(status) && typeof field(status, "message") === "string")
167
+ lastMessage = field(status, "message");
168
+ } catch {
169
+ }
170
+ return {
171
+ paired: config.pairing !== null,
172
+ machine_id: config.pairing?.machine_id ?? null,
173
+ connection,
174
+ last_message: lastMessage,
175
+ close_code: closeCode,
176
+ close_disposition: closeDisposition,
177
+ harnesses: await drivers.detect(),
178
+ launch: await executor.status(),
179
+ launch_source: "status-probe",
180
+ last_daemon_launch: daemonLaunch,
181
+ repositories: Object.keys(config.repositories),
182
+ reporting: config.reporting
183
+ };
184
+ }
185
+ function harnessName(drivers) {
186
+ return (harness) => drivers.get(harness).displayName;
187
+ }
188
+ async function printStatus(paths, config, drivers, executor, json) {
189
+ const status = await readStatus(paths, config, drivers, executor);
190
+ if (json) {
191
+ console.log(JSON.stringify(status, null, 2));
192
+ return;
193
+ }
194
+ const view = machineView(status);
195
+ const setups = await folderSetups(drivers, config, null);
196
+ for (const line of statusLines(view, setups, harnessName(drivers))) console.log(line);
197
+ }
198
+ function machineView(status) {
199
+ return {
200
+ machineId: status.machine_id,
201
+ connection: status.connection,
202
+ lastMessage: status.last_message,
203
+ launch: status.launch,
204
+ reporting: status.reporting
205
+ };
206
+ }
207
+ function startupOptions(args, version) {
208
+ const options = args[0] === "start" ? parseArgs({
209
+ args: args.slice(1),
210
+ options: {
211
+ "expected-version": { type: "string" },
212
+ "config-file": { type: "string" },
213
+ "state-dir": { type: "string" },
214
+ "login-path": { type: "string" }
215
+ }
216
+ }).values : void 0;
217
+ if (options?.["expected-version"] !== void 0 && options["expected-version"] !== version)
218
+ throw new Error("Installed gateway version changed. Run tsp-gateway install again.");
219
+ const defaults = locations();
220
+ const paths = {
221
+ config: options?.["config-file"] ?? defaults.config,
222
+ state: options?.["state-dir"] ?? defaults.state
223
+ };
224
+ if (!isAbsolute(paths.config) || !isAbsolute(paths.state))
225
+ throw new Error("Gateway storage paths must be absolute");
226
+ return { paths, loginPath: options?.["login-path"] };
227
+ }
228
+ async function openAuthorization(url) {
229
+ const platform = process.platform;
230
+ const result = platform === "darwin" ? await execute("open", [url], process.env) : platform === "win32" ? await execute("rundll32.exe", ["url.dll,FileProtocolHandler", url], process.env) : await execute("xdg-open", [url], process.env);
231
+ if (result.code !== 0) throw new Error("Could not open the authorization browser");
232
+ }
233
+ function gatewayOrigin(config) {
234
+ return validateOrigin(
235
+ process.env["TSP_GATEWAY_ORIGIN"] ?? config.pairing?.origin ?? "https://treestructuredplanning.com"
236
+ );
237
+ }
238
+ async function configureLaunch(args, config, path) {
239
+ const json = args[1];
240
+ if (!json || args.length !== 2)
241
+ throw new Error("Usage: tsp-gateway configure-launch '<JSON object>'");
242
+ config.launch = decodeLaunchConfig(parseJson(json));
243
+ await saveConfig(path, config);
244
+ console.log("Launch settings saved. The running gateway picks up the change automatically.");
245
+ }
246
+ async function configureReporting(args, config, path) {
247
+ if (args.length !== 2) throw new Error("Usage: tsp-gateway configure-reporting <activity|off>");
248
+ config.reporting = decodeReporting(args[1]);
249
+ await saveConfig(path, config);
250
+ console.log(
251
+ 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."
252
+ );
253
+ }
254
+ var VERBS = {
255
+ connect: async ({ args, argument, config, host, paths, drivers, executor }) => {
256
+ if (args.length > 2) throw new Error("Usage: tsp-gateway connect [folder]");
257
+ const since = Date.now();
258
+ const outcome = await connect(host, config, argument);
259
+ const reported = outcome.loginItem === "installed" ? await awaitDaemonConnection(join(paths.state, "status.json"), since) : null;
260
+ const status = await readStatus(
261
+ paths,
262
+ config,
263
+ drivers,
264
+ executor,
265
+ outcome.loginItem === "installed" && reported === null ? "Starting" : void 0
266
+ );
267
+ const setups = await folderSetups(drivers, config, outcome.repository);
268
+ for (const line of connectLines(machineView(status), setups, harnessName(drivers)))
269
+ console.log(line);
270
+ },
271
+ disconnect: async ({ args, host, config }) => {
272
+ if (args.length !== 1) throw new Error("Usage: tsp-gateway disconnect");
273
+ const outcome = await disconnect(host, config);
274
+ console.log(
275
+ `${outcome.loginItem === "removed" ? "Login item removed." : "No login item was installed."} ${outcome.pairing} Registered folders are kept.`
276
+ );
277
+ },
278
+ pair: async ({ host, config }) => {
279
+ await pairMachine(host, config);
280
+ console.log("Paired. Use tsp-gateway add <folder>, then tsp-gateway install.");
281
+ },
282
+ add: async ({ args, argument, host, config, drivers }) => {
283
+ if (!argument || args.length !== 2) throw new Error("Usage: tsp-gateway add <folder>");
284
+ const registered = await addRepository(host, config, argument);
285
+ console.log(
286
+ `Registered ${registered.slug}. ${drivers.setupInstructions().join(" ")} The running gateway picks up the change automatically.`
287
+ );
288
+ },
289
+ remove: async ({ argument, config, paths }) => {
290
+ if (!argument || !validSlug(argument.toLowerCase()))
291
+ throw new Error("Usage: tsp-gateway remove <owner/name>");
292
+ delete config.repositories[argument.toLowerCase()];
293
+ await saveConfig(paths.config, config);
294
+ console.log("Repository removed. The running gateway picks up the change automatically.");
295
+ },
296
+ "configure-launch": ({ args, config, paths }) => configureLaunch(args, config, paths.config),
297
+ "configure-reporting": ({ args, config, paths }) => configureReporting(args, config, paths.config),
298
+ status: ({ args, paths, config, drivers, executor }) => {
299
+ const json = args[1] === "--json";
300
+ if (args.length > 2 || args.length === 2 && !json)
301
+ throw new Error("Usage: tsp-gateway status [--json]");
302
+ return printStatus(paths, config, drivers, executor, json);
303
+ },
304
+ install: async ({ host, config, version }) => {
305
+ await installLoginItem(host, config);
306
+ console.log(`Installed tsp-gateway ${version} as a login item.`);
307
+ },
308
+ uninstall: async ({ host }) => {
309
+ console.log(
310
+ `${await removeLoginItem(host) === "removed" ? "Login item removed." : "No login item was installed."} Pairing and folders are retained.`
311
+ );
312
+ },
313
+ unpair: async ({ host, config }) => {
314
+ console.log(await unpairMachine(host, config));
315
+ },
316
+ start: ({ loginPath, paths, config, version }) => runLocal(loginPath, paths, config, version)
317
+ };
318
+ function isVerbName(name) {
319
+ return Object.hasOwn(VERBS, name);
320
+ }
321
+ function verbNamed(name) {
322
+ return name !== void 0 && isVerbName(name) ? VERBS[name] : null;
323
+ }
324
+ async function main(args) {
325
+ const [command, argument] = args;
326
+ const verb = verbNamed(command);
327
+ if (!verb) {
328
+ console.log(
329
+ "Usage: tsp-gateway connect [folder] | disconnect | pair | add <folder> | remove <slug> | configure-launch <json> | configure-reporting <activity|off> | status [--json] | start | install | uninstall | unpair"
330
+ );
331
+ return;
332
+ }
333
+ const version = package_default.version;
334
+ const { paths, loginPath } = startupOptions(args, version);
335
+ const config = await readConfig(paths.config);
336
+ const environment = { ...process.env, PATH: config.loginPath ?? process.env["PATH"] };
337
+ const executor = new HarnessExecutor(environment, {
338
+ config: async () => config.launch,
339
+ log: () => {
340
+ }
341
+ });
342
+ await verb({
343
+ args,
344
+ argument,
345
+ version,
346
+ paths,
347
+ loginPath,
348
+ config,
349
+ drivers: builtinHarnesses(environment, executor),
350
+ executor,
351
+ host: {
352
+ paths,
353
+ origin: gatewayOrigin(config),
354
+ version,
355
+ node: process.execPath,
356
+ entry: fileURLToPath(import.meta.url),
357
+ env: process.env,
358
+ platform: process.platform,
359
+ home: homedir(),
360
+ cwd: process.cwd(),
361
+ tokens: keychain,
362
+ openBrowser: openAuthorization,
363
+ report: (line) => console.log(line)
364
+ }
365
+ });
366
+ }
367
+ void main(process.argv.slice(2)).catch((error) => {
368
+ console.error(
369
+ error instanceof Error ? error.message : "Gateway could not complete the command"
370
+ );
371
+ process.exitCode = 1;
372
+ });
373
+ //# sourceMappingURL=cli.js.map