@deckco/cli 1.1.0 → 1.3.0

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 (3) hide show
  1. package/README.md +34 -280
  2. package/dist/deck.js +1460 -881
  3. package/package.json +2 -2
package/dist/deck.js CHANGED
@@ -3606,12 +3606,12 @@ var require_utils = __commonJS({
3606
3606
  uriTokens.push(host);
3607
3607
  }
3608
3608
  if (typeof component.port === "number" || typeof component.port === "string") {
3609
- const port = String(component.port);
3610
- if (!isPort(port)) {
3609
+ const port2 = String(component.port);
3610
+ if (!isPort(port2)) {
3611
3611
  throw new TypeError("URI port is malformed.");
3612
3612
  }
3613
3613
  uriTokens.push(":");
3614
- uriTokens.push(port);
3614
+ uriTokens.push(port2);
3615
3615
  }
3616
3616
  return uriTokens.length ? uriTokens.join("") : void 0;
3617
3617
  }
@@ -7662,7 +7662,7 @@ var RESERVED_ARGUMENTS = /* @__PURE__ */ new Set([
7662
7662
  ...TOLERATED_ARGUMENTS,
7663
7663
  ...SYNTHETIC_ARGUMENTS.map((arg) => arg.name)
7664
7664
  ]);
7665
- var CLI_OWN_ARGUMENTS = ["wait", "timeout", "download"];
7665
+ var CLI_OWN_ARGUMENTS = ["wait", "timeout", "download", "link"];
7666
7666
  function unknownArguments(row, args) {
7667
7667
  const offeredSynthetic = new Set(SYNTHETIC_ARGUMENTS.filter((arg) => arg.appliesTo(row)).map((arg) => arg.name));
7668
7668
  const synthetic = new Set(SYNTHETIC_ARGUMENTS.map((arg) => arg.name));
@@ -7821,15 +7821,115 @@ function withConfirm(schema2, destructive) {
7821
7821
  return { ...schema2, properties };
7822
7822
  }
7823
7823
 
7824
+ // ../table/src/tools/credential-link.ts
7825
+ import { randomUUID } from "node:crypto";
7826
+ var DEFAULT_AUTH_COMPONENT_URL = "https://auth.components.deck.co";
7827
+ var LINK_LAYOUT = {
7828
+ maxWidth: "400px",
7829
+ maxHeight: "500px",
7830
+ border: "1px solid #e4e4e7",
7831
+ borderRadius: "8px"
7832
+ };
7833
+ function credentialLinkTool(port2) {
7834
+ return {
7835
+ name: "create_credential_link",
7836
+ description: "Create a link for a person to enter credentials. Deck never gives an agent a way to set a password directly \u2014 send this link to whoever holds the credentials and they enter them in Deck's own hosted form. Name a `source_id` if you know which source; leave it out and the person chooses from the organization's sources themselves. The link is short-lived, so pass it on promptly. Nothing reports back when it is used; check `list_credentials` for the new credential.",
7837
+ inputSchema: {
7838
+ type: "object",
7839
+ properties: {
7840
+ source_id: {
7841
+ type: "string",
7842
+ description: "The source the credentials are for, as `list_sources` gives it. Omit it to let the person choose."
7843
+ },
7844
+ external_id: {
7845
+ type: "string",
7846
+ description: "Only when checking on a link already sent: the `external_id` a previous call returned. No new link is created."
7847
+ }
7848
+ },
7849
+ required: [],
7850
+ additionalProperties: false
7851
+ },
7852
+ // Not read-only: it mints a credential-capturing token. Not destructive:
7853
+ // nothing existing is changed or removed by making one.
7854
+ annotations: { readOnlyHint: false, destructiveHint: false },
7855
+ kind: "handwritten",
7856
+ call: (args) => callCredentialLink(port2, args)
7857
+ };
7858
+ }
7859
+ async function callCredentialLink(port2, args) {
7860
+ const sourceId = String(args["source_id"] ?? "").trim();
7861
+ const given = String(args["external_id"] ?? "").trim();
7862
+ if (given !== "") return await credentialOutcome(port2, given);
7863
+ const externalId = (port2.newExternalId ?? (() => `mcp_${randomUUID()}`))();
7864
+ const minted = await port2.mintToken();
7865
+ if (!minted.ok) return minted;
7866
+ const token = minted.body?.token;
7867
+ const expiresAt = minted.body?.expires_at;
7868
+ if (typeof token !== "string" || token === "") {
7869
+ return {
7870
+ ok: false,
7871
+ status: minted.status,
7872
+ body: {
7873
+ error: "link_unavailable",
7874
+ message: "Deck issued no token for this link, so there is no link to give out."
7875
+ }
7876
+ };
7877
+ }
7878
+ const url = new URL(port2.authComponentUrl);
7879
+ url.searchParams.set("token", token);
7880
+ if (sourceId !== "") url.searchParams.set("sourceId", sourceId);
7881
+ url.searchParams.set("externalId", externalId);
7882
+ url.searchParams.set("appearance", JSON.stringify({ layout: LINK_LAYOUT }));
7883
+ return {
7884
+ ok: true,
7885
+ status: 0,
7886
+ body: {
7887
+ pending: true,
7888
+ url: url.toString(),
7889
+ expires_at: typeof expiresAt === "string" ? expiresAt : null,
7890
+ external_id: externalId,
7891
+ source_id: sourceId === "" ? null : sourceId,
7892
+ next_step: (sourceId === "" ? "Give this link to the person who holds the credentials; they choose which source to connect. " : "Give this link to the person who holds the credentials. ") + `It is short-lived, so send it now. Nothing reports back when they finish \u2014 call this tool again with external_id "${externalId}" to see whether the credential exists.`
7893
+ }
7894
+ };
7895
+ }
7896
+ async function credentialOutcome(port2, externalId) {
7897
+ const result = await port2.findByExternalId(externalId);
7898
+ if (!result.ok) return result;
7899
+ const data = result.body?.data;
7900
+ const found = Array.isArray(data) && data.length > 0 ? data[0] : null;
7901
+ if (found !== null) {
7902
+ return {
7903
+ ok: true,
7904
+ status: 0,
7905
+ body: {
7906
+ pending: false,
7907
+ credential: found,
7908
+ external_id: externalId,
7909
+ next_step: "The credential exists. Its status is `unverified` until a task run authenticates with it, so a wrong password shows up on the first run rather than here."
7910
+ }
7911
+ };
7912
+ }
7913
+ return {
7914
+ ok: true,
7915
+ status: 0,
7916
+ body: {
7917
+ pending: true,
7918
+ external_id: externalId,
7919
+ next_step: `Still nobody. Call this tool again with external_id "${externalId}" to check, or ask the person whether they opened the link.`
7920
+ }
7921
+ };
7922
+ }
7923
+
7824
7924
  // ../table/src/tools/docs.ts
7825
7925
  var DEFAULT_DOCS_MCP_URL = "https://docs.deck.co/mcp";
7826
7926
  var DOCS_TIMEOUT_MS = 15e3;
7827
7927
  var SEARCH_TOOL = "search_deck_docs";
7828
- var READ_TOOL = "query_docs_filesystem";
7928
+ var READ_TOOL = "query_docs_filesystem_deck_docs";
7829
7929
  var PAGE_PATH = /^(?!.*\.\.)[A-Za-z0-9][A-Za-z0-9._\-]*(?:\/[A-Za-z0-9][A-Za-z0-9._\-]*)*$/;
7830
- function docsTools(port) {
7930
+ function docsTools(port2) {
7831
7931
  const readOnly = { readOnlyHint: true, destructiveHint: false };
7832
- const forward = (tool, args) => callDocs(port.baseUrl, port.fetchImpl, tool, args);
7932
+ const forward = (tool, args) => callDocs(port2.baseUrl, port2.fetchImpl, tool, args);
7833
7933
  return [
7834
7934
  {
7835
7935
  name: "search_deck_docs",
@@ -7942,6 +8042,43 @@ function parseRpc(text3, contentType) {
7942
8042
  return null;
7943
8043
  }
7944
8044
 
8045
+ // ../table/src/tools/feedback.ts
8046
+ function feedbackTool(capture) {
8047
+ return {
8048
+ name: "submit_product_feedback",
8049
+ description: "Report friction with Deck itself: a tool that is missing, an argument that did not behave as documented, or a task you could not complete. Describe the PROBLEM only \u2014 do not include customer data, credentials, task input, or anything from a run's output.",
8050
+ inputSchema: {
8051
+ type: "object",
8052
+ properties: {
8053
+ message: {
8054
+ type: "string",
8055
+ description: "What was missing or wrong, and what would have helped."
8056
+ },
8057
+ blocked: {
8058
+ type: "boolean",
8059
+ description: "True if this stopped you completing what you were asked to do."
8060
+ }
8061
+ },
8062
+ required: ["message"],
8063
+ additionalProperties: false
8064
+ },
8065
+ annotations: { readOnlyHint: false, destructiveHint: false },
8066
+ kind: "handwritten",
8067
+ call: async (args) => {
8068
+ const message = String(args["message"] ?? "").trim();
8069
+ if (message === "") {
8070
+ return {
8071
+ ok: false,
8072
+ status: 0,
8073
+ body: { error: "empty_feedback", message: "Say what was missing or wrong. Nothing was sent." }
8074
+ };
8075
+ }
8076
+ capture({ message, blocked: args["blocked"] === true });
8077
+ return { ok: true, status: 0, body: { received: true } };
8078
+ }
8079
+ };
8080
+ }
8081
+
7945
8082
  // ../table/src/follow.ts
7946
8083
  var FIRST_DELAY_MS = 1e3;
7947
8084
  var MAX_DELAY_MS = 1e4;
@@ -7969,7 +8106,7 @@ function sleepOrAbort(sleep, ms, signal) {
7969
8106
  void sleep(ms).then(done);
7970
8107
  });
7971
8108
  }
7972
- async function follow(descriptor, started, port, opts) {
8109
+ async function follow(descriptor, started, port2, opts) {
7973
8110
  const now = opts.now ?? Date.now;
7974
8111
  const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
7975
8112
  const id = at(started, descriptor.id_from);
@@ -7998,7 +8135,7 @@ async function follow(descriptor, started, port, opts) {
7998
8135
  polls += 1;
7999
8136
  let res;
8000
8137
  try {
8001
- res = await port.poll({ [descriptor.id_as]: id });
8138
+ res = await port2.poll({ [descriptor.id_as]: id });
8002
8139
  } catch {
8003
8140
  return { outcome: "unreadable", body, polls };
8004
8141
  }
@@ -8187,320 +8324,108 @@ function replaceItems(body, descriptor, replaced) {
8187
8324
  return rebuild(body, 0);
8188
8325
  }
8189
8326
 
8190
- // src/aliases.ts
8191
- var ALIAS_TABLE = [
8192
- { canonical: "list", aliases: ["ls"] },
8193
- { canonical: "retrieve", aliases: ["get", "show", "view", "inspect"] },
8194
- { canonical: "create", aliases: ["add", "new"] },
8195
- { canonical: "update", aliases: ["edit", "patch", "set"] },
8196
- { canonical: "delete", aliases: ["rm", "remove", "del"] },
8197
- { canonical: "run", aliases: ["execute", "start"], under: ["tasks", "workflows"] },
8198
- { canonical: "rerun", aliases: ["retry"] },
8199
- { canonical: "cancel", aliases: ["stop", "abort"] },
8200
- { canonical: "interaction", aliases: ["interact", "respond", "answer"] },
8201
- { canonical: "screenshots", aliases: ["shots", "screens"] },
8202
- { canonical: "browser-logs", aliases: ["logs"] },
8203
- { canonical: "browser-access", aliases: ["cdp", "attach"] },
8204
- // `follow` is in two rows. It never collides: `watch` lives on runs and `tail`
8205
- // on events, and a word only resolves to a canonical command that exists at
8206
- // that spot, so `task-runs follow` is watch and `events follow` is tail.
8207
- { canonical: "watch", aliases: ["wait", "follow"] },
8208
- { canonical: "tail", aliases: ["follow", "stream"] },
8209
- { canonical: "reset", aliases: ["clear"] },
8210
- { canonical: "test", aliases: ["ping"], under: ["event-destinations"] },
8211
- { canonical: "deliveries", aliases: ["attempts"] },
8212
- { canonical: "agents", aliases: ["agent"] },
8213
- { canonical: "sources", aliases: ["source", "src"] },
8214
- { canonical: "credentials", aliases: ["credential", "creds", "cred"] },
8215
- { canonical: "tasks", aliases: ["task"] },
8216
- { canonical: "task-runs", aliases: ["task-run", "runs", "trun"] },
8217
- { canonical: "routines", aliases: ["routine", "rtn"] },
8218
- { canonical: "routine-builds", aliases: ["routine-build", "builds", "rbld"] },
8219
- { canonical: "workflows", aliases: ["workflow", "wf"] },
8220
- { canonical: "workflow-runs", aliases: ["workflow-run", "wruns", "wrun"] },
8221
- { canonical: "triggers", aliases: ["trigger", "trg"] },
8222
- { canonical: "sessions", aliases: ["session", "sess"] },
8223
- { canonical: "events", aliases: ["event", "evt"] },
8224
- {
8225
- canonical: "event-destinations",
8226
- aliases: ["event-destination", "destinations", "destination", "dest", "webhooks", "evtd"]
8327
+ // src/errors.ts
8328
+ var DOCS = "https://docs.deck.co/cli/errors";
8329
+ var CODES = {
8330
+ auth_required: {
8331
+ exit: 3,
8332
+ retryable: false,
8333
+ message: "No credential found. Sign in, set DECK_API_KEY, or provision an organization.",
8334
+ // NOT `deck keys create`: minting a key needs a credential, so the most
8335
+ // common error in the CLI offered a step that answers itself with this
8336
+ // same error. `deck init` is the one way in that needs nothing.
8337
+ next_steps: () => ["deck login", "export DECK_API_KEY=sk_live_...", "deck init"]
8227
8338
  },
8228
- { canonical: "storage", aliases: ["stor", "files"] },
8229
- { canonical: "keys", aliases: ["key", "api-keys", "api-key", "tokens"] },
8230
- { canonical: "orgs", aliases: ["org", "organizations", "organization"] },
8231
- { canonical: "login", aliases: ["signin", "sign-in", "auth login"] },
8232
- { canonical: "logout", aliases: ["signout", "sign-out", "auth logout"] },
8233
- { canonical: "whoami", aliases: ["me", "status", "auth status"] },
8234
- { canonical: "upgrade", aliases: ["update", "self-update"] },
8235
- { canonical: "agent setup", aliases: ["setup"] },
8236
- { canonical: "agent-guide", aliases: ["guide"] },
8237
- { canonical: "docs search", aliases: ["search"] },
8238
- { canonical: "feedback", aliases: ["bug"] }
8239
- ];
8240
- var ALIAS_INDEX = (() => {
8241
- const index = /* @__PURE__ */ new Map();
8242
- for (const { canonical, aliases, under } of ALIAS_TABLE) {
8243
- for (const alias of aliases) {
8244
- const targets = index.get(alias) ?? [];
8245
- targets.push({ canonical: canonical.split(" "), ...under === void 0 ? {} : { under } });
8246
- index.set(alias, targets);
8247
- }
8339
+ org_required: {
8340
+ exit: 2,
8341
+ retryable: false,
8342
+ message: "More than one organization is available. Choose one.",
8343
+ next_steps: () => ["deck orgs list", "deck orgs switch <org_id>"]
8344
+ },
8345
+ secret_in_argv: {
8346
+ exit: 2,
8347
+ retryable: false,
8348
+ message: "A secret was passed as a command-line argument, where shell history and process lists can read it.",
8349
+ next_steps: () => ["export DECK_API_KEY=sk_live_...", "deck login"]
8350
+ },
8351
+ task_sensitive: {
8352
+ exit: 1,
8353
+ retryable: false,
8354
+ message: "This task takes sensitive input, which the CLI will not send.",
8355
+ next_steps: () => ["deck tasks get <task_id>"]
8356
+ },
8357
+ login_pending: {
8358
+ exit: 3,
8359
+ retryable: true,
8360
+ message: "Sign-in has not been approved yet.",
8361
+ next_steps: () => ["deck login"]
8362
+ },
8363
+ confirmation_required: {
8364
+ exit: 2,
8365
+ retryable: false,
8366
+ message: "This command changes or deletes data and needs --yes. The CLI never prompts.",
8367
+ // Without the command there is no honest "<command> --yes"; point at the command list instead.
8368
+ next_steps: (cmd) => [cmd ? `${cmd} --yes` : "deck --help"]
8369
+ },
8370
+ input_invalid: {
8371
+ exit: 2,
8372
+ retryable: false,
8373
+ message: "The command's input is invalid.",
8374
+ next_steps: (cmd) => [cmd ? `${cmd} --help` : "deck --help"]
8375
+ },
8376
+ network_error: {
8377
+ exit: 1,
8378
+ retryable: true,
8379
+ // "Run it again" belongs in the MESSAGE, not in next_steps. A step is a
8380
+ // literal command to paste, and a re-run step can only be the invocation
8381
+ // rebuilt from argv — which `invocationOf` has stripped `--yes` from (right
8382
+ // for `confirmation_required`, which appends its own) and masked the key
8383
+ // in. The pasted result is refused with `confirmation_required`, or fails
8384
+ // auth, or both. Nothing can repair that reconstruction: a masked secret is
8385
+ // by definition not pasteable. `retryable: true` already tells an agent
8386
+ // that retrying is correct, and a human has the command in shell history.
8387
+ message: "The request did not reach the host. Run the same command again; a transport failure is usually transient. If it keeps failing, the host may be wrong.",
8388
+ next_steps: () => ["export DECK_API_URL=https://api.deck.co"]
8389
+ },
8390
+ // The CLI itself broke: a bug here, never the user's input and never the server's
8391
+ // answer. It is the catch-all for anything non-`CliError` escaping the pipeline,
8392
+ // and the jq engine's own failure. Exit 1: the command ran and failed.
8393
+ internal_error: {
8394
+ exit: 1,
8395
+ retryable: false,
8396
+ message: "The CLI itself failed. This is a bug in the CLI, not in your command or in the API. Please report it at https://github.com/deckco/cli/issues with the output of the command below.",
8397
+ // Without the command there is no honest "<command> --verbose"; point at the command list.
8398
+ next_steps: (cmd) => [cmd ? `${cmd} --verbose` : "deck --help"]
8399
+ },
8400
+ // A wrong target (docs site, proxy login page), not a transient fault: never retryable.
8401
+ unexpected_response: {
8402
+ exit: 1,
8403
+ retryable: false,
8404
+ message: "The server answered with something that is not the Deck API.",
8405
+ next_steps: () => ["export DECK_API_URL=https://api.deck.co"]
8248
8406
  }
8249
- return index;
8250
- })();
8251
- var ALIAS_WORDS = 2;
8252
- var COMMAND_WORD = /^[a-z][a-z0-9-]*$/;
8253
- function singularOf(word) {
8254
- if (word.endsWith("ies")) return `${word.slice(0, -3)}y`;
8255
- if (word.endsWith("s") && !word.endsWith("ss")) return word.slice(0, -1);
8256
- return void 0;
8257
- }
8258
- var SHAPES = /* @__PURE__ */ new WeakMap();
8259
- function shapeOf(registry2) {
8260
- const cached2 = SHAPES.get(registry2);
8261
- if (cached2) return cached2;
8262
- const prefixes = /* @__PURE__ */ new Set();
8263
- const children = /* @__PURE__ */ new Map();
8264
- for (const command of registry2.keys()) {
8265
- const words = command.split(" ");
8266
- words.forEach((word, i) => {
8267
- const parent = words.slice(0, i).join(" ");
8268
- prefixes.add(words.slice(0, i + 1).join(" "));
8269
- const kids = children.get(parent) ?? /* @__PURE__ */ new Set();
8270
- kids.add(word);
8271
- children.set(parent, kids);
8272
- });
8273
- }
8274
- const shape = { prefixes, children: new Map([...children].map(([k, v]) => [k, [...v]])) };
8275
- SHAPES.set(registry2, shape);
8276
- return shape;
8277
- }
8278
- function resolveWords(registry2, argv) {
8279
- const { prefixes, children } = shapeOf(registry2);
8280
- const walk = (prefix, at4) => {
8281
- const options = [];
8282
- const word = argv[at4];
8283
- if (word !== void 0 && COMMAND_WORD.test(word)) {
8284
- const key = prefix.join(" ");
8285
- const join13 = (words) => [...prefix, ...words].join(" ");
8286
- if (prefixes.has(join13([word]))) options.push({ words: [word], take: 1, alias: false });
8287
- for (let len = ALIAS_WORDS; len >= 1; len--) {
8288
- const typed = argv.slice(at4, at4 + len);
8289
- if (typed.length < len || !typed.every((w) => COMMAND_WORD.test(w))) continue;
8290
- for (const target of ALIAS_INDEX.get(typed.join(" ")) ?? []) {
8291
- if (target.under !== void 0 && !target.under.includes(key)) continue;
8292
- if (prefixes.has(join13(target.canonical))) options.push({ words: target.canonical, take: len, alias: true });
8293
- }
8294
- }
8295
- for (const child of children.get(key) ?? []) {
8296
- if (singularOf(child) === word) options.push({ words: [child], take: 1, alias: true });
8297
- }
8298
- }
8299
- for (const option of options) {
8300
- const hit = walk([...prefix, ...option.words], at4 + option.take);
8301
- if (hit) return { ...hit, aliasUsed: hit.aliasUsed || option.alias };
8302
- }
8303
- return prefix.length > 0 && registry2.has(prefix.join(" ")) ? { words: prefix, consumed: at4, aliasUsed: false } : void 0;
8304
- };
8305
- return walk([], 0);
8306
- }
8307
- function normalizeFlagAliases(argv) {
8308
- let aliasUsed = false;
8309
- const out = [];
8310
- let tokens = argv;
8311
- if (tokens[0] === "--version" || tokens[0] === "-v") {
8312
- out.push("version");
8313
- tokens = tokens.slice(1);
8314
- aliasUsed = true;
8315
- }
8316
- let endOfFlags = false;
8317
- for (let i = 0; i < tokens.length; i++) {
8318
- const token = tokens[i];
8319
- if (endOfFlags || !token.startsWith("--")) {
8320
- out.push(token);
8321
- continue;
8322
- }
8323
- if (token === "--") {
8324
- endOfFlags = true;
8325
- out.push(token);
8326
- } else if (token === "--key" || token.startsWith("--key=")) {
8327
- out.push(`--api-key${token.slice("--key".length)}`);
8328
- aliasUsed = true;
8329
- } else if (token === "--output=json") {
8330
- out.push("--json");
8331
- aliasUsed = true;
8332
- } else if (token === "--output" && tokens[i + 1] === "json") {
8333
- out.push("--json");
8334
- i++;
8335
- aliasUsed = true;
8336
- } else {
8337
- out.push(token);
8338
- }
8339
- }
8340
- return { argv: out, aliasUsed };
8341
- }
8342
- function shortOutputAlias(parsed) {
8343
- const positionals = [];
8344
- let used = false;
8345
- for (let i = 0; i < parsed.positionals.length; i++) {
8346
- if (parsed.positionals[i] === "-o" && parsed.positionals[i + 1] === "json") {
8347
- used = true;
8348
- i++;
8349
- } else {
8350
- positionals.push(parsed.positionals[i]);
8351
- }
8352
- }
8353
- if (!used) return { parsed, aliasUsed: false };
8354
- const flags = new Map(parsed.flags);
8355
- flags.set("json", [...flags.get("json") ?? [], "true"]);
8356
- return { parsed: { ...parsed, flags, positionals }, aliasUsed: true };
8357
- }
8358
-
8359
- // src/dates.ts
8360
- var isDateParam = (param) => param.schema.format === "date-time" || /_(after|before)$/.test(param.name);
8361
- var ABSOLUTE = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
8362
- var isAbsoluteTimestamp = (value) => ABSOLUTE.test(value) && !Number.isNaN(Date.parse(value));
8363
- var SECOND_MS = 1e3;
8364
- var MINUTE_MS = 60 * SECOND_MS;
8365
- var HOUR_MS = 60 * MINUTE_MS;
8366
- var DAY_MS = 24 * HOUR_MS;
8367
- var WEEK_MS = 7 * DAY_MS;
8368
- var UNIT_MS = {
8369
- s: SECOND_MS,
8370
- m: MINUTE_MS,
8371
- h: HOUR_MS,
8372
- d: DAY_MS,
8373
- w: WEEK_MS
8374
- };
8375
- var SHORT_FORM = /^-(\d+)([smhdw])$/;
8376
- var ISO_FORM = /^-P(?=\d|T\d)(?:(\d+)W)?(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
8377
- var iso = (ms) => {
8378
- const d = new Date(ms);
8379
- return Number.isNaN(d.getTime()) ? null : d.toISOString();
8380
- };
8381
- function toAbsolute(value, now) {
8382
- const nowMs = now.getTime();
8383
- if (value === "today" || value === "yesterday") {
8384
- const midnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
8385
- const dayOffset = value === "yesterday" ? -DAY_MS : 0;
8386
- return iso(midnight + dayOffset);
8387
- }
8388
- const short = SHORT_FORM.exec(value);
8389
- if (short) {
8390
- const amount = Number(short[1]);
8391
- return iso(nowMs - amount * UNIT_MS[short[2]]);
8392
- }
8393
- const match = ISO_FORM.exec(value);
8394
- if (match) {
8395
- const [, weeks, days, hours, minutes, seconds] = match;
8396
- const totalMs = Number(weeks ?? 0) * WEEK_MS + Number(days ?? 0) * DAY_MS + Number(hours ?? 0) * HOUR_MS + Number(minutes ?? 0) * MINUTE_MS + Number(seconds ?? 0) * SECOND_MS;
8397
- return iso(nowMs - totalMs);
8398
- }
8399
- return null;
8400
- }
8401
-
8402
- // src/errors.ts
8403
- var DOCS = "https://docs.deck.co/cli/errors";
8404
- var CODES = {
8405
- auth_required: {
8406
- exit: 3,
8407
- retryable: false,
8408
- message: "No credential found. Sign in, set DECK_API_KEY, or provision an organization.",
8409
- // NOT `deck keys create`: minting a key needs a credential, so the most
8410
- // common error in the CLI offered a step that answers itself with this
8411
- // same error. `deck init` is the one way in that needs nothing.
8412
- next_steps: () => ["deck login", "export DECK_API_KEY=sk_live_...", "deck init"]
8413
- },
8414
- org_required: {
8415
- exit: 2,
8416
- retryable: false,
8417
- message: "More than one organization is available. Choose one.",
8418
- next_steps: () => ["deck orgs list", "deck orgs switch <org_id>"]
8419
- },
8420
- secret_in_argv: {
8421
- exit: 2,
8422
- retryable: false,
8423
- message: "A secret was passed as a command-line argument, where shell history and process lists can read it.",
8424
- next_steps: () => ["export DECK_API_KEY=sk_live_...", "deck login"]
8425
- },
8426
- task_sensitive: {
8427
- exit: 1,
8428
- retryable: false,
8429
- message: "This task takes sensitive input, which the CLI will not send.",
8430
- next_steps: () => ["deck tasks get <task_id>"]
8431
- },
8432
- login_pending: {
8433
- exit: 3,
8434
- retryable: true,
8435
- message: "Sign-in has not been approved yet.",
8436
- next_steps: () => ["deck login"]
8437
- },
8438
- confirmation_required: {
8439
- exit: 2,
8440
- retryable: false,
8441
- message: "This command changes or deletes data and needs --yes. The CLI never prompts.",
8442
- // Without the command there is no honest "<command> --yes"; point at the command list instead.
8443
- next_steps: (cmd) => [cmd ? `${cmd} --yes` : "deck --help"]
8444
- },
8445
- input_invalid: {
8446
- exit: 2,
8447
- retryable: false,
8448
- message: "The command's input is invalid.",
8449
- next_steps: (cmd) => [cmd ? `${cmd} --help` : "deck --help"]
8450
- },
8451
- network_error: {
8452
- exit: 1,
8453
- retryable: true,
8454
- // "Run it again" belongs in the MESSAGE, not in next_steps. A step is a
8455
- // literal command to paste, and a re-run step can only be the invocation
8456
- // rebuilt from argv — which `invocationOf` has stripped `--yes` from (right
8457
- // for `confirmation_required`, which appends its own) and masked the key
8458
- // in. The pasted result is refused with `confirmation_required`, or fails
8459
- // auth, or both. Nothing can repair that reconstruction: a masked secret is
8460
- // by definition not pasteable. `retryable: true` already tells an agent
8461
- // that retrying is correct, and a human has the command in shell history.
8462
- message: "The request did not reach the host. Run the same command again; a transport failure is usually transient. If it keeps failing, the host may be wrong.",
8463
- next_steps: () => ["export DECK_API_URL=https://api.deck.co"]
8464
- },
8465
- // The CLI itself broke: a bug here, never the user's input and never the server's
8466
- // answer. It is the catch-all for anything non-`CliError` escaping the pipeline,
8467
- // and the jq engine's own failure. Exit 1: the command ran and failed.
8468
- internal_error: {
8469
- exit: 1,
8470
- retryable: false,
8471
- message: "The CLI itself failed. This is a bug in the CLI, not in your command or in the API. Please report it at https://github.com/deckco/cli/issues with the output of the command below.",
8472
- // Without the command there is no honest "<command> --verbose"; point at the command list.
8473
- next_steps: (cmd) => [cmd ? `${cmd} --verbose` : "deck --help"]
8474
- },
8475
- // A wrong target (docs site, proxy login page), not a transient fault: never retryable.
8476
- unexpected_response: {
8477
- exit: 1,
8478
- retryable: false,
8479
- message: "The server answered with something that is not the Deck API.",
8480
- next_steps: () => ["export DECK_API_URL=https://api.deck.co"]
8481
- }
8482
- };
8483
- var EXIT_FOR_CODE = Object.fromEntries(
8484
- Object.keys(CODES).map((code) => [code, CODES[code].exit])
8485
- );
8486
- var codesExiting = (exit) => Object.keys(CODES).filter((c) => CODES[c].exit === exit);
8487
- var CliError = class _CliError extends Error {
8488
- constructor(code, init = {}) {
8489
- const row = CODES[code];
8490
- const steps = init.next_steps?.length ? [...init.next_steps] : row.next_steps(init.command);
8491
- const defaultMessage = `${row.message} Run \`${steps[0]}\`.`;
8492
- const problems = init.problems?.length ? init.problems.map((p) => ({ ...p })) : [{ field: init.field, message: init.message ?? defaultMessage }];
8493
- super(
8494
- problems.length === 1 ? problems[0]?.message ?? defaultMessage : `${problems.length} problems: ${problems.map((p) => p.message).join("; ")}`
8495
- );
8496
- this.code = code;
8497
- this.init = init;
8498
- this.name = "CliError";
8499
- this.problems = problems;
8500
- this.field = problems[0]?.field;
8501
- this.retryable = row.retryable;
8502
- this.next_steps = steps;
8503
- this.docs_url = `${DOCS}#${code}`;
8407
+ };
8408
+ var EXIT_FOR_CODE = Object.fromEntries(
8409
+ Object.keys(CODES).map((code) => [code, CODES[code].exit])
8410
+ );
8411
+ var codesExiting = (exit) => Object.keys(CODES).filter((c) => CODES[c].exit === exit);
8412
+ var CliError = class _CliError extends Error {
8413
+ constructor(code, init = {}) {
8414
+ const row = CODES[code];
8415
+ const steps = init.next_steps?.length ? [...init.next_steps] : row.next_steps(init.command);
8416
+ const defaultMessage = `${row.message} Run \`${steps[0]}\`.`;
8417
+ const problems = init.problems?.length ? init.problems.map((p) => ({ ...p })) : [{ field: init.field, message: init.message ?? defaultMessage }];
8418
+ super(
8419
+ problems.length === 1 ? problems[0]?.message ?? defaultMessage : `${problems.length} problems: ${problems.map((p) => p.message).join("; ")}`
8420
+ );
8421
+ this.code = code;
8422
+ this.init = init;
8423
+ this.name = "CliError";
8424
+ this.problems = problems;
8425
+ this.field = problems[0]?.field;
8426
+ this.retryable = row.retryable;
8427
+ this.next_steps = steps;
8428
+ this.docs_url = `${DOCS}#${code}`;
8504
8429
  }
8505
8430
  code;
8506
8431
  init;
@@ -8533,282 +8458,164 @@ function renderError(e) {
8533
8458
  return { json: JSON.stringify(body), exit: CODES[e.code].exit };
8534
8459
  }
8535
8460
 
8536
- // src/flags.ts
8537
- var toFlag = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
8538
- var toSnake = (flag) => toFlag(flag).replace(/-/g, "_");
8539
- var typedFlagKey = (typed) => typed.replace(/_/g, "-");
8540
- var typesOf = (schema2) => schema2.type === void 0 ? [] : Array.isArray(schema2.type) ? schema2.type : [schema2.type];
8541
-
8542
- // src/bind.ts
8543
- var reason = (e) => e instanceof Error ? e.message : String(e);
8544
- function readInput(raw, io) {
8545
- let text3;
8546
- if (raw === "-") {
8547
- if (io.stdinIsTty) {
8548
- throw new CliError("input_invalid", { field: "input", message: "--input - reads stdin, but stdin is a terminal; pipe JSON in or use --input @file" });
8549
- }
8550
- text3 = io.readStdin();
8551
- } else if (raw.startsWith("@")) {
8552
- try {
8553
- text3 = io.readFile(raw.slice(1));
8554
- } catch (e) {
8555
- throw new CliError("input_invalid", { field: "input", message: `--input could not read ${raw.slice(1)}: ${reason(e)}` });
8556
- }
8557
- } else {
8558
- text3 = raw;
8559
- }
8560
- let parsed;
8561
- try {
8562
- parsed = JSON.parse(text3);
8563
- } catch (e) {
8564
- const at4 = /position (\d+)/.exec(reason(e))?.[1];
8565
- throw new CliError("input_invalid", {
8566
- field: "input",
8567
- message: `--input is not valid JSON${at4 === void 0 ? "" : ` (at character ${at4})`}. The parser's own message is not shown, because it quotes the input.`
8568
- });
8569
- }
8570
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
8571
- throw new CliError("input_invalid", { field: "input", message: "--input must be a JSON object" });
8572
- }
8573
- return parsed;
8574
- }
8575
- var isFreeForm = (schema2) => typesOf(schema2).length === 0 && !schema2.enum && !schema2.items;
8576
- function coerceBodyValue(name, raw, schema2) {
8577
- const types = typesOf(schema2);
8578
- if (isFreeForm(schema2)) {
8579
- try {
8580
- return JSON.parse(raw);
8581
- } catch {
8582
- return raw;
8583
- }
8584
- }
8585
- if (types.includes("object") || types.includes("array")) {
8586
- if (raw === "null" && types.includes("null")) return null;
8587
- try {
8588
- return JSON.parse(raw);
8589
- } catch {
8590
- return raw;
8591
- }
8592
- }
8593
- if (types.includes("boolean") && (raw === "true" || raw === "false")) return raw === "true";
8594
- if (types.includes("integer") && /^-?\d+$/.test(raw)) return Number(raw);
8595
- if (types.includes("number") && /^-?\d+(\.\d+)?$/.test(raw)) return Number(raw);
8596
- return raw;
8461
+ // src/http.ts
8462
+ var DEFAULT_BASE_URL = "https://api.deck.co";
8463
+ var apiBaseUrl = (env) => env["DECK_API_URL"]?.trim() || DEFAULT_BASE_URL;
8464
+ var MAX_ATTEMPTS = 5;
8465
+ var BASE_DELAY_MS = 250;
8466
+ var MAX_BACKOFF_MS = 3e4;
8467
+ var MAX_RETRY_AFTER_MS = 6e4;
8468
+ var ATTEMPT_TIMEOUT_MS = 6e4;
8469
+ var EXCERPT_CHARS = 200;
8470
+ var isRetryableStatus = (status) => status === 429 || status >= 500;
8471
+ var defaultSleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
8472
+ var isWrite = (method) => !["GET", "HEAD"].includes(method.toUpperCase());
8473
+ function retryAfterMs(h, now = Date.now()) {
8474
+ const v = h.get("retry-after")?.trim();
8475
+ if (!v) return null;
8476
+ if (/^\d+(\.\d+)?$/.test(v)) return Number(v) * 1e3;
8477
+ const at4 = Date.parse(v);
8478
+ return Number.isNaN(at4) ? null : Math.max(0, at4 - now);
8597
8479
  }
8598
- var fillsPath2 = (value) => value.trim() !== "";
8599
- function bindQuery(param, values, now) {
8600
- const items = param.schema.type === "array" ? values.flatMap((v) => v.split(",")) : values;
8601
- return isDateParam(param) ? items.map((v) => toAbsolute(v, now) ?? v) : items;
8480
+ function networkError(host, e) {
8481
+ const cause = e?.cause;
8482
+ const name = e?.name;
8483
+ const why = typeof cause?.code === "string" ? cause.code : name === "TimeoutError" ? "timed out" : e instanceof Error ? e.message : "unknown";
8484
+ return new CliError("network_error", {
8485
+ message: `Could not reach ${host}: ${why}. Run the same command again; a transport failure is usually transient. If it keeps failing, check DECK_API_URL and your network.`
8486
+ });
8602
8487
  }
8603
- function bind(row, parsed, io, now) {
8604
- const unknownFields = [];
8605
- const query = {};
8606
- const pathValues = /* @__PURE__ */ new Map();
8607
- const flagBody = {};
8608
- const bodyProps = row.body_schema?.properties ?? {};
8609
- const byFlag = (items) => new Map(items.map(([name, v]) => [toFlag(name), [name, v]]));
8610
- const pathByFlag = byFlag(row.path_params.map((p) => [p.name, p]));
8611
- const queryByFlag = byFlag(row.query_params.map((p) => [p.name, p]));
8612
- const bodyByFlag = byFlag(Object.entries(bodyProps));
8613
- for (const [typed, values] of parsed.flags) {
8614
- if (typed === "input" || GLOBAL_BOOLEAN_FLAGS.has(typed)) continue;
8615
- const key = typedFlagKey(typed);
8616
- const pathHit = pathByFlag.get(key);
8617
- const queryHit = queryByFlag.get(key);
8618
- const bodyHit = bodyByFlag.get(key);
8619
- if (pathHit) {
8620
- const value = values[values.length - 1];
8621
- if (fillsPath2(value)) pathValues.set(pathHit[0], value);
8622
- } else if (queryHit) query[queryHit[0]] = bindQuery(queryHit[1], values, now);
8623
- else if (bodyHit) flagBody[bodyHit[0]] = coerceBodyValue(bodyHit[0], values[values.length - 1], bodyHit[1]);
8624
- else unknownFields.push(typed);
8488
+ function redactUrl(url) {
8489
+ const u = new URL(url);
8490
+ u.username = "";
8491
+ u.password = "";
8492
+ return u.toString();
8493
+ }
8494
+ function buildUrl(baseUrl, req) {
8495
+ if (/\{[^}]+\}/.test(req.path)) {
8496
+ throw new CliError("input_invalid", {
8497
+ field: "path",
8498
+ message: "The path still has an unfilled {placeholder}, so nothing was sent."
8499
+ });
8625
8500
  }
8626
- const open3 = row.path_params.filter((p) => !pathValues.has(p.name));
8627
- parsed.positionals.slice(0, open3.length).forEach((v, i) => {
8628
- if (fillsPath2(v)) pathValues.set(open3[i].name, v);
8629
- });
8630
- const extraArguments = parsed.positionals.slice(open3.length);
8631
- let path = row.path;
8632
- for (const [name, value] of pathValues) path = path.replace(`{${name}}`, encodeURIComponent(value));
8633
- const inputFlag = parsed.flags.get("input");
8634
- const input = inputFlag ? readInput(inputFlag[inputFlag.length - 1], io) : void 0;
8635
- const declared = row.body_schema?.properties;
8636
- const unknownInputKeys = input !== void 0 && declared ? Object.keys(input).filter((k) => !(k in declared)) : [];
8637
- const body = input !== void 0 || row.body_schema !== null || Object.keys(flagBody).length > 0 ? { ...input, ...flagBody } : null;
8638
- return { method: row.method, path, query, body, unknownFields, extraArguments, unknownInputKeys };
8501
+ const pairs = [];
8502
+ for (const [key, values] of Object.entries(req.query)) {
8503
+ for (const v of values) pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(v)}`);
8504
+ }
8505
+ return baseUrl.replace(/\/+$/, "") + req.path + (pairs.length ? `?${pairs.join("&")}` : "");
8639
8506
  }
8640
-
8641
- // src/suggest.ts
8642
- function distance(a, b) {
8643
- let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
8644
- for (let i = 1; i <= a.length; i++) {
8645
- const cur = [i];
8646
- for (let j = 1; j <= b.length; j++) {
8647
- cur[j] = Math.min(
8648
- prev[j] + 1,
8649
- cur[j - 1] + 1,
8650
- prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
8651
- );
8507
+ async function readBody(res, host) {
8508
+ let text3;
8509
+ try {
8510
+ text3 = await res.text();
8511
+ } catch (e) {
8512
+ throw networkError(host, e);
8513
+ }
8514
+ if (text3.trim() === "") return null;
8515
+ try {
8516
+ return JSON.parse(text3);
8517
+ } catch {
8518
+ if (res.ok) {
8519
+ throw new CliError("unexpected_response", {
8520
+ message: `${host} answered HTTP ${res.status} with a body that is not JSON. Check that DECK_API_URL points at the Deck API.`
8521
+ });
8652
8522
  }
8653
- prev = cur;
8523
+ const excerpt = text3.replace(/\s+/g, " ").trim().slice(0, EXCERPT_CHARS);
8524
+ const body = {
8525
+ request_id: res.headers.get("x-request-id") ?? "",
8526
+ errors: [
8527
+ {
8528
+ type: "api",
8529
+ code: "non_json_response",
8530
+ field: null,
8531
+ message: `HTTP ${res.status}: the response was not JSON. Body began: ${excerpt}`,
8532
+ // The CLI builds this body, so nothing else will fill `retryable` in.
8533
+ // An ingress HTML 502 is the shape this case was written for, and it
8534
+ // is exactly the one a caller should try again.
8535
+ retryable: isRetryableStatus(res.status)
8536
+ }
8537
+ ]
8538
+ };
8539
+ return body;
8654
8540
  }
8655
- return prev[b.length];
8656
8541
  }
8657
- function suggest(input, candidates) {
8658
- const limit = Math.max(1, Math.floor(input.length / 3));
8659
- let best;
8660
- let bestDistance = Infinity;
8661
- for (const candidate of candidates) {
8662
- const d = distance(input, candidate);
8663
- if (d <= limit && d < bestDistance) {
8664
- best = candidate;
8665
- bestDistance = d;
8542
+ function prepare(req, opts) {
8543
+ let parsed;
8544
+ try {
8545
+ parsed = new URL(opts.baseUrl);
8546
+ } catch {
8547
+ throw new CliError("input_invalid", {
8548
+ field: "DECK_API_URL",
8549
+ message: `DECK_API_URL is not an absolute URL (include https://). Run \`export DECK_API_URL=https://api.deck.co\`.`
8550
+ });
8551
+ }
8552
+ const url = buildUrl(opts.baseUrl, req);
8553
+ const headers = {
8554
+ ...opts.credential === null ? {} : { authorization: `Bearer ${opts.credential.token}` },
8555
+ "user-agent": `deck-cli/${opts.version}`,
8556
+ accept: "application/json"
8557
+ };
8558
+ if (opts.idempotencyKey) headers["idempotency-key"] = opts.idempotencyKey;
8559
+ if (req.body !== null) headers["content-type"] = "application/json";
8560
+ return {
8561
+ url,
8562
+ host: parsed.host,
8563
+ headers,
8564
+ // The one redaction site. `--dry-run` prints this, never its own copy.
8565
+ request: {
8566
+ method: req.method,
8567
+ url: redactUrl(url),
8568
+ headers: opts.credential === null ? { ...headers } : { ...headers, authorization: "Bearer [redacted]" }
8569
+ }
8570
+ };
8571
+ }
8572
+ function requestView(req, opts) {
8573
+ return prepare(req, opts).request;
8574
+ }
8575
+ async function send(req, opts) {
8576
+ const doFetch = opts.fetch ?? fetch;
8577
+ const sleep = opts.sleep ?? defaultSleep;
8578
+ const { url, host, headers, request: request3 } = prepare(req, opts);
8579
+ const hasBody = req.body !== null;
8580
+ const body = hasBody ? { body: JSON.stringify(req.body) } : {};
8581
+ const attempts = opts.retry ? MAX_ATTEMPTS : 1;
8582
+ for (let attempt = 1; ; attempt++) {
8583
+ let res;
8584
+ try {
8585
+ res = await doFetch(url, { method: req.method, headers, ...body, signal: AbortSignal.timeout(ATTEMPT_TIMEOUT_MS) });
8586
+ } catch (e) {
8587
+ throw networkError(host, e);
8588
+ }
8589
+ const retryable = res.status === 429 || res.status >= 500 && (!isWrite(req.method) || !!opts.idempotencyKey);
8590
+ const wait = retryAfterMs(res.headers);
8591
+ if (!retryable || attempt >= attempts || wait !== null && wait > MAX_RETRY_AFTER_MS) {
8592
+ return { status: res.status, body: await readBody(res, host), headers: res.headers, request: request3 };
8666
8593
  }
8594
+ await res.body?.cancel();
8595
+ await sleep(wait ?? Math.min(BASE_DELAY_MS * 2 ** (attempt - 1), MAX_BACKOFF_MS));
8667
8596
  }
8668
- return best;
8669
8597
  }
8670
8598
 
8671
- // src/check.ts
8672
- var INTEGER = /^-?\d+$/;
8673
- var NUMBER = /^-?\d+(\.\d+)?$/;
8674
- function typeFits(value, types, pattern) {
8675
- if (types.length === 0) return true;
8676
- if (value === null) return types.includes("null");
8677
- if (typeof value === "string") {
8678
- if (pattern !== void 0 && !new RegExp(pattern).test(value)) return false;
8679
- if (types.includes("string")) return true;
8680
- if (types.includes("integer") && INTEGER.test(value)) return true;
8681
- if (types.includes("number") && NUMBER.test(value)) return true;
8682
- return types.includes("boolean") && (value === "true" || value === "false");
8683
- }
8684
- if (typeof value === "number") {
8685
- return types.includes("number") || types.includes("integer") && Number.isInteger(value);
8599
+ // src/state/config.ts
8600
+ import { join as join3 } from "node:path";
8601
+
8602
+ // src/credentials.ts
8603
+ import { join as join2 } from "node:path";
8604
+ async function resolveCredential(sources) {
8605
+ for (const s of sources) {
8606
+ const c = await s.get();
8607
+ if (c) return c;
8686
8608
  }
8687
- if (typeof value === "boolean") return types.includes("boolean");
8688
- if (Array.isArray(value)) return types.includes("array");
8689
- return types.includes("object");
8609
+ throw new CliError("auth_required");
8690
8610
  }
8691
- function describeType(types) {
8692
- const real = types.filter((t) => t !== "null");
8693
- if (real.includes("integer")) return "an integer";
8694
- if (real.includes("number")) return "a number";
8695
- if (real.includes("boolean")) return "true or false";
8696
- return real.length === 1 ? `${/^[aeiou]/.test(real[0]) ? "an" : "a"} ${real[0]}` : `one of ${real.join(", ")}`;
8697
- }
8698
- var show = (value) => typeof value === "string" ? JSON.stringify(value) : String(JSON.stringify(value));
8699
- function checkValue(name, value, schema2) {
8700
- const flag = `--${toFlag(name)}`;
8701
- const types = typesOf(schema2);
8702
- if (Array.isArray(value) && types.includes("array") && schema2.items) {
8703
- return value.flatMap((item) => checkValue(name, item, schema2.items));
8704
- }
8705
- if (!typeFits(value, types, schema2.pattern)) {
8706
- return [{ field: name, message: `${flag} must be ${describeType(types)}, got ${show(value)}` }];
8707
- }
8708
- if (schema2.enum && !schema2.enum.some((allowed) => allowed === value)) {
8709
- return [{
8710
- field: name,
8711
- message: `${flag} must be one of ${schema2.enum.join(", ")}, got ${show(value)}`
8712
- }];
8713
- }
8714
- return [];
8715
- }
8716
- var missing = (name) => ({
8717
- field: name,
8718
- message: `--${toFlag(name)} is required`
8719
- });
8720
- function check(row, bound) {
8721
- const problems = [];
8722
- const body = row.body_schema;
8723
- const bodyProps = Object.entries(body?.properties ?? {});
8724
- const known2 = /* @__PURE__ */ new Set([
8725
- ...row.path_params.map((p) => toFlag(p.name)),
8726
- ...row.query_params.map((p) => toFlag(p.name)),
8727
- ...bodyProps.map(([name]) => toFlag(name))
8728
- ]);
8729
- const candidates = [...known2];
8730
- for (const raw of bound.unknownFields) {
8731
- const flag = toFlag(raw);
8732
- const found = known2.has(flag) ? flag : suggest(flag, candidates);
8733
- const hint = found === raw ? void 0 : found;
8734
- const note = hint === flag ? " (flags are lower-case, with hyphens)" : "";
8735
- problems.push({
8736
- field: toSnake(raw),
8737
- message: `unknown flag --${raw}${hint ? `, did you mean --${hint}?${note}` : ""}`
8738
- });
8739
- }
8740
- for (const extra of bound.extraArguments) {
8741
- problems.push({ field: "arguments", message: `unexpected argument ${JSON.stringify(extra)}` });
8742
- }
8743
- if ((row.method === "GET" || row.method === "HEAD") && bound.body !== null) {
8744
- problems.push({
8745
- field: "input",
8746
- message: `--input sends a request body and \`deck ${row.command}\` is a ${row.method}, which carries none.`
8747
- });
8748
- }
8749
- const bodyNames = bodyProps.map(([name]) => name);
8750
- for (const key of bound.unknownInputKeys) {
8751
- const hint = suggest(key, bodyNames);
8752
- problems.push({
8753
- field: key,
8754
- message: `unknown field ${JSON.stringify(key)} in --input${hint && hint !== key ? `, did you mean ${JSON.stringify(hint)}?` : ""}`
8755
- });
8756
- }
8757
- for (const p of row.path_params) {
8758
- if (p.required && bound.path.includes(`{${p.name}}`)) problems.push(missing(p.name));
8759
- }
8760
- for (const p of row.query_params) {
8761
- const values = bound.query[p.name];
8762
- if (values === void 0 || values.length === 0) {
8763
- if (p.required) problems.push(missing(p.name));
8764
- continue;
8765
- }
8766
- problems.push(...queryProblems(p, values));
8767
- }
8768
- const given = bound.body ?? {};
8769
- for (const required2 of body?.required ?? []) {
8770
- if (given[required2] === void 0 || given[required2] === null) problems.push(missing(required2));
8771
- }
8772
- for (const [name, schema2] of bodyProps) {
8773
- const value = given[name];
8774
- if (value === void 0) continue;
8775
- if (value === null && (body?.required ?? []).includes(name)) continue;
8776
- problems.push(...checkValue(name, value, schema2));
8777
- }
8778
- return problems;
8779
- }
8780
- function queryProblems(param, values) {
8781
- const schema2 = param.schema.type === "array" && param.schema.items ? param.schema.items : param.schema;
8782
- return values.flatMap((value) => [
8783
- ...checkValue(param.name, value, schema2),
8784
- ...dateProblems(param, value)
8785
- ]);
8786
- }
8787
- function dateProblems(param, value) {
8788
- if (!isDateParam(param) || isAbsoluteTimestamp(value)) return [];
8789
- return [{
8790
- field: param.name,
8791
- message: `--${toFlag(param.name)} must be a timestamp (2026-10-29, 2026-10-29T14:00:00Z) or a relative value (-7d, -PT1H, today, yesterday), got ${JSON.stringify(value)}. Units are s, m, h, d, w, lower-case: -1M is not a month.`
8792
- }];
8793
- }
8794
-
8795
- // src/credentials.ts
8796
- import { join as join2 } from "node:path";
8797
- async function resolveCredential(sources) {
8798
- for (const s of sources) {
8799
- const c = await s.get();
8800
- if (c) return c;
8801
- }
8802
- throw new CliError("auth_required");
8803
- }
8804
- var usable = (v) => typeof v === "string" && v.trim() !== "";
8805
- function flagSource(parsed) {
8806
- return {
8807
- async get() {
8808
- const v = parsed.flags.get("api-key")?.at(-1);
8809
- return usable(v) ? { token: v.trim(), source: "--api-key" } : null;
8810
- }
8811
- };
8611
+ var usable = (v) => typeof v === "string" && v.trim() !== "";
8612
+ function flagSource(parsed) {
8613
+ return {
8614
+ async get() {
8615
+ const v = parsed.flags.get("api-key")?.at(-1);
8616
+ return usable(v) ? { token: v.trim(), source: "--api-key" } : null;
8617
+ }
8618
+ };
8812
8619
  }
8813
8620
  function envSource(env) {
8814
8621
  return {
@@ -8848,146 +8655,7 @@ function liveLoginJwt(s, now) {
8848
8655
  return { token: s.access_token.trim(), source: "deck login" };
8849
8656
  }
8850
8657
 
8851
- // src/http.ts
8852
- var DEFAULT_BASE_URL = "https://api.deck.co";
8853
- var apiBaseUrl = (env) => env["DECK_API_URL"]?.trim() || DEFAULT_BASE_URL;
8854
- var MAX_ATTEMPTS = 5;
8855
- var BASE_DELAY_MS = 250;
8856
- var MAX_BACKOFF_MS = 3e4;
8857
- var MAX_RETRY_AFTER_MS = 6e4;
8858
- var ATTEMPT_TIMEOUT_MS = 6e4;
8859
- var EXCERPT_CHARS = 200;
8860
- var isRetryableStatus = (status) => status === 429 || status >= 500;
8861
- var defaultSleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
8862
- var isWrite = (method) => !["GET", "HEAD"].includes(method.toUpperCase());
8863
- function retryAfterMs(h, now = Date.now()) {
8864
- const v = h.get("retry-after")?.trim();
8865
- if (!v) return null;
8866
- if (/^\d+(\.\d+)?$/.test(v)) return Number(v) * 1e3;
8867
- const at4 = Date.parse(v);
8868
- return Number.isNaN(at4) ? null : Math.max(0, at4 - now);
8869
- }
8870
- function networkError(host, e) {
8871
- const cause = e?.cause;
8872
- const name = e?.name;
8873
- const why = typeof cause?.code === "string" ? cause.code : name === "TimeoutError" ? "timed out" : e instanceof Error ? e.message : "unknown";
8874
- return new CliError("network_error", {
8875
- message: `Could not reach ${host}: ${why}. Run the same command again; a transport failure is usually transient. If it keeps failing, check DECK_API_URL and your network.`
8876
- });
8877
- }
8878
- function redactUrl(url) {
8879
- const u = new URL(url);
8880
- u.username = "";
8881
- u.password = "";
8882
- return u.toString();
8883
- }
8884
- function buildUrl(baseUrl, req) {
8885
- if (/\{[^}]+\}/.test(req.path)) {
8886
- throw new CliError("input_invalid", {
8887
- field: "path",
8888
- message: "The path still has an unfilled {placeholder}, so nothing was sent."
8889
- });
8890
- }
8891
- const pairs = [];
8892
- for (const [key, values] of Object.entries(req.query)) {
8893
- for (const v of values) pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(v)}`);
8894
- }
8895
- return baseUrl.replace(/\/+$/, "") + req.path + (pairs.length ? `?${pairs.join("&")}` : "");
8896
- }
8897
- async function readBody(res, host) {
8898
- let text3;
8899
- try {
8900
- text3 = await res.text();
8901
- } catch (e) {
8902
- throw networkError(host, e);
8903
- }
8904
- if (text3.trim() === "") return null;
8905
- try {
8906
- return JSON.parse(text3);
8907
- } catch {
8908
- if (res.ok) {
8909
- throw new CliError("unexpected_response", {
8910
- message: `${host} answered HTTP ${res.status} with a body that is not JSON. Check that DECK_API_URL points at the Deck API.`
8911
- });
8912
- }
8913
- const excerpt = text3.replace(/\s+/g, " ").trim().slice(0, EXCERPT_CHARS);
8914
- const body = {
8915
- request_id: res.headers.get("x-request-id") ?? "",
8916
- errors: [
8917
- {
8918
- type: "api",
8919
- code: "non_json_response",
8920
- field: null,
8921
- message: `HTTP ${res.status}: the response was not JSON. Body began: ${excerpt}`,
8922
- // The CLI builds this body, so nothing else will fill `retryable` in.
8923
- // An ingress HTML 502 is the shape this case was written for, and it
8924
- // is exactly the one a caller should try again.
8925
- retryable: isRetryableStatus(res.status)
8926
- }
8927
- ]
8928
- };
8929
- return body;
8930
- }
8931
- }
8932
- function prepare(req, opts) {
8933
- let parsed;
8934
- try {
8935
- parsed = new URL(opts.baseUrl);
8936
- } catch {
8937
- throw new CliError("input_invalid", {
8938
- field: "DECK_API_URL",
8939
- message: `DECK_API_URL is not an absolute URL (include https://). Run \`export DECK_API_URL=https://api.deck.co\`.`
8940
- });
8941
- }
8942
- const url = buildUrl(opts.baseUrl, req);
8943
- const headers = {
8944
- ...opts.credential === null ? {} : { authorization: `Bearer ${opts.credential.token}` },
8945
- "user-agent": `deck-cli/${opts.version}`,
8946
- accept: "application/json"
8947
- };
8948
- if (opts.idempotencyKey) headers["idempotency-key"] = opts.idempotencyKey;
8949
- if (req.body !== null) headers["content-type"] = "application/json";
8950
- return {
8951
- url,
8952
- host: parsed.host,
8953
- headers,
8954
- // The one redaction site. `--dry-run` prints this, never its own copy.
8955
- request: {
8956
- method: req.method,
8957
- url: redactUrl(url),
8958
- headers: opts.credential === null ? { ...headers } : { ...headers, authorization: "Bearer [redacted]" }
8959
- }
8960
- };
8961
- }
8962
- function requestView(req, opts) {
8963
- return prepare(req, opts).request;
8964
- }
8965
- async function send(req, opts) {
8966
- const doFetch = opts.fetch ?? fetch;
8967
- const sleep = opts.sleep ?? defaultSleep;
8968
- const { url, host, headers, request: request2 } = prepare(req, opts);
8969
- const hasBody = req.body !== null;
8970
- const body = hasBody ? { body: JSON.stringify(req.body) } : {};
8971
- const attempts = opts.retry ? MAX_ATTEMPTS : 1;
8972
- for (let attempt = 1; ; attempt++) {
8973
- let res;
8974
- try {
8975
- res = await doFetch(url, { method: req.method, headers, ...body, signal: AbortSignal.timeout(ATTEMPT_TIMEOUT_MS) });
8976
- } catch (e) {
8977
- throw networkError(host, e);
8978
- }
8979
- const retryable = res.status === 429 || res.status >= 500 && (!isWrite(req.method) || !!opts.idempotencyKey);
8980
- const wait = retryAfterMs(res.headers);
8981
- if (!retryable || attempt >= attempts || wait !== null && wait > MAX_RETRY_AFTER_MS) {
8982
- return { status: res.status, body: await readBody(res, host), headers: res.headers, request: request2 };
8983
- }
8984
- await res.body?.cancel();
8985
- await sleep(wait ?? Math.min(BASE_DELAY_MS * 2 ** (attempt - 1), MAX_BACKOFF_MS));
8986
- }
8987
- }
8988
-
8989
8658
  // src/state/config.ts
8990
- import { join as join3 } from "node:path";
8991
8659
  function configPath(env, platform, home) {
8992
8660
  return join3(configDir(env, platform, home), "deck", "config.json");
8993
8661
  }
@@ -13405,7 +13073,7 @@ var asOption = (value) => {
13405
13073
  return { organization_id: row["organization_id"], name: row["name"], role: row["role"] };
13406
13074
  };
13407
13075
  async function exchange(env, clerkToken2, clerkOrgId) {
13408
- const request2 = {
13076
+ const request3 = {
13409
13077
  method: "POST",
13410
13078
  path: "/v2/bot/token",
13411
13079
  query: {},
@@ -13416,7 +13084,7 @@ async function exchange(env, clerkToken2, clerkOrgId) {
13416
13084
  };
13417
13085
  let body;
13418
13086
  try {
13419
- body = await env.call(request2, { token: clerkToken2, source: CLERK_SOURCE });
13087
+ body = await env.call(request3, { token: clerkToken2, source: CLERK_SOURCE });
13420
13088
  } catch (e) {
13421
13089
  if (statusOf2(e) === 403) return { status: "no_membership" };
13422
13090
  if (statusOf2(e) === 401) {
@@ -13727,22 +13395,567 @@ var logoutCommand = {
13727
13395
  `);
13728
13396
  return 0;
13729
13397
  }
13730
- await store.clear();
13731
- const path = configPath(ctx.env, ctx.platform, ctx.homedir);
13732
- const before = await readConfig(path, ctx.io);
13733
- if (before.user_id !== void 0) await writeConfig(path, { user_id: void 0 }, ctx.io);
13734
- const remaining = before.api_key !== void 0;
13735
- ctx.stdout.write(
13736
- `${JSON.stringify({
13737
- logged_out: true,
13738
- stored_in: store.backing,
13739
- ...remaining ? { note: `An API key in ${path} is still in place, and commands will use it.` } : {}
13740
- })}
13741
- `
13742
- );
13743
- return 0;
13398
+ await store.clear();
13399
+ const path = configPath(ctx.env, ctx.platform, ctx.homedir);
13400
+ const before = await readConfig(path, ctx.io);
13401
+ if (before.user_id !== void 0) await writeConfig(path, { user_id: void 0 }, ctx.io);
13402
+ const remaining = before.api_key !== void 0;
13403
+ ctx.stdout.write(
13404
+ `${JSON.stringify({
13405
+ logged_out: true,
13406
+ stored_in: store.backing,
13407
+ ...remaining ? { note: `An API key in ${path} is still in place, and commands will use it.` } : {}
13408
+ })}
13409
+ `
13410
+ );
13411
+ return 0;
13412
+ }
13413
+ };
13414
+
13415
+ // src/native/credential-link.ts
13416
+ var POLL_INTERVAL_MS = 2e3;
13417
+ var DEFAULT_TIMEOUT_SECONDS = 600;
13418
+ var request = (method, path, query = {}) => ({
13419
+ method,
13420
+ path,
13421
+ query,
13422
+ body: method === "POST" ? {} : null,
13423
+ unknownFields: [],
13424
+ extraArguments: [],
13425
+ unknownInputKeys: []
13426
+ });
13427
+ function port(call, credential, authComponentUrl2) {
13428
+ const attempt = async (req) => {
13429
+ try {
13430
+ return { ok: true, status: 200, body: await call(req, credential) };
13431
+ } catch (e) {
13432
+ const status = typeof e.status === "number" ? e.status : 0;
13433
+ const body = e.body ?? { message: String(e) };
13434
+ return { ok: false, status, body };
13435
+ }
13436
+ };
13437
+ return {
13438
+ authComponentUrl: authComponentUrl2,
13439
+ mintToken: () => attempt(request("POST", "/v2/token")),
13440
+ findByExternalId: (externalId) => attempt(request("GET", "/v2/credentials", { external_id: [externalId] }))
13441
+ };
13442
+ }
13443
+ var answerOf = (outcome) => typeof outcome.body === "object" && outcome.body !== null ? outcome.body : {};
13444
+ async function credentialLinkFlow(ctx, print, call, credential, authComponentUrl2, options) {
13445
+ const tool = credentialLinkTool(port(call, credential, authComponentUrl2));
13446
+ const mint = await tool.call(options.sourceId === void 0 ? {} : { source_id: options.sourceId });
13447
+ const created = answerOf(mint);
13448
+ if (!mint.ok || created.url === void 0) {
13449
+ throw new CliError("unexpected_response", {
13450
+ message: `The link could not be created: ${JSON.stringify(created)}`,
13451
+ next_steps: ["deck credentials create --link --help"],
13452
+ command: "deck credentials create"
13453
+ });
13454
+ }
13455
+ await print(created);
13456
+ if (options.openBrowser) await openVerificationPage(ctx, created.url);
13457
+ const externalId = created.external_id;
13458
+ if (externalId === void 0) return 0;
13459
+ const clock = () => ctx.clock?.now() ?? Date.now();
13460
+ const sleep = (ms) => ctx.clock ? ctx.clock.sleep(ms) : new Promise((resolve3) => setTimeout(resolve3, ms));
13461
+ const deadline = clock() + (options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1e3;
13462
+ for (; ; ) {
13463
+ await sleep(POLL_INTERVAL_MS);
13464
+ const lookup = await tool.call({ external_id: externalId });
13465
+ if (!lookup.ok) {
13466
+ throw new CliError("unexpected_response", {
13467
+ message: `The link is good, but checking whether it was used failed: ${JSON.stringify(lookup.body)}. Run \`deck credentials list --external-id ${externalId}\` to see whether the credential exists.`,
13468
+ next_steps: [`deck credentials list --external-id ${externalId}`],
13469
+ command: "deck credentials create"
13470
+ });
13471
+ }
13472
+ const found = answerOf(lookup);
13473
+ if (found.credential !== void 0 && found.credential !== null) {
13474
+ await print(found.credential);
13475
+ return 0;
13476
+ }
13477
+ if (clock() >= deadline) {
13478
+ await print({
13479
+ waited: true,
13480
+ credential: null,
13481
+ external_id: externalId,
13482
+ message: "The wait ended before the credential was entered. The link is still good until it expires."
13483
+ });
13484
+ return 1;
13485
+ }
13486
+ }
13487
+ }
13488
+
13489
+ // src/aliases.ts
13490
+ var ALIAS_TABLE = [
13491
+ { canonical: "list", aliases: ["ls"] },
13492
+ { canonical: "retrieve", aliases: ["get", "show", "view", "inspect"] },
13493
+ { canonical: "create", aliases: ["add", "new"] },
13494
+ { canonical: "update", aliases: ["edit", "patch", "set"] },
13495
+ { canonical: "delete", aliases: ["rm", "remove", "del"] },
13496
+ { canonical: "run", aliases: ["execute", "start"], under: ["tasks", "workflows"] },
13497
+ { canonical: "rerun", aliases: ["retry"] },
13498
+ { canonical: "cancel", aliases: ["stop", "abort"] },
13499
+ { canonical: "interaction", aliases: ["interact", "respond", "answer"] },
13500
+ { canonical: "screenshots", aliases: ["shots", "screens"] },
13501
+ { canonical: "browser-logs", aliases: ["logs"] },
13502
+ { canonical: "browser-access", aliases: ["cdp", "attach"] },
13503
+ // `follow` is in two rows. It never collides: `watch` lives on runs and `tail`
13504
+ // on events, and a word only resolves to a canonical command that exists at
13505
+ // that spot, so `task-runs follow` is watch and `events follow` is tail.
13506
+ { canonical: "watch", aliases: ["wait", "follow"] },
13507
+ { canonical: "tail", aliases: ["follow", "stream"] },
13508
+ { canonical: "reset", aliases: ["clear"] },
13509
+ { canonical: "test", aliases: ["ping"], under: ["event-destinations"] },
13510
+ { canonical: "deliveries", aliases: ["attempts"] },
13511
+ { canonical: "agents", aliases: ["agent"] },
13512
+ { canonical: "sources", aliases: ["source", "src"] },
13513
+ { canonical: "credentials", aliases: ["credential", "creds", "cred"] },
13514
+ { canonical: "tasks", aliases: ["task"] },
13515
+ { canonical: "task-runs", aliases: ["task-run", "runs", "trun"] },
13516
+ { canonical: "routines", aliases: ["routine", "rtn"] },
13517
+ { canonical: "routine-builds", aliases: ["routine-build", "builds", "rbld"] },
13518
+ { canonical: "workflows", aliases: ["workflow", "wf"] },
13519
+ { canonical: "workflow-runs", aliases: ["workflow-run", "wruns", "wrun"] },
13520
+ { canonical: "triggers", aliases: ["trigger", "trg"] },
13521
+ { canonical: "sessions", aliases: ["session", "sess"] },
13522
+ { canonical: "events", aliases: ["event", "evt"] },
13523
+ {
13524
+ canonical: "event-destinations",
13525
+ aliases: ["event-destination", "destinations", "destination", "dest", "webhooks", "evtd"]
13526
+ },
13527
+ { canonical: "storage", aliases: ["stor", "files"] },
13528
+ { canonical: "keys", aliases: ["key", "api-keys", "api-key", "tokens"] },
13529
+ { canonical: "orgs", aliases: ["org", "organizations", "organization"] },
13530
+ { canonical: "login", aliases: ["signin", "sign-in", "auth login"] },
13531
+ { canonical: "logout", aliases: ["signout", "sign-out", "auth logout"] },
13532
+ { canonical: "whoami", aliases: ["me", "status", "auth status"] },
13533
+ { canonical: "upgrade", aliases: ["update", "self-update"] },
13534
+ { canonical: "agent setup", aliases: ["setup"] },
13535
+ { canonical: "agent-guide", aliases: ["guide"] },
13536
+ { canonical: "docs search", aliases: ["search"] },
13537
+ { canonical: "feedback", aliases: ["bug"] }
13538
+ ];
13539
+ var ALIAS_INDEX = (() => {
13540
+ const index = /* @__PURE__ */ new Map();
13541
+ for (const { canonical, aliases, under } of ALIAS_TABLE) {
13542
+ for (const alias of aliases) {
13543
+ const targets = index.get(alias) ?? [];
13544
+ targets.push({ canonical: canonical.split(" "), ...under === void 0 ? {} : { under } });
13545
+ index.set(alias, targets);
13546
+ }
13547
+ }
13548
+ return index;
13549
+ })();
13550
+ var ALIAS_WORDS = 2;
13551
+ var COMMAND_WORD = /^[a-z][a-z0-9-]*$/;
13552
+ function singularOf(word) {
13553
+ if (word.endsWith("ies")) return `${word.slice(0, -3)}y`;
13554
+ if (word.endsWith("s") && !word.endsWith("ss")) return word.slice(0, -1);
13555
+ return void 0;
13556
+ }
13557
+ var SHAPES = /* @__PURE__ */ new WeakMap();
13558
+ function shapeOf(registry2) {
13559
+ const cached2 = SHAPES.get(registry2);
13560
+ if (cached2) return cached2;
13561
+ const prefixes = /* @__PURE__ */ new Set();
13562
+ const children = /* @__PURE__ */ new Map();
13563
+ for (const command of registry2.keys()) {
13564
+ const words = command.split(" ");
13565
+ words.forEach((word, i) => {
13566
+ const parent = words.slice(0, i).join(" ");
13567
+ prefixes.add(words.slice(0, i + 1).join(" "));
13568
+ const kids = children.get(parent) ?? /* @__PURE__ */ new Set();
13569
+ kids.add(word);
13570
+ children.set(parent, kids);
13571
+ });
13572
+ }
13573
+ const shape = { prefixes, children: new Map([...children].map(([k, v]) => [k, [...v]])) };
13574
+ SHAPES.set(registry2, shape);
13575
+ return shape;
13576
+ }
13577
+ function resolveWords(registry2, argv) {
13578
+ const { prefixes, children } = shapeOf(registry2);
13579
+ const walk = (prefix, at4) => {
13580
+ const options = [];
13581
+ const word = argv[at4];
13582
+ if (word !== void 0 && COMMAND_WORD.test(word)) {
13583
+ const key = prefix.join(" ");
13584
+ const join13 = (words) => [...prefix, ...words].join(" ");
13585
+ if (prefixes.has(join13([word]))) options.push({ words: [word], take: 1, alias: false });
13586
+ for (let len = ALIAS_WORDS; len >= 1; len--) {
13587
+ const typed = argv.slice(at4, at4 + len);
13588
+ if (typed.length < len || !typed.every((w) => COMMAND_WORD.test(w))) continue;
13589
+ for (const target of ALIAS_INDEX.get(typed.join(" ")) ?? []) {
13590
+ if (target.under !== void 0 && !target.under.includes(key)) continue;
13591
+ if (prefixes.has(join13(target.canonical))) options.push({ words: target.canonical, take: len, alias: true });
13592
+ }
13593
+ }
13594
+ for (const child of children.get(key) ?? []) {
13595
+ if (singularOf(child) === word) options.push({ words: [child], take: 1, alias: true });
13596
+ }
13597
+ }
13598
+ for (const option of options) {
13599
+ const hit = walk([...prefix, ...option.words], at4 + option.take);
13600
+ if (hit) return { ...hit, aliasUsed: hit.aliasUsed || option.alias };
13601
+ }
13602
+ return prefix.length > 0 && registry2.has(prefix.join(" ")) ? { words: prefix, consumed: at4, aliasUsed: false } : void 0;
13603
+ };
13604
+ return walk([], 0);
13605
+ }
13606
+ function normalizeFlagAliases(argv) {
13607
+ let aliasUsed = false;
13608
+ const out = [];
13609
+ let tokens = argv;
13610
+ if (tokens[0] === "--version" || tokens[0] === "-v") {
13611
+ out.push("version");
13612
+ tokens = tokens.slice(1);
13613
+ aliasUsed = true;
13614
+ }
13615
+ let endOfFlags = false;
13616
+ for (let i = 0; i < tokens.length; i++) {
13617
+ const token = tokens[i];
13618
+ if (endOfFlags || !token.startsWith("--")) {
13619
+ out.push(token);
13620
+ continue;
13621
+ }
13622
+ if (token === "--") {
13623
+ endOfFlags = true;
13624
+ out.push(token);
13625
+ } else if (token === "--key" || token.startsWith("--key=")) {
13626
+ out.push(`--api-key${token.slice("--key".length)}`);
13627
+ aliasUsed = true;
13628
+ } else if (token === "--output=json") {
13629
+ out.push("--json");
13630
+ aliasUsed = true;
13631
+ } else if (token === "--output" && tokens[i + 1] === "json") {
13632
+ out.push("--json");
13633
+ i++;
13634
+ aliasUsed = true;
13635
+ } else {
13636
+ out.push(token);
13637
+ }
13638
+ }
13639
+ return { argv: out, aliasUsed };
13640
+ }
13641
+ function shortOutputAlias(parsed) {
13642
+ const positionals = [];
13643
+ let used = false;
13644
+ for (let i = 0; i < parsed.positionals.length; i++) {
13645
+ if (parsed.positionals[i] === "-o" && parsed.positionals[i + 1] === "json") {
13646
+ used = true;
13647
+ i++;
13648
+ } else {
13649
+ positionals.push(parsed.positionals[i]);
13650
+ }
13651
+ }
13652
+ if (!used) return { parsed, aliasUsed: false };
13653
+ const flags = new Map(parsed.flags);
13654
+ flags.set("json", [...flags.get("json") ?? [], "true"]);
13655
+ return { parsed: { ...parsed, flags, positionals }, aliasUsed: true };
13656
+ }
13657
+
13658
+ // src/dates.ts
13659
+ var isDateParam = (param) => param.schema.format === "date-time" || /_(after|before)$/.test(param.name);
13660
+ var ABSOLUTE = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
13661
+ var isAbsoluteTimestamp = (value) => ABSOLUTE.test(value) && !Number.isNaN(Date.parse(value));
13662
+ var SECOND_MS = 1e3;
13663
+ var MINUTE_MS = 60 * SECOND_MS;
13664
+ var HOUR_MS = 60 * MINUTE_MS;
13665
+ var DAY_MS = 24 * HOUR_MS;
13666
+ var WEEK_MS = 7 * DAY_MS;
13667
+ var UNIT_MS = {
13668
+ s: SECOND_MS,
13669
+ m: MINUTE_MS,
13670
+ h: HOUR_MS,
13671
+ d: DAY_MS,
13672
+ w: WEEK_MS
13673
+ };
13674
+ var SHORT_FORM = /^-(\d+)([smhdw])$/;
13675
+ var ISO_FORM = /^-P(?=\d|T\d)(?:(\d+)W)?(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
13676
+ var iso = (ms) => {
13677
+ const d = new Date(ms);
13678
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
13679
+ };
13680
+ function toAbsolute(value, now) {
13681
+ const nowMs = now.getTime();
13682
+ if (value === "today" || value === "yesterday") {
13683
+ const midnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
13684
+ const dayOffset = value === "yesterday" ? -DAY_MS : 0;
13685
+ return iso(midnight + dayOffset);
13686
+ }
13687
+ const short = SHORT_FORM.exec(value);
13688
+ if (short) {
13689
+ const amount = Number(short[1]);
13690
+ return iso(nowMs - amount * UNIT_MS[short[2]]);
13691
+ }
13692
+ const match = ISO_FORM.exec(value);
13693
+ if (match) {
13694
+ const [, weeks, days, hours, minutes, seconds] = match;
13695
+ const totalMs = Number(weeks ?? 0) * WEEK_MS + Number(days ?? 0) * DAY_MS + Number(hours ?? 0) * HOUR_MS + Number(minutes ?? 0) * MINUTE_MS + Number(seconds ?? 0) * SECOND_MS;
13696
+ return iso(nowMs - totalMs);
13697
+ }
13698
+ return null;
13699
+ }
13700
+
13701
+ // src/flags.ts
13702
+ var toFlag = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
13703
+ var toSnake = (flag) => toFlag(flag).replace(/-/g, "_");
13704
+ var typedFlagKey = (typed) => typed.replace(/_/g, "-");
13705
+ var typesOf = (schema2) => schema2.type === void 0 ? [] : Array.isArray(schema2.type) ? schema2.type : [schema2.type];
13706
+
13707
+ // src/bind.ts
13708
+ var reason = (e) => e instanceof Error ? e.message : String(e);
13709
+ function readInput(raw, io) {
13710
+ let text3;
13711
+ if (raw === "-") {
13712
+ if (io.stdinIsTty) {
13713
+ throw new CliError("input_invalid", { field: "input", message: "--input - reads stdin, but stdin is a terminal; pipe JSON in or use --input @file" });
13714
+ }
13715
+ text3 = io.readStdin();
13716
+ } else if (raw.startsWith("@")) {
13717
+ try {
13718
+ text3 = io.readFile(raw.slice(1));
13719
+ } catch (e) {
13720
+ throw new CliError("input_invalid", { field: "input", message: `--input could not read ${raw.slice(1)}: ${reason(e)}` });
13721
+ }
13722
+ } else {
13723
+ text3 = raw;
13724
+ }
13725
+ let parsed;
13726
+ try {
13727
+ parsed = JSON.parse(text3);
13728
+ } catch (e) {
13729
+ const at4 = /position (\d+)/.exec(reason(e))?.[1];
13730
+ throw new CliError("input_invalid", {
13731
+ field: "input",
13732
+ message: `--input is not valid JSON${at4 === void 0 ? "" : ` (at character ${at4})`}. The parser's own message is not shown, because it quotes the input.`
13733
+ });
13734
+ }
13735
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
13736
+ throw new CliError("input_invalid", { field: "input", message: "--input must be a JSON object" });
13737
+ }
13738
+ return parsed;
13739
+ }
13740
+ var isFreeForm = (schema2) => typesOf(schema2).length === 0 && !schema2.enum && !schema2.items;
13741
+ function coerceBodyValue(name, raw, schema2) {
13742
+ const types = typesOf(schema2);
13743
+ if (isFreeForm(schema2)) {
13744
+ try {
13745
+ return JSON.parse(raw);
13746
+ } catch {
13747
+ return raw;
13748
+ }
13749
+ }
13750
+ if (types.includes("object") || types.includes("array")) {
13751
+ if (raw === "null" && types.includes("null")) return null;
13752
+ try {
13753
+ return JSON.parse(raw);
13754
+ } catch {
13755
+ return raw;
13756
+ }
13757
+ }
13758
+ if (types.includes("boolean") && (raw === "true" || raw === "false")) return raw === "true";
13759
+ if (types.includes("integer") && /^-?\d+$/.test(raw)) return Number(raw);
13760
+ if (types.includes("number") && /^-?\d+(\.\d+)?$/.test(raw)) return Number(raw);
13761
+ return raw;
13762
+ }
13763
+ var fillsPath2 = (value) => value.trim() !== "";
13764
+ function bindQuery(param, values, now) {
13765
+ const items = param.schema.type === "array" ? values.flatMap((v) => v.split(",")) : values;
13766
+ return isDateParam(param) ? items.map((v) => toAbsolute(v, now) ?? v) : items;
13767
+ }
13768
+ function bind(row, parsed, io, now) {
13769
+ const unknownFields = [];
13770
+ const query = {};
13771
+ const pathValues = /* @__PURE__ */ new Map();
13772
+ const flagBody = {};
13773
+ const bodyProps = row.body_schema?.properties ?? {};
13774
+ const byFlag = (items) => new Map(items.map(([name, v]) => [toFlag(name), [name, v]]));
13775
+ const pathByFlag = byFlag(row.path_params.map((p) => [p.name, p]));
13776
+ const queryByFlag = byFlag(row.query_params.map((p) => [p.name, p]));
13777
+ const bodyByFlag = byFlag(Object.entries(bodyProps));
13778
+ for (const [typed, values] of parsed.flags) {
13779
+ if (typed === "input" || GLOBAL_BOOLEAN_FLAGS.has(typed)) continue;
13780
+ const key = typedFlagKey(typed);
13781
+ const pathHit = pathByFlag.get(key);
13782
+ const queryHit = queryByFlag.get(key);
13783
+ const bodyHit = bodyByFlag.get(key);
13784
+ if (pathHit) {
13785
+ const value = values[values.length - 1];
13786
+ if (fillsPath2(value)) pathValues.set(pathHit[0], value);
13787
+ } else if (queryHit) query[queryHit[0]] = bindQuery(queryHit[1], values, now);
13788
+ else if (bodyHit) flagBody[bodyHit[0]] = coerceBodyValue(bodyHit[0], values[values.length - 1], bodyHit[1]);
13789
+ else unknownFields.push(typed);
13790
+ }
13791
+ const open3 = row.path_params.filter((p) => !pathValues.has(p.name));
13792
+ parsed.positionals.slice(0, open3.length).forEach((v, i) => {
13793
+ if (fillsPath2(v)) pathValues.set(open3[i].name, v);
13794
+ });
13795
+ const extraArguments = parsed.positionals.slice(open3.length);
13796
+ let path = row.path;
13797
+ for (const [name, value] of pathValues) path = path.replace(`{${name}}`, encodeURIComponent(value));
13798
+ const inputFlag = parsed.flags.get("input");
13799
+ const input = inputFlag ? readInput(inputFlag[inputFlag.length - 1], io) : void 0;
13800
+ const declared = row.body_schema?.properties;
13801
+ const unknownInputKeys = input !== void 0 && declared ? Object.keys(input).filter((k) => !(k in declared)) : [];
13802
+ const body = input !== void 0 || row.body_schema !== null || Object.keys(flagBody).length > 0 ? { ...input, ...flagBody } : null;
13803
+ return { method: row.method, path, query, body, unknownFields, extraArguments, unknownInputKeys };
13804
+ }
13805
+
13806
+ // src/suggest.ts
13807
+ function distance(a, b) {
13808
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
13809
+ for (let i = 1; i <= a.length; i++) {
13810
+ const cur = [i];
13811
+ for (let j = 1; j <= b.length; j++) {
13812
+ cur[j] = Math.min(
13813
+ prev[j] + 1,
13814
+ cur[j - 1] + 1,
13815
+ prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
13816
+ );
13817
+ }
13818
+ prev = cur;
13819
+ }
13820
+ return prev[b.length];
13821
+ }
13822
+ function suggest(input, candidates) {
13823
+ const limit = Math.max(1, Math.floor(input.length / 3));
13824
+ let best;
13825
+ let bestDistance = Infinity;
13826
+ for (const candidate of candidates) {
13827
+ const d = distance(input, candidate);
13828
+ if (d <= limit && d < bestDistance) {
13829
+ best = candidate;
13830
+ bestDistance = d;
13831
+ }
13832
+ }
13833
+ return best;
13834
+ }
13835
+
13836
+ // src/check.ts
13837
+ var INTEGER = /^-?\d+$/;
13838
+ var NUMBER = /^-?\d+(\.\d+)?$/;
13839
+ function typeFits(value, types, pattern) {
13840
+ if (types.length === 0) return true;
13841
+ if (value === null) return types.includes("null");
13842
+ if (typeof value === "string") {
13843
+ if (pattern !== void 0 && !new RegExp(pattern).test(value)) return false;
13844
+ if (types.includes("string")) return true;
13845
+ if (types.includes("integer") && INTEGER.test(value)) return true;
13846
+ if (types.includes("number") && NUMBER.test(value)) return true;
13847
+ return types.includes("boolean") && (value === "true" || value === "false");
13848
+ }
13849
+ if (typeof value === "number") {
13850
+ return types.includes("number") || types.includes("integer") && Number.isInteger(value);
13851
+ }
13852
+ if (typeof value === "boolean") return types.includes("boolean");
13853
+ if (Array.isArray(value)) return types.includes("array");
13854
+ return types.includes("object");
13855
+ }
13856
+ function describeType(types) {
13857
+ const real = types.filter((t) => t !== "null");
13858
+ if (real.includes("integer")) return "an integer";
13859
+ if (real.includes("number")) return "a number";
13860
+ if (real.includes("boolean")) return "true or false";
13861
+ return real.length === 1 ? `${/^[aeiou]/.test(real[0]) ? "an" : "a"} ${real[0]}` : `one of ${real.join(", ")}`;
13862
+ }
13863
+ var show = (value) => typeof value === "string" ? JSON.stringify(value) : String(JSON.stringify(value));
13864
+ function checkValue(name, value, schema2) {
13865
+ const flag = `--${toFlag(name)}`;
13866
+ const types = typesOf(schema2);
13867
+ if (Array.isArray(value) && types.includes("array") && schema2.items) {
13868
+ return value.flatMap((item) => checkValue(name, item, schema2.items));
13869
+ }
13870
+ if (!typeFits(value, types, schema2.pattern)) {
13871
+ return [{ field: name, message: `${flag} must be ${describeType(types)}, got ${show(value)}` }];
13872
+ }
13873
+ if (schema2.enum && !schema2.enum.some((allowed) => allowed === value)) {
13874
+ return [{
13875
+ field: name,
13876
+ message: `${flag} must be one of ${schema2.enum.join(", ")}, got ${show(value)}`
13877
+ }];
13878
+ }
13879
+ return [];
13880
+ }
13881
+ var missing = (name) => ({
13882
+ field: name,
13883
+ message: `--${toFlag(name)} is required`
13884
+ });
13885
+ function check(row, bound) {
13886
+ const problems = [];
13887
+ const body = row.body_schema;
13888
+ const bodyProps = Object.entries(body?.properties ?? {});
13889
+ const known2 = /* @__PURE__ */ new Set([
13890
+ ...row.path_params.map((p) => toFlag(p.name)),
13891
+ ...row.query_params.map((p) => toFlag(p.name)),
13892
+ ...bodyProps.map(([name]) => toFlag(name))
13893
+ ]);
13894
+ const candidates = [...known2];
13895
+ for (const raw of bound.unknownFields) {
13896
+ const flag = toFlag(raw);
13897
+ const found = known2.has(flag) ? flag : suggest(flag, candidates);
13898
+ const hint = found === raw ? void 0 : found;
13899
+ const note = hint === flag ? " (flags are lower-case, with hyphens)" : "";
13900
+ problems.push({
13901
+ field: toSnake(raw),
13902
+ message: `unknown flag --${raw}${hint ? `, did you mean --${hint}?${note}` : ""}`
13903
+ });
13904
+ }
13905
+ for (const extra of bound.extraArguments) {
13906
+ problems.push({ field: "arguments", message: `unexpected argument ${JSON.stringify(extra)}` });
13907
+ }
13908
+ if ((row.method === "GET" || row.method === "HEAD") && bound.body !== null) {
13909
+ problems.push({
13910
+ field: "input",
13911
+ message: `--input sends a request body and \`deck ${row.command}\` is a ${row.method}, which carries none.`
13912
+ });
13913
+ }
13914
+ const bodyNames = bodyProps.map(([name]) => name);
13915
+ for (const key of bound.unknownInputKeys) {
13916
+ const hint = suggest(key, bodyNames);
13917
+ problems.push({
13918
+ field: key,
13919
+ message: `unknown field ${JSON.stringify(key)} in --input${hint && hint !== key ? `, did you mean ${JSON.stringify(hint)}?` : ""}`
13920
+ });
13921
+ }
13922
+ for (const p of row.path_params) {
13923
+ if (p.required && bound.path.includes(`{${p.name}}`)) problems.push(missing(p.name));
13924
+ }
13925
+ for (const p of row.query_params) {
13926
+ const values = bound.query[p.name];
13927
+ if (values === void 0 || values.length === 0) {
13928
+ if (p.required) problems.push(missing(p.name));
13929
+ continue;
13930
+ }
13931
+ problems.push(...queryProblems(p, values));
13744
13932
  }
13745
- };
13933
+ const given = bound.body ?? {};
13934
+ for (const required2 of body?.required ?? []) {
13935
+ if (given[required2] === void 0 || given[required2] === null) problems.push(missing(required2));
13936
+ }
13937
+ for (const [name, schema2] of bodyProps) {
13938
+ const value = given[name];
13939
+ if (value === void 0) continue;
13940
+ if (value === null && (body?.required ?? []).includes(name)) continue;
13941
+ problems.push(...checkValue(name, value, schema2));
13942
+ }
13943
+ return problems;
13944
+ }
13945
+ function queryProblems(param, values) {
13946
+ const schema2 = param.schema.type === "array" && param.schema.items ? param.schema.items : param.schema;
13947
+ return values.flatMap((value) => [
13948
+ ...checkValue(param.name, value, schema2),
13949
+ ...dateProblems(param, value)
13950
+ ]);
13951
+ }
13952
+ function dateProblems(param, value) {
13953
+ if (!isDateParam(param) || isAbsoluteTimestamp(value)) return [];
13954
+ return [{
13955
+ field: param.name,
13956
+ message: `--${toFlag(param.name)} must be a timestamp (2026-10-29, 2026-10-29T14:00:00Z) or a relative value (-7d, -PT1H, today, yesterday), got ${JSON.stringify(value)}. Units are s, m, h, d, w, lower-case: -1M is not a month.`
13957
+ }];
13958
+ }
13746
13959
 
13747
13960
  // src/credential-sources.ts
13748
13961
  function credentialSources(ctx, parsed) {
@@ -13894,6 +14107,22 @@ function flagsOf(row) {
13894
14107
  description: `Seconds --wait gives up after (default ${row.follow.default_timeout_seconds}).`
13895
14108
  }
13896
14109
  ] : [];
14110
+ const linkFlags = row.operationId === "createCredential" ? [
14111
+ {
14112
+ name: "--link",
14113
+ type: "boolean",
14114
+ required: false,
14115
+ in: "global",
14116
+ description: "Print a link for a PERSON to enter the credentials on Deck's hosted page, instead of sending them from here. No secret passes through this machine. Prints the link, then waits for the credential and prints it."
14117
+ },
14118
+ {
14119
+ name: "--timeout",
14120
+ type: "number",
14121
+ required: false,
14122
+ in: "global",
14123
+ description: "Seconds --link waits for the person to finish (default 600). Exit 1 if it passes; the link stays good."
14124
+ }
14125
+ ] : [];
13897
14126
  const artifactFlags = row.artifacts ? [
13898
14127
  {
13899
14128
  name: "--download",
@@ -13905,6 +14134,7 @@ function flagsOf(row) {
13905
14134
  ] : [];
13906
14135
  const globals = [
13907
14136
  ...followFlags,
14137
+ ...linkFlags,
13908
14138
  ...artifactFlags,
13909
14139
  ...[...GLOBAL_BOOLEAN_FLAGS].filter((g) => g !== "all" || paginated).map((g) => ({
13910
14140
  name: `--${g}`,
@@ -14204,7 +14434,7 @@ function idOf(started, path) {
14204
14434
  }
14205
14435
  async function followAndPrint(ctx, f) {
14206
14436
  let failure3;
14207
- const port = {
14437
+ const port2 = {
14208
14438
  poll: async (args) => {
14209
14439
  try {
14210
14440
  return { ok: true, status: 200, body: await f.call(pollRequest(f.pollRow, args)) };
@@ -14215,7 +14445,7 @@ async function followAndPrint(ctx, f) {
14215
14445
  }
14216
14446
  };
14217
14447
  const seconds = f.timeoutSeconds ?? f.descriptor.default_timeout_seconds;
14218
- const result = await follow(f.descriptor, f.started, port, {
14448
+ const result = await follow(f.descriptor, f.started, port2, {
14219
14449
  timeoutMs: seconds * 1e3,
14220
14450
  ...ctx.clock ? { now: ctx.clock.now, sleep: ctx.clock.sleep } : {}
14221
14451
  });
@@ -22323,8 +22553,8 @@ var Protocol = class {
22323
22553
  this._taskStore = _options?.taskStore;
22324
22554
  this._taskMessageQueue = _options?.taskMessageQueue;
22325
22555
  if (this._taskStore) {
22326
- this.setRequestHandler(GetTaskRequestSchema, async (request2, extra) => {
22327
- const task = await this._taskStore.getTask(request2.params.taskId, extra.sessionId);
22556
+ this.setRequestHandler(GetTaskRequestSchema, async (request3, extra) => {
22557
+ const task = await this._taskStore.getTask(request3.params.taskId, extra.sessionId);
22328
22558
  if (!task) {
22329
22559
  throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
22330
22560
  }
@@ -22332,9 +22562,9 @@ var Protocol = class {
22332
22562
  ...task
22333
22563
  };
22334
22564
  });
22335
- this.setRequestHandler(GetTaskPayloadRequestSchema, async (request2, extra) => {
22565
+ this.setRequestHandler(GetTaskPayloadRequestSchema, async (request3, extra) => {
22336
22566
  const handleTaskResult = async () => {
22337
- const taskId = request2.params.taskId;
22567
+ const taskId = request3.params.taskId;
22338
22568
  if (!await this._taskStore.getTask(taskId, extra.sessionId)) {
22339
22569
  throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
22340
22570
  }
@@ -22388,9 +22618,9 @@ var Protocol = class {
22388
22618
  };
22389
22619
  return await handleTaskResult();
22390
22620
  });
22391
- this.setRequestHandler(ListTasksRequestSchema, async (request2, extra) => {
22621
+ this.setRequestHandler(ListTasksRequestSchema, async (request3, extra) => {
22392
22622
  try {
22393
- const { tasks, nextCursor } = await this._taskStore.listTasks(request2.params?.cursor, extra.sessionId);
22623
+ const { tasks, nextCursor } = await this._taskStore.listTasks(request3.params?.cursor, extra.sessionId);
22394
22624
  return {
22395
22625
  tasks,
22396
22626
  nextCursor,
@@ -22400,20 +22630,20 @@ var Protocol = class {
22400
22630
  throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`);
22401
22631
  }
22402
22632
  });
22403
- this.setRequestHandler(CancelTaskRequestSchema, async (request2, extra) => {
22633
+ this.setRequestHandler(CancelTaskRequestSchema, async (request3, extra) => {
22404
22634
  try {
22405
- const task = await this._taskStore.getTask(request2.params.taskId, extra.sessionId);
22635
+ const task = await this._taskStore.getTask(request3.params.taskId, extra.sessionId);
22406
22636
  if (!task) {
22407
- throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request2.params.taskId}`);
22637
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request3.params.taskId}`);
22408
22638
  }
22409
22639
  if (isTerminal(task.status)) {
22410
22640
  throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
22411
22641
  }
22412
- await this._taskStore.updateTaskStatus(request2.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
22413
- this._clearTaskQueue(request2.params.taskId, extra.sessionId);
22414
- const cancelledTask = await this._taskStore.getTask(request2.params.taskId, extra.sessionId);
22642
+ await this._taskStore.updateTaskStatus(request3.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
22643
+ this._clearTaskQueue(request3.params.taskId, extra.sessionId);
22644
+ const cancelledTask = await this._taskStore.getTask(request3.params.taskId, extra.sessionId);
22415
22645
  if (!cancelledTask) {
22416
- throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request2.params.taskId}`);
22646
+ throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request3.params.taskId}`);
22417
22647
  }
22418
22648
  return {
22419
22649
  _meta: {},
@@ -22534,10 +22764,10 @@ var Protocol = class {
22534
22764
  }
22535
22765
  Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)));
22536
22766
  }
22537
- _onrequest(request2, extra) {
22538
- const handler = this._requestHandlers.get(request2.method) ?? this.fallbackRequestHandler;
22767
+ _onrequest(request3, extra) {
22768
+ const handler = this._requestHandlers.get(request3.method) ?? this.fallbackRequestHandler;
22539
22769
  const capturedTransport = this._transport;
22540
- const relatedTaskId = request2.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
22770
+ const relatedTaskId = request3.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
22541
22771
  const sessionId = capturedTransport?.sessionId;
22542
22772
  const store = this._taskStore;
22543
22773
  let relatedTaskFound = true;
@@ -22554,7 +22784,7 @@ var Protocol = class {
22554
22784
  if (handler === void 0) {
22555
22785
  const errorResponse = {
22556
22786
  jsonrpc: "2.0",
22557
- id: request2.id,
22787
+ id: request3.id,
22558
22788
  error: {
22559
22789
  code: ErrorCode.MethodNotFound,
22560
22790
  message: "Method not found"
@@ -22575,17 +22805,17 @@ var Protocol = class {
22575
22805
  return;
22576
22806
  }
22577
22807
  const abortController = new AbortController();
22578
- this._requestHandlerAbortControllers.set(request2.id, abortController);
22579
- const taskCreationParams = isTaskAugmentedRequestParams(request2.params) ? request2.params.task : void 0;
22580
- const taskStore = this._taskStore ? this.requestTaskStore(request2, capturedTransport?.sessionId) : void 0;
22808
+ this._requestHandlerAbortControllers.set(request3.id, abortController);
22809
+ const taskCreationParams = isTaskAugmentedRequestParams(request3.params) ? request3.params.task : void 0;
22810
+ const taskStore = this._taskStore ? this.requestTaskStore(request3, capturedTransport?.sessionId) : void 0;
22581
22811
  const fullExtra = {
22582
22812
  signal: abortController.signal,
22583
22813
  sessionId: capturedTransport?.sessionId,
22584
- _meta: request2.params?._meta,
22814
+ _meta: request3.params?._meta,
22585
22815
  sendNotification: async (notification) => {
22586
22816
  if (abortController.signal.aborted)
22587
22817
  return;
22588
- const notificationOptions = { relatedRequestId: request2.id };
22818
+ const notificationOptions = { relatedRequestId: request3.id };
22589
22819
  if (relatedTaskId) {
22590
22820
  notificationOptions.relatedTask = { taskId: relatedTaskId };
22591
22821
  }
@@ -22595,7 +22825,7 @@ var Protocol = class {
22595
22825
  if (abortController.signal.aborted) {
22596
22826
  throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
22597
22827
  }
22598
- const requestOptions = { ...options, relatedRequestId: request2.id };
22828
+ const requestOptions = { ...options, relatedRequestId: request3.id };
22599
22829
  if (relatedTaskId && !requestOptions.relatedTask) {
22600
22830
  requestOptions.relatedTask = { taskId: relatedTaskId };
22601
22831
  }
@@ -22606,7 +22836,7 @@ var Protocol = class {
22606
22836
  return await this.request(r, resultSchema, requestOptions);
22607
22837
  },
22608
22838
  authInfo: extra?.authInfo,
22609
- requestId: request2.id,
22839
+ requestId: request3.id,
22610
22840
  requestInfo: extra?.requestInfo,
22611
22841
  taskId: relatedTaskId,
22612
22842
  taskStore,
@@ -22619,16 +22849,16 @@ var Protocol = class {
22619
22849
  throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
22620
22850
  }
22621
22851
  if (taskCreationParams) {
22622
- this.assertTaskHandlerCapability(request2.method);
22852
+ this.assertTaskHandlerCapability(request3.method);
22623
22853
  }
22624
- }).then(() => handler(request2, fullExtra)).then(async (result) => {
22854
+ }).then(() => handler(request3, fullExtra)).then(async (result) => {
22625
22855
  if (abortController.signal.aborted) {
22626
22856
  return;
22627
22857
  }
22628
22858
  const response = {
22629
22859
  result,
22630
22860
  jsonrpc: "2.0",
22631
- id: request2.id
22861
+ id: request3.id
22632
22862
  };
22633
22863
  if (relatedTaskId && this._taskMessageQueue) {
22634
22864
  await this._enqueueTaskMessage(relatedTaskId, {
@@ -22645,7 +22875,7 @@ var Protocol = class {
22645
22875
  }
22646
22876
  const errorResponse = {
22647
22877
  jsonrpc: "2.0",
22648
- id: request2.id,
22878
+ id: request3.id,
22649
22879
  error: {
22650
22880
  code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError,
22651
22881
  message: error2.message ?? "Internal error",
@@ -22662,8 +22892,8 @@ var Protocol = class {
22662
22892
  await capturedTransport?.send(errorResponse);
22663
22893
  }
22664
22894
  }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => {
22665
- if (this._requestHandlerAbortControllers.get(request2.id) === abortController) {
22666
- this._requestHandlerAbortControllers.delete(request2.id);
22895
+ if (this._requestHandlerAbortControllers.get(request3.id) === abortController) {
22896
+ this._requestHandlerAbortControllers.delete(request3.id);
22667
22897
  }
22668
22898
  });
22669
22899
  }
@@ -22767,11 +22997,11 @@ var Protocol = class {
22767
22997
  *
22768
22998
  * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
22769
22999
  */
22770
- async *requestStream(request2, resultSchema, options) {
23000
+ async *requestStream(request3, resultSchema, options) {
22771
23001
  const { task } = options ?? {};
22772
23002
  if (!task) {
22773
23003
  try {
22774
- const result = await this.request(request2, resultSchema, options);
23004
+ const result = await this.request(request3, resultSchema, options);
22775
23005
  yield { type: "result", result };
22776
23006
  } catch (error2) {
22777
23007
  yield {
@@ -22783,7 +23013,7 @@ var Protocol = class {
22783
23013
  }
22784
23014
  let taskId;
22785
23015
  try {
22786
- const createResult = await this.request(request2, CreateTaskResultSchema, options);
23016
+ const createResult = await this.request(request3, CreateTaskResultSchema, options);
22787
23017
  if (createResult.task) {
22788
23018
  taskId = createResult.task.taskId;
22789
23019
  yield { type: "taskCreated", task: createResult.task };
@@ -22831,7 +23061,7 @@ var Protocol = class {
22831
23061
  *
22832
23062
  * Do not use this method to emit notifications! Use notification() instead.
22833
23063
  */
22834
- request(request2, resultSchema, options) {
23064
+ request(request3, resultSchema, options) {
22835
23065
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
22836
23066
  return new Promise((resolve3, reject) => {
22837
23067
  const earlyReject = (error2) => {
@@ -22843,9 +23073,9 @@ var Protocol = class {
22843
23073
  }
22844
23074
  if (this._options?.enforceStrictCapabilities === true) {
22845
23075
  try {
22846
- this.assertCapabilityForMethod(request2.method);
23076
+ this.assertCapabilityForMethod(request3.method);
22847
23077
  if (task) {
22848
- this.assertTaskCapability(request2.method);
23078
+ this.assertTaskCapability(request3.method);
22849
23079
  }
22850
23080
  } catch (e) {
22851
23081
  earlyReject(e);
@@ -22855,16 +23085,16 @@ var Protocol = class {
22855
23085
  options?.signal?.throwIfAborted();
22856
23086
  const messageId = this._requestMessageId++;
22857
23087
  const jsonrpcRequest = {
22858
- ...request2,
23088
+ ...request3,
22859
23089
  jsonrpc: "2.0",
22860
23090
  id: messageId
22861
23091
  };
22862
23092
  if (options?.onprogress) {
22863
23093
  this._progressHandlers.set(messageId, options.onprogress);
22864
23094
  jsonrpcRequest.params = {
22865
- ...request2.params,
23095
+ ...request3.params,
22866
23096
  _meta: {
22867
- ...request2.params?._meta || {},
23097
+ ...request3.params?._meta || {},
22868
23098
  progressToken: messageId
22869
23099
  }
22870
23100
  };
@@ -23068,8 +23298,8 @@ var Protocol = class {
23068
23298
  setRequestHandler(requestSchema, handler) {
23069
23299
  const method = getMethodLiteral(requestSchema);
23070
23300
  this.assertRequestHandlerCapability(method);
23071
- this._requestHandlers.set(method, (request2, extra) => {
23072
- const parsed = parseWithCompat(requestSchema, request2);
23301
+ this._requestHandlers.set(method, (request3, extra) => {
23302
+ const parsed = parseWithCompat(requestSchema, request3);
23073
23303
  return Promise.resolve(handler(parsed, extra));
23074
23304
  });
23075
23305
  }
@@ -23185,19 +23415,19 @@ var Protocol = class {
23185
23415
  }, { once: true });
23186
23416
  });
23187
23417
  }
23188
- requestTaskStore(request2, sessionId) {
23418
+ requestTaskStore(request3, sessionId) {
23189
23419
  const taskStore = this._taskStore;
23190
23420
  if (!taskStore) {
23191
23421
  throw new Error("No task store configured");
23192
23422
  }
23193
23423
  return {
23194
23424
  createTask: async (taskParams) => {
23195
- if (!request2) {
23425
+ if (!request3) {
23196
23426
  throw new Error("No request provided");
23197
23427
  }
23198
- return await taskStore.createTask(taskParams, request2.id, {
23199
- method: request2.method,
23200
- params: request2.params
23428
+ return await taskStore.createTask(taskParams, request3.id, {
23429
+ method: request3.method,
23430
+ params: request3.params
23201
23431
  }, sessionId);
23202
23432
  },
23203
23433
  getTask: async (taskId) => {
@@ -23358,8 +23588,8 @@ var ExperimentalServerTasks = class {
23358
23588
  *
23359
23589
  * @experimental
23360
23590
  */
23361
- requestStream(request2, resultSchema, options) {
23362
- return this._server.requestStream(request2, resultSchema, options);
23591
+ requestStream(request3, resultSchema, options) {
23592
+ return this._server.requestStream(request3, resultSchema, options);
23363
23593
  }
23364
23594
  /**
23365
23595
  * Sends a sampling request and returns an AsyncGenerator that yields response messages.
@@ -23604,12 +23834,12 @@ var Server = class extends Protocol {
23604
23834
  this._capabilities = options?.capabilities ?? {};
23605
23835
  this._instructions = options?.instructions;
23606
23836
  this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
23607
- this.setRequestHandler(InitializeRequestSchema, (request2) => this._oninitialize(request2));
23837
+ this.setRequestHandler(InitializeRequestSchema, (request3) => this._oninitialize(request3));
23608
23838
  this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());
23609
23839
  if (this._capabilities.logging) {
23610
- this.setRequestHandler(SetLevelRequestSchema, async (request2, extra) => {
23840
+ this.setRequestHandler(SetLevelRequestSchema, async (request3, extra) => {
23611
23841
  const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0;
23612
- const { level } = request2.params;
23842
+ const { level } = request3.params;
23613
23843
  const parseResult = LoggingLevelSchema.safeParse(level);
23614
23844
  if (parseResult.success) {
23615
23845
  this._loggingLevels.set(transportSessionId, parseResult.data);
@@ -23659,14 +23889,14 @@ var Server = class extends Protocol {
23659
23889
  }
23660
23890
  const method = methodValue;
23661
23891
  if (method === "tools/call") {
23662
- const wrappedHandler = async (request2, extra) => {
23663
- const validatedRequest = safeParse2(CallToolRequestSchema, request2);
23892
+ const wrappedHandler = async (request3, extra) => {
23893
+ const validatedRequest = safeParse2(CallToolRequestSchema, request3);
23664
23894
  if (!validatedRequest.success) {
23665
23895
  const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
23666
23896
  throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
23667
23897
  }
23668
23898
  const { params } = validatedRequest.data;
23669
- const result = await Promise.resolve(handler(request2, extra));
23899
+ const result = await Promise.resolve(handler(request3, extra));
23670
23900
  if (params.task) {
23671
23901
  const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
23672
23902
  if (!taskValidationResult.success) {
@@ -23797,10 +24027,10 @@ var Server = class extends Protocol {
23797
24027
  }
23798
24028
  assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server");
23799
24029
  }
23800
- async _oninitialize(request2) {
23801
- const requestedVersion = request2.params.protocolVersion;
23802
- this._clientCapabilities = request2.params.capabilities;
23803
- this._clientVersion = request2.params.clientInfo;
24030
+ async _oninitialize(request3) {
24031
+ const requestedVersion = request3.params.protocolVersion;
24032
+ this._clientCapabilities = request3.params.capabilities;
24033
+ this._clientVersion = request3.params.clientInfo;
23804
24034
  const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;
23805
24035
  return {
23806
24036
  protocolVersion,
@@ -24065,6 +24295,83 @@ var StdioServerTransport = class {
24065
24295
  }
24066
24296
  };
24067
24297
 
24298
+ // src/native/feedback.ts
24299
+ async function identity(env, ctx, fallbackOrgId) {
24300
+ try {
24301
+ let timer;
24302
+ const credential = await Promise.race([
24303
+ env.credential(),
24304
+ new Promise((resolve3) => {
24305
+ timer = setTimeout(() => resolve3(null), LOOKUP_TIMEOUT_MS);
24306
+ })
24307
+ ]).finally(() => clearTimeout(timer));
24308
+ const found = credential === null ? null : await lookupIdentity(ctx, credential.token);
24309
+ if (found?.org_id !== void 0) return found;
24310
+ } catch {
24311
+ }
24312
+ return fallbackOrgId === void 0 ? {} : { org_id: fallbackOrgId };
24313
+ }
24314
+ async function sendProductFeedback(ctx, env, message, source, extra = {}) {
24315
+ const config2 = await readConfig(configPath(ctx.env, ctx.platform, ctx.homedir), ctx.io);
24316
+ const who = await identity(env, ctx, config2.org_id);
24317
+ const destination = destinationFor(ctx.env);
24318
+ if (destination.key === "") {
24319
+ return {
24320
+ sent: false,
24321
+ cause: "no_destination",
24322
+ reason: "this build has no feedback destination configured, so the message was not sent."
24323
+ };
24324
+ }
24325
+ const analytics = openAnalytics(ctx, config2, { always: source === "cli", timeoutMs: FEEDBACK_TIMEOUT_MS });
24326
+ if (source !== "cli" && !telemetryState(ctx.env, config2).on) {
24327
+ return { sent: false, cause: "telemetry_off", reason: "telemetry is disabled on this machine, so nothing was sent." };
24328
+ }
24329
+ analytics.identify(who.user_id ?? distinctIdFrom(config2) ?? who.org_id ?? "cli-anonymous");
24330
+ const shared = {
24331
+ platform: ctx.platform,
24332
+ org_id: who.org_id,
24333
+ org_name: who.org_name
24334
+ };
24335
+ if (destination.surveyId !== "") {
24336
+ analytics.capture("survey sent", { ...shared, $survey_id: destination.surveyId, $survey_response: message });
24337
+ }
24338
+ analytics.capture("user_feedback", { ...shared, ...extra, message, source });
24339
+ await analytics.flush();
24340
+ return analytics.delivered ? { sent: true } : {
24341
+ sent: false,
24342
+ cause: "not_delivered",
24343
+ reason: "the feedback service did not answer, so the message was not sent. Try again."
24344
+ };
24345
+ }
24346
+ var feedbackCommand = {
24347
+ kind: "native",
24348
+ command: "feedback",
24349
+ help: {
24350
+ description: "Send feedback to the Deck team.",
24351
+ usage: "deck feedback <message>",
24352
+ notes: [
24353
+ "Sent even when telemetry is disabled: you asked us to.",
24354
+ "Carries your message and your organization, and nothing else about the machine or the commands you ran.",
24355
+ "Exits 1 and says `sent: false` when it could not be delivered."
24356
+ ]
24357
+ },
24358
+ run: async (ctx, env) => {
24359
+ const message = env.parsed.positionals.join(" ").trim();
24360
+ if (message === "") {
24361
+ throw new CliError("input_invalid", {
24362
+ field: "message",
24363
+ message: "`deck feedback` needs the message to send.",
24364
+ next_steps: ['deck feedback "what is wrong or missing"'],
24365
+ command: "deck feedback"
24366
+ });
24367
+ }
24368
+ const result = await sendProductFeedback(ctx, env, message, "cli");
24369
+ ctx.stdout.write(`${JSON.stringify(result.sent ? { sent: true } : { sent: false, reason: result.reason })}
24370
+ `);
24371
+ return result.sent ? 0 : 1;
24372
+ }
24373
+ };
24374
+
24068
24375
  // src/state/project.ts
24069
24376
  import { dirname as dirname4, join as join6 } from "node:path";
24070
24377
  var IGNORE_ENTRY = ".deck/";
@@ -24268,6 +24575,9 @@ function localTools(rows, flags, ports = {}) {
24268
24575
  const specs = catalogue({ reachable: rowsHere, named });
24269
24576
  const narrowed = (name) => flags.only === null || flags.only.includes(name);
24270
24577
  const extra = [];
24578
+ if (ports.captureFeedback && !flags.readOnly && narrowed("submit_product_feedback")) {
24579
+ extra.push(feedbackTool(ports.captureFeedback));
24580
+ }
24271
24581
  if (ports.docs !== void 0) {
24272
24582
  extra.push(...docsTools(ports.docs).filter((tool) => narrowed(tool.name)));
24273
24583
  }
@@ -24431,7 +24741,7 @@ async function runRow(given, args, env, cred, waiting = { rows: [] }) {
24431
24741
  return ok(projectSuccess(started, args));
24432
24742
  }
24433
24743
  let pollFailure;
24434
- const port = {
24744
+ const port2 = {
24435
24745
  poll: async (pollArgs) => {
24436
24746
  try {
24437
24747
  return { ok: true, status: 200, body: await env.call(pollRequest(pollRow, pollArgs), cred) };
@@ -24441,7 +24751,7 @@ async function runRow(given, args, env, cred, waiting = { rows: [] }) {
24441
24751
  }
24442
24752
  }
24443
24753
  };
24444
- const result = await follow(descriptor, started, port, {
24754
+ const result = await follow(descriptor, started, port2, {
24445
24755
  timeoutMs: seconds * 1e3,
24446
24756
  ...waiting.clock ? { now: waiting.clock.now, sleep: waiting.clock.sleep } : {},
24447
24757
  ...waiting.hooks ?? {}
@@ -24496,8 +24806,32 @@ function mcpServeCommand(rows) {
24496
24806
  },
24497
24807
  run: async (ctx, env) => {
24498
24808
  const flags = parseToolFlags(env.rest);
24809
+ const config2 = await readConfig(configPath(ctx.env, ctx.platform, ctx.homedir), ctx.io);
24810
+ const feedbackReachable = destinationFor(ctx.env).key !== "" && telemetryState(ctx.env, config2).on;
24499
24811
  const reachable = reachableRows(rows, flags);
24500
- const tools = localTools(rows, flags, { docs: docsPort(ctx), whoami: () => whoamiReport(ctx, env) });
24812
+ const tools = localTools(rows, flags, {
24813
+ docs: docsPort(ctx),
24814
+ whoami: () => whoamiReport(ctx, env),
24815
+ // Offered ONLY when there is somewhere for a message to go, which is the
24816
+ // hosted server's own rule. The tool answers `{received: true}` the
24817
+ // moment it accepts a message — it cannot wait for PostHog without
24818
+ // holding an MCP call open — so a build with no destination, or a
24819
+ // machine with telemetry off, would be telling a model its feedback was
24820
+ // taken and then dropping it. Absent is the honest answer.
24821
+ ...feedbackReachable ? {
24822
+ captureFeedback: ({ message, blocked }) => {
24823
+ void sendProductFeedback(ctx, env, message, "mcp", { blocked }).then((result) => {
24824
+ if (!result.sent) {
24825
+ ctx.stderr.write(`deck mcp: feedback not sent \u2014 ${result.reason ?? "unknown reason"}
24826
+ `);
24827
+ }
24828
+ }).catch((e) => {
24829
+ ctx.stderr.write(`deck mcp: feedback not sent \u2014 ${e instanceof Error ? e.message : String(e)}
24830
+ `);
24831
+ });
24832
+ }
24833
+ } : {}
24834
+ });
24501
24835
  const byName = new Map(tools.map((tool) => [tool.name, tool]));
24502
24836
  const registered = new Set(tools.filter((tool) => tool.kind === "row").map((tool) => tool.name));
24503
24837
  const files = localFiles(ctx.fetch);
@@ -24525,11 +24859,11 @@ function mcpServeCommand(rows) {
24525
24859
  ...ctx.clock ? { clock: ctx.clock } : {}
24526
24860
  });
24527
24861
  };
24528
- server.setRequestHandler(CallToolRequestSchema, async (request2, extra) => {
24529
- const tool = byName.get(request2.params.name);
24530
- const args = request2.params.arguments ?? {};
24531
- if (!tool) return fail("unknown_tool", `No tool named ${request2.params.name}.`);
24532
- const hooks = waitHooks(request2, extra);
24862
+ server.setRequestHandler(CallToolRequestSchema, async (request3, extra) => {
24863
+ const tool = byName.get(request3.params.name);
24864
+ const args = request3.params.arguments ?? {};
24865
+ if (!tool) return fail("unknown_tool", `No tool named ${request3.params.name}.`);
24866
+ const hooks = waitHooks(request3, extra);
24533
24867
  if (tool.kind === "row" && tool.row) return sendRow(tool.row, args, hooks);
24534
24868
  if (tool.kind === "handwritten") return runHandwritten(tool, args);
24535
24869
  const operation = typeof args["operation"] === "string" ? args["operation"] : "";
@@ -24572,8 +24906,8 @@ function mcpServeCommand(rows) {
24572
24906
  }
24573
24907
  };
24574
24908
  }
24575
- function waitHooks(request2, extra) {
24576
- const progressToken = request2.params?._meta?.progressToken;
24909
+ function waitHooks(request3, extra) {
24910
+ const progressToken = request3.params?._meta?.progressToken;
24577
24911
  if (progressToken === void 0) return { signal: extra.signal };
24578
24912
  return {
24579
24913
  signal: extra.signal,
@@ -25790,7 +26124,7 @@ var doctorCommand = {
25790
26124
  fixable: false
25791
26125
  });
25792
26126
  } else {
25793
- const request2 = {
26127
+ const request3 = {
25794
26128
  method: "GET",
25795
26129
  // Not `/v2/test`: that is secret-key-only and refuses a `deck login`
25796
26130
  // session with a 403, so it would report a working login as broken.
@@ -25803,7 +26137,7 @@ var doctorCommand = {
25803
26137
  unknownInputKeys: []
25804
26138
  };
25805
26139
  try {
25806
- await env.call(request2, credential);
26140
+ await env.call(request3, credential);
25807
26141
  checks.push({ name: "credential-works", ok: true, detail: "the API accepted it", fixable: false });
25808
26142
  } catch (e) {
25809
26143
  const refused = refusedCredential(e);
@@ -26003,76 +26337,242 @@ async function versionCheck(ctx, timeoutMs = REGISTRY_TIMEOUT_MS) {
26003
26337
  }
26004
26338
  }
26005
26339
 
26006
- // src/native/feedback.ts
26007
- async function identity(env, ctx, fallbackOrgId) {
26340
+ // src/native/docs.ts
26341
+ var toolNamed = (ctx, name) => {
26342
+ const tool = docsTools(docsPort(ctx)).find((t) => t.name === name);
26343
+ if (!tool) throw new Error(`docs tool ${name} is not registered`);
26344
+ return tool;
26345
+ };
26346
+ function argument(env, command, field, example) {
26347
+ const value = env.parsed.positionals.join(" ").trim();
26348
+ if (value === "") {
26349
+ throw new CliError("input_invalid", {
26350
+ field,
26351
+ message: `\`deck ${command}\` needs ${field === "query" ? "something to search for" : "the page path to read"}.`,
26352
+ next_steps: [`deck ${command} ${example}`],
26353
+ command: `deck ${command}`
26354
+ });
26355
+ }
26356
+ return value;
26357
+ }
26358
+ async function callAndPrint(ctx, env, tool, args) {
26359
+ const outcome = await tool.call(args);
26360
+ ctx.stdout.write(`${await env.print(outcome.body)}
26361
+ `);
26362
+ return outcome.ok ? 0 : 1;
26363
+ }
26364
+ var docsSearchCommand = {
26365
+ kind: "native",
26366
+ command: "docs search",
26367
+ help: {
26368
+ description: "Search the Deck documentation and print the results as JSON.",
26369
+ usage: "deck docs search <query>",
26370
+ notes: [
26371
+ "The same search the `search_deck_docs` MCP tool runs, for agents without MCP.",
26372
+ "Needs no credential: the documentation is public."
26373
+ ]
26374
+ },
26375
+ run: async (ctx, env) => callAndPrint(ctx, env, toolNamed(ctx, "search_deck_docs"), {
26376
+ query: argument(env, "docs search", "query", '"how do I run a task"')
26377
+ })
26378
+ };
26379
+ var docsReadCommand = {
26380
+ kind: "native",
26381
+ command: "docs read",
26382
+ help: {
26383
+ description: "Print one Deck documentation page in full, by the path a search result gives.",
26384
+ usage: "deck docs read <page>",
26385
+ notes: [
26386
+ "The same read the `read_deck_docs_page` MCP tool does, for agents without MCP.",
26387
+ "The page path comes from `deck docs search`; a leading slash is accepted.",
26388
+ "Needs no credential: the documentation is public."
26389
+ ]
26390
+ },
26391
+ run: async (ctx, env) => callAndPrint(ctx, env, toolNamed(ctx, "read_deck_docs_page"), {
26392
+ page: argument(env, "docs read", "page", "api-reference/tasks/run-a-task")
26393
+ })
26394
+ };
26395
+
26396
+ // src/native/events-verify.ts
26397
+ import { createHmac, timingSafeEqual } from "node:crypto";
26398
+ var ID_HEADER = "webhook-id";
26399
+ var TIMESTAMP_HEADER = "webhook-timestamp";
26400
+ var SIGNATURE_HEADER = "webhook-signature";
26401
+ async function readOrFail(ctx, path, field) {
26008
26402
  try {
26009
- let timer;
26010
- const credential = await Promise.race([
26011
- env.credential(),
26012
- new Promise((resolve3) => {
26013
- timer = setTimeout(() => resolve3(null), LOOKUP_TIMEOUT_MS);
26014
- })
26015
- ]).finally(() => clearTimeout(timer));
26016
- const found = credential === null ? null : await lookupIdentity(ctx, credential.token);
26017
- if (found?.org_id !== void 0) return found;
26403
+ return await ctx.io.readFileAsync(path);
26018
26404
  } catch {
26405
+ throw new CliError("input_invalid", {
26406
+ field,
26407
+ message: `Could not read ${path}.`,
26408
+ next_steps: ["deck events verify --help"],
26409
+ command: "deck events verify"
26410
+ });
26019
26411
  }
26020
- return fallbackOrgId === void 0 ? {} : { org_id: fallbackOrgId };
26021
26412
  }
26022
- var feedbackCommand = {
26413
+ var headerOf = (headers, name) => Object.entries(headers).find(([key]) => key.toLowerCase() === name)?.[1];
26414
+ function fail2(message, next) {
26415
+ throw new CliError("input_invalid", {
26416
+ field: "delivery",
26417
+ message,
26418
+ next_steps: next,
26419
+ command: "deck events verify"
26420
+ });
26421
+ }
26422
+ function parseDelivery(text3) {
26423
+ let parsed;
26424
+ try {
26425
+ parsed = JSON.parse(text3);
26426
+ } catch {
26427
+ fail2('The delivery file is not JSON. Save the delivery as {"headers": {...}, "body": "<the raw body>"}.', [
26428
+ "deck events verify --delivery delivery.json --secret-stdin"
26429
+ ]);
26430
+ }
26431
+ if (typeof parsed !== "object" || parsed === null) {
26432
+ fail2('The delivery file must be a JSON object with "headers" and "body".', ["deck events verify --help"]);
26433
+ }
26434
+ const { headers, body } = parsed;
26435
+ if (typeof headers !== "object" || headers === null) {
26436
+ fail2(`The delivery file has no "headers" object. Save the delivery's request headers under "headers".`, [
26437
+ "deck events verify --help"
26438
+ ]);
26439
+ }
26440
+ if (typeof body !== "string") {
26441
+ fail2(
26442
+ body === void 0 ? 'The delivery file has no "body". Save the raw request body, as a string, under "body".' : `The delivery's "body" must be the raw body as a STRING. A parsed object cannot be verified: the signature covers the exact bytes that arrived, and re-serializing changes key order and whitespace.`,
26443
+ ["deck events verify --help"]
26444
+ );
26445
+ }
26446
+ return {
26447
+ headers: Object.fromEntries(Object.entries(headers).map(([k, v]) => [k, String(v)])),
26448
+ body
26449
+ };
26450
+ }
26451
+ function signingKey(secret) {
26452
+ const trimmed = secret.trim();
26453
+ if (trimmed === "") {
26454
+ throw new CliError("input_invalid", {
26455
+ field: "secret",
26456
+ message: "The signing secret is empty.",
26457
+ next_steps: ["deck events verify --help"],
26458
+ command: "deck events verify"
26459
+ });
26460
+ }
26461
+ const material = trimmed.startsWith("whsec_") ? trimmed.slice("whsec_".length) : trimmed;
26462
+ const key = Buffer.from(material, "base64");
26463
+ if (key.length === 0 || Buffer.from(key).toString("base64").replace(/=+$/, "") !== material.replace(/=+$/, "")) {
26464
+ throw new CliError("input_invalid", {
26465
+ field: "secret",
26466
+ message: "The signing secret is not valid base64. It is the `whsec_` value exactly as the destination's create response gave it.",
26467
+ next_steps: ["deck events verify --help"],
26468
+ command: "deck events verify"
26469
+ });
26470
+ }
26471
+ return key;
26472
+ }
26473
+ var sameSignature = (a, b) => {
26474
+ const left = Buffer.from(a, "utf8");
26475
+ const right = Buffer.from(b, "utf8");
26476
+ return left.length === right.length && timingSafeEqual(left, right);
26477
+ };
26478
+ function verifyDelivery(delivery, secret, now) {
26479
+ const id = headerOf(delivery.headers, ID_HEADER);
26480
+ const timestamp = headerOf(delivery.headers, TIMESTAMP_HEADER);
26481
+ const signature = headerOf(delivery.headers, SIGNATURE_HEADER);
26482
+ const missing2 = [
26483
+ id === void 0 ? ID_HEADER : null,
26484
+ timestamp === void 0 ? TIMESTAMP_HEADER : null,
26485
+ signature === void 0 ? SIGNATURE_HEADER : null
26486
+ ].filter((h) => h !== null);
26487
+ if (missing2.length > 0) {
26488
+ return { verified: false, reason: `the delivery is missing ${missing2.join(", ")}` };
26489
+ }
26490
+ const expected = createHmac("sha256", signingKey(secret)).update(`${id}.${timestamp}.${delivery.body}`, "utf8").digest("base64");
26491
+ const offered = signature.split(" ").map((part) => part.trim()).filter((part) => part.startsWith("v1,")).map((part) => part.slice("v1,".length));
26492
+ if (offered.length === 0) {
26493
+ return { verified: false, reason: `${SIGNATURE_HEADER} carries no v1 signature` };
26494
+ }
26495
+ const seconds = Number(timestamp);
26496
+ const age = Number.isFinite(seconds) ? Math.round(now.getTime() / 1e3 - seconds) : void 0;
26497
+ const verified = offered.some((candidate) => sameSignature(candidate, expected));
26498
+ return {
26499
+ verified,
26500
+ webhook_id: id,
26501
+ timestamp,
26502
+ ...age === void 0 ? {} : { age_seconds: age },
26503
+ ...verified ? {} : { reason: "the signature does not match this secret and body" }
26504
+ };
26505
+ }
26506
+ async function secretFrom(ctx, env) {
26507
+ if (env.parsed.flags.has("secret")) {
26508
+ throw new CliError("secret_in_argv", {
26509
+ field: "secret",
26510
+ message: "`--secret` puts the signing secret in the command line, where shell history and process lists can read it.",
26511
+ next_steps: [
26512
+ "DECK_WEBHOOK_SECRET=whsec_\u2026 deck events verify --delivery delivery.json",
26513
+ "deck events verify --delivery delivery.json --secret-file .secrets/whsec",
26514
+ "deck events verify --delivery delivery.json --secret-stdin < .secrets/whsec"
26515
+ ]
26516
+ });
26517
+ }
26518
+ const file = env.parsed.flags.get("secret-file")?.at(-1)?.trim();
26519
+ if (file !== void 0 && file !== "") return (await readOrFail(ctx, file, "secret-file")).trim();
26520
+ if (env.parsed.flags.get("secret-stdin")?.at(-1) === "true") {
26521
+ if (ctx.io.stdinIsTty) {
26522
+ throw new CliError("input_invalid", {
26523
+ field: "secret-stdin",
26524
+ message: "--secret-stdin reads the secret from standard input, and nothing was piped in.",
26525
+ next_steps: ["deck events verify --delivery delivery.json --secret-stdin < .secrets/whsec"],
26526
+ command: "deck events verify"
26527
+ });
26528
+ }
26529
+ return ctx.io.readStdin().trim();
26530
+ }
26531
+ const fromEnv = ctx.env["DECK_WEBHOOK_SECRET"]?.trim();
26532
+ if (fromEnv) return fromEnv;
26533
+ throw new CliError("input_invalid", {
26534
+ field: "secret",
26535
+ message: "No signing secret. It is the `whsec_` value from the destination's create response.",
26536
+ next_steps: [
26537
+ "DECK_WEBHOOK_SECRET=whsec_\u2026 deck events verify --delivery delivery.json",
26538
+ "deck events verify --delivery delivery.json --secret-file .secrets/whsec"
26539
+ ],
26540
+ command: "deck events verify"
26541
+ });
26542
+ }
26543
+ var eventsVerifyCommand = {
26023
26544
  kind: "native",
26024
- command: "feedback",
26545
+ command: "events verify",
26546
+ valueFlags: ["delivery", "secret-file", "secret"],
26547
+ // `--secret` is here to be REFUSED, not used, so it is never suggested and
26548
+ // never listed: a "did you mean --secret?" is an instruction to put a live
26549
+ // signing secret in the command line.
26550
+ unadvertisedFlags: ["secret"],
26551
+ flags: ["secret-stdin"],
26025
26552
  help: {
26026
- description: "Send feedback to the Deck team.",
26027
- usage: "deck feedback <message>",
26553
+ description: "Check a captured delivery's Standard Webhooks signature. Makes no network call.",
26554
+ usage: "deck events verify --delivery <file> [--secret-file <path> | --secret-stdin]",
26028
26555
  notes: [
26029
- "Sent even when telemetry is disabled: you asked us to.",
26030
- "Carries your message and your organization, and nothing else about the machine or the commands you ran.",
26031
- "Exits 1 and says `sent: false` when it could not be delivered."
26556
+ 'The delivery file is {"headers": {...}, "body": "<the raw body>"} \u2014 the body as the exact string that arrived.',
26557
+ "The secret comes from DECK_WEBHOOK_SECRET, --secret-file or --secret-stdin, never a flag.",
26558
+ "Exit 0 when the signature matches, 1 when it does not. The timestamp's age is reported, never enforced."
26032
26559
  ]
26033
26560
  },
26034
26561
  run: async (ctx, env) => {
26035
- const message = env.parsed.positionals.join(" ").trim();
26036
- if (message === "") {
26562
+ const path = env.parsed.flags.get("delivery")?.at(-1)?.trim();
26563
+ if (path === void 0 || path === "") {
26037
26564
  throw new CliError("input_invalid", {
26038
- field: "message",
26039
- message: "`deck feedback` needs the message to send.",
26040
- next_steps: ['deck feedback "what is wrong or missing"'],
26041
- command: "deck feedback"
26565
+ field: "delivery",
26566
+ message: "`deck events verify` needs --delivery, the file holding the captured delivery.",
26567
+ next_steps: ["deck events verify --delivery delivery.json --secret-stdin"],
26568
+ command: "deck events verify"
26042
26569
  });
26043
26570
  }
26044
- const config2 = await readConfig(configPath(ctx.env, ctx.platform, ctx.homedir), ctx.io);
26045
- const who = await identity(env, ctx, config2.org_id);
26046
- const destination = destinationFor(ctx.env);
26047
- if (destination.key === "") {
26048
- ctx.stdout.write(
26049
- `${JSON.stringify({ sent: false, reason: "this build has no feedback destination configured, so the message was not sent." })}
26050
- `
26051
- );
26052
- return 1;
26053
- }
26054
- const analytics = openAnalytics(ctx, config2, { always: true, timeoutMs: FEEDBACK_TIMEOUT_MS });
26055
- analytics.identify(who.user_id ?? distinctIdFrom(config2) ?? who.org_id ?? "cli-anonymous");
26056
- const shared = {
26057
- platform: ctx.platform,
26058
- org_id: who.org_id,
26059
- org_name: who.org_name
26060
- };
26061
- if (destination.surveyId !== "") {
26062
- analytics.capture("survey sent", { ...shared, $survey_id: destination.surveyId, $survey_response: message });
26063
- }
26064
- analytics.capture("user_feedback", { ...shared, message, source: "cli" });
26065
- await analytics.flush();
26066
- if (!analytics.delivered) {
26067
- ctx.stdout.write(
26068
- `${JSON.stringify({ sent: false, reason: "the feedback service did not answer, so the message was not sent. Try again." })}
26069
- `
26070
- );
26071
- return 1;
26072
- }
26073
- ctx.stdout.write(`${JSON.stringify({ sent: true })}
26571
+ const secret = await secretFrom(ctx, env);
26572
+ const verdict = verifyDelivery(parseDelivery(await readOrFail(ctx, path, "delivery")), secret, ctx.now);
26573
+ ctx.stdout.write(`${await env.print(verdict)}
26074
26574
  `);
26075
- return 0;
26575
+ return verdict.verified ? 0 : 1;
26076
26576
  }
26077
26577
  };
26078
26578
 
@@ -26285,7 +26785,7 @@ var initCommand = {
26285
26785
  ];
26286
26786
  ctx.stdout.write(`${JSON.stringify({ phase: "plan", steps: plan2 })}
26287
26787
  `);
26288
- const request2 = {
26788
+ const request3 = {
26289
26789
  method: "POST",
26290
26790
  path: "/v2/organizations",
26291
26791
  query: {},
@@ -26294,7 +26794,7 @@ var initCommand = {
26294
26794
  extraArguments: [],
26295
26795
  unknownInputKeys: []
26296
26796
  };
26297
- const provisioned = await env.call(request2, null);
26797
+ const provisioned = await env.call(request3, null);
26298
26798
  if (provisioned?.api_key?.key === void 0 || provisioned?.organization?.id === void 0) {
26299
26799
  throw new CliError("unexpected_response", {
26300
26800
  message: "POST /v2/organizations answered without an organization and a key, so there is nothing to write."
@@ -26456,7 +26956,7 @@ function tokenFrom(claimUrl) {
26456
26956
  }
26457
26957
 
26458
26958
  // src/native/keys.ts
26459
- var request = (method, path, body = null) => ({
26959
+ var request2 = (method, path, body = null) => ({
26460
26960
  method,
26461
26961
  path,
26462
26962
  query: {},
@@ -26498,7 +26998,7 @@ var keysListCommand = {
26498
26998
  notes: ["Prints the API's body unchanged. Only a key's preview is ever listed, never its secret."]
26499
26999
  },
26500
27000
  run: async (ctx, env) => {
26501
- const sent = await send2(ctx, env, request("GET", "/v2/api-keys"));
27001
+ const sent = await send2(ctx, env, request2("GET", "/v2/api-keys"));
26502
27002
  if (sent) ctx.stdout.write(`${await env.print(sent.body)}
26503
27003
  `);
26504
27004
  return 0;
@@ -26515,7 +27015,7 @@ var keysRetrieveCommand = {
26515
27015
  },
26516
27016
  run: async (ctx, env) => {
26517
27017
  const id = oneId(env.parsed.positionals, "retrieve");
26518
- const sent = await send2(ctx, env, request("GET", "/v2/api-keys"));
27018
+ const sent = await send2(ctx, env, request2("GET", "/v2/api-keys"));
26519
27019
  if (!sent) return 0;
26520
27020
  const data = sent.body?.data;
26521
27021
  if (!Array.isArray(data)) {
@@ -26559,7 +27059,7 @@ var keysCreateCommand = {
26559
27059
  next_steps: ["deck keys create --name <name>"]
26560
27060
  });
26561
27061
  }
26562
- const sent = await send2(ctx, env, request("POST", "/v2/api-keys", { name }));
27062
+ const sent = await send2(ctx, env, request2("POST", "/v2/api-keys", { name }));
26563
27063
  if (!sent) return 0;
26564
27064
  if (typeof sent.body !== "object" || sent.body === null || Array.isArray(sent.body)) {
26565
27065
  throw new CliError("unexpected_response", {
@@ -26586,7 +27086,7 @@ var keysDeleteCommand = {
26586
27086
  run: async (ctx, env) => {
26587
27087
  const id = oneId(env.parsed.positionals, "delete");
26588
27088
  confirmGate(DELETE_GATE, env.parsed, id);
26589
- const sent = await send2(ctx, env, request("DELETE", `/v2/api-keys/${encodeURIComponent(id)}`));
27089
+ const sent = await send2(ctx, env, request2("DELETE", `/v2/api-keys/${encodeURIComponent(id)}`));
26590
27090
  if (!sent) return 0;
26591
27091
  ctx.stdout.write(`${await env.print({ deleted: true, id })}
26592
27092
  `);
@@ -26927,7 +27427,10 @@ function natives(rows, registry2) {
26927
27427
  upgradeCommand,
26928
27428
  changelogCommand,
26929
27429
  telemetryCommand,
26930
- feedbackCommand
27430
+ feedbackCommand,
27431
+ docsSearchCommand,
27432
+ docsReadCommand,
27433
+ eventsVerifyCommand
26931
27434
  ];
26932
27435
  }
26933
27436
 
@@ -26981,6 +27484,7 @@ var lastOf = (p, name) => p.flags.get(name)?.at(-1);
26981
27484
  function booleanFlagsFor(row) {
26982
27485
  const out = new Set(GLOBAL_BOOLEAN_FLAG_SPELLINGS);
26983
27486
  out.add("wait");
27487
+ out.add("link");
26984
27488
  const consider = (name, schema2) => {
26985
27489
  const types = typesOf(schema2).filter((t) => t !== "null");
26986
27490
  if (types.length === 1 && types[0] === "boolean") {
@@ -27019,6 +27523,7 @@ var unchecked = (subject, why, retryable = true) => `${subject}: ${why}, so its
27019
27523
  // circle. Every other one here is a lookup that may answer next time.
27020
27524
  (retryable ? "; try again." : ", and nothing about this item will change that.");
27021
27525
  var CLI_OWN_FLAGS = CLI_OWN_ARGUMENTS;
27526
+ var authComponentUrl = (env) => env["DECK_AUTH_COMPONENT_URL"]?.trim() || DEFAULT_AUTH_COMPONENT_URL;
27022
27527
  var CHECKED_BOOLEAN_GLOBALS = [...GLOBAL_BOOLEAN_FLAGS].filter((f) => f !== "yes");
27023
27528
  function booleanValueProblems(parsed, names) {
27024
27529
  const out = [];
@@ -27035,20 +27540,27 @@ function booleanValueProblems(parsed, names) {
27035
27540
  function offeredFlagProblems(row, parsed) {
27036
27541
  const out = [];
27037
27542
  const used = (name) => parsed.flags.has(name) || parsed.missingValues.includes(name);
27543
+ const linkWaits = row.operationId === "createCredential" && flagOn3(parsed, "link");
27038
27544
  if (!row.follow) {
27039
27545
  if (used("wait")) {
27040
27546
  out.push({
27041
27547
  field: "wait",
27042
- message: `--wait waits for something to finish, and \`deck ${row.command}\` starts nothing to wait for. It answers at once.`
27548
+ message: linkWaits ? "--link always waits for the person to finish, so --wait says nothing. Bound it with --timeout." : `--wait waits for something to finish, and \`deck ${row.command}\` starts nothing to wait for. It answers at once.`
27043
27549
  });
27044
27550
  }
27045
- if (used("timeout")) {
27551
+ if (used("timeout") && !linkWaits) {
27046
27552
  out.push({
27047
27553
  field: "timeout",
27048
27554
  message: `--timeout bounds a wait, and \`deck ${row.command}\` has no wait to bound.`
27049
27555
  });
27050
27556
  }
27051
27557
  }
27558
+ if (row.operationId !== "createCredential" && used("link")) {
27559
+ out.push({
27560
+ field: "link",
27561
+ message: `--link hands someone a page to enter credentials on, and \`deck ${row.command}\` takes no credentials.`
27562
+ });
27563
+ }
27052
27564
  if (!row.artifacts && used("download")) {
27053
27565
  out.push({
27054
27566
  field: "download",
@@ -27458,17 +27970,26 @@ async function execute(ctx, remember, facts, analytics) {
27458
27970
  const bound = bind(row, stripFlags(stripGlobals(parsed), CLI_OWN_FLAGS), bindIo, ctx.now);
27459
27971
  const cursorParam = row.query_params.find((p) => toFlag(p.name) === "cursor");
27460
27972
  const timeoutFault = timeoutProblem(timeoutRaw);
27973
+ const linkWaits = row.operationId === "createCredential" && flagOn3(parsed, "link");
27974
+ const linkTimeoutRaw = linkWaits ? lastOf(parsed, "timeout") : void 0;
27975
+ const linkTimeoutFault = linkWaits ? timeoutProblem(linkTimeoutRaw) : void 0;
27976
+ const linkTimeoutSeconds = linkTimeoutRaw === void 0 ? void 0 : Number(linkTimeoutRaw);
27461
27977
  const localProblems = [
27462
27978
  ...missingValueProblems,
27463
27979
  ...flagValueProblems,
27464
27980
  // `--wait` is a boolean here too, and only here: on a row with no `follow`
27465
27981
  // it is refused outright below rather than value-checked.
27466
27982
  ...row.follow ? booleanValueProblems(parsed, ["wait"]) : [],
27983
+ // `--link=1` must not read as "not link". Unchecked, it fell through to
27984
+ // this row's real POST /v2/credentials carrying the secret — the exact
27985
+ // disclosure the flag exists to prevent, with nothing said.
27986
+ ...row.operationId === "createCredential" ? booleanValueProblems(parsed, ["link"]) : [],
27467
27987
  // Refused by name, not left to `check`: the flag exists, it just does not
27468
27988
  // apply to this command, and saying so is what stops a caller believing a
27469
27989
  // bound held or a file was saved.
27470
27990
  ...offeredFlagProblems(row, parsed),
27471
27991
  ...timeoutFault === void 0 ? [] : [{ field: "timeout", message: timeoutFault }],
27992
+ ...linkTimeoutFault === void 0 ? [] : [{ field: "timeout", message: linkTimeoutFault }],
27472
27993
  // Refused, not ignored: a `--timeout` that waits for nothing would read as a bound that held.
27473
27994
  ...timeoutRaw !== void 0 && !wait ? [{ field: "timeout", message: "--timeout bounds a wait, and this command was not given --wait." }] : [],
27474
27995
  ...downloadDir === "" ? [{ field: "download", message: "--download needs a directory to save into." }] : [],
@@ -27479,7 +28000,14 @@ async function execute(ctx, remember, facts, analytics) {
27479
28000
  ];
27480
28001
  confirmGate(row, parsed, firstPathValue(row, bound.path));
27481
28002
  secretGate(row, parsed);
27482
- const problems = [...localProblems, ...check(row, bound)];
28003
+ const linkRequested = row.operationId === "createCredential" && flagOn3(parsed, "link");
28004
+ const problems = [
28005
+ ...localProblems,
28006
+ // `--link` may name no source: the PRD says the person chooses one on the
28007
+ // page when it is omitted. Only THAT problem is dropped — a misspelled
28008
+ // flag or a wrong type is still a refusal.
28009
+ ...check(row, bound).filter((p) => !(linkRequested && p.field === "source_id" && /required/i.test(p.message)))
28010
+ ];
27483
28011
  if (problems.length > 0) throw new CliError("input_invalid", { problems });
27484
28012
  if (row.sensitive_rule && !dryRun) {
27485
28013
  const idParam = row.path_params.find((p) => p.name === "run_id") ?? row.path_params[0];
@@ -27489,6 +28017,56 @@ async function execute(ctx, remember, facts, analytics) {
27489
28017
  }
27490
28018
  }
27491
28019
  const cred = row.anonymous ? await optionalCredential() : await credential();
28020
+ if (linkRequested) {
28021
+ const bodyIn = bound.body ?? {};
28022
+ const sourceId = typeof bodyIn["source_id"] === "string" && bodyIn["source_id"].trim() !== "" ? bodyIn["source_id"] : void 0;
28023
+ const carried = /* @__PURE__ */ new Set(["source_id"]);
28024
+ const dropped = Object.keys(bodyIn).filter((key) => !carried.has(key)).sort();
28025
+ if (dropped.length > 0) {
28026
+ throw new CliError("input_invalid", {
28027
+ problems: dropped.map((field) => ({
28028
+ field,
28029
+ message: `--${toFlag(field)} cannot travel on a link: the person fills the credential in on Deck's hosted page, and --link sends only the source. Create it without --link to set this field yourself.`
28030
+ }))
28031
+ });
28032
+ }
28033
+ if (dryRun) {
28034
+ const view = requestView(
28035
+ { method: "POST", path: "/v2/token", query: {}, body: {}, unknownFields: [], extraArguments: [], unknownInputKeys: [] },
28036
+ { baseUrl, credential: cred, version: VERSION, ...idempotencyKey === void 0 ? {} : { idempotencyKey } }
28037
+ );
28038
+ write(
28039
+ `${JSON.stringify({
28040
+ method: view.method,
28041
+ url: view.url,
28042
+ path: "/v2/token",
28043
+ query: {},
28044
+ body: {},
28045
+ notes: [
28046
+ "--link does not send this command's own POST /v2/credentials. It mints a component token and prints the hosted Auth Component URL for a person to enter the credentials on.",
28047
+ `The link would point at ${authComponentUrl(ctx.env)}${sourceId === void 0 ? ", with no source, so the person chooses one" : ` for source ${sourceId}`}.`
28048
+ ]
28049
+ })}
28050
+ `
28051
+ );
28052
+ return 0;
28053
+ }
28054
+ return credentialLinkFlow(
28055
+ ctx,
28056
+ async (body2) => write(`${await render(body2, renderOptions)}
28057
+ `),
28058
+ dispatch,
28059
+ cred,
28060
+ authComponentUrl(ctx.env),
28061
+ {
28062
+ sourceId,
28063
+ timeoutSeconds: linkTimeoutSeconds,
28064
+ // A person at a terminal gets the page opened; an agent gets the URL
28065
+ // to pass on and nothing surprising happening on someone's desktop.
28066
+ openBrowser: ctx.io.stdoutIsTty
28067
+ }
28068
+ );
28069
+ }
27492
28070
  if (dryRun) {
27493
28071
  const view = requestView(bound, {
27494
28072
  baseUrl,
@@ -27583,14 +28161,15 @@ var get = (path) => ({
27583
28161
  function nativeFlagProblems(entry, parsed) {
27584
28162
  if (entry.anyFlag === true) return [];
27585
28163
  const known2 = /* @__PURE__ */ new Set([...GLOBAL_FLAGS, ...entry.valueFlags ?? [], ...entry.flags ?? []]);
27586
- const candidates = [...known2];
28164
+ const unadvertised = new Set(entry.unadvertisedFlags ?? []);
28165
+ const candidates = [...known2].filter((f) => !unadvertised.has(f));
27587
28166
  const problems = [];
27588
28167
  for (const raw of parsed.flags.keys()) {
27589
28168
  if (known2.has(raw)) continue;
27590
28169
  const hint = suggest(raw, candidates);
27591
28170
  problems.push({
27592
28171
  field: raw,
27593
- message: `unknown flag --${raw}${hint === void 0 ? "" : `, did you mean --${hint}?`} (deck ${entry.command} takes: ${[...entry.flags ?? [], ...entry.valueFlags ?? []].map((f) => `--${f}`).join(", ") || "no flags of its own"})`
28172
+ message: `unknown flag --${raw}${hint === void 0 ? "" : `, did you mean --${hint}?`} (deck ${entry.command} takes: ${[...entry.flags ?? [], ...entry.valueFlags ?? []].filter((f) => !unadvertised.has(f)).map((f) => `--${f}`).join(", ") || "no flags of its own"})`
27594
28173
  });
27595
28174
  }
27596
28175
  return problems;