@nurix/nustack 0.23.8 → 0.23.10

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/index.js CHANGED
@@ -1,453 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from "node:fs";
3
- import { Command } from "commander";
4
- import { runLogin } from "./commands/login.js";
5
- import { runInit } from "./commands/init.js";
6
- import { runAdd } from "./commands/add.js";
7
- import { runList } from "./commands/list.js";
8
- import { runSync } from "./commands/sync.js";
9
- import { runDescribe } from "./commands/describe.js";
10
- import { runValidate } from "./commands/validate.js";
11
- import { runGraph } from "./commands/graph.js";
12
- import { runLogscope } from "./commands/logscope.js";
13
- import { runDoctor } from "./commands/doctor.js";
14
- import { runTokenCreate, runTokenList, runTokenRevoke } from "./commands/token.js";
15
- import { runOpen } from "./commands/open.js";
16
- import { runBootstrap } from "./commands/bootstrap.js";
17
- import { runLogout } from "./commands/logout.js";
18
- import { runTelemetry } from "./commands/telemetry.js";
19
- import { runSearch, runSearchServices } from "./commands/search.js";
20
- import { runDeviceList, runDeviceRevoke, runDeviceStatus } from "./commands/device.js";
21
- import { registerProjectSyncCommands } from "./commands/project-sync.js";
22
- import { registerProjectCommands } from "./commands/project.js";
23
- import { registerDeployCommands, registerLogsCommand, registerProjectSetCommand } from "./commands/deploy.js";
24
- import { registerActivityCommand } from "./commands/activity.js";
25
- import { registerWhoamiCommand } from "./commands/whoami.js";
26
- import { registerApiCommand } from "./commands/api.js";
27
- import { registerMcpCommands } from "./commands/mcp.js";
28
- import { NON_INTERACTIVE_VARIABLE } from "./lib/interactive.js";
29
- import { runOrganizationList, runOrganizationCreate, runOrganizationUse } from "./commands/organization.js";
30
- import { runDocsList, runDocsShow, runDocsStatus } from "./commands/docs.js";
31
- import { runHandoffList, runHandoffShow } from "./commands/handoff.js";
32
- import { runToolkitStatus, runToolkitReconcile } from "./commands/toolkit.js";
33
- import { runHarnessMount, runHarnessStatus } from "./commands/harness.js";
34
- import { runSessionsList, runSessionsPrune, runSessionsRecord, runSessionsServe, } from "./commands/sessions.js";
35
- import { registerReviewCommands } from "./commands/review.js";
36
- import { registerRecordsCommands, startDrainIfDue } from "./commands/records.js";
37
- import { RECORD_ALIAS_GROUPS, registerRecordAliases } from "./commands/recordAliases.js";
38
- import { runAgentContext, runAgentHookInstall, runAgentHookRemove } from "./commands/agent.js";
39
- import { printJsonError } from "./lib/json_output.js";
40
- import { setCliVersion } from "./lib/auth_grant.js";
41
- const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
42
- setCliVersion(version);
43
- const program = new Command();
44
- program
45
- .name("nustack")
46
- .description("Bootstrap NuStack services into your repo via the NuStack discovery plane.")
47
- .version(version)
48
- .option("--nustack-url <url>", "NuStack base URL (defaults to $NUSTACK_URL, then the hosted instance)")
49
- .option("--non-interactive", `never prompt — take the default or refuse with a coded error (also $${NON_INTERACTIVE_VARIABLE}=1)`)
50
- .action(async () => runBootstrap(program.opts()));
51
- program.addHelpText("after", "\nRun `nustack` with no command to bootstrap: it checks your sign-in, runs login if needed, then init.");
52
- program
53
- .command("login")
54
- .description("Sign in with your browser; this machine's grant is saved to your OS keychain")
55
- .option("--no-open", "don't auto-open the browser; just print the sign-in URL")
56
- .option("--manual", "sign in anywhere and paste the code here instead of using a browser on this machine")
57
- .option("--force", "sign in again even if this machine is already signed in")
58
- .action(async (options) => runLogin(program.opts(), options));
59
- program
60
- .command("logout")
61
- .description("Sign out: end this machine's grant and clear the shared keychain credential (both CLI and desktop)")
62
- .option("--forget-device", "also clear the shared ~/.nustack/device_id machine identity")
63
- .action(async (options) => runLogout(program.opts(), { forgetDevice: options.forgetDevice }));
64
- program
65
- .command("init")
66
- .description("Onboard this folder: sign in, then bind it to a Project (the onboarding router)")
67
- .option("--organization <id>", "the Organization to create or select the Project in")
68
- .option("--yes", "pre-confirm the populated-folder onboarding guard")
69
- .action(async (options) => runInit({ ...program.opts(), ...options }));
70
- program
71
- .command("add [service]")
72
- .description("Record a stack service in this repo: install its package, add the consumes edge")
73
- .option("--json", "emit the versioned machine envelope instead of interactive output")
74
- .option("--yes", "assume yes for the package-install and manifest-scaffold prompts")
75
- .action(async (service, options) => runAdd(service, { ...program.opts(), ...options }));
76
- program
77
- .command("list")
78
- .description("List the services in the NuStack catalogue")
79
- .option("--json", "emit the versioned machine envelope wrapping the catalogue entries")
80
- .action(async (options) => runList(options, program.opts()));
81
- program
82
- .command("sync")
83
- .description("Project this Project's Service credentials into the managed .env block (not Documents or Git)")
84
- .option("--project <id>", "the Project to act as (defaults to nustack.service.json / NUSTACK_WORKSPACE_ID)")
85
- .option("--json", "emit the versioned machine envelope instead of interactive output")
86
- .action(async (options) => runSync({ ...program.opts(), ...options }));
87
- program
88
- .command("describe <service>")
89
- .description("Show the full catalogue entry for a service")
90
- .option("--json", "emit the raw catalogue entry as JSON")
91
- .action(async (service, options) => runDescribe(service, options, program.opts()));
92
- program
93
- .command("validate [manifest]")
94
- .description("Validate an nustack.service.json (path or URL) against the nustack.dev/v1 schema")
95
- .option("--schema <pathOrUrl>", "override the bundled packages/contracts/spec/schema.json")
96
- .option("--json", "emit the versioned machine envelope with { target, isValid, errors }")
97
- .action(async (manifest, options) => runValidate(manifest, options));
98
- program
99
- .command("graph [fn] [args...]")
100
- .description("The code graph: ask a question of this repository's index, or `index` / `status` / `functions`")
101
- .option("--repo <pathOrId>", "the repository to ask about (default: the working tree's root)")
102
- .option("--no-refresh", "answer from the index as it stands, however old")
103
- .option("--budget <n>", "token ceiling for the answer; 0 means unbounded")
104
- .option("--commits <n>", "history depth for `graph index` (default 5000)")
105
- .option("--json", "emit the versioned machine envelope with the answer as data")
106
- .allowUnknownOption()
107
- .allowExcessArguments()
108
- .action(async (_fn, _args, options) => runGraph(process.argv, options));
109
- program
110
- .command("logscope [fn] [args...]")
111
- .description("Log tracking: ask this machine's log corpus a question, or `index` / `corpora` / `allow` / `prune`")
112
- .option("--root <dir>", "the project this command is about (default: the working tree's root)")
113
- .option("--corpus <ref>", "a corpus id, or a path belonging to one")
114
- .option("--budget <n>", "token ceiling for the answer; 0 means unbounded")
115
- .option("--limit <n>", "rows requested — beats a default budget, never an explicit one")
116
- .option("--retain <days>", "retention for `index`; 0 keeps the corpus until it is forgotten")
117
- .option("--examples", "keep up to three exemplar log lines per template (off by default)")
118
- .option("--no-redact", "store exemplars unredacted (loud, recorded on the corpus)")
119
- .option("--since <ts>", "window start for container sources")
120
- .option("--until <ts>", "window end for container sources")
121
- .option("--revision <sha>", "the source revision these logs were written by")
122
- .option("--note <text>", "a note recorded with an `allow` grant")
123
- .option("--dry-run", "for `prune`: report what would be dropped and delete nothing")
124
- .option("--json", "emit the versioned machine envelope with the answer as data")
125
- .allowUnknownOption()
126
- .allowExcessArguments()
127
- .action(async (_fn, _args, options) => runLogscope(process.argv, options));
128
- program
129
- .command("doctor")
130
- .description("Run the full local diagnostics matrix (identity, repository, manifests, toolkit, telemetry, credentials)")
131
- .option("--project <id>", "the Project to diagnose (defaults to the bound repository)")
132
- .option("--json", "emit the versioned machine envelope (secrets and absolute paths redacted)")
133
- .option("--local-verbose", "include Device-local absolute paths in the output")
134
- .action(async (options) => runDoctor({ ...program.opts(), ...options }));
135
- registerDeployCommands(program, () => program.opts());
136
- registerLogsCommand(program, () => program.opts());
137
- registerWhoamiCommand(program, () => program.opts());
138
- registerApiCommand(program, () => program.opts());
139
- registerMcpCommands(program, () => program.opts());
140
- program
141
- .command("open <service>")
142
- .description("Open the service's dev endpoint (or repository) in the browser")
143
- .option("--env <name>", "pick a specific endpoint environment (default: dev)")
144
- .option("--json", "print the resolved URL as the machine envelope instead of launching")
145
- .action(async (service, options) => runOpen(service, options, program.opts()));
146
- const token = program.command("token").description("Mint, list and revoke your personal access tokens (the NUSTACK_TOKEN a pipeline or agent uses)");
147
- token
148
- .command("create")
149
- .description("Mint a personal access token; the secret is printed once, on stdout alone")
150
- .requiredOption("--label <label>", "a name for the token, unique among your live ones")
151
- .option("--expires <days>", "days until the token expires (1–365); no expiry when omitted")
152
- .option("--json", "emit the versioned machine envelope")
153
- .action(async (options) => runTokenCreate(options, program.opts()));
154
- token
155
- .command("list")
156
- .description("List your personal access tokens (never a secret)")
157
- .option("--json", "emit the versioned machine envelope")
158
- .action(async (options) => runTokenList(options, program.opts()));
159
- token
160
- .command("revoke <token-id>")
161
- .description("Revoke a personal access token; it stops working on the next request")
162
- .option("--json", "emit the versioned machine envelope")
163
- .action(async (tokenId, options) => runTokenRevoke(tokenId, options, program.opts()));
164
- const device = program.command("device").description("Inspect your signed-in devices and end this machine's access");
165
- device
166
- .command("list")
167
- .description("List your signed-in devices (never a token)")
168
- .option("--json", "emit the versioned machine envelope")
169
- .action(async (options) => runDeviceList(options, program.opts()));
170
- device
171
- .command("status")
172
- .description("Show this device's local state merged with its server record")
173
- .option("--json", "emit the versioned machine envelope")
174
- .action(async (options) => runDeviceStatus(options, program.opts()));
175
- device
176
- .command("revoke [device-id]")
177
- .description("End this machine's access (other machines are revoked from Profile › Devices)")
178
- .option("--json", "emit the versioned machine envelope")
179
- .option("--yes", "skip the confirmation prompt")
180
- .action(async (deviceId, options) => runDeviceRevoke(deviceId, options, program.opts()));
181
- program
182
- .command("telemetry [action]")
183
- .description("Inspect or control telemetry (status | enable | disable | reinstall | output). Inside a bound folder, enable/disable move that folder alone; output points the shipper at your own Elastic, its key read from NUSTACK_ELASTIC_API_KEY")
184
- .option("--json", "emit the versioned machine envelope")
185
- .option("--device", "move this machine's switch instead of the current folder's")
186
- .option("--local-verbose", "include each folder's absolute path (local consumers only — never pipe into a log)")
187
- .option("--elastic-url <url>", "output: the Elastic endpoint (default NUSTACK_ELASTIC_URL)")
188
- .option("--index <name>", "output: the index events are written to (default claude-sessions)")
189
- .action(async (action, options) => {
190
- const allowed = ["status", "enable", "disable", "reinstall", "output"];
191
- const chosen = (allowed.includes(action ?? "") ? action : "status");
192
- return runTelemetry(chosen, {
193
- ...program.opts(),
194
- json: options.json,
195
- device: options.device,
196
- localVerbose: options.localVerbose,
197
- elasticUrl: options.elasticUrl,
198
- index: options.index,
199
- });
200
- });
201
- const toLimit = (value) => Number.parseInt(value, 10);
202
- const search = program
203
- .command("search [keywords...]")
204
- .description("Search the NuStack Directory for projects by keyword")
205
- .option("--json", "emit the raw results array as JSON")
206
- .option("--category <cat>", "filter projects by category")
207
- .option("--limit <n>", "max results (default 20)", toLimit)
208
- .action(async (keywords, options) => runSearch(keywords, options, program.opts()));
209
- search
210
- .command("services [keywords...]")
211
- .description("Search the services registry by keyword (then `nustack add <name>` to integrate)")
212
- .option("--json", "emit the raw results array as JSON")
213
- .option("--type <type>", "filter services by type")
214
- .option("--limit <n>", "max results (default 20)", toLimit)
215
- .action(async (keywords, options) => runSearchServices(keywords, { ...search.opts(), ...options }, program.opts()));
216
- search.addHelpText("after", '\n`services` is a reserved subcommand. To search projects for the literal word "services", use the\n' +
217
- "explicit separator: `nustack search -- services` (everything after `--` is an projects query).");
218
- const organization = program.command("organization").description("Work with your NuStack Organizations");
219
- organization
220
- .command("list")
221
- .description("List your Organization memberships (name, slug, role, active marker)")
222
- .option("--json", "emit the versioned machine envelope")
223
- .action(async (options) => runOrganizationList(options, program.opts()));
224
- organization
225
- .command("create <name>")
226
- .description("Create an Organization and print it")
227
- .option("--json", "emit the versioned machine envelope")
228
- .action(async (name, options) => runOrganizationCreate(name, options, program.opts()));
229
- organization
230
- .command("use <id-or-slug>")
231
- .description("Set the active Organization context for this device")
232
- .option("--json", "emit the versioned machine envelope")
233
- .action(async (target, options) => runOrganizationUse(target, options, program.opts()));
234
- const project = program.command("project").description("Work with NuStack Projects");
235
- registerProjectCommands(project, () => program.opts());
236
- registerProjectSetCommand(project, () => program.opts());
237
- registerActivityCommand(project, () => program.opts());
238
- registerProjectSyncCommands(project, () => program.opts());
239
- registerReviewCommands(program.command("review").description("Read and mirror NuStack Review items"), () => program.opts());
240
- registerRecordsCommands(program.command("records").description("Emit, send and list harness records"), () => program.opts());
241
- registerRecordAliases(program, () => program.opts());
242
- program.hook("preAction", async (_program, action) => {
243
- if (program.opts().nonInteractive)
244
- process.env[NON_INTERACTIVE_VARIABLE] = "1";
245
- const group = action.parent?.name() ?? "";
246
- if (group !== "records" && !RECORD_ALIAS_GROUPS.includes(group))
247
- await startDrainIfDue(program.opts());
248
- });
249
- const docs = program.command("docs").description("Work with a Project's Documents");
250
- docs
251
- .command("list")
252
- .description("List the Project's Documents")
253
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
254
- .option("--json", "emit the versioned machine envelope")
255
- .action(async (options) => runDocsList(options, program.opts()));
256
- docs
257
- .command("show <slug-or-id>")
258
- .description("Show a Document: a bounded inline body or its content URL")
259
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
260
- .option("--json", "emit the versioned machine envelope")
261
- .action(async (target, options) => runDocsShow(target, options, program.opts()));
262
- docs
263
- .command("status")
264
- .description("Report per-path local/cloud Document convergence for the bound repository")
265
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
266
- .option("--json", "emit the versioned machine envelope")
267
- .action(async (options) => runDocsStatus(options, program.opts()));
268
- const handoff = program.command("handoff").description("Work with a Project's Handoffs");
269
- handoff
270
- .command("list")
271
- .description("List the Project's Handoffs")
272
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
273
- .option("--json", "emit the versioned machine envelope")
274
- .action(async (options) => runHandoffList(options, program.opts()));
275
- handoff
276
- .command("show <id>")
277
- .description("Show a Handoff (add --targets for the binding-scoped per-target manifest)")
278
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
279
- .option("--targets", "list each target's path, operation, and base semantics")
280
- .option("--json", "emit the versioned machine envelope")
281
- .action(async (id, options) => runHandoffShow(id, options, program.opts()));
282
- const sessions = program
283
- .command("sessions")
284
- .description("Sessions on this machine — the engine the desktop drives, and the record of what ran");
285
- sessions
286
- .command("serve")
287
- .description("Run the long-lived session supervisor: JSONL frames on stdin/stdout (used by the NuStack desktop)")
288
- .action(async () => runSessionsServe(version));
289
- sessions
290
- .command("record")
291
- .description("Record the sessions one desktop scan found in a bound folder (used by the NuStack desktop)")
292
- .option("--scan <json>", "the scan payload as JSON, or @<path> to read it from a file")
293
- .option("--json", "emit the versioned machine envelope")
294
- .action(async (options) => runSessionsRecord(options, program.opts()));
295
- sessions
296
- .command("list")
297
- .description("List the sessions this machine's engine opened, and what each one's worktree and branch still hold")
298
- .option("--json", "emit the versioned machine envelope")
299
- .action(async (options) => runSessionsList(options));
300
- sessions
301
- .command("prune")
302
- .description("Reclaim the worktree and branch of a session that has ended (preview unless --yes)")
303
- .option("--session <id>", "reclaim one session instead of every reclaimable one")
304
- .option("--yes", "apply the preview without prompting")
305
- .option("--force", "also reclaim an unmerged or dirty session — never one whose engine is running")
306
- .option("--json", "emit the versioned machine envelope")
307
- .action(async (options) => runSessionsPrune(options));
308
- const harness = program.command("harness").description("Mount the Project's harness and compare it with the cloud pin");
309
- harness
310
- .command("mount [path]")
311
- .description("Mount the resolved harness version into a checkout (default: the current repository)")
312
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
313
- .option("--manifest <url>", "mount this manifest instead of the one the Project resolves")
314
- .option("--json", "emit the versioned machine envelope")
315
- .action(async (target, options) => runHarnessMount(target, options, program.opts()));
316
- harness
317
- .command("status")
318
- .description("Print the mounted harness against the cloud pin; exits 1 when they differ")
319
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
320
- .option("--json", "emit the versioned machine envelope")
321
- .action(async (options) => runHarnessStatus(options, program.opts()));
322
- const toolkit = program.command("toolkit").description("Inspect and reconcile the Project's toolkit pin");
323
- toolkit
324
- .command("status")
325
- .description("Compare the cloud pin against .nustack/workspace.json and nustack.service.json (F-026)")
326
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
327
- .option("--json", "emit the versioned machine envelope")
328
- .action(async (options) => runToolkitStatus(options, program.opts()));
329
- toolkit
330
- .command("reconcile")
331
- .description("Preview and apply the deterministic toolkit repair (no User content is touched)")
332
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
333
- .option("--yes", "apply the deterministic preview without prompting")
334
- .option("--json", "emit the versioned machine envelope")
335
- .action(async (options) => runToolkitReconcile(options, program.opts()));
336
- const agent = program.command("agent").description("The discovery hook an agent uses to find the running NuStack desktop");
337
- agent
338
- .command("context")
339
- .description("Print the SessionStart hook payload when the NuStack desktop is reachable (silent otherwise)")
340
- .action(async () => runAgentContext());
341
- const agentHook = agent.command("hook").description("Manage the `nustack agent context` SessionStart hook in ~/.claude/settings.json");
342
- agentHook
343
- .command("install")
344
- .description("Register the SessionStart hook (idempotent — a second install is a no-op)")
345
- .action(async () => runAgentHookInstall());
346
- agentHook
347
- .command("remove")
348
- .description("Remove exactly the managed SessionStart hook entry")
349
- .action(async () => runAgentHookRemove());
350
- function describeError(error) {
351
- const directCode = error?.code;
352
- if (directCode === "PROJECT_CONTEXT_MISSING") {
353
- return "no Project in context — run inside a bound repository (`.nustack/workspace.json`) or pass `--project <id>`.";
354
- }
355
- if (directCode === "ORGANIZATION_CONTEXT_MISSING") {
356
- return "no Organization in context — run `nustack organization use <id>` or pass `--organization <id>`.";
357
- }
358
- if (directCode === "TOOLKIT_INCOMPATIBLE") {
359
- return "the installed toolkit is incompatible with the Project's cloud pin — run `nustack toolkit reconcile`.";
360
- }
361
- const cause = error?.cause;
362
- const code = cause?.code;
363
- if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
364
- return "couldn't resolve the NuStack host — check your connection or pass --nustack-url.";
365
- }
366
- if (code === "ECONNREFUSED") {
367
- return "the NuStack host refused the connection — is it up? Override with --nustack-url.";
368
- }
369
- if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
370
- return "the request to NuStack timed out — check your connection or try again.";
371
- }
372
- if (error instanceof Error && error.message === "fetch failed") {
373
- return "couldn't reach NuStack — check your connection or pass --nustack-url.";
374
- }
375
- return error instanceof Error ? error.message : String(error);
376
- }
377
- function searchSeparatorInvocation(rawArgv) {
378
- const args = rawArgv.slice(2);
379
- const searchIdx = args.indexOf("search");
380
- if (searchIdx === -1)
381
- return null;
382
- if (searchIdx > 0 && args[searchIdx - 1] === "--nustack-url")
383
- return null;
384
- let cut = searchIdx + 1;
385
- while (cut < args.length) {
386
- const token = args[cut] ?? "";
387
- if (token === "--category" || token === "--limit" || token === "--nustack-url") {
388
- cut += 2;
389
- }
390
- else if (token.startsWith("--") && token !== "--") {
391
- cut += 1;
392
- }
393
- else {
394
- break;
395
- }
396
- }
397
- if (args[cut] !== "--")
398
- return null;
399
- const beforeSeparator = args.slice(0, cut);
400
- const literalKeywords = args.slice(cut + 1);
401
- return {
402
- run: async () => {
403
- const scoped = new Command();
404
- scoped.exitOverride();
405
- scoped.name("nustack").option("--nustack-url <url>", "");
406
- scoped
407
- .command("search [keywords...]")
408
- .option("--json", "")
409
- .option("--category <cat>", "")
410
- .option("--limit <n>", "", toLimit)
411
- .action(async (keywords, options) => runSearch(keywords, options, scoped.opts()));
412
- await scoped.parseAsync(["node", "nustack", ...beforeSeparator, ...literalKeywords]);
413
- },
414
- };
415
- }
416
- function isJsonInvocation(argv) {
417
- return argv.slice(2).includes("--json");
418
- }
419
- function commandLabelFromArgv(argv) {
420
- const args = argv.slice(2);
421
- const parts = [];
422
- for (let i = 0; i < args.length; i++) {
423
- const token = args[i] ?? "";
424
- if (token === "--nustack-url") {
425
- i++;
426
- continue;
427
- }
428
- if (token.startsWith("-"))
429
- break;
430
- parts.push(token);
431
- }
432
- return parts.length ? parts.join(" ") : "nustack";
433
- }
434
- function errorCodeOf(error) {
435
- const direct = error?.code ?? error?.cause?.code;
436
- return typeof direct === "string" ? direct : "UNEXPECTED";
437
- }
438
- try {
439
- const separated = searchSeparatorInvocation(process.argv);
440
- if (separated)
441
- await separated.run();
442
- else
443
- await program.parseAsync(process.argv);
444
- }
445
- catch (error) {
446
- if (isJsonInvocation(process.argv)) {
447
- printJsonError(commandLabelFromArgv(process.argv), { code: errorCodeOf(error), message: describeError(error) });
448
- }
449
- else {
450
- console.error(`nustack: ${describeError(error)}`);
451
- process.exitCode = 1;
452
- }
2
+ import { HOOK_SUBCOMMANDS } from "./lib/gate/subcommands.js";
3
+ const [, , command, subcommand] = process.argv;
4
+ if (command === "gate" && subcommand !== undefined && HOOK_SUBCOMMANDS.includes(subcommand)) {
5
+ const { runGateHook } = await import("./lib/gate/hook.js");
6
+ await runGateHook(subcommand);
7
+ }
8
+ else {
9
+ await import("./program.js");
453
10
  }
@@ -2,11 +2,14 @@ import { readFile, writeFile, mkdir } from "node:fs/promises";
2
2
  import { existsSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  const MANAGED_MARKER = "nustack:managed";
5
- const MANAGED_COMMAND = `nustack agent context # ${MANAGED_MARKER}`;
6
- function managedEntry() {
7
- return { matcher: "", hooks: [{ type: "command", command: MANAGED_COMMAND }] };
5
+ const SESSION_START_COMMAND = "nustack agent context";
6
+ function managedEntry(matcher, command, options) {
7
+ const hook = { type: "command", command: `${command} # ${MANAGED_MARKER}` };
8
+ if (options.timeout !== undefined)
9
+ hook.timeout = options.timeout;
10
+ return { matcher, hooks: [hook] };
8
11
  }
9
- function isManagedEntry(entry) {
12
+ function carriesMarker(entry) {
10
13
  if (entry === null || typeof entry !== "object")
11
14
  return false;
12
15
  const hooks = entry.hooks;
@@ -17,6 +20,12 @@ function isManagedEntry(entry) {
17
20
  typeof hook.command === "string" &&
18
21
  hook.command.includes(MANAGED_MARKER));
19
22
  }
23
+ function isManagedEntry(entry, matcher) {
24
+ if (!carriesMarker(entry))
25
+ return false;
26
+ const entryMatcher = entry.matcher;
27
+ return (typeof entryMatcher === "string" ? entryMatcher : "") === matcher;
28
+ }
20
29
  const DEFAULT_INDENT = 2;
21
30
  function detectIndent(raw) {
22
31
  const indented = /\n(\x20+)"/.exec(raw);
@@ -34,44 +43,55 @@ async function writeSettings(settingsPath, settings, indent) {
34
43
  await mkdir(path.dirname(settingsPath), { recursive: true });
35
44
  await writeFile(settingsPath, `${JSON.stringify(settings, null, indent)}\n`, "utf8");
36
45
  }
37
- export async function installSessionStartHook(settingsPath) {
46
+ export async function installManagedHook(settingsPath, event, matcher, command, options = {}) {
38
47
  const { settings, indent } = await readSettings(settingsPath);
39
48
  const hooks = { ...(settings.hooks ?? {}) };
40
- const sessionStart = Array.isArray(hooks.SessionStart) ? [...hooks.SessionStart] : [];
41
- const existingIndex = sessionStart.findIndex(isManagedEntry);
42
- const entry = managedEntry();
49
+ const entries = Array.isArray(hooks[event]) ? [...hooks[event]] : [];
50
+ const existingIndex = entries.findIndex((entry) => isManagedEntry(entry, matcher));
51
+ const entry = managedEntry(matcher, command, options);
43
52
  if (existingIndex !== -1) {
44
- const current = sessionStart[existingIndex];
53
+ const current = entries[existingIndex];
45
54
  if (JSON.stringify(current) === JSON.stringify(entry)) {
46
55
  return { changed: false };
47
56
  }
48
- sessionStart[existingIndex] = entry;
57
+ entries[existingIndex] = entry;
49
58
  }
50
59
  else {
51
- sessionStart.push(entry);
60
+ entries.push(entry);
52
61
  }
53
- hooks.SessionStart = sessionStart;
62
+ hooks[event] = entries;
54
63
  settings.hooks = hooks;
55
64
  await writeSettings(settingsPath, settings, indent);
56
65
  return { changed: true };
57
66
  }
58
- export async function removeSessionStartHook(settingsPath) {
67
+ export async function removeManagedHook(settingsPath, event, matcher) {
59
68
  const { settings, indent } = await readSettings(settingsPath);
60
69
  const hooks = settings.hooks;
61
- const sessionStart = hooks?.SessionStart;
62
- if (!hooks || !Array.isArray(sessionStart))
70
+ const entries = hooks?.[event];
71
+ if (!hooks || !Array.isArray(entries))
63
72
  return { removed: false };
64
- const filtered = sessionStart.filter((entry) => !isManagedEntry(entry));
65
- if (filtered.length === sessionStart.length)
73
+ const filtered = entries.filter((entry) => !isManagedEntry(entry, matcher));
74
+ if (filtered.length === entries.length)
66
75
  return { removed: false };
67
76
  const nextHooks = { ...hooks };
68
77
  if (filtered.length > 0) {
69
- nextHooks.SessionStart = filtered;
78
+ nextHooks[event] = filtered;
70
79
  }
71
80
  else {
72
- delete nextHooks.SessionStart;
81
+ delete nextHooks[event];
73
82
  }
74
83
  settings.hooks = nextHooks;
75
84
  await writeSettings(settingsPath, settings, indent);
76
85
  return { removed: true };
77
86
  }
87
+ export async function hasManagedHook(settingsPath, event, matcher) {
88
+ const { settings } = await readSettings(settingsPath);
89
+ const entries = settings.hooks?.[event];
90
+ return Array.isArray(entries) && entries.some((entry) => isManagedEntry(entry, matcher));
91
+ }
92
+ export async function installSessionStartHook(settingsPath) {
93
+ return installManagedHook(settingsPath, "SessionStart", "", SESSION_START_COMMAND);
94
+ }
95
+ export async function removeSessionStartHook(settingsPath) {
96
+ return removeManagedHook(settingsPath, "SessionStart", "");
97
+ }