@osd-project/osd-cli 0.0.0-stage → 0.8.3

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.
Files changed (52) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +585 -2
  3. package/THIRD_PARTY_NOTICES.md +96 -0
  4. package/dist/auth-store.d.ts +38 -0
  5. package/dist/auth-store.js +239 -0
  6. package/dist/brand-catalog.d.ts +65 -0
  7. package/dist/brand-catalog.js +175 -0
  8. package/dist/connect-gate.d.ts +31 -0
  9. package/dist/connect-gate.js +82 -0
  10. package/dist/contracts.d.ts +61 -0
  11. package/dist/contracts.js +145 -0
  12. package/dist/exit-codes.d.ts +32 -0
  13. package/dist/exit-codes.js +40 -0
  14. package/dist/format.d.ts +71 -0
  15. package/dist/format.js +99 -0
  16. package/dist/generated/schemas.d.ts +2 -0
  17. package/dist/generated/schemas.js +1781 -0
  18. package/dist/guarded-fetch.d.ts +28 -0
  19. package/dist/guarded-fetch.js +252 -0
  20. package/dist/help.d.ts +27 -0
  21. package/dist/help.js +32 -0
  22. package/dist/http-fetch.d.ts +1 -0
  23. package/dist/http-fetch.js +17 -0
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.js +821 -0
  26. package/dist/logout.d.ts +16 -0
  27. package/dist/logout.js +82 -0
  28. package/dist/mcp-auth.d.ts +70 -0
  29. package/dist/mcp-auth.js +603 -0
  30. package/dist/mcp-card.d.ts +23 -0
  31. package/dist/mcp-card.js +18 -0
  32. package/dist/mcp-client.d.ts +77 -0
  33. package/dist/mcp-client.js +193 -0
  34. package/dist/net-guard.d.ts +66 -0
  35. package/dist/net-guard.js +152 -0
  36. package/dist/proxy-config.d.ts +51 -0
  37. package/dist/proxy-config.js +147 -0
  38. package/dist/request.d.ts +32 -0
  39. package/dist/request.js +62 -0
  40. package/dist/resolve-endpoint.d.ts +62 -0
  41. package/dist/resolve-endpoint.js +172 -0
  42. package/dist/search.d.ts +39 -0
  43. package/dist/search.js +69 -0
  44. package/dist/skill.d.ts +155 -0
  45. package/dist/skill.js +320 -0
  46. package/dist/updates.d.ts +101 -0
  47. package/dist/updates.js +541 -0
  48. package/dist/verify.d.ts +92 -0
  49. package/dist/verify.js +379 -0
  50. package/package.json +55 -3
  51. package/skill/osd/SKILL.md +400 -0
  52. package/skill/osd/references/connect-mcp.md +48 -0
package/dist/index.js ADDED
@@ -0,0 +1,821 @@
1
+ #!/usr/bin/env node
2
+ import { Command, CommanderError, InvalidArgumentError } from "commander";
3
+ import { readFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { DEFAULT_CONTRACT_VERSION } from "./contracts.js";
7
+ import { formatHumanError, formatHumanSearchResponse, formatHumanVerifyOutcome, verdictName } from "./format.js";
8
+ import { ExitCode, exitCodeForErrorCode } from "./exit-codes.js";
9
+ import { parsePageSize } from "./request.js";
10
+ import { runSearch } from "./search.js";
11
+ import { checkTargetVerified } from "./connect-gate.js";
12
+ import { extractBrandDomain, exitCodeForVerification, runVerify, renderDiffValue, verifySearchResults } from "./verify.js";
13
+ import { resolveEndpoint } from "./resolve-endpoint.js";
14
+ import { callMcpTool, probeMcpServer } from "./mcp-client.js";
15
+ import { authorizeMcpEndpoint, CliOAuthProvider, openInBrowser } from "./mcp-auth.js";
16
+ import { logout, resolveLogoutTarget } from "./logout.js";
17
+ import { CLI_VERSION, PACKAGE_NAME, REFRESH_COMMAND, compareVersions, fetchRegistryState, acquireLock, installVersion, installedVersionOnDisk, isInGlobalRoot, isNewer, isPackageInstall, notifyAndRefresh, npmGlobalRoot, packageRoot, refreshCacheNow, releaseLock, updatesSupported, writeCache, } from "./updates.js";
18
+ import { buildHelpJson } from "./help.js";
19
+ import { installSkill, listBundledSkills, skillStatus, uninstallSkill } from "./skill.js";
20
+ /**
21
+ * Default target used when neither --target nor OSD_REGISTRY_URL is provided.
22
+ * Points at the production OSD directory. Use --target or OSD_REGISTRY_URL
23
+ * to point at staging during development.
24
+ */
25
+ const DEFAULT_TARGET = "https://directory.zendesk.com";
26
+ const program = new Command();
27
+ // By default, Commander calls process.exit(1) directly for any parse-time
28
+ // error (missing required option, invalid option argument, --help/--version).
29
+ // exitOverride() makes it throw a CommanderError instead, so we can map parse
30
+ // errors onto this CLI's own ExitCode.Usage (64) instead of Commander's
31
+ // hardcoded 1 -- otherwise a bad --page-size or a missing --target would exit
32
+ // with a different code than the rest of this CLI's "bad invocation" cases.
33
+ program.exitOverride();
34
+ program.name("osd").description("Command-line client for the OSD discovery contracts.").version(CLI_VERSION);
35
+ // Global safety valve for testing local deployments: loopback, private, and
36
+ // link-local targets. resolveNetPolicy already reads OSD_ALLOW_PRIVATE, so
37
+ // the flag just sets that one variable -- one resolution point, no threading.
38
+ // It is a program-level option, so it precedes the subcommand:
39
+ // `osd --allow-private-addresses mcp ...`.
40
+ program
41
+ .option("--allow-private-addresses", "also connect to loopback, private, and link-local addresses, to test a local deployment (same as OSD_ALLOW_PRIVATE=1)")
42
+ .hook("preAction", () => {
43
+ if (program.opts().allowPrivateAddresses === true)
44
+ process.env.OSD_ALLOW_PRIVATE = "1";
45
+ });
46
+ function parsePageSizeOption(value) {
47
+ try {
48
+ return parsePageSize(value);
49
+ }
50
+ catch (error) {
51
+ const message = error instanceof Error ? error.message : String(error);
52
+ throw new InvalidArgumentError(message);
53
+ }
54
+ }
55
+ program
56
+ .command("search")
57
+ .description("Search a registry or resolver and print matching candidates.")
58
+ .argument("<query>", "natural-language search text")
59
+ .option("-t, --target <url>", "base URL of the registry or resolver to query (or set OSD_REGISTRY_URL)", process.env.OSD_REGISTRY_URL ?? DEFAULT_TARGET)
60
+ .option("--json", "print the raw JSON response instead of a human-readable summary", false)
61
+ .option("--contract-version <version>", "exact OSD contract version to request", DEFAULT_CONTRACT_VERSION)
62
+ .option("--federation <mode>", "federation mode: auto, referrals, or none", "auto")
63
+ .option("--page-size <n>", "maximum number of results to return", parsePageSizeOption)
64
+ .option("--page-token <token>", "pagination token from a previous response")
65
+ .option("--verify", "verify every result against its brand domain's published catalog (structural match); the exit code reflects the worst verdict", false)
66
+ .option("--filter <key=value>", "structured filter, e.g. --filter capabilities=osd.ask (repeatable)", (value, previous = []) => [...previous, value])
67
+ .action(async (query, opts) => {
68
+ if (!opts.target) {
69
+ // An empty OSD_REGISTRY_URL falls through here -- Commander keeps the
70
+ // explicit empty string rather than substituting the default.
71
+ console.error("Error: --target is required (or set OSD_REGISTRY_URL).");
72
+ process.exitCode = ExitCode.Usage;
73
+ return;
74
+ }
75
+ if (!["auto", "referrals", "none"].includes(opts.federation)) {
76
+ console.error(`Error: --federation must be one of auto, referrals, none (got "${opts.federation}").`);
77
+ process.exitCode = ExitCode.Usage;
78
+ return;
79
+ }
80
+ let filters = opts.filter;
81
+ try {
82
+ const outcome = await runSearch({
83
+ target: opts.target,
84
+ text: query,
85
+ filters,
86
+ federation: opts.federation,
87
+ pageSize: opts.pageSize,
88
+ pageToken: opts.pageToken,
89
+ contractVersion: opts.contractVersion,
90
+ });
91
+ switch (outcome.kind) {
92
+ case "success": {
93
+ let verifyExitCode = ExitCode.Success;
94
+ if (opts.verify) {
95
+ await verifySearchResults(outcome.response.results, opts.contractVersion);
96
+ verifyExitCode = exitCodeForVerification(outcome.response.results);
97
+ }
98
+ if (outcome.validation.length > 0) {
99
+ console.error("Warning: response did not validate against the pinned contract schema:");
100
+ for (const issue of outcome.validation)
101
+ console.error(` ${issue}`);
102
+ }
103
+ if (opts.json) {
104
+ console.log(JSON.stringify(outcome.response, null, 2));
105
+ }
106
+ else if (outcome.validation.length > 0) {
107
+ console.log(JSON.stringify(outcome.response, null, 2));
108
+ }
109
+ else {
110
+ console.log(formatHumanSearchResponse(outcome.response));
111
+ }
112
+ process.exitCode = outcome.validation.length > 0 ? ExitCode.GeneralError : verifyExitCode;
113
+ return;
114
+ }
115
+ case "error": {
116
+ if (opts.json) {
117
+ console.log(JSON.stringify(outcome.error, null, 2));
118
+ }
119
+ else {
120
+ console.error(formatHumanError(outcome.status, outcome.error));
121
+ }
122
+ process.exitCode = exitCodeForErrorCode(outcome.error.errorCode);
123
+ return;
124
+ }
125
+ case "malformed": {
126
+ console.error(`Error: target returned HTTP ${outcome.status} with a body that is not a valid response.`);
127
+ process.exitCode = ExitCode.GeneralError;
128
+ return;
129
+ }
130
+ case "schemasMissing": {
131
+ console.error(SCHEMAS_MISSING_MESSAGE);
132
+ process.exitCode = ExitCode.GeneralError;
133
+ return;
134
+ }
135
+ case "unsupportedContractVersion": {
136
+ console.error(`Error: unsupported local contract version "${outcome.contractVersion}".`);
137
+ process.exitCode = ExitCode.Usage;
138
+ return;
139
+ }
140
+ case "unreachable": {
141
+ console.error(`Error: ${outcome.message}`);
142
+ process.exitCode = ExitCode.Unreachable;
143
+ return;
144
+ }
145
+ }
146
+ }
147
+ catch (error) {
148
+ const message = error instanceof Error ? error.message : String(error);
149
+ console.error(`Error: ${message}`);
150
+ process.exitCode = ExitCode.Usage;
151
+ }
152
+ });
153
+ /** Candidates are single catalog entries; 1 MiB is far beyond any real one. */
154
+ const MAX_CANDIDATE_BYTES = 1024 * 1024;
155
+ /** Reads all of stdin; returns null when the input exceeds `limit` bytes. */
156
+ async function readStdin(limit) {
157
+ const chunks = [];
158
+ let total = 0;
159
+ for await (const chunk of process.stdin) {
160
+ const buffer = chunk;
161
+ total += buffer.length;
162
+ if (total > limit) {
163
+ process.stdin.destroy();
164
+ return null;
165
+ }
166
+ chunks.push(buffer);
167
+ }
168
+ return Buffer.concat(chunks).toString("utf8");
169
+ }
170
+ /** Peeks at stdin without draining it: true once any non-whitespace byte arrives, false on EOF.
171
+ * Accepted edge: a whitespace-only stream that never closes still blocks
172
+ * (pathological; the pre-peek behavior hung on ANY piped stdin). */
173
+ async function stdinHasData() {
174
+ for await (const chunk of process.stdin) {
175
+ if (/\S/.test(String(chunk))) {
176
+ process.stdin.destroy();
177
+ return true;
178
+ }
179
+ }
180
+ return false;
181
+ }
182
+ function candidateBrandDomain(candidate, contractVersion) {
183
+ const brandDomain = extractBrandDomain(candidate, contractVersion);
184
+ return typeof brandDomain === "string" ? brandDomain : null;
185
+ }
186
+ const SCHEMAS_MISSING_MESSAGE = "Error: this build of @osd-project/osd-cli is missing its embedded contract " +
187
+ "schemas (the gen-schemas build step did not run or the package is " +
188
+ "corrupted) -- reinstall it: npm install -g @osd-project/osd-cli";
189
+ program
190
+ .command("verify")
191
+ .description("Verify a candidate against its brand domain's published catalog (exact structural match).")
192
+ .option("--candidate <file>", "candidate JSON file (a single catalog entry); reads stdin when omitted")
193
+ .option("--json", "print the verdict as a JSON object for scripting", false)
194
+ .option("--contract-version <version>", "exact OSD contract version to use", DEFAULT_CONTRACT_VERSION)
195
+ .action(async (opts) => {
196
+ try {
197
+ let raw;
198
+ if (opts.candidate !== undefined) {
199
+ if (!process.stdin.isTTY && (await stdinHasData())) {
200
+ console.error("Error: pass the candidate via --candidate <file> or stdin, not both.");
201
+ process.exitCode = ExitCode.Usage;
202
+ return;
203
+ }
204
+ try {
205
+ raw = await readFile(opts.candidate, "utf8");
206
+ }
207
+ catch (error) {
208
+ const message = error instanceof Error ? error.message : String(error);
209
+ console.error(`Error: could not read --candidate file "${opts.candidate}": ${message}`);
210
+ process.exitCode = ExitCode.InvalidArgument;
211
+ return;
212
+ }
213
+ }
214
+ else {
215
+ if (process.stdin.isTTY) {
216
+ console.error("Error: no candidate input -- pipe one via stdin or pass --candidate <file>.");
217
+ console.error(`Example: osd search "shoe repair" --json | jq '.results[0]' | osd verify`);
218
+ process.exitCode = ExitCode.Usage;
219
+ return;
220
+ }
221
+ const piped = await readStdin(MAX_CANDIDATE_BYTES);
222
+ if (piped === null) {
223
+ console.error(`Error: candidate input exceeds the ${MAX_CANDIDATE_BYTES}-byte cap.`);
224
+ process.exitCode = ExitCode.InvalidArgument;
225
+ return;
226
+ }
227
+ raw = piped;
228
+ }
229
+ if (raw.trim().length === 0) {
230
+ console.error("Error: candidate input is empty.");
231
+ process.exitCode = ExitCode.InvalidArgument;
232
+ return;
233
+ }
234
+ let candidate;
235
+ try {
236
+ candidate = JSON.parse(raw);
237
+ }
238
+ catch {
239
+ console.error("Error: candidate input is not valid JSON.");
240
+ process.exitCode = ExitCode.InvalidArgument;
241
+ return;
242
+ }
243
+ const outcome = await runVerify({ candidate, contractVersion: opts.contractVersion });
244
+ switch (outcome.kind) {
245
+ case "verified":
246
+ case "mismatch":
247
+ case "noMatch":
248
+ case "unreachable": {
249
+ if (opts.json) {
250
+ console.log(JSON.stringify({
251
+ verdict: verdictName(outcome.kind),
252
+ brandDomain: candidateBrandDomain(candidate, opts.contractVersion),
253
+ catalogUrl: outcome.catalogUrl ?? null,
254
+ detail: outcome.kind === "unreachable" ? outcome.message : null,
255
+ diff: outcome.kind === "mismatch"
256
+ ? outcome.diff.map((entry) => ({
257
+ path: entry.path,
258
+ registryValue: renderDiffValue(entry.registryValue),
259
+ brandValue: renderDiffValue(entry.brandValue),
260
+ }))
261
+ : [],
262
+ }, null, 2));
263
+ }
264
+ else {
265
+ console.log(formatHumanVerifyOutcome(outcome));
266
+ }
267
+ process.exitCode =
268
+ outcome.kind === "verified"
269
+ ? ExitCode.Success
270
+ : outcome.kind === "mismatch"
271
+ ? ExitCode.Mismatch
272
+ : outcome.kind === "noMatch"
273
+ ? ExitCode.NoMatch
274
+ : ExitCode.Unreachable;
275
+ return;
276
+ }
277
+ case "invalidCandidate": {
278
+ console.error(`Error: invalid candidate: ${outcome.message}`);
279
+ process.exitCode = ExitCode.InvalidArgument;
280
+ return;
281
+ }
282
+ case "malformedCatalog": {
283
+ console.error(`Error: malformed catalog: ${outcome.message}`);
284
+ process.exitCode = ExitCode.GeneralError;
285
+ return;
286
+ }
287
+ case "unsupportedContractVersion": {
288
+ console.error(`Error: unsupported local contract version "${outcome.contractVersion}".`);
289
+ process.exitCode = ExitCode.Usage;
290
+ return;
291
+ }
292
+ case "schemasMissing": {
293
+ console.error(SCHEMAS_MISSING_MESSAGE);
294
+ process.exitCode = ExitCode.GeneralError;
295
+ return;
296
+ }
297
+ }
298
+ }
299
+ catch (error) {
300
+ const message = error instanceof Error ? error.message : String(error);
301
+ console.error(`Error: ${message}`);
302
+ process.exitCode = ExitCode.Usage;
303
+ }
304
+ });
305
+ /**
306
+ * The one and only bypass for the connect gate: an interactive confirmation.
307
+ * Defaults to No -- anything but an explicit "y"/"yes" aborts.
308
+ */
309
+ async function confirmUnverifiedConnect() {
310
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
311
+ try {
312
+ const answer = await rl.question("Connect to this unverified target anyway? [y/N] ");
313
+ return /^y(es)?$/i.test(answer.trim());
314
+ }
315
+ finally {
316
+ rl.close();
317
+ }
318
+ }
319
+ const mcp = program.command("mcp");
320
+ mcp
321
+ .command("logout")
322
+ .description("Delete cached OAuth credentials, optionally for one MCP target, and attempt token revocation.")
323
+ .argument("[target]", "server-card URL or streamable-http endpoint URL; omit to clear all local credentials")
324
+ .action(async (target) => {
325
+ let endpoint;
326
+ if (target !== undefined) {
327
+ const resolved = resolveLogoutTarget(target, await resolveEndpoint(target));
328
+ if ("error" in resolved) {
329
+ console.error(`Error: ${resolved.error}`);
330
+ process.exitCode = ExitCode.InvalidArgument;
331
+ return;
332
+ }
333
+ if (resolved.warning)
334
+ console.error(`Warning: ${resolved.warning}`);
335
+ endpoint = resolved.endpoint;
336
+ }
337
+ try {
338
+ await logout(endpoint);
339
+ }
340
+ catch (error) {
341
+ console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
342
+ process.exitCode = ExitCode.GeneralError;
343
+ }
344
+ });
345
+ mcp
346
+ .description("Use a discovered MCP server right now: list its tools or call one, without registering anything.")
347
+ .argument("<target>", "server-card URL or streamable-http endpoint URL")
348
+ .option("-t, --target <url>", "base URL of the OSD directory the target is verified against with --verify (or set OSD_REGISTRY_URL)", process.env.OSD_REGISTRY_URL ?? DEFAULT_TARGET)
349
+ .option("--verify", "verify the target against the directory and the brand's own manifest before connecting; connect only if verification passes", false)
350
+ .option("--call <tool>", "call the named tool instead of listing the server's tools")
351
+ .option("--args <json>", "tool arguments as a JSON object (only meaningful with --call)")
352
+ .option("--json", "print the result as a JSON object for scripting", false)
353
+ .option("--no-auth", "never start a sign-in flow; report auth-required and stop")
354
+ .option("--login", "start a fresh sign-in, preferring advertised device authorization (also works in non-interactive shells)", false)
355
+ .option("--resolve-only", "print the resolved endpoint URL and stop -- no connection, no auth (for handing to a client's own MCP configuration)", false)
356
+ .action(async (target, opts) => {
357
+ if (opts.login && (!opts.auth || opts.resolveOnly)) {
358
+ console.error("Error: --login cannot be combined with --no-auth or --resolve-only.");
359
+ process.exitCode = ExitCode.Usage;
360
+ return;
361
+ }
362
+ // Presence check, not value check: "--args {}" without --call must still
363
+ // be a usage error.
364
+ if (opts.call === undefined && opts.args !== undefined) {
365
+ console.error("Error: --args only makes sense together with --call <tool>.");
366
+ process.exitCode = ExitCode.Usage;
367
+ return;
368
+ }
369
+ let toolArgs = {};
370
+ if (opts.resolveOnly && opts.call !== undefined) {
371
+ console.error("Error: --resolve-only makes no sense together with --call.");
372
+ process.exitCode = ExitCode.Usage;
373
+ return;
374
+ }
375
+ if (opts.call !== undefined) {
376
+ try {
377
+ const parsed = JSON.parse(opts.args ?? "{}");
378
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
379
+ throw new Error("not a JSON object");
380
+ }
381
+ toolArgs = parsed;
382
+ }
383
+ catch {
384
+ console.error(`Error: --args must be a JSON object, got: ${opts.args}`);
385
+ process.exitCode = ExitCode.InvalidArgument;
386
+ return;
387
+ }
388
+ }
389
+ if (opts.verify) {
390
+ if (!opts.target) {
391
+ // An empty OSD_REGISTRY_URL falls through here -- Commander keeps the
392
+ // explicit empty string rather than substituting the default.
393
+ console.error("Error: --target is required (or set OSD_REGISTRY_URL).");
394
+ process.exitCode = ExitCode.Usage;
395
+ return;
396
+ }
397
+ // Verify-before-connect, opt-in: the
398
+ // target must be listed in the directory and brand-verified before any
399
+ // resolution, connection, or --resolve-only handoff. The only bypass is
400
+ // an explicit interactive confirmation; non-interactive runs refuse.
401
+ const gate = await checkTargetVerified(target, {
402
+ registry: opts.target,
403
+ contractVersion: DEFAULT_CONTRACT_VERSION,
404
+ });
405
+ if (gate.kind === "refused") {
406
+ if (process.stderr.isTTY && process.stdin.isTTY) {
407
+ console.error(`Refusing to connect: ${gate.message}`);
408
+ if (!(await confirmUnverifiedConnect())) {
409
+ console.error("Aborted.");
410
+ process.exitCode = gate.exitCode;
411
+ return;
412
+ }
413
+ console.error("Continuing to the unverified target at the user's explicit request.");
414
+ }
415
+ else {
416
+ console.error(`Error: refusing to connect: ${gate.message}`);
417
+ process.exitCode = gate.exitCode;
418
+ return;
419
+ }
420
+ }
421
+ }
422
+ // Card URL and endpoint URL converge here, behind the shared SSRF guards.
423
+ const resolved = await resolveEndpoint(target, { willConnect: !opts.resolveOnly });
424
+ if (resolved.kind !== "endpoint") {
425
+ console.error(`Error: ${resolved.message}`);
426
+ process.exitCode =
427
+ resolved.kind === "invalid" ? ExitCode.InvalidArgument : ExitCode.Unreachable;
428
+ return;
429
+ }
430
+ if (opts.resolveOnly) {
431
+ // Resolve-only: print the guarded, checked endpoint without
432
+ // connecting, so the human's client does registration and first
433
+ // sign-in itself.
434
+ if (resolved.warning)
435
+ console.error(`Warning: ${resolved.warning}`);
436
+ if (opts.json) {
437
+ console.log(JSON.stringify({ endpoint: resolved.url }));
438
+ }
439
+ else {
440
+ console.log(resolved.url);
441
+ }
442
+ return;
443
+ }
444
+ // Cached credentials allow the transport to refresh silently. Without
445
+ // tokens, leave authorization to our capability-aware sign-in selection
446
+ // rather than letting the transport start an authorization-code flow.
447
+ let browserAllowed = false;
448
+ let provider;
449
+ try {
450
+ provider = await CliOAuthProvider.fromStore(resolved.url, (authorizationUrl) => {
451
+ if (!browserAllowed)
452
+ return;
453
+ console.error(`Authorize osd-cli with this server:\n ${authorizationUrl.toString()}`);
454
+ void openInBrowser(authorizationUrl).then((opened) => {
455
+ if (opened)
456
+ console.error("Opened the browser to continue sign-in.");
457
+ else
458
+ console.error("Could not open a browser; visit the URL above to sign in.");
459
+ });
460
+ });
461
+ }
462
+ catch (error) {
463
+ console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
464
+ process.exitCode = ExitCode.InvalidArgument;
465
+ return;
466
+ }
467
+ const run = () => opts.call !== undefined
468
+ ? callMcpTool(resolved.url, opts.call, toolArgs, { authProvider: provider.tokens() ? provider : undefined })
469
+ : probeMcpServer(resolved.url, { authProvider: provider.tokens() ? provider : undefined });
470
+ const signIn = async () => {
471
+ browserAllowed = true;
472
+ const authorization = await authorizeMcpEndpoint(resolved.url, provider, {
473
+ info: (message) => console.error(message),
474
+ });
475
+ if (authorization.kind !== "authorized") {
476
+ console.error(`Error: ${authorization.message}`);
477
+ process.exitCode = ExitCode.GeneralError;
478
+ return false;
479
+ }
480
+ console.error("Signed in; connecting...");
481
+ return true;
482
+ };
483
+ if (opts.login && !(await signIn()))
484
+ return;
485
+ let outcome = await run();
486
+ if (outcome.kind === "authRequired" && opts.auth && !opts.login) {
487
+ if (!process.stderr.isTTY) {
488
+ console.error("Error: the server requires authorization and this shell is non-interactive.\n" +
489
+ "Run `osd mcp <target> --login` to sign in; the tokens are cached for later runs.");
490
+ process.exitCode = ExitCode.GeneralError;
491
+ return;
492
+ }
493
+ console.error("The server requires authorization; starting the sign-in flow...");
494
+ if (!(await signIn()))
495
+ return;
496
+ outcome = await run();
497
+ }
498
+ switch (outcome.kind) {
499
+ case "connected": {
500
+ if (opts.json) {
501
+ console.log(JSON.stringify({ server: outcome.serverInfo ?? null, endpoint: resolved.url, tools: outcome.tools }, null, 2));
502
+ }
503
+ else {
504
+ const server = outcome.serverInfo;
505
+ console.log(`Connected to ${server?.name ?? "(unnamed server)"}${server?.version ? ` v${server.version}` : ""} at ${resolved.url}`);
506
+ console.log(`${outcome.tools.length} tool(s):`);
507
+ for (const tool of outcome.tools) {
508
+ console.log(` ${tool.name}${tool.description ? ` -- ${tool.description}` : ""}`);
509
+ }
510
+ }
511
+ return;
512
+ }
513
+ case "called": {
514
+ // Tool results are already structured content; JSON.stringify is the
515
+ // faithful human rendering too.
516
+ console.log(JSON.stringify(outcome.result, null, 2));
517
+ return;
518
+ }
519
+ case "authRequired": {
520
+ // --no-auth, or a newly issued token that the resource rejected.
521
+ console.error(`Error: the server requires authorization (${outcome.message}).`);
522
+ process.exitCode = ExitCode.GeneralError;
523
+ return;
524
+ }
525
+ case "unreachable": {
526
+ console.error(`Error: ${outcome.message}`);
527
+ process.exitCode = ExitCode.Unreachable;
528
+ return;
529
+ }
530
+ case "protocolError": {
531
+ console.error(`Error: the target did not speak MCP correctly: ${outcome.message}`);
532
+ process.exitCode = ExitCode.GeneralError;
533
+ return;
534
+ }
535
+ }
536
+ });
537
+ // The agent skill ships in this package; `osd skill` installs,
538
+ // prints, checks, or removes it. No harness knowledge beyond evidence-gated
539
+ // default resolution, and no network -- everything is in the package.
540
+ const skill = program
541
+ .command("skill")
542
+ .description("Manage the agent skill bundled in this package.");
543
+ skill
544
+ .command("install")
545
+ .description("Copy the bundled skill into a skills directory (default: the detected one, else ~/.agents/skills).")
546
+ .option("--dir <path>", "skills directory to install into (default: detected, or ~/.agents/skills)")
547
+ .option("--force", "replace a skill directory this package did not create", false)
548
+ .option("--print", "write SKILL.md to stdout; touch no files", false)
549
+ .option("--json", "print the result as JSON", false)
550
+ .action((opts) => {
551
+ const outcome = installSkill({ flagDir: opts.dir, force: opts.force, print: opts.print });
552
+ switch (outcome.kind) {
553
+ case "print":
554
+ process.stdout.write(outcome.markdown);
555
+ return;
556
+ case "installed":
557
+ if (opts.json) {
558
+ console.log(JSON.stringify({
559
+ installed: outcome.name,
560
+ version: outcome.version,
561
+ dir: outcome.dir,
562
+ basis: outcome.basis,
563
+ replaced: outcome.replacedFrom ?? undefined,
564
+ }, null, 2));
565
+ }
566
+ else {
567
+ if (outcome.replacedFrom !== null) {
568
+ console.log(`replaced ${outcome.name} skill ${outcome.replacedFrom} with ${outcome.version}`);
569
+ }
570
+ console.log(`installed ${outcome.name} skill ${outcome.version} -> ${path.join(outcome.dir, "SKILL.md")} (${outcome.basis})`);
571
+ }
572
+ return;
573
+ case "already-installed":
574
+ if (opts.json) {
575
+ console.log(JSON.stringify({ installed: outcome.name, version: outcome.version, dir: outcome.dir, basis: outcome.basis, upToDate: true }, null, 2));
576
+ }
577
+ else {
578
+ console.log(`${outcome.name} skill ${outcome.version} is already installed at ${outcome.dir}; nothing to do`);
579
+ }
580
+ return;
581
+ case "refused":
582
+ case "ambiguous":
583
+ case "error": {
584
+ const message = outcome.kind === "refused" ? outcome.reason : outcome.kind === "ambiguous" ? outcome.error : outcome.message;
585
+ console.error(`Error: ${message}`);
586
+ process.exitCode = ExitCode.GeneralError;
587
+ return;
588
+ }
589
+ }
590
+ });
591
+ skill
592
+ .command("uninstall")
593
+ .description("Remove the bundled skill from a skills directory (only if this package installed it).")
594
+ .option("--dir <path>", "skills directory to uninstall from (default: detected, or ~/.agents/skills)")
595
+ .option("--json", "print the result as JSON", false)
596
+ .action((opts) => {
597
+ const outcome = uninstallSkill({ flagDir: opts.dir });
598
+ switch (outcome.kind) {
599
+ case "removed":
600
+ if (opts.json)
601
+ console.log(JSON.stringify({ removed: outcome.name, dir: outcome.dir }, null, 2));
602
+ else
603
+ console.log(`removed ${outcome.name} skill -> ${outcome.dir}`);
604
+ return;
605
+ case "not-installed":
606
+ if (opts.json)
607
+ console.log(JSON.stringify({ removed: null, dir: outcome.dir }, null, 2));
608
+ else
609
+ console.log(`${outcome.name} skill is not installed at ${outcome.dir}; nothing to do`);
610
+ return;
611
+ case "refused":
612
+ case "ambiguous":
613
+ case "error": {
614
+ const message = outcome.kind === "refused" ? outcome.reason : outcome.kind === "ambiguous" ? outcome.error : outcome.message;
615
+ console.error(`Error: ${message}`);
616
+ process.exitCode = ExitCode.GeneralError;
617
+ return;
618
+ }
619
+ }
620
+ });
621
+ skill
622
+ .command("status")
623
+ .description("Report whether the installed skill matches this CLI's version; exit 1 if not.")
624
+ .option("--dir <path>", "skills directory to check (default: detected, or ~/.agents/skills)")
625
+ .option("--json", "print the result as JSON", false)
626
+ .action((opts) => {
627
+ const outcome = skillStatus({ flagDir: opts.dir });
628
+ switch (outcome.kind) {
629
+ case "current":
630
+ if (opts.json) {
631
+ console.log(JSON.stringify({ name: outcome.name, version: outcome.version, dir: outcome.dir, upToDate: true }, null, 2));
632
+ }
633
+ else {
634
+ console.log(`${outcome.name} skill ${outcome.version} is current (${outcome.dir})`);
635
+ }
636
+ return;
637
+ case "stale":
638
+ if (opts.json) {
639
+ console.log(JSON.stringify({
640
+ name: outcome.name,
641
+ installedVersion: outcome.installedVersion,
642
+ cliVersion: outcome.cliVersion,
643
+ dir: outcome.dir,
644
+ upToDate: false,
645
+ }, null, 2));
646
+ }
647
+ else {
648
+ console.log(`${outcome.name} skill is stale: installed ${outcome.installedVersion}, CLI ${outcome.cliVersion} (${outcome.dir}); re-run: npx -y ${PACKAGE_NAME}@latest skill install`);
649
+ }
650
+ process.exitCode = ExitCode.GeneralError;
651
+ return;
652
+ case "missing":
653
+ if (opts.json)
654
+ console.log(JSON.stringify({ name: outcome.name, dir: outcome.dir, installed: false }, null, 2));
655
+ else
656
+ console.log(`${outcome.name} skill is not installed at ${outcome.dir}`);
657
+ process.exitCode = ExitCode.GeneralError;
658
+ return;
659
+ case "foreign":
660
+ case "ambiguous":
661
+ case "error": {
662
+ const message = outcome.kind === "foreign" ? outcome.reason : outcome.kind === "ambiguous" ? outcome.error : outcome.message;
663
+ console.error(`Error: ${message}`);
664
+ process.exitCode = ExitCode.GeneralError;
665
+ return;
666
+ }
667
+ }
668
+ });
669
+ skill
670
+ .command("list")
671
+ .description("List the skill(s) bundled in this package.")
672
+ .option("--json", "print the result as JSON", false)
673
+ .action((opts) => {
674
+ const skills = listBundledSkills();
675
+ if (skills.length === 0) {
676
+ console.error("Error: this osd package is missing its bundled skill directory (skill/); reinstall it: npm install -g @osd-project/osd-cli@latest");
677
+ process.exitCode = ExitCode.GeneralError;
678
+ return;
679
+ }
680
+ if (opts.json) {
681
+ console.log(JSON.stringify({ skills }, null, 2));
682
+ return;
683
+ }
684
+ for (const bundled of skills) {
685
+ console.log(`${bundled.name} ${bundled.version} ${bundled.description}`);
686
+ }
687
+ });
688
+ program
689
+ .command("update")
690
+ .description(`Upgrade osd to the newest published version (npm install -g ${PACKAGE_NAME}@<version>).`)
691
+ .option("--check", "only report whether an update is available; install nothing", false)
692
+ .option("--json", "print the check result as JSON", false)
693
+ .action(async (opts) => {
694
+ if (!updatesSupported()) {
695
+ console.error(`Error: \`osd update\` is not supported on this platform (${process.platform}). Run: npm install -g ${PACKAGE_NAME}@latest`);
696
+ process.exitCode = ExitCode.GeneralError;
697
+ return;
698
+ }
699
+ const lookup = fetchRegistryState(30_000);
700
+ if (!lookup.ok) {
701
+ console.error(`Error: could not query the registry for ${PACKAGE_NAME} (${lookup.error}). ` +
702
+ "Check your npm configuration (~/.npmrc) and network access.");
703
+ process.exitCode = ExitCode.Unreachable;
704
+ return;
705
+ }
706
+ const latest = lookup.state.latest;
707
+ // A deprecated install moves to `latest` even if that is older (the rollback path).
708
+ const deprecated = lookup.state.installedDeprecated;
709
+ const updateAvailable = isNewer(latest, CLI_VERSION) || (deprecated !== null && compareVersions(latest, CLI_VERSION) !== 0);
710
+ try {
711
+ writeCache({
712
+ checkedAt: new Date().toISOString(),
713
+ installedVersion: CLI_VERSION,
714
+ latestVersion: latest,
715
+ global: isGlobalInstall(),
716
+ });
717
+ }
718
+ catch {
719
+ // cache only drives the notice
720
+ }
721
+ if (opts.check || !updateAvailable) {
722
+ if (opts.json) {
723
+ console.log(JSON.stringify({ current: CLI_VERSION, latest, updateAvailable }, null, 2));
724
+ }
725
+ else if (updateAvailable) {
726
+ console.log(`update available: ${CLI_VERSION} -> ${latest}. Run \`osd update\` to upgrade.`);
727
+ }
728
+ else {
729
+ console.log(`osd is up to date (${CLI_VERSION}).`);
730
+ }
731
+ process.exitCode = ExitCode.Success;
732
+ return;
733
+ }
734
+ const root = packageRoot();
735
+ if (!isGlobalInstall()) {
736
+ console.error(`Error: this osd (${root}) is not a global npm install, so \`osd update\` will not touch it.\n` +
737
+ ` To upgrade a global install: npm install -g ${PACKAGE_NAME}@${latest}\n` +
738
+ " For a workspace build: pull and rebuild the checkout.");
739
+ process.exitCode = ExitCode.GeneralError;
740
+ return;
741
+ }
742
+ // Same lock as the background updater, so the two never rewrite the install at once.
743
+ const lock = acquireLock();
744
+ if (lock === null) {
745
+ console.error("Error: a background update of osd is in progress. Run `osd update` again in a minute.");
746
+ process.exitCode = ExitCode.GeneralError;
747
+ return;
748
+ }
749
+ try {
750
+ const onDisk = installedVersionOnDisk(root);
751
+ if (onDisk !== CLI_VERSION) {
752
+ if (opts.json) {
753
+ console.log(JSON.stringify({ previous: CLI_VERSION, current: onDisk, updated: false }, null, 2));
754
+ }
755
+ else {
756
+ console.log(`osd was already updated to ${onDisk ?? "another version"} in the background.`);
757
+ }
758
+ process.exitCode = ExitCode.Success;
759
+ return;
760
+ }
761
+ console.error(`Updating osd ${CLI_VERSION} -> ${latest} ...`);
762
+ const result = installVersion(latest);
763
+ if (!result.ok) {
764
+ console.error(`Error: npm install failed (${result.error ?? `exit ${result.status}`}).\n` +
765
+ " If your ~/.npmrc sets min-release-age, a just-published version is refused until it ages past\n" +
766
+ " that window; retry later.");
767
+ process.exitCode = ExitCode.GeneralError;
768
+ return;
769
+ }
770
+ try {
771
+ writeCache({ checkedAt: new Date().toISOString(), installedVersion: latest, latestVersion: latest, global: true });
772
+ }
773
+ catch { }
774
+ if (opts.json) {
775
+ console.log(JSON.stringify({ previous: CLI_VERSION, current: latest, updated: true }, null, 2));
776
+ }
777
+ else {
778
+ console.log(`updated osd ${CLI_VERSION} -> ${latest}`);
779
+ }
780
+ }
781
+ finally {
782
+ releaseLock(lock);
783
+ }
784
+ process.exitCode = ExitCode.Success;
785
+ });
786
+ function isGlobalInstall() {
787
+ const root = packageRoot();
788
+ const globalRoot = isPackageInstall(root) ? npmGlobalRoot() : null;
789
+ return globalRoot !== null && isInGlobalRoot(root, globalRoot);
790
+ }
791
+ // Spawned by notifyAndRefresh().
792
+ program
793
+ .command(REFRESH_COMMAND, { hidden: true })
794
+ .option("--apply", "install an available update", false)
795
+ .action((opts) => {
796
+ refreshCacheNow({ apply: opts.apply });
797
+ });
798
+ // `update` checks inline; the refresher must not spawn itself. Neither
799
+ // does --help-json: it is a dump, not a CLI run.
800
+ const invoked = process.argv[2];
801
+ // Only as the sole top-level argument: scanning every argv element would
802
+ // hijack a `--help-json` that belongs to a subcommand or sits after `--`.
803
+ const helpJsonRequested = process.argv.length === 3 && invoked === "--help-json";
804
+ if (!helpJsonRequested && invoked !== "update" && invoked !== REFRESH_COMMAND) {
805
+ notifyAndRefresh();
806
+ }
807
+ if (helpJsonRequested) {
808
+ // The full command surface as stable JSON, generated from the live
809
+ // parser -- never hand-written, validated in CI.
810
+ console.log(JSON.stringify(buildHelpJson(program), null, 2));
811
+ }
812
+ else {
813
+ program.parseAsync(process.argv).catch((error) => {
814
+ if (error instanceof CommanderError) {
815
+ // exitCode 0 covers --help/--version, which aren't error conditions.
816
+ process.exitCode = error.exitCode === 0 ? 0 : ExitCode.Usage;
817
+ return;
818
+ }
819
+ throw error;
820
+ });
821
+ }