@kashdao/cli 0.1.1 → 0.2.1

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 (93) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +78 -27
  3. package/dist/{account-CVJZ3HVT.js → account-QHPOIZ6I.js} +9 -9
  4. package/dist/{auth-V5WVZBCO.js → auth-TE7BCN5Q.js} +12 -12
  5. package/dist/{auth-V5WVZBCO.js.map → auth-TE7BCN5Q.js.map} +1 -1
  6. package/dist/{chunk-MQUJG224.js → chunk-2HFKULGG.js} +2 -2
  7. package/dist/{chunk-BVFDUI73.js → chunk-2SR77BYA.js} +10 -9
  8. package/dist/chunk-2SR77BYA.js.map +1 -0
  9. package/dist/chunk-6QSTFU4R.js +9 -0
  10. package/dist/{chunk-KAM6KOFD.js.map → chunk-6QSTFU4R.js.map} +1 -1
  11. package/dist/{chunk-R4NGUZKN.js → chunk-6UU43MF5.js} +5 -3
  12. package/dist/chunk-6UU43MF5.js.map +1 -0
  13. package/dist/{chunk-A3IH5HUV.js → chunk-AROIP4EQ.js} +3 -3
  14. package/dist/chunk-AROIP4EQ.js.map +1 -0
  15. package/dist/{chunk-QALDZHTX.js → chunk-H2QGFDZP.js} +9 -11
  16. package/dist/chunk-H2QGFDZP.js.map +1 -0
  17. package/dist/{chunk-L4AFV2HK.js → chunk-IOLKGV45.js} +3 -3
  18. package/dist/chunk-IOLKGV45.js.map +1 -0
  19. package/dist/{chunk-KADB3OKE.js → chunk-VFBQVUL4.js} +2 -2
  20. package/dist/{chunk-X2VM6VKM.js → chunk-WL7XUYPH.js} +19 -20
  21. package/dist/chunk-WL7XUYPH.js.map +1 -0
  22. package/dist/{chunk-N26VGVGB.js → chunk-ZSMI63N3.js} +109 -37
  23. package/dist/chunk-ZSMI63N3.js.map +1 -0
  24. package/dist/client-REDY6K7J.js +14 -0
  25. package/dist/{completion-PK74S3EZ.js → completion-MXTJYK3D.js} +4 -4
  26. package/dist/{config-T5U6E6KU.js → config-TIJXUJ5N.js} +32 -23
  27. package/dist/config-TIJXUJ5N.js.map +1 -0
  28. package/dist/{config-store-UTFDUCKW.js → config-store-INJY4DDT.js} +6 -4
  29. package/dist/{docs-VA7CJ2ZF.js → docs-M5RZAQ6P.js} +5 -5
  30. package/dist/{eoa-RL3NLN3H.js → eoa-N55DYIN3.js} +18 -16
  31. package/dist/eoa-N55DYIN3.js.map +1 -0
  32. package/dist/{errors-2NNXRNES.js → errors-SMR7X5DU.js} +2 -2
  33. package/dist/{explain-3SPMWDYX.js → explain-HIDEZVLV.js} +31 -8
  34. package/dist/explain-HIDEZVLV.js.map +1 -0
  35. package/dist/{global-options-WFQ6CEFK.js → global-options-YONBFB7N.js} +4 -4
  36. package/dist/{health-2KD6XUTJ.js → health-LSJKP3NH.js} +9 -9
  37. package/dist/index.js +31 -28
  38. package/dist/index.js.map +1 -1
  39. package/dist/{markets-H6EK2XDE.js → markets-AGL6Q2ES.js} +23 -12
  40. package/dist/markets-AGL6Q2ES.js.map +1 -0
  41. package/dist/{output-FGTXXZEQ.js → output-M4NFSWGW.js} +4 -4
  42. package/dist/{portfolio-R63D5QB2.js → portfolio-RBRVUEYP.js} +11 -11
  43. package/dist/{portfolio-R63D5QB2.js.map → portfolio-RBRVUEYP.js.map} +1 -1
  44. package/dist/{protocol-ZB6R25IM.js → protocol-WYQAKN6N.js} +18 -16
  45. package/dist/protocol-WYQAKN6N.js.map +1 -0
  46. package/dist/{quote-OF6BTAPQ.js → quote-6CNHU36A.js} +10 -10
  47. package/dist/redeem-JESSTZ46.js +108 -0
  48. package/dist/redeem-JESSTZ46.js.map +1 -0
  49. package/dist/{schema-3HQN4RFL.js → schema-6EXADLRW.js} +12 -8
  50. package/dist/{schema-3HQN4RFL.js.map → schema-6EXADLRW.js.map} +1 -1
  51. package/dist/{setup-IIPQXLPL.js → setup-H46GTSVW.js} +8 -8
  52. package/dist/{trace-WMO3KDHS.js → trace-VDBWWTYL.js} +10 -10
  53. package/dist/{trade-YBCI6XD2.js → trade-FTSY23QG.js} +10 -10
  54. package/dist/trade-FTSY23QG.js.map +1 -0
  55. package/dist/{version-WB2ACHMU.js → version-JTLF3464.js} +7 -7
  56. package/dist/{version-check-PRAVPFC6.js → version-check-7JGBY6FZ.js} +4 -4
  57. package/dist/{webhooks-DVS55O4T.js → webhooks-JEWNX5HZ.js} +10 -10
  58. package/dist/{webhooks-DVS55O4T.js.map → webhooks-JEWNX5HZ.js.map} +1 -1
  59. package/dist/{with-retry-2MD2CNK2.js → with-retry-DYSHNLG7.js} +12 -6
  60. package/dist/with-retry-DYSHNLG7.js.map +1 -0
  61. package/package.json +5 -5
  62. package/dist/chunk-A3IH5HUV.js.map +0 -1
  63. package/dist/chunk-BVFDUI73.js.map +0 -1
  64. package/dist/chunk-KAM6KOFD.js +0 -9
  65. package/dist/chunk-L4AFV2HK.js.map +0 -1
  66. package/dist/chunk-N26VGVGB.js.map +0 -1
  67. package/dist/chunk-QALDZHTX.js.map +0 -1
  68. package/dist/chunk-R4NGUZKN.js.map +0 -1
  69. package/dist/chunk-X2VM6VKM.js.map +0 -1
  70. package/dist/client-75FVHGOH.js +0 -14
  71. package/dist/config-T5U6E6KU.js.map +0 -1
  72. package/dist/eoa-RL3NLN3H.js.map +0 -1
  73. package/dist/explain-3SPMWDYX.js.map +0 -1
  74. package/dist/markets-H6EK2XDE.js.map +0 -1
  75. package/dist/protocol-ZB6R25IM.js.map +0 -1
  76. package/dist/trade-YBCI6XD2.js.map +0 -1
  77. package/dist/with-retry-2MD2CNK2.js.map +0 -1
  78. /package/dist/{account-CVJZ3HVT.js.map → account-QHPOIZ6I.js.map} +0 -0
  79. /package/dist/{chunk-MQUJG224.js.map → chunk-2HFKULGG.js.map} +0 -0
  80. /package/dist/{chunk-KADB3OKE.js.map → chunk-VFBQVUL4.js.map} +0 -0
  81. /package/dist/{client-75FVHGOH.js.map → client-REDY6K7J.js.map} +0 -0
  82. /package/dist/{completion-PK74S3EZ.js.map → completion-MXTJYK3D.js.map} +0 -0
  83. /package/dist/{config-store-UTFDUCKW.js.map → config-store-INJY4DDT.js.map} +0 -0
  84. /package/dist/{docs-VA7CJ2ZF.js.map → docs-M5RZAQ6P.js.map} +0 -0
  85. /package/dist/{errors-2NNXRNES.js.map → errors-SMR7X5DU.js.map} +0 -0
  86. /package/dist/{global-options-WFQ6CEFK.js.map → global-options-YONBFB7N.js.map} +0 -0
  87. /package/dist/{health-2KD6XUTJ.js.map → health-LSJKP3NH.js.map} +0 -0
  88. /package/dist/{output-FGTXXZEQ.js.map → output-M4NFSWGW.js.map} +0 -0
  89. /package/dist/{quote-OF6BTAPQ.js.map → quote-6CNHU36A.js.map} +0 -0
  90. /package/dist/{setup-IIPQXLPL.js.map → setup-H46GTSVW.js.map} +0 -0
  91. /package/dist/{trace-WMO3KDHS.js.map → trace-VDBWWTYL.js.map} +0 -0
  92. /package/dist/{version-WB2ACHMU.js.map → version-JTLF3464.js.map} +0 -0
  93. /package/dist/{version-check-PRAVPFC6.js.map → version-check-7JGBY6FZ.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  CLI_VERSION
4
- } from "./chunk-KAM6KOFD.js";
4
+ } from "./chunk-6QSTFU4R.js";
5
5
 
6
6
  // src/utils/debug-hint.ts
7
7
  function isTruthyEnv(value) {
@@ -45,8 +45,8 @@ var argv = process.argv;
45
45
  if (argv[2] === "--version" || argv[2] === "-V") {
46
46
  if (argv.slice(3).includes("--json")) {
47
47
  const [{ buildVersionManifest }, { printJson: printJson2 }] = await Promise.all([
48
- import("./version-WB2ACHMU.js"),
49
- import("./output-FGTXXZEQ.js")
48
+ import("./version-JTLF3464.js"),
49
+ import("./output-M4NFSWGW.js")
50
50
  ]);
51
51
  printJson2(buildVersionManifest());
52
52
  } else {
@@ -79,10 +79,10 @@ if (isBareInvocation) {
79
79
  }
80
80
  const { buildIntroEnvelope, INTRO_SUGGESTIONS, DOCS_URL } = await import("./intro-PQQTYWR7.js");
81
81
  if (wantsJson) {
82
- const { printJson: printJson2 } = await import("./output-FGTXXZEQ.js");
82
+ const { printJson: printJson2 } = await import("./output-M4NFSWGW.js");
83
83
  printJson2(buildIntroEnvelope(CLI_VERSION));
84
84
  } else {
85
- const { print, style } = await import("./output-FGTXXZEQ.js");
85
+ const { print, style } = await import("./output-M4NFSWGW.js");
86
86
  print("");
87
87
  print(`${style.bold("kash")} ${style.dim(`v${CLI_VERSION}`)} \u2014 Kash prediction markets CLI`);
88
88
  print("");
@@ -106,28 +106,30 @@ function isTruthyEnv2(value) {
106
106
  return v === "1" || v === "true" || v === "yes" || v === "on";
107
107
  }
108
108
  var { Command } = await import("commander");
109
- var { authCommand } = await import("./auth-V5WVZBCO.js");
110
- var { configCommand } = await import("./config-T5U6E6KU.js");
111
- var { buildDocsCommand } = await import("./docs-VA7CJ2ZF.js");
112
- var { eoaCommand } = await import("./eoa-RL3NLN3H.js");
113
- var { explainCommand } = await import("./explain-3SPMWDYX.js");
114
- var { accountCommand } = await import("./account-CVJZ3HVT.js");
115
- var { healthCommand } = await import("./health-2KD6XUTJ.js");
116
- var { marketsCommand } = await import("./markets-H6EK2XDE.js");
117
- var { portfolioCommand } = await import("./portfolio-R63D5QB2.js");
118
- var { protocolCommand } = await import("./protocol-ZB6R25IM.js");
119
- var { quoteCommand } = await import("./quote-OF6BTAPQ.js");
120
- var { schemaCommand } = await import("./schema-3HQN4RFL.js");
121
- var { setupCommand } = await import("./setup-IIPQXLPL.js");
122
- var { traceCommand } = await import("./trace-WMO3KDHS.js");
123
- var { tradeCommand } = await import("./trade-YBCI6XD2.js");
124
- var { withRetryCommand } = await import("./with-retry-2MD2CNK2.js");
125
- var { versionCommand } = await import("./version-WB2ACHMU.js");
126
- var { webhooksCommand } = await import("./webhooks-DVS55O4T.js");
127
- var { createCompletionCommand, initCompletion } = await import("./completion-PK74S3EZ.js");
128
- var { EXIT_CODES, toCliError } = await import("./errors-2NNXRNES.js");
129
- var { readGlobals } = await import("./global-options-WFQ6CEFK.js");
130
- var { configureOutput, log, printJson } = await import("./output-FGTXXZEQ.js");
109
+ var { SDK_API_VERSION } = await import("@kashdao/sdk");
110
+ var { authCommand } = await import("./auth-TE7BCN5Q.js");
111
+ var { configCommand } = await import("./config-TIJXUJ5N.js");
112
+ var { buildDocsCommand } = await import("./docs-M5RZAQ6P.js");
113
+ var { eoaCommand } = await import("./eoa-N55DYIN3.js");
114
+ var { explainCommand } = await import("./explain-HIDEZVLV.js");
115
+ var { accountCommand } = await import("./account-QHPOIZ6I.js");
116
+ var { healthCommand } = await import("./health-LSJKP3NH.js");
117
+ var { marketsCommand } = await import("./markets-AGL6Q2ES.js");
118
+ var { portfolioCommand } = await import("./portfolio-RBRVUEYP.js");
119
+ var { protocolCommand } = await import("./protocol-WYQAKN6N.js");
120
+ var { quoteCommand } = await import("./quote-6CNHU36A.js");
121
+ var { redeemCommand } = await import("./redeem-JESSTZ46.js");
122
+ var { schemaCommand } = await import("./schema-6EXADLRW.js");
123
+ var { setupCommand } = await import("./setup-H46GTSVW.js");
124
+ var { traceCommand } = await import("./trace-VDBWWTYL.js");
125
+ var { tradeCommand } = await import("./trade-FTSY23QG.js");
126
+ var { withRetryCommand } = await import("./with-retry-DYSHNLG7.js");
127
+ var { versionCommand } = await import("./version-JTLF3464.js");
128
+ var { webhooksCommand } = await import("./webhooks-JEWNX5HZ.js");
129
+ var { createCompletionCommand, initCompletion } = await import("./completion-MXTJYK3D.js");
130
+ var { EXIT_CODES, toCliError } = await import("./errors-SMR7X5DU.js");
131
+ var { readGlobals } = await import("./global-options-YONBFB7N.js");
132
+ var { configureOutput, log, printJson } = await import("./output-M4NFSWGW.js");
131
133
  var program = new Command();
132
134
  program.name("kash").description("Official command-line interface for the Kash public API.").version(CLI_VERSION, "-V, --version", "output the CLI version").option("--json", "emit machine-readable JSON instead of human-formatted output", false).option(
133
135
  "--quiet",
@@ -145,7 +147,7 @@ program.name("kash").description("Official command-line interface for the Kash p
145
147
  "use an explicit config file path instead of ~/.kash/config.json (overrides KASH_CONFIG)"
146
148
  ).option("--base-url <url>", "override the API base URL for this invocation only").option("--max-retries <n>", "override the SDK retry budget for this invocation only").option("--timeout-ms <n>", "override the SDK request timeout (ms) for this invocation only").option(
147
149
  "--api-version <date>",
148
- "pin against a public-API contract date (sent as 'X-Kash-Api-Version: <date>'). Omit to let the server use its canonical default."
150
+ `pin against a public-API contract date (sent as 'X-Kash-Api-Version: <date>'). Overrides the profile's apiVersion and KASH_API_VERSION (default ${SDK_API_VERSION}).`
149
151
  ).option(
150
152
  "--fields <list>",
151
153
  "comma-separated dot-paths to project on JSON output (e.g. id,title,outcomes.label)"
@@ -192,6 +194,7 @@ program.addCommand(accountCommand);
192
194
  program.addCommand(marketsCommand);
193
195
  program.addCommand(quoteCommand);
194
196
  program.addCommand(tradeCommand);
197
+ program.addCommand(redeemCommand);
195
198
  program.addCommand(portfolioCommand);
196
199
  program.addCommand(protocolCommand);
197
200
  program.addCommand(eoaCommand);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/debug-hint.ts","../src/index.ts"],"sourcesContent":["/**\n * Helpers for the \"Re-run with --debug for verbose HTTP logs\" hint\n * emitted on the error path in `src/index.ts`.\n *\n * Factored out of `src/index.ts` so the helpers are unit-testable —\n * `index.ts` is the CLI entry point and runs Commander at module load,\n * so importing it from a test triggers `process.exit`.\n */\n\n/**\n * Recognise truthy env values the way every other tool does: `1`,\n * `true`, `yes`, `on` (case-insensitive). Empty string and `0` are\n * falsy. Anything else is a no-op rather than an error — env\n * pollution is common and shouldn't fail builds.\n *\n * Local copy of the same helper that lives in `utils/global-options.ts`\n * — kept in sync intentionally; the two MUST agree on what counts as\n * \"debug on\" or the UX gets confusing (readGlobals decides \"is\n * --debug active?\" via isTruthyEnv, and the error path's hint decides\n * \"should I suggest --debug?\" via the same rule).\n */\nfunction isTruthyEnv(value: string | undefined): boolean {\n if (value === undefined) return false;\n const v = value.trim().toLowerCase();\n return v === '1' || v === 'true' || v === 'yes' || v === 'on';\n}\n\n/**\n * \"Is debug already on?\" — used on the error path to decide whether to\n * promote `--debug` as a next-step hint. Mirrors readGlobals'\n * resolution: either the `--debug` flag is in argv, or `KASH_DEBUG`\n * is a *truthy* value per the shared `isTruthyEnv` rule.\n *\n * Critical: a bare presence check on `KASH_DEBUG` would mistakenly\n * skip the hint when the user has `KASH_DEBUG=0` / `=false` / `=no`\n * set — those env values do NOT enable debug mode in readGlobals,\n * so the hint should still fire. The two resolution paths must\n * agree or the UX gets confused.\n *\n * Pure inputs → pure output; safe to invoke with synthetic argv/env\n * in unit tests without touching `process`.\n */\nexport function isDebugOn(\n argv: readonly string[] = process.argv,\n env: NodeJS.ProcessEnv = process.env\n): boolean {\n return argv.slice(2).includes('--debug') || isTruthyEnv(env['KASH_DEBUG']);\n}\n\n/**\n * Promote `--debug` for codes where verbose HTTP logs help — anything\n * the operator can't fix by changing input. Validation / config /\n * input errors don't benefit from more logs (the cause is right there\n * in the message).\n */\nexport function shouldPromoteDebug(code: string): boolean {\n switch (code) {\n case 'INVALID_INPUT':\n case 'CONFIGURATION':\n case 'INVALID_USEROP':\n case 'INSUFFICIENT_FUNDS':\n case 'INSUFFICIENT_GAS':\n case 'INSUFFICIENT_SCOPE':\n return false;\n default:\n return true;\n }\n}\n","/**\n * `kash` — official command-line interface for the Kash public API.\n *\n * The binary is a thin wrapper over `@kashdao/sdk`. Every command\n * resolves its config (file → env), constructs a KashClient, and\n * defers to the SDK for the actual work. This file is only the\n * Commander wiring: registration, global flags, and the top-level\n * error boundary.\n *\n * **Cold-start strategy.** Plain `kash --version` and `kash -V` are the\n * single hottest invocation in CI/agent contexts (every health probe,\n * every doctor script). We short-circuit them before any of the\n * subcommand modules load — they pull `@kashdao/sdk`, `chalk`, `ora`,\n * etc., none of which `--version` needs. The full Commander tree is\n * built only when the user actually asks for a real command.\n */\n\nimport { isDebugOn, shouldPromoteDebug } from './utils/debug-hint.js';\nimport { CLI_VERSION } from './version.js';\n\n// ── SIGPIPE-safe stdout/stderr ──────────────────────────────────────\n//\n// `kash <cmd> | head` is a common shell pattern; without this guard,\n// when `head` closes the pipe early Node throws `EPIPE` from the next\n// `process.stdout.write`, which surfaces as exit code 1 — surprising\n// for users piping output into `head`/`less`/`column`. We treat\n// EPIPE / EIO as a clean exit (0): downstream told us to stop, we\n// stop. Any other write error still propagates so real I/O failures\n// aren't masked.\n//\n// Two listeners are needed:\n// 1. `'error'` on the streams catches EPIPE delivered as an event\n// (async writes / future flushes).\n// 2. `'uncaughtException'` catches EPIPE thrown synchronously by a\n// `process.stdout.write` call when the pipe is already closed —\n// this is what `head -c 5` triggers and the stream listener\n// doesn't see.\nfor (const stream of [process.stdout, process.stderr]) {\n stream.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE' || err.code === 'EIO') {\n process.exit(0);\n }\n throw err;\n });\n}\nprocess.on('uncaughtException', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE' || err.code === 'EIO') {\n process.exit(0);\n }\n // Re-throw so Node's default handler logs and exits with 1.\n throw err;\n});\n\n// ── Fast path: plain `--version` / `-V` ─────────────────────────────\n//\n// Short-circuits before commander, the SDK, and every command module\n// are imported. The structured `--version --json` path still needs\n// `buildVersionManifest` (which reads `os` info) and `printJson`, but\n// even those load lazily so the simpler `kash --version` only pays\n// for `version.js`.\nconst argv = process.argv;\nif (argv[2] === '--version' || argv[2] === '-V') {\n if (argv.slice(3).includes('--json')) {\n const [{ buildVersionManifest }, { printJson }] = await Promise.all([\n import('./commands/version.js'),\n import('./utils/output.js'),\n ]);\n printJson(buildVersionManifest());\n } else {\n process.stdout.write(`${CLI_VERSION}\\n`);\n }\n process.exit(0);\n}\n\n// ── Fast path: `kash --help --json` / `kash --json --help` ──────────\n//\n// Commander's default `--help` renderer emits human-formatted text —\n// useful for operators, useless for AI agents probing the surface.\n// When `--help` is paired with `--json` (any order, no other args),\n// route to the structured `kash docs --json --quiet` envelope. That's\n// the canonical machine-readable help and pinning to it keeps the\n// agent contract clean.\n//\n// We don't try to handle `kash <subcommand> --help --json` — those\n// fall through to Commander's text help, and the right answer for\n// agents is to fetch the full tree once via `kash docs --json` and\n// drill down.\n{\n const tail = argv.slice(2);\n const helpIdx = tail.indexOf('--help');\n const dashHIdx = tail.indexOf('-h');\n const hasHelp = helpIdx !== -1 || dashHIdx !== -1;\n const hasJson = tail.includes('--json');\n const hasOther = tail.some(\n (t) => t !== '--help' && t !== '-h' && t !== '--json' && t !== '--quiet'\n );\n if (hasHelp && hasJson && !hasOther) {\n // Use the existing docs command via its describeCommand walker.\n // We need a fully-built program to walk, so we let the eager\n // imports below run and handle this in the docs command's own\n // action. Mark it with the flag and let it fall through.\n process.argv = [argv[0]!, argv[1]!, 'docs', '--json'];\n if (tail.includes('--quiet')) process.argv.push('--quiet');\n }\n}\n\n// ── Friendly intro: `kash` (no args, optionally with --json) ─────────\n//\n// Default Commander behaviour for a no-args invocation is to dump\n// `--help`, which is overwhelming on first contact. Show a curated\n// landing instead. Detected by argv length: pure `kash`, `kash --json`,\n// or `kash --quiet` (with no other tokens) trip this path.\n//\n// **Quiet contracts.** CI environments and orchestrators that spawn\n// `kash` with no extra args shouldn't see decorative output. Honour\n// `--quiet`, `KASH_QUIET=1` (env mirror — same truthy parser as\n// `KASH_DEBUG`), and the de-facto-standard `NO_COLOR`/`CI` are\n// deliberately NOT included because they have unrelated semantics.\n// In quiet mode we exit 0 with no output at all — no JSON envelope\n// either, since a script triggering this path didn't ask for it.\n//\n// Anything else (`kash foo`, `kash --help`, `kash markets …`) falls\n// through to Commander as before.\nconst onlyArgs = argv.slice(2);\nconst isBareInvocation =\n onlyArgs.length === 0 ||\n (onlyArgs.length === 1 && (onlyArgs[0] === '--json' || onlyArgs[0] === '--quiet'));\nif (isBareInvocation) {\n const wantsJson = onlyArgs.includes('--json');\n const wantsQuiet = onlyArgs.includes('--quiet') || isTruthyEnv(process.env['KASH_QUIET']);\n\n // Quiet mode: emit nothing — neither the human banner nor the JSON\n // envelope. CI scripts that bare-invoke `kash` to test the binary\n // works don't need decorative output. (`--json` still wins if the\n // user is explicit about wanting structured output.)\n if (wantsQuiet && !wantsJson) {\n process.exit(0);\n }\n\n const { buildIntroEnvelope, INTRO_SUGGESTIONS, DOCS_URL } = await import('./utils/intro.js');\n if (wantsJson) {\n const { printJson } = await import('./utils/output.js');\n printJson(buildIntroEnvelope(CLI_VERSION));\n } else {\n const { print, style } = await import('./utils/output.js');\n print('');\n print(`${style.bold('kash')} ${style.dim(`v${CLI_VERSION}`)} — Kash prediction markets CLI`);\n print('');\n for (const s of INTRO_SUGGESTIONS) {\n print(` ${style.bold(s.title)}`);\n print(` ${style.cyan(s.command)}`);\n print(` ${style.dim(s.description)}`);\n print('');\n }\n print(\n `${style.dim('Run')} ${style.cyan('kash --help')} ${style.dim('for the full command list.')}`\n );\n print(`${style.dim('Docs:')} ${DOCS_URL}`);\n print('');\n }\n process.exit(0);\n}\n\n/**\n * Mirror of the `isTruthyEnv` helper in `utils/global-options.ts`.\n * Inlined here so the bare-invocation fast path doesn't pay for the\n * full import. Same truth values: `1`, `true`, `yes`, `on`\n * (case-insensitive). Empty string and `0` are falsy.\n */\nfunction isTruthyEnv(value: string | undefined): boolean {\n if (value === undefined) return false;\n const v = value.trim().toLowerCase();\n return v === '1' || v === 'true' || v === 'yes' || v === 'on';\n}\n\n// Eager imports below run only for invocations that actually need a\n// command. The SDK-heavy modules still load — Commander needs every\n// subcommand registered up-front to render `--help` correctly — but\n// individual commands lazy-load their own dependencies (`omelette`,\n// `zod-to-json-schema`, `@kashdao/protocol-sdk`, `viem`) inside their\n// action handlers.\nconst { Command } = await import('commander');\nconst { authCommand } = await import('./commands/auth/index.js');\nconst { configCommand } = await import('./commands/config/index.js');\nconst { buildDocsCommand } = await import('./commands/docs.js');\nconst { eoaCommand } = await import('./commands/eoa/index.js');\nconst { explainCommand } = await import('./commands/explain.js');\nconst { accountCommand } = await import('./commands/account/index.js');\nconst { healthCommand } = await import('./commands/health.js');\nconst { marketsCommand } = await import('./commands/markets/index.js');\nconst { portfolioCommand } = await import('./commands/portfolio/index.js');\nconst { protocolCommand } = await import('./commands/protocol/index.js');\nconst { quoteCommand } = await import('./commands/quote/index.js');\nconst { schemaCommand } = await import('./commands/schema.js');\nconst { setupCommand } = await import('./commands/setup.js');\nconst { traceCommand } = await import('./commands/trace.js');\nconst { tradeCommand } = await import('./commands/trade/index.js');\nconst { withRetryCommand } = await import('./commands/with-retry.js');\nconst { versionCommand } = await import('./commands/version.js');\nconst { webhooksCommand } = await import('./commands/webhooks/index.js');\nconst { createCompletionCommand, initCompletion } = await import('./completion.js');\nconst { EXIT_CODES, toCliError } = await import('./errors.js');\nconst { readGlobals } = await import('./utils/global-options.js');\nconst { configureOutput, log, printJson } = await import('./utils/output.js');\n\nimport type { CliError } from './errors.js';\n\nconst program = new Command();\n\nprogram\n .name('kash')\n .description('Official command-line interface for the Kash public API.')\n .version(CLI_VERSION, '-V, --version', 'output the CLI version')\n // Output controls\n .option('--json', 'emit machine-readable JSON instead of human-formatted output', false)\n .option(\n '--quiet',\n 'suppress spinners, progress, informational logs, AND human-mode tables (pair with --json — bare --quiet on a list/get command produces no stdout at all by design)',\n false\n )\n .option('--no-color', 'disable ANSI color in human-mode output')\n .option(\n '--debug',\n 'emit SDK request/response/retry/error traces to stderr; pairs with --json for NDJSON traces',\n false\n )\n // Config selection\n .option(\n '-p, --profile <name>',\n 'pick a named profile from ~/.kash/config.json (overrides KASH_PROFILE)'\n )\n .option(\n '--config <path>',\n 'use an explicit config file path instead of ~/.kash/config.json (overrides KASH_CONFIG)'\n )\n // SDK overrides — useful for staging tests, CI matrix builds, agent retry tuning\n .option('--base-url <url>', 'override the API base URL for this invocation only')\n .option('--max-retries <n>', 'override the SDK retry budget for this invocation only')\n .option('--timeout-ms <n>', 'override the SDK request timeout (ms) for this invocation only')\n .option(\n '--api-version <date>',\n \"pin against a public-API contract date (sent as 'X-Kash-Api-Version: <date>'). \" +\n 'Omit to let the server use its canonical default.'\n )\n // Output projection — applied only on --json/--ndjson output\n .option(\n '--fields <list>',\n 'comma-separated dot-paths to project on JSON output (e.g. id,title,outcomes.label)'\n )\n .option(\n '--filter <expr>',\n \"boolean predicate on JSON entries (e.g. 'status==ACTIVE && outcomeCount>2')\"\n )\n .hook('preAction', (thisCommand) => {\n const globals = readGlobals(thisCommand);\n configureOutput({\n quiet: globals.quiet,\n noColor: globals.noColor,\n fields: globals.fields,\n filter: globals.filter,\n });\n })\n .addHelpText(\n 'after',\n `\nCommon workflows:\n First-time setup kash setup\n Switch / inspect profile kash su <name>\n Browse markets kash markets list --status ACTIVE\n Place a trade and wait kash trade buy <id> --outcome 0 --amount 10 --wait\n Inspect portfolio kash portfolio show && kash portfolio positions\n\nFor AI agents:\n Universal agent mode kash <any-command> --json --quiet\n Discover all commands kash docs --json --quiet\n Get a request schema kash schema CreateTradeBody --json\n Recover from an error kash explain RATE_LIMITED --json\n Stream paginated reads kash markets list --ndjson\n\nExit codes:\n 0 success\n 1 generic error (validation, server, network, …)\n 2 auth failure (missing or invalid API key, missing scope)\n\nRun \\`kash <command> --help\\` for command-specific help and examples.\nDocs: https://kash.bot/docs/cli\n`\n );\n\n// Hand control of Commander's exit behaviour to our top-level error\n// boundary. Without this, Commander calls `process.exit(1)` directly\n// on unknown commands / unknown options, skipping our structured\n// error envelope. With `exitOverride`, Commander throws a\n// `CommanderError` we can map to a `CliError` (see `toCliError` in\n// errors.ts).\n//\n// Help and version short-circuits still get filtered there — they\n// surface as `commander.help`/`commander.helpDisplayed`/`commander.version`\n// codes which the mapper detects and treats as clean exits.\nprogram.exitOverride();\n\n// Register top-level command groups.\nprogram.addCommand(authCommand);\nprogram.addCommand(accountCommand);\nprogram.addCommand(marketsCommand);\nprogram.addCommand(quoteCommand);\nprogram.addCommand(tradeCommand);\nprogram.addCommand(portfolioCommand);\nprogram.addCommand(protocolCommand);\nprogram.addCommand(eoaCommand);\nprogram.addCommand(webhooksCommand);\nprogram.addCommand(configCommand);\nprogram.addCommand(healthCommand);\nprogram.addCommand(versionCommand);\nprogram.addCommand(explainCommand);\nprogram.addCommand(schemaCommand);\nprogram.addCommand(setupCommand);\nprogram.addCommand(traceCommand);\nprogram.addCommand(withRetryCommand);\nprogram.addCommand(buildDocsCommand(() => program));\nprogram.addCommand(createCompletionCommand());\n\n// Append a per-command \"More: <docs-url>\" footer to every top-level\n// `--help` page. Done after every command is registered so we walk\n// the fully-populated tree once.\nconst { attachDocsFooters } = await import('./utils/help-footer.js');\nattachDocsFooters(program);\n\n// Initialize shell completion before parseAsync — omelette needs to\n// see the args first to detect a completion request. Now async because\n// `initCompletion` lazy-imports omelette only when the args look like\n// a completion handshake.\nawait initCompletion();\n\ntry {\n await program.parseAsync(process.argv);\n // Let Node exit naturally on success so any buffered stdout writes\n // (NDJSON streams, large `--all` exports through a pipe) flush\n // cleanly. Calling `process.exit` here would truncate the buffer\n // when stdout is connected to a slow consumer. The error path\n // still calls `process.exit` because we want a deterministic exit\n // code; data loss isn't a concern when we already failed.\n} catch (rawError) {\n const error = toCliError(rawError);\n // Clean exits (e.g. `--help` and `--version` short-circuits surfaced\n // via Commander's `exitOverride`) bypass the error renderer — they\n // already wrote their output to stdout and there's nothing to add.\n if (error.code === 'NOOP' && error.exitCode === EXIT_CODES.OK) {\n process.exit(0);\n }\n emitError(error);\n process.exit(error.exitCode);\n}\n\n/**\n * Render the error using whichever output mode is currently active.\n * In JSON mode we stay machine-readable so an AI agent can branch on\n * `code` without parsing prose; in human mode we surface the\n * suggestion (when available) and the request id (when available).\n *\n * `readGlobals` itself can throw when a flag value is malformed\n * (`--base-url not-a-url`, `--max-retries 99`). On the error path\n * we shouldn't double-throw — fall back to a minimal mode (sniff the\n * raw argv for `--json` / `--quiet`) so the original error is still\n * surfaced cleanly.\n */\nfunction emitError(error: CliError): void {\n const json = safeReadJsonFlag();\n if (json) {\n printJson(error.toEnvelope());\n return;\n }\n log.error(`[${error.code}] ${error.message}`);\n if (error.suggestion) {\n log.detail('Suggestion', error.suggestion);\n }\n if (error.retryAfterMs !== undefined) {\n log.detail('Retry after', `${String(Math.round(error.retryAfterMs / 1000))}s`);\n }\n if (error.docsUrl) {\n log.detail('Docs', error.docsUrl);\n }\n if (error.requestId) {\n log.detail('Request ID', error.requestId);\n }\n // Always promote the explainer for the structured-actions catalog —\n // it's the deepest source of recovery info the CLI ships with and\n // every catalog entry has a `kash explain CODE` payload. Skipped\n // when the code itself isn't in the catalog (UNEXPECTED, etc.) to\n // avoid pointing the user at an empty page.\n if (error.code !== 'UNEXPECTED') {\n log.detail('More', `kash explain ${error.code}`);\n }\n // For non-trivial failures, surface --debug as the next-step lever.\n // It enables verbose request/response logging on the SDK's HTTP\n // path — the natural diagnostic when an error keeps recurring.\n // Skipped when --debug is already on (don't suggest what they're\n // already doing) and on plain validation errors (the user needs to\n // fix input, not log more bytes).\n if (!isDebugOn(process.argv, process.env) && shouldPromoteDebug(error.code)) {\n log.detail('Debug', 'Re-run with --debug for verbose HTTP logs.');\n }\n}\n\n/**\n * Inspect the raw argv for `--json` without re-running validation —\n * used on the error path so a malformed flag value (which is what\n * triggered the error in the first place) doesn't double-throw and\n * obscure the original failure.\n */\nfunction safeReadJsonFlag(): boolean {\n return process.argv.slice(2).includes('--json');\n}\n"],"mappings":";;;;;;AAqBA,SAAS,YAAY,OAAoC;AACvD,MAAI,UAAU,OAAW,QAAO;AAChC,QAAM,IAAI,MAAM,KAAK,EAAE,YAAY;AACnC,SAAO,MAAM,OAAO,MAAM,UAAU,MAAM,SAAS,MAAM;AAC3D;AAiBO,SAAS,UACdA,QAA0B,QAAQ,MAClC,MAAyB,QAAQ,KACxB;AACT,SAAOA,MAAK,MAAM,CAAC,EAAE,SAAS,SAAS,KAAK,YAAY,IAAI,YAAY,CAAC;AAC3E;AAQO,SAAS,mBAAmB,MAAuB;AACxD,UAAQ,MAAM;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAAA,IACL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OAAO;AAAA,EAClC;AACA,MAAI,MAAM,WAAW;AACnB,QAAI,OAAO,cAAc,MAAM,SAAS;AAAA,EAC1C;AAMA,MAAI,MAAM,SAAS,cAAc;AAC/B,QAAI,OAAO,QAAQ,gBAAgB,MAAM,IAAI,EAAE;AAAA,EACjD;AAOA,MAAI,CAAC,UAAU,QAAQ,MAAM,QAAQ,GAAG,KAAK,mBAAmB,MAAM,IAAI,GAAG;AAC3E,QAAI,OAAO,SAAS,4CAA4C;AAAA,EAClE;AACF;AAQA,SAAS,mBAA4B;AACnC,SAAO,QAAQ,KAAK,MAAM,CAAC,EAAE,SAAS,QAAQ;AAChD;","names":["argv","printJson","isTruthyEnv"]}
1
+ {"version":3,"sources":["../src/utils/debug-hint.ts","../src/index.ts"],"sourcesContent":["/**\n * Helpers for the \"Re-run with --debug for verbose HTTP logs\" hint\n * emitted on the error path in `src/index.ts`.\n *\n * Factored out of `src/index.ts` so the helpers are unit-testable —\n * `index.ts` is the CLI entry point and runs Commander at module load,\n * so importing it from a test triggers `process.exit`.\n */\n\n/**\n * Recognise truthy env values the way every other tool does: `1`,\n * `true`, `yes`, `on` (case-insensitive). Empty string and `0` are\n * falsy. Anything else is a no-op rather than an error — env\n * pollution is common and shouldn't fail builds.\n *\n * Local copy of the same helper that lives in `utils/global-options.ts`\n * — kept in sync intentionally; the two MUST agree on what counts as\n * \"debug on\" or the UX gets confusing (readGlobals decides \"is\n * --debug active?\" via isTruthyEnv, and the error path's hint decides\n * \"should I suggest --debug?\" via the same rule).\n */\nfunction isTruthyEnv(value: string | undefined): boolean {\n if (value === undefined) return false;\n const v = value.trim().toLowerCase();\n return v === '1' || v === 'true' || v === 'yes' || v === 'on';\n}\n\n/**\n * \"Is debug already on?\" — used on the error path to decide whether to\n * promote `--debug` as a next-step hint. Mirrors readGlobals'\n * resolution: either the `--debug` flag is in argv, or `KASH_DEBUG`\n * is a *truthy* value per the shared `isTruthyEnv` rule.\n *\n * Critical: a bare presence check on `KASH_DEBUG` would mistakenly\n * skip the hint when the user has `KASH_DEBUG=0` / `=false` / `=no`\n * set — those env values do NOT enable debug mode in readGlobals,\n * so the hint should still fire. The two resolution paths must\n * agree or the UX gets confused.\n *\n * Pure inputs → pure output; safe to invoke with synthetic argv/env\n * in unit tests without touching `process`.\n */\nexport function isDebugOn(\n argv: readonly string[] = process.argv,\n env: NodeJS.ProcessEnv = process.env\n): boolean {\n return argv.slice(2).includes('--debug') || isTruthyEnv(env['KASH_DEBUG']);\n}\n\n/**\n * Promote `--debug` for codes where verbose HTTP logs help — anything\n * the operator can't fix by changing input. Validation / config /\n * input errors don't benefit from more logs (the cause is right there\n * in the message).\n */\nexport function shouldPromoteDebug(code: string): boolean {\n switch (code) {\n case 'INVALID_INPUT':\n case 'CONFIGURATION':\n case 'INVALID_USEROP':\n case 'INSUFFICIENT_FUNDS':\n case 'INSUFFICIENT_GAS':\n case 'INSUFFICIENT_SCOPE':\n return false;\n default:\n return true;\n }\n}\n","/**\n * `kash` — official command-line interface for the Kash public API.\n *\n * The binary is a thin wrapper over `@kashdao/sdk`. Every command\n * resolves its config (file → env), constructs a KashClient, and\n * defers to the SDK for the actual work. This file is only the\n * Commander wiring: registration, global flags, and the top-level\n * error boundary.\n *\n * **Cold-start strategy.** Plain `kash --version` and `kash -V` are the\n * single hottest invocation in CI/agent contexts (every health probe,\n * every doctor script). We short-circuit them before any of the\n * subcommand modules load — they pull `@kashdao/sdk`, `chalk`, `ora`,\n * etc., none of which `--version` needs. The full Commander tree is\n * built only when the user actually asks for a real command.\n */\n\nimport { isDebugOn, shouldPromoteDebug } from './utils/debug-hint.js';\nimport { CLI_VERSION } from './version.js';\n\n// ── SIGPIPE-safe stdout/stderr ──────────────────────────────────────\n//\n// `kash <cmd> | head` is a common shell pattern; without this guard,\n// when `head` closes the pipe early Node throws `EPIPE` from the next\n// `process.stdout.write`, which surfaces as exit code 1 — surprising\n// for users piping output into `head`/`less`/`column`. We treat\n// EPIPE / EIO as a clean exit (0): downstream told us to stop, we\n// stop. Any other write error still propagates so real I/O failures\n// aren't masked.\n//\n// Two listeners are needed:\n// 1. `'error'` on the streams catches EPIPE delivered as an event\n// (async writes / future flushes).\n// 2. `'uncaughtException'` catches EPIPE thrown synchronously by a\n// `process.stdout.write` call when the pipe is already closed —\n// this is what `head -c 5` triggers and the stream listener\n// doesn't see.\nfor (const stream of [process.stdout, process.stderr]) {\n stream.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE' || err.code === 'EIO') {\n process.exit(0);\n }\n throw err;\n });\n}\nprocess.on('uncaughtException', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE' || err.code === 'EIO') {\n process.exit(0);\n }\n // Re-throw so Node's default handler logs and exits with 1.\n throw err;\n});\n\n// ── Fast path: plain `--version` / `-V` ─────────────────────────────\n//\n// Short-circuits before commander, the SDK, and every command module\n// are imported. The structured `--version --json` path still needs\n// `buildVersionManifest` (which reads `os` info) and `printJson`, but\n// even those load lazily so the simpler `kash --version` only pays\n// for `version.js`.\nconst argv = process.argv;\nif (argv[2] === '--version' || argv[2] === '-V') {\n if (argv.slice(3).includes('--json')) {\n const [{ buildVersionManifest }, { printJson }] = await Promise.all([\n import('./commands/version.js'),\n import('./utils/output.js'),\n ]);\n printJson(buildVersionManifest());\n } else {\n process.stdout.write(`${CLI_VERSION}\\n`);\n }\n process.exit(0);\n}\n\n// ── Fast path: `kash --help --json` / `kash --json --help` ──────────\n//\n// Commander's default `--help` renderer emits human-formatted text —\n// useful for operators, useless for AI agents probing the surface.\n// When `--help` is paired with `--json` (any order, no other args),\n// route to the structured `kash docs --json --quiet` envelope. That's\n// the canonical machine-readable help and pinning to it keeps the\n// agent contract clean.\n//\n// We don't try to handle `kash <subcommand> --help --json` — those\n// fall through to Commander's text help, and the right answer for\n// agents is to fetch the full tree once via `kash docs --json` and\n// drill down.\n{\n const tail = argv.slice(2);\n const helpIdx = tail.indexOf('--help');\n const dashHIdx = tail.indexOf('-h');\n const hasHelp = helpIdx !== -1 || dashHIdx !== -1;\n const hasJson = tail.includes('--json');\n const hasOther = tail.some(\n (t) => t !== '--help' && t !== '-h' && t !== '--json' && t !== '--quiet'\n );\n if (hasHelp && hasJson && !hasOther) {\n // Use the existing docs command via its describeCommand walker.\n // We need a fully-built program to walk, so we let the eager\n // imports below run and handle this in the docs command's own\n // action. Mark it with the flag and let it fall through.\n process.argv = [argv[0]!, argv[1]!, 'docs', '--json'];\n if (tail.includes('--quiet')) process.argv.push('--quiet');\n }\n}\n\n// ── Friendly intro: `kash` (no args, optionally with --json) ─────────\n//\n// Default Commander behaviour for a no-args invocation is to dump\n// `--help`, which is overwhelming on first contact. Show a curated\n// landing instead. Detected by argv length: pure `kash`, `kash --json`,\n// or `kash --quiet` (with no other tokens) trip this path.\n//\n// **Quiet contracts.** CI environments and orchestrators that spawn\n// `kash` with no extra args shouldn't see decorative output. Honour\n// `--quiet`, `KASH_QUIET=1` (env mirror — same truthy parser as\n// `KASH_DEBUG`), and the de-facto-standard `NO_COLOR`/`CI` are\n// deliberately NOT included because they have unrelated semantics.\n// In quiet mode we exit 0 with no output at all — no JSON envelope\n// either, since a script triggering this path didn't ask for it.\n//\n// Anything else (`kash foo`, `kash --help`, `kash markets …`) falls\n// through to Commander as before.\nconst onlyArgs = argv.slice(2);\nconst isBareInvocation =\n onlyArgs.length === 0 ||\n (onlyArgs.length === 1 && (onlyArgs[0] === '--json' || onlyArgs[0] === '--quiet'));\nif (isBareInvocation) {\n const wantsJson = onlyArgs.includes('--json');\n const wantsQuiet = onlyArgs.includes('--quiet') || isTruthyEnv(process.env['KASH_QUIET']);\n\n // Quiet mode: emit nothing — neither the human banner nor the JSON\n // envelope. CI scripts that bare-invoke `kash` to test the binary\n // works don't need decorative output. (`--json` still wins if the\n // user is explicit about wanting structured output.)\n if (wantsQuiet && !wantsJson) {\n process.exit(0);\n }\n\n const { buildIntroEnvelope, INTRO_SUGGESTIONS, DOCS_URL } = await import('./utils/intro.js');\n if (wantsJson) {\n const { printJson } = await import('./utils/output.js');\n printJson(buildIntroEnvelope(CLI_VERSION));\n } else {\n const { print, style } = await import('./utils/output.js');\n print('');\n print(`${style.bold('kash')} ${style.dim(`v${CLI_VERSION}`)} — Kash prediction markets CLI`);\n print('');\n for (const s of INTRO_SUGGESTIONS) {\n print(` ${style.bold(s.title)}`);\n print(` ${style.cyan(s.command)}`);\n print(` ${style.dim(s.description)}`);\n print('');\n }\n print(\n `${style.dim('Run')} ${style.cyan('kash --help')} ${style.dim('for the full command list.')}`\n );\n print(`${style.dim('Docs:')} ${DOCS_URL}`);\n print('');\n }\n process.exit(0);\n}\n\n/**\n * Mirror of the `isTruthyEnv` helper in `utils/global-options.ts`.\n * Inlined here so the bare-invocation fast path doesn't pay for the\n * full import. Same truth values: `1`, `true`, `yes`, `on`\n * (case-insensitive). Empty string and `0` are falsy.\n */\nfunction isTruthyEnv(value: string | undefined): boolean {\n if (value === undefined) return false;\n const v = value.trim().toLowerCase();\n return v === '1' || v === 'true' || v === 'yes' || v === 'on';\n}\n\n// Eager imports below run only for invocations that actually need a\n// command. The SDK-heavy modules still load — Commander needs every\n// subcommand registered up-front to render `--help` correctly — but\n// individual commands lazy-load their own dependencies (`omelette`,\n// `zod-to-json-schema`, `@kashdao/protocol-sdk`, `viem`) inside their\n// action handlers.\nconst { Command } = await import('commander');\nconst { SDK_API_VERSION } = await import('@kashdao/sdk');\nconst { authCommand } = await import('./commands/auth/index.js');\nconst { configCommand } = await import('./commands/config/index.js');\nconst { buildDocsCommand } = await import('./commands/docs.js');\nconst { eoaCommand } = await import('./commands/eoa/index.js');\nconst { explainCommand } = await import('./commands/explain.js');\nconst { accountCommand } = await import('./commands/account/index.js');\nconst { healthCommand } = await import('./commands/health.js');\nconst { marketsCommand } = await import('./commands/markets/index.js');\nconst { portfolioCommand } = await import('./commands/portfolio/index.js');\nconst { protocolCommand } = await import('./commands/protocol/index.js');\nconst { quoteCommand } = await import('./commands/quote/index.js');\nconst { redeemCommand } = await import('./commands/redeem.js');\nconst { schemaCommand } = await import('./commands/schema.js');\nconst { setupCommand } = await import('./commands/setup.js');\nconst { traceCommand } = await import('./commands/trace.js');\nconst { tradeCommand } = await import('./commands/trade/index.js');\nconst { withRetryCommand } = await import('./commands/with-retry.js');\nconst { versionCommand } = await import('./commands/version.js');\nconst { webhooksCommand } = await import('./commands/webhooks/index.js');\nconst { createCompletionCommand, initCompletion } = await import('./completion.js');\nconst { EXIT_CODES, toCliError } = await import('./errors.js');\nconst { readGlobals } = await import('./utils/global-options.js');\nconst { configureOutput, log, printJson } = await import('./utils/output.js');\n\nimport type { CliError } from './errors.js';\n\nconst program = new Command();\n\nprogram\n .name('kash')\n .description('Official command-line interface for the Kash public API.')\n .version(CLI_VERSION, '-V, --version', 'output the CLI version')\n // Output controls\n .option('--json', 'emit machine-readable JSON instead of human-formatted output', false)\n .option(\n '--quiet',\n 'suppress spinners, progress, informational logs, AND human-mode tables (pair with --json — bare --quiet on a list/get command produces no stdout at all by design)',\n false\n )\n .option('--no-color', 'disable ANSI color in human-mode output')\n .option(\n '--debug',\n 'emit SDK request/response/retry/error traces to stderr; pairs with --json for NDJSON traces',\n false\n )\n // Config selection\n .option(\n '-p, --profile <name>',\n 'pick a named profile from ~/.kash/config.json (overrides KASH_PROFILE)'\n )\n .option(\n '--config <path>',\n 'use an explicit config file path instead of ~/.kash/config.json (overrides KASH_CONFIG)'\n )\n // SDK overrides — useful for staging tests, CI matrix builds, agent retry tuning\n .option('--base-url <url>', 'override the API base URL for this invocation only')\n .option('--max-retries <n>', 'override the SDK retry budget for this invocation only')\n .option('--timeout-ms <n>', 'override the SDK request timeout (ms) for this invocation only')\n .option(\n '--api-version <date>',\n \"pin against a public-API contract date (sent as 'X-Kash-Api-Version: <date>'). \" +\n `Overrides the profile's apiVersion and KASH_API_VERSION (default ${SDK_API_VERSION}).`\n )\n // Output projection — applied only on --json/--ndjson output\n .option(\n '--fields <list>',\n 'comma-separated dot-paths to project on JSON output (e.g. id,title,outcomes.label)'\n )\n .option(\n '--filter <expr>',\n \"boolean predicate on JSON entries (e.g. 'status==ACTIVE && outcomeCount>2')\"\n )\n .hook('preAction', (thisCommand) => {\n const globals = readGlobals(thisCommand);\n configureOutput({\n quiet: globals.quiet,\n noColor: globals.noColor,\n fields: globals.fields,\n filter: globals.filter,\n });\n })\n .addHelpText(\n 'after',\n `\nCommon workflows:\n First-time setup kash setup\n Switch / inspect profile kash su <name>\n Browse markets kash markets list --status ACTIVE\n Place a trade and wait kash trade buy <id> --outcome 0 --amount 10 --wait\n Inspect portfolio kash portfolio show && kash portfolio positions\n\nFor AI agents:\n Universal agent mode kash <any-command> --json --quiet\n Discover all commands kash docs --json --quiet\n Get a request schema kash schema CreateTradeBody --json\n Recover from an error kash explain RATE_LIMITED --json\n Stream paginated reads kash markets list --ndjson\n\nExit codes:\n 0 success\n 1 generic error (validation, server, network, …)\n 2 auth failure (missing or invalid API key, missing scope)\n\nRun \\`kash <command> --help\\` for command-specific help and examples.\nDocs: https://kash.bot/docs/cli\n`\n );\n\n// Hand control of Commander's exit behaviour to our top-level error\n// boundary. Without this, Commander calls `process.exit(1)` directly\n// on unknown commands / unknown options, skipping our structured\n// error envelope. With `exitOverride`, Commander throws a\n// `CommanderError` we can map to a `CliError` (see `toCliError` in\n// errors.ts).\n//\n// Help and version short-circuits still get filtered there — they\n// surface as `commander.help`/`commander.helpDisplayed`/`commander.version`\n// codes which the mapper detects and treats as clean exits.\nprogram.exitOverride();\n\n// Register top-level command groups.\nprogram.addCommand(authCommand);\nprogram.addCommand(accountCommand);\nprogram.addCommand(marketsCommand);\nprogram.addCommand(quoteCommand);\nprogram.addCommand(tradeCommand);\nprogram.addCommand(redeemCommand);\nprogram.addCommand(portfolioCommand);\nprogram.addCommand(protocolCommand);\nprogram.addCommand(eoaCommand);\nprogram.addCommand(webhooksCommand);\nprogram.addCommand(configCommand);\nprogram.addCommand(healthCommand);\nprogram.addCommand(versionCommand);\nprogram.addCommand(explainCommand);\nprogram.addCommand(schemaCommand);\nprogram.addCommand(setupCommand);\nprogram.addCommand(traceCommand);\nprogram.addCommand(withRetryCommand);\nprogram.addCommand(buildDocsCommand(() => program));\nprogram.addCommand(createCompletionCommand());\n\n// Append a per-command \"More: <docs-url>\" footer to every top-level\n// `--help` page. Done after every command is registered so we walk\n// the fully-populated tree once.\nconst { attachDocsFooters } = await import('./utils/help-footer.js');\nattachDocsFooters(program);\n\n// Initialize shell completion before parseAsync — omelette needs to\n// see the args first to detect a completion request. Now async because\n// `initCompletion` lazy-imports omelette only when the args look like\n// a completion handshake.\nawait initCompletion();\n\ntry {\n await program.parseAsync(process.argv);\n // Let Node exit naturally on success so any buffered stdout writes\n // (NDJSON streams, large `--all` exports through a pipe) flush\n // cleanly. Calling `process.exit` here would truncate the buffer\n // when stdout is connected to a slow consumer. The error path\n // still calls `process.exit` because we want a deterministic exit\n // code; data loss isn't a concern when we already failed.\n} catch (rawError) {\n const error = toCliError(rawError);\n // Clean exits (e.g. `--help` and `--version` short-circuits surfaced\n // via Commander's `exitOverride`) bypass the error renderer — they\n // already wrote their output to stdout and there's nothing to add.\n if (error.code === 'NOOP' && error.exitCode === EXIT_CODES.OK) {\n process.exit(0);\n }\n emitError(error);\n process.exit(error.exitCode);\n}\n\n/**\n * Render the error using whichever output mode is currently active.\n * In JSON mode we stay machine-readable so an AI agent can branch on\n * `code` without parsing prose; in human mode we surface the\n * suggestion (when available) and the request id (when available).\n *\n * `readGlobals` itself can throw when a flag value is malformed\n * (`--base-url not-a-url`, `--max-retries 99`). On the error path\n * we shouldn't double-throw — fall back to a minimal mode (sniff the\n * raw argv for `--json` / `--quiet`) so the original error is still\n * surfaced cleanly.\n */\nfunction emitError(error: CliError): void {\n const json = safeReadJsonFlag();\n if (json) {\n printJson(error.toEnvelope());\n return;\n }\n log.error(`[${error.code}] ${error.message}`);\n if (error.suggestion) {\n log.detail('Suggestion', error.suggestion);\n }\n if (error.retryAfterMs !== undefined) {\n log.detail('Retry after', `${String(Math.round(error.retryAfterMs / 1000))}s`);\n }\n if (error.docsUrl) {\n log.detail('Docs', error.docsUrl);\n }\n if (error.requestId) {\n log.detail('Request ID', error.requestId);\n }\n // Always promote the explainer for the structured-actions catalog —\n // it's the deepest source of recovery info the CLI ships with and\n // every catalog entry has a `kash explain CODE` payload. Skipped\n // when the code itself isn't in the catalog (UNEXPECTED, etc.) to\n // avoid pointing the user at an empty page.\n if (error.code !== 'UNEXPECTED') {\n log.detail('More', `kash explain ${error.code}`);\n }\n // For non-trivial failures, surface --debug as the next-step lever.\n // It enables verbose request/response logging on the SDK's HTTP\n // path — the natural diagnostic when an error keeps recurring.\n // Skipped when --debug is already on (don't suggest what they're\n // already doing) and on plain validation errors (the user needs to\n // fix input, not log more bytes).\n if (!isDebugOn(process.argv, process.env) && shouldPromoteDebug(error.code)) {\n log.detail('Debug', 'Re-run with --debug for verbose HTTP logs.');\n }\n}\n\n/**\n * Inspect the raw argv for `--json` without re-running validation —\n * used on the error path so a malformed flag value (which is what\n * triggered the error in the first place) doesn't double-throw and\n * obscure the original failure.\n */\nfunction safeReadJsonFlag(): boolean {\n return process.argv.slice(2).includes('--json');\n}\n"],"mappings":";;;;;;AAqBA,SAAS,YAAY,OAAoC;AACvD,MAAI,UAAU,OAAW,QAAO;AAChC,QAAM,IAAI,MAAM,KAAK,EAAE,YAAY;AACnC,SAAO,MAAM,OAAO,MAAM,UAAU,MAAM,SAAS,MAAM;AAC3D;AAiBO,SAAS,UACdA,QAA0B,QAAQ,MAClC,MAAyB,QAAQ,KACxB;AACT,SAAOA,MAAK,MAAM,CAAC,EAAE,SAAS,SAAS,KAAK,YAAY,IAAI,YAAY,CAAC;AAC3E;AAQO,SAAS,mBAAmB,MAAuB;AACxD,UAAQ,MAAM;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;;;AC9BA,WAAW,U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AAO,QAAQ,MAAM,OAAO;AAAA,EAClC;AACA,MAAI,MAAM,WAAW;AACnB,QAAI,OAAO,cAAc,MAAM,SAAS;AAAA,EAC1C;AAMA,MAAI,MAAM,SAAS,cAAc;AAC/B,QAAI,OAAO,QAAQ,gBAAgB,MAAM,IAAI,EAAE;AAAA,EACjD;AAOA,MAAI,CAAC,UAAU,QAAQ,MAAM,QAAQ,GAAG,KAAK,mBAAmB,MAAM,IAAI,GAAG;AAC3E,QAAI,OAAO,SAAS,4CAA4C;AAAA,EAClE;AACF;AAQA,SAAS,mBAA4B;AACnC,SAAO,QAAQ,KAAK,MAAM,CAAC,EAAE,SAAS,QAAQ;AAChD;","names":["argv","printJson","isTruthyEnv"]}
@@ -7,31 +7,33 @@ import {
7
7
  formatProbability,
8
8
  shortId,
9
9
  truncate
10
- } from "./chunk-R4NGUZKN.js";
10
+ } from "./chunk-6UU43MF5.js";
11
11
  import {
12
12
  buildClient
13
- } from "./chunk-QALDZHTX.js";
14
- import "./chunk-N26VGVGB.js";
13
+ } from "./chunk-H2QGFDZP.js";
14
+ import {
15
+ marketChainLabel
16
+ } from "./chunk-ZSMI63N3.js";
15
17
  import {
16
18
  parseOutcomeIndex
17
- } from "./chunk-BVFDUI73.js";
18
- import "./chunk-KAM6KOFD.js";
19
+ } from "./chunk-2SR77BYA.js";
20
+ import "./chunk-6QSTFU4R.js";
19
21
  import {
20
22
  parsePositiveInt,
21
23
  readGlobals
22
- } from "./chunk-A3IH5HUV.js";
24
+ } from "./chunk-AROIP4EQ.js";
23
25
  import {
24
26
  log,
25
27
  print,
26
28
  printJson,
27
29
  style,
28
30
  writeNdjson
29
- } from "./chunk-MQUJG224.js";
30
- import "./chunk-KADB3OKE.js";
31
+ } from "./chunk-2HFKULGG.js";
32
+ import "./chunk-VFBQVUL4.js";
31
33
  import {
32
34
  CliValidationError,
33
35
  toCliError
34
- } from "./chunk-X2VM6VKM.js";
36
+ } from "./chunk-WL7XUYPH.js";
35
37
 
36
38
  // src/commands/markets/index.ts
37
39
  import { Command as Command4 } from "commander";
@@ -64,7 +66,7 @@ Examples:
64
66
  print(`${style.bold(market.title ?? "(untitled)")}`);
65
67
  print(` ${style.dim("ID ")} ${market.id}`);
66
68
  print(` ${style.dim("Contract ")} ${formatAddress(market.contractAddress)}`);
67
- print(` ${style.dim("Chain ")} ${String(market.chainId)}`);
69
+ print(` ${style.dim("Chain ")} ${marketChainLabel(market)}`);
68
70
  print(` ${style.dim("Status ")} ${colorStatus(market.status ?? "UNKNOWN")}`);
69
71
  print(` ${style.dim("Outcomes ")} ${String(market.outcomeCount)}`);
70
72
  print(` ${style.dim("Created ")} ${formatDate(market.createdAt)}`);
@@ -163,7 +165,15 @@ Notes:
163
165
  }
164
166
  });
165
167
  function renderTable(markets) {
166
- const table = createTable(["ID", "Title", "Status", "Outcomes", "Top outcome", "Created"]);
168
+ const table = createTable([
169
+ "ID",
170
+ "Title",
171
+ "Chain",
172
+ "Status",
173
+ "Outcomes",
174
+ "Top outcome",
175
+ "Created"
176
+ ]);
167
177
  for (const market of markets) {
168
178
  const outcomes = market.outcomes;
169
179
  const top = outcomes.reduce((acc, current) => {
@@ -173,6 +183,7 @@ function renderTable(markets) {
173
183
  table.push([
174
184
  shortId(market.id),
175
185
  truncate(market.title ?? "(untitled)", 42),
186
+ marketChainLabel(market),
176
187
  colorStatus(market.status ?? "UNKNOWN"),
177
188
  String(market.outcomeCount),
178
189
  top ? `${truncate(top.label, 18)} (${formatProbability(top.probability)})` : "-",
@@ -292,4 +303,4 @@ var marketsCommand = new Command4("markets").description("List and inspect predi
292
303
  export {
293
304
  marketsCommand
294
305
  };
295
- //# sourceMappingURL=markets-H6EK2XDE.js.map
306
+ //# sourceMappingURL=markets-AGL6Q2ES.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/markets/index.ts","../src/commands/markets/get.ts","../src/commands/markets/list.ts","../src/commands/markets/predictions.ts"],"sourcesContent":["/**\n * `kash markets` — read-only market queries.\n *\n * Subcommands: `list`, `get`, `predictions`. All require an API key\n * with `markets:read` scope (granted by default on every tier). Quotes\n * are a separate command group (`kash quote buy|sell`) under the\n * `markets:quote` scope, split so customers can throttle RPC-heavy\n * quote traffic independently from cheap market reads.\n */\n\nimport { Command } from 'commander';\n\nimport { getMarketCommand } from './get.js';\nimport { listMarketsCommand } from './list.js';\nimport { predictionsCommand } from './predictions.js';\n\nexport const marketsCommand = new Command('markets')\n .description('List and inspect prediction markets.')\n .addCommand(listMarketsCommand)\n .addCommand(getMarketCommand)\n .addCommand(predictionsCommand);\n","/**\n * `kash markets get <id>` — fetch a single market.\n */\n\nimport { Command } from 'commander';\n\nimport { toCliError } from '../../errors.js';\nimport { marketChainLabel } from '../../utils/chain.js';\nimport { buildClient } from '../../utils/client.js';\nimport {\n colorStatus,\n createTable,\n formatAddress,\n formatDate,\n formatProbability,\n} from '../../utils/formatting.js';\nimport { readGlobals } from '../../utils/global-options.js';\nimport { print, printJson, style } from '../../utils/output.js';\n\nexport const getMarketCommand = new Command('get')\n .description('Fetch a single market by id.')\n .argument('<id>', 'market UUID')\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash markets get 9f0b...\n $ kash markets get 9f0b... --json | jq '.outcomes'\n $ kash markets get 9f0b... --json --quiet | jq -r '.outcomes[].label' # agent shape\n $ kash markets get 9f0b... --fields id,status,resolvedOutcomeIndex --json --quiet\n`\n )\n .action(async (id: string, _opts, cmd: Command) => {\n const globals = readGlobals(cmd);\n let market;\n try {\n const { client } = await buildClient({ requireAuth: true, globals });\n market = await client.markets.get(id);\n } catch (cause) {\n throw toCliError(cause);\n }\n\n if (globals.json) {\n printJson(market);\n return;\n }\n\n print('');\n print(`${style.bold(market.title ?? '(untitled)')}`);\n print(` ${style.dim('ID ')} ${market.id}`);\n print(` ${style.dim('Contract ')} ${formatAddress(market.contractAddress)}`);\n print(` ${style.dim('Chain ')} ${marketChainLabel(market)}`);\n print(` ${style.dim('Status ')} ${colorStatus(market.status ?? 'UNKNOWN')}`);\n print(` ${style.dim('Outcomes ')} ${String(market.outcomeCount)}`);\n print(` ${style.dim('Created ')} ${formatDate(market.createdAt)}`);\n if (market.expiresAt) {\n print(` ${style.dim('Expires ')} ${formatDate(market.expiresAt)}`);\n }\n if (market.resolvedAt) {\n print(` ${style.dim('Resolved ')} ${formatDate(market.resolvedAt)}`);\n }\n if (market.description) {\n print('');\n print(market.description);\n }\n\n print('');\n const table = createTable(['#', 'Outcome', 'Probability']);\n for (const outcome of market.outcomes) {\n table.push([String(outcome.index), outcome.label, formatProbability(outcome.probability)]);\n }\n print(table.toString());\n });\n","/**\n * `kash markets list` — page through markets.\n *\n * Default human output is a table of the first page. `--all` walks\n * the SDK's auto-paginator and prints every market — useful for\n * exporting to JSON. Status is uppercased before sending so users\n * don't have to remember the canonical casing.\n */\n\nimport { Command } from 'commander';\n\nimport { CliValidationError, toCliError } from '../../errors.js';\nimport { marketChainLabel } from '../../utils/chain.js';\nimport { buildClient } from '../../utils/client.js';\nimport {\n colorStatus,\n createTable,\n formatProbability,\n shortId,\n truncate,\n} from '../../utils/formatting.js';\nimport { parsePositiveInt, readGlobals } from '../../utils/global-options.js';\nimport { log, print, printJson, writeNdjson } from '../../utils/output.js';\n\nimport type { MarketResource, MarketStatus } from '@kashdao/sdk';\n\ntype ListOptions = {\n status?: string;\n limit?: string;\n cursor?: string;\n all?: boolean;\n ndjson?: boolean;\n};\n\nconst ALLOWED_STATUSES: ReadonlySet<MarketStatus> = new Set(['UNSEEDED', 'ACTIVE', 'RESOLVED']);\n\nexport const listMarketsCommand = new Command('list')\n .description('List markets.')\n .option('-s, --status <status>', 'filter by status (UNSEEDED | ACTIVE | RESOLVED)')\n .option('-l, --limit <n>', 'page size (1-100)', '20')\n .option('-c, --cursor <cursor>', 'pagination cursor returned by a previous call')\n .option('-a, --all', 'walk every page (use with --json for export)')\n .option(\n '--ndjson',\n 'stream results as newline-delimited JSON (one record per line); implies --all'\n )\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash markets list --status ACTIVE\n $ kash markets list --json --quiet | jq '.data[].id'\n $ kash markets list --ndjson | while read -r line; do echo \"$line\" | jq -r .id; done\n $ kash markets list --all --json --quiet > markets.json\n\nNotes:\n --ndjson emits one JSON record per line. Consumers must read\n line-by-line (\\`while read -r\\`, \\`jq -c\\`, \\`split('\\n')\\`) — DO NOT\n buffer-then-parse, as the stream may run for arbitrarily many pages.\n`\n )\n .action(async (options: ListOptions, cmd: Command) => {\n const globals = readGlobals(cmd);\n\n const limit = options.limit === undefined ? 20 : parsePositiveInt(options.limit, 'limit');\n if (limit < 1 || limit > 100) {\n throw new CliValidationError('--limit must be between 1 and 100.', undefined, 'limit');\n }\n\n const status = options.status ? normaliseStatus(options.status) : undefined;\n\n let response;\n try {\n const { client } = await buildClient({ requireAuth: true, globals });\n response = await client.markets.list({\n limit,\n ...(status === undefined ? {} : { status }),\n ...(options.cursor === undefined ? {} : { cursor: options.cursor }),\n });\n\n if (options.ndjson) {\n // Stream every record as one line of NDJSON to stdout. Avoids\n // buffering the full result set — the agent reads as we go.\n for await (const market of response) {\n writeNdjson(market);\n }\n return;\n }\n\n if (options.all) {\n const collected: MarketResource[] = [];\n for await (const market of response) collected.push(market);\n if (globals.json) {\n // Canonical list-envelope shape: `{data, pagination, count}`.\n // After walking every page, `pagination.hasMore` is false\n // and `cursor` is null — same fields, terminal values.\n // Agents pin to this single shape across both modes.\n printJson({\n data: collected,\n pagination: { hasMore: false, cursor: null },\n count: collected.length,\n });\n } else {\n renderTable(collected);\n }\n return;\n }\n } catch (cause) {\n throw toCliError(cause);\n }\n\n if (globals.json) {\n printJson({\n data: response.data,\n pagination: response.pagination,\n count: response.data.length,\n });\n return;\n }\n\n if (response.data.length === 0) {\n log.info('No markets matched the filter.');\n return;\n }\n renderTable(response.data);\n\n if (response.pagination.hasMore && response.pagination.cursor) {\n log.detail('Next page', `--cursor ${response.pagination.cursor}`);\n }\n });\n\nfunction renderTable(markets: readonly MarketResource[]): void {\n const table = createTable([\n 'ID',\n 'Title',\n 'Chain',\n 'Status',\n 'Outcomes',\n 'Top outcome',\n 'Created',\n ]);\n for (const market of markets) {\n const outcomes = market.outcomes;\n const top = outcomes.reduce<(typeof outcomes)[number] | undefined>((acc, current) => {\n if (acc === undefined) return current;\n return current.probability > acc.probability ? current : acc;\n }, undefined);\n table.push([\n shortId(market.id),\n truncate(market.title ?? '(untitled)', 42),\n marketChainLabel(market),\n colorStatus(market.status ?? 'UNKNOWN'),\n String(market.outcomeCount),\n top ? `${truncate(top.label, 18)} (${formatProbability(top.probability)})` : '-',\n market.createdAt.slice(0, 10),\n ]);\n }\n print(table.toString());\n}\n\nfunction normaliseStatus(value: string): MarketStatus {\n const upper = value.toUpperCase() as MarketStatus;\n if (!ALLOWED_STATUSES.has(upper)) {\n throw new CliValidationError(\n `Unknown market status \"${value}\".`,\n 'Allowed: UNSEEDED, ACTIVE, RESOLVED.'\n );\n }\n return upper;\n}\n","/**\n * `kash markets predictions <market-id>` — paginated feed of recent\n * trades against a single market. Wraps `kash.markets.predictions`.\n *\n * Requires API key with `markets:read` scope (granted by default on every\n * tier). Pagination shape mirrors `kash markets list` and `kash trade list`:\n * default first-page render, `--all` to walk every page, `--ndjson`\n * to stream NDJSON one-record-per-line for agents.\n */\n\nimport { Command } from 'commander';\n\nimport { CliValidationError, toCliError } from '../../errors.js';\nimport { buildClient } from '../../utils/client.js';\nimport { createTable, formatDate, shortId } from '../../utils/formatting.js';\nimport { parsePositiveInt, readGlobals } from '../../utils/global-options.js';\nimport { log, print, printJson, writeNdjson } from '../../utils/output.js';\nimport { parseOutcomeIndex } from '../../utils/trade-input.js';\n\nimport type { PredictionResource } from '@kashdao/sdk';\n\ntype PredictionsOptions = {\n side?: string;\n outcome?: string;\n limit?: string;\n cursor?: string;\n all?: boolean;\n ndjson?: boolean;\n};\n\nexport const predictionsCommand = new Command('predictions')\n .description('Recent trades against a market (cursor-paginated, newest first).')\n .argument('<marketId>', 'market UUID')\n .option('-s, --side <side>', 'filter to a single side: buy | sell')\n .option('-o, --outcome <index>', 'filter to a single outcome index (0-based)')\n .option('-l, --limit <n>', 'page size (1-100)', '50')\n .option('-c, --cursor <cursor>', 'pagination cursor returned by a previous call')\n .option('-a, --all', 'walk every page (use with --json for export)')\n .option(\n '--ndjson',\n 'stream results as newline-delimited JSON (one record per line); implies --all'\n )\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash markets predictions 9f0b...\n $ kash markets predictions 9f0b... --side buy --outcome 0\n $ kash markets predictions 9f0b... --json --quiet | jq -r '.data[].transactionHash'\n $ kash markets predictions 9f0b... --ndjson | head -100\n $ kash markets predictions 9f0b... --all --json --quiet > history.json\n`\n )\n .action(async (marketId: string, options: PredictionsOptions, cmd: Command) => {\n const globals = readGlobals(cmd);\n\n const limit = options.limit === undefined ? 50 : parsePositiveInt(options.limit, 'limit');\n if (limit < 1 || limit > 100) {\n throw new CliValidationError('--limit must be between 1 and 100.', undefined, 'limit');\n }\n\n const side = options.side ? validateSide(options.side) : undefined;\n const outcomeIndex = options.outcome ? parseOutcomeIndex(options.outcome) : undefined;\n\n let response;\n try {\n // Requires API key with `markets:read` scope (granted by default\n // on every tier). Fail fast at build time if no key is configured\n // rather than waiting for the server's 401.\n const { client } = await buildClient({ requireAuth: true, globals });\n response = await client.markets.predictions(marketId, {\n limit,\n ...(side === undefined ? {} : { side }),\n ...(outcomeIndex === undefined ? {} : { outcomeIndex }),\n ...(options.cursor === undefined ? {} : { cursor: options.cursor }),\n });\n\n if (options.ndjson) {\n for await (const prediction of response) {\n writeNdjson(prediction);\n }\n return;\n }\n\n if (options.all) {\n const collected: PredictionResource[] = [];\n for await (const prediction of response) collected.push(prediction);\n if (globals.json) {\n // Canonical `{data, pagination, count}` envelope — matches\n // every other list-shaped command (`markets list`,\n // `trade list`, `webhooks list`). After walking every\n // page, `pagination.hasMore` is false and `cursor` is null.\n printJson({\n data: collected,\n pagination: { hasMore: false, cursor: null },\n count: collected.length,\n });\n } else {\n renderTable(collected);\n }\n return;\n }\n } catch (cause) {\n throw toCliError(cause);\n }\n\n if (globals.json) {\n printJson({\n data: response.data,\n pagination: response.pagination,\n count: response.data.length,\n });\n return;\n }\n\n if (response.data.length === 0) {\n log.info('No predictions matched the filter.');\n return;\n }\n renderTable(response.data);\n\n if (response.pagination.hasMore && response.pagination.cursor) {\n log.detail('Next page', `--cursor ${response.pagination.cursor}`);\n }\n });\n\nfunction renderTable(predictions: readonly PredictionResource[]): void {\n const table = createTable(['Time', 'Side', 'Out#', 'Amount', 'Price', 'Tx']);\n for (const p of predictions) {\n const amount = p.side === 'buy' ? (p.usdcIn ?? '-') : (p.tokensIn ?? '-');\n table.push([\n formatDate(p.timestamp),\n p.side,\n String(p.outcomeIndex),\n amount,\n p.price,\n shortId(p.transactionHash),\n ]);\n }\n print(table.toString());\n}\n\nfunction validateSide(value: string): 'buy' | 'sell' {\n const lower = value.toLowerCase();\n if (lower !== 'buy' && lower !== 'sell') {\n throw new CliValidationError(`Unknown --side \"${value}\".`, 'Allowed: buy, sell.', 'side');\n }\n return lower;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,SAAS,WAAAA,gBAAe;;;ACNxB,SAAS,eAAe;AAejB,IAAM,mBAAmB,IAAI,QAAQ,KAAK,EAC9C,YAAY,8BAA8B,EAC1C,SAAS,QAAQ,aAAa,EAC9B;AAAA,EACC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOF,EACC,OAAO,OAAO,IAAY,OAAO,QAAiB;AACjD,QAAM,UAAU,YAAY,GAAG;AAC/B,MAAI;AACJ,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,YAAY,EAAE,aAAa,MAAM,QAAQ,CAAC;AACnE,aAAS,MAAM,OAAO,QAAQ,IAAI,EAAE;AAAA,EACtC,SAAS,OAAO;AACd,UAAM,WAAW,KAAK;AAAA,EACxB;AAEA,MAAI,QAAQ,MAAM;AAChB,cAAU,MAAM;AAChB;AA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eAAe;AAAA,IAC3B,CAAC;AAAA,EACH;AACA,QAAM,MAAM,SAAS,CAAC;AACxB;AAEA,SAAS,aAAa,OAA+B;AACnD,QAAM,QAAQ,MAAM,YAAY;AAChC,MAAI,UAAU,SAAS,UAAU,QAAQ;AACvC,UAAM,IAAI,mBAAmB,mBAAmB,KAAK,MAAM,uBAAuB,MAAM;AAAA,EAC1F;AACA,SAAO;AACT;;;AHpIO,IAAM,iBAAiB,IAAIC,SAAQ,SAAS,EAChD,YAAY,sCAAsC,EAClD,WAAW,kBAAkB,EAC7B,WAAW,gBAAgB,EAC3B,WAAW,kBAAkB;","names":["Command","Command","Command","Command","Command","renderTable","Command"]}
@@ -7,9 +7,9 @@ import {
7
7
  printJson,
8
8
  style,
9
9
  writeNdjson
10
- } from "./chunk-MQUJG224.js";
11
- import "./chunk-KADB3OKE.js";
12
- import "./chunk-X2VM6VKM.js";
10
+ } from "./chunk-2HFKULGG.js";
11
+ import "./chunk-VFBQVUL4.js";
12
+ import "./chunk-WL7XUYPH.js";
13
13
  export {
14
14
  configureOutput,
15
15
  isQuiet,
@@ -19,4 +19,4 @@ export {
19
19
  style,
20
20
  writeNdjson
21
21
  };
22
- //# sourceMappingURL=output-FGTXXZEQ.js.map
22
+ //# sourceMappingURL=output-M4NFSWGW.js.map
@@ -6,26 +6,26 @@ import {
6
6
  formatUsdcAtomic,
7
7
  formatWad,
8
8
  shortId
9
- } from "./chunk-R4NGUZKN.js";
9
+ } from "./chunk-6UU43MF5.js";
10
10
  import {
11
11
  buildClient
12
- } from "./chunk-QALDZHTX.js";
13
- import "./chunk-N26VGVGB.js";
14
- import "./chunk-BVFDUI73.js";
15
- import "./chunk-KAM6KOFD.js";
12
+ } from "./chunk-H2QGFDZP.js";
13
+ import "./chunk-ZSMI63N3.js";
14
+ import "./chunk-2SR77BYA.js";
15
+ import "./chunk-6QSTFU4R.js";
16
16
  import {
17
17
  readGlobals
18
- } from "./chunk-A3IH5HUV.js";
18
+ } from "./chunk-AROIP4EQ.js";
19
19
  import {
20
20
  log,
21
21
  print,
22
22
  printJson,
23
23
  style
24
- } from "./chunk-MQUJG224.js";
25
- import "./chunk-KADB3OKE.js";
24
+ } from "./chunk-2HFKULGG.js";
25
+ import "./chunk-VFBQVUL4.js";
26
26
  import {
27
27
  toCliError
28
- } from "./chunk-X2VM6VKM.js";
28
+ } from "./chunk-WL7XUYPH.js";
29
29
 
30
30
  // src/commands/portfolio/index.ts
31
31
  import { Command as Command3 } from "commander";
@@ -101,7 +101,7 @@ Examples:
101
101
  }
102
102
  print("");
103
103
  print(
104
- ` ${style.dim("Smart account ")} ${formatAddress(portfolio.smartAccountAddress, 10, 8)}`
104
+ ` ${style.dim("Wallet ")} ${formatAddress(portfolio.smartAccountAddress, 10, 8)}`
105
105
  );
106
106
  print(` ${style.dim("Active ")} ${String(portfolio.activePositions)} positions`);
107
107
  print(` ${style.dim("Cost basis ")} ${formatUsdcAtomic(portfolio.totalCostBasisAtomic)}`);
@@ -112,4 +112,4 @@ var portfolioCommand = new Command3("portfolio").description("View your portfoli
112
112
  export {
113
113
  portfolioCommand
114
114
  };
115
- //# sourceMappingURL=portfolio-R63D5QB2.js.map
115
+ //# sourceMappingURL=portfolio-RBRVUEYP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/portfolio/index.ts","../src/commands/portfolio/positions.ts","../src/commands/portfolio/show.ts"],"sourcesContent":["/**\n * `kash portfolio` — read-only snapshot of the authenticating user's\n * positions and aggregate cost basis.\n */\n\nimport { Command } from 'commander';\n\nimport { positionsCommand } from './positions.js';\nimport { showPortfolioCommand } from './show.js';\n\nexport const portfolioCommand = new Command('portfolio')\n .description('View your portfolio.')\n .addCommand(showPortfolioCommand)\n .addCommand(positionsCommand);\n","/**\n * `kash portfolio positions` — per-position breakdown for the\n * authenticating user's smart account.\n */\n\nimport { Command } from 'commander';\n\nimport { toCliError } from '../../errors.js';\nimport { buildClient } from '../../utils/client.js';\nimport {\n createTable,\n formatDate,\n formatUsdcAtomic,\n formatWad,\n shortId,\n} from '../../utils/formatting.js';\nimport { readGlobals } from '../../utils/global-options.js';\nimport { log, print, printJson } from '../../utils/output.js';\n\ntype PositionsOptions = {\n market?: string;\n};\n\nexport const positionsCommand = new Command('positions')\n .description('List active positions.')\n .option('-m, --market <id>', 'filter by market id')\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash portfolio positions\n $ kash portfolio positions --market 9f0b...\n $ kash portfolio positions --json --quiet | jq '.data[] | select(.shares != \"0\")'\n`\n )\n .action(async (options: PositionsOptions, cmd: Command) => {\n const globals = readGlobals(cmd);\n let positions;\n try {\n const { client } = await buildClient({ requireAuth: true, globals });\n positions = await client.portfolio.positions(\n options.market === undefined ? {} : { marketId: options.market }\n );\n } catch (cause) {\n throw toCliError(cause);\n }\n\n if (globals.json) {\n // Canonical list-envelope shape `{data, pagination, count}` —\n // matches `markets list / trade list / webhooks list /\n // markets predictions`. Positions is non-paginated server-side\n // (full set returned in one call), so pagination always carries\n // terminal values; the field is present for shape parity so\n // agents can pin one schema across every list-shaped command.\n printJson({\n data: positions,\n pagination: { hasMore: false, cursor: null },\n count: positions.length,\n });\n return;\n }\n\n if (positions.length === 0) {\n log.info('No positions found.');\n return;\n }\n\n const table = createTable(['Market', 'Out#', 'Shares (WAD)', 'Cost basis', 'Trades', 'Last']);\n for (const p of positions) {\n table.push([\n shortId(p.marketId),\n String(p.outcomeIndex),\n formatWad(p.shares),\n formatUsdcAtomic(p.costBasisAtomic),\n String(p.tradeCount),\n formatDate(p.lastTradeAt),\n ]);\n }\n print(table.toString());\n });\n","/**\n * `kash portfolio show` — aggregate summary for the authenticating\n * user's smart account.\n */\n\nimport { Command } from 'commander';\n\nimport { toCliError } from '../../errors.js';\nimport { buildClient } from '../../utils/client.js';\nimport { formatAddress, formatUsdcAtomic } from '../../utils/formatting.js';\nimport { readGlobals } from '../../utils/global-options.js';\nimport { print, printJson, style } from '../../utils/output.js';\n\nexport const showPortfolioCommand = new Command('show')\n .description('Show the aggregate portfolio summary.')\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash portfolio show\n $ kash portfolio show --json --quiet | jq -r '.smartAccountAddress'\n`\n )\n .action(async (_opts, cmd: Command) => {\n const globals = readGlobals(cmd);\n let portfolio;\n try {\n const { client } = await buildClient({ requireAuth: true, globals });\n portfolio = await client.portfolio.get();\n } catch (cause) {\n throw toCliError(cause);\n }\n\n if (globals.json) {\n printJson(portfolio);\n return;\n }\n\n print('');\n print(\n ` ${style.dim('Smart account ')} ${formatAddress(portfolio.smartAccountAddress, 10, 8)}`\n );\n print(` ${style.dim('Active ')} ${String(portfolio.activePositions)} positions`);\n print(` ${style.dim('Cost basis ')} ${formatUsdcAtomic(portfolio.totalCostBasisAtomic)}`);\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,WAAAA,gBAAe;;;ACAxB,SAAS,eAAe;AAkBjB,IAAM,mBAAmB,IAAI,QAAQ,WAAW,EACpD,YAAY,wBAAwB,EACpC,OAAO,qBAAqB,qBAAqB,EACjD;AAAA,EACC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMF,EACC,OAAO,OAAO,SAA2B,QAAiB;AACzD,QAAM,UAAU,YAAY,GAAG;AAC/B,MAAI;AACJ,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,YAAY,EAAE,aAAa,MAAM,QAAQ,CAAC;AACnE,gBAAY,MAAM,OAAO,UAAU;AAAA,MACjC,QAAQ,WAAW,SAAY,CAAC,IAAI,EAAE,UAAU,QAAQ,OAAO;AAAA,IACjE;AAAA,EACF,SAAS,OAAO;AACd,UAAM,WAAW,KAAK;AAAA,EACxB;AAEA,MAAI,QAAQ,MAAM;AAOhB,cAAU;AAAA,MACR,MAAM;AAAA,MACN,YAAY,EAAE,SAAS,OAAO,QAAQ,KAAK;AAAA,MAC3C,OAAO,UAAU;AAAA,IACnB,CAAC;AACD;AAAA,EACF;AAEA,MAAI,UAAU,WAAW,GAA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,EACpD,YAAY,sBAAsB,EAClC,WAAW,oBAAoB,EAC/B,WAAW,gBAAgB;","names":["Command","Command","Command","Command"]}
1
+ {"version":3,"sources":["../src/commands/portfolio/index.ts","../src/commands/portfolio/positions.ts","../src/commands/portfolio/show.ts"],"sourcesContent":["/**\n * `kash portfolio` — read-only snapshot of the authenticating user's\n * positions and aggregate cost basis.\n */\n\nimport { Command } from 'commander';\n\nimport { positionsCommand } from './positions.js';\nimport { showPortfolioCommand } from './show.js';\n\nexport const portfolioCommand = new Command('portfolio')\n .description('View your portfolio.')\n .addCommand(showPortfolioCommand)\n .addCommand(positionsCommand);\n","/**\n * `kash portfolio positions` — per-position breakdown for the\n * authenticating user's smart account.\n */\n\nimport { Command } from 'commander';\n\nimport { toCliError } from '../../errors.js';\nimport { buildClient } from '../../utils/client.js';\nimport {\n createTable,\n formatDate,\n formatUsdcAtomic,\n formatWad,\n shortId,\n} from '../../utils/formatting.js';\nimport { readGlobals } from '../../utils/global-options.js';\nimport { log, print, printJson } from '../../utils/output.js';\n\ntype PositionsOptions = {\n market?: string;\n};\n\nexport const positionsCommand = new Command('positions')\n .description('List active positions.')\n .option('-m, --market <id>', 'filter by market id')\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash portfolio positions\n $ kash portfolio positions --market 9f0b...\n $ kash portfolio positions --json --quiet | jq '.data[] | select(.shares != \"0\")'\n`\n )\n .action(async (options: PositionsOptions, cmd: Command) => {\n const globals = readGlobals(cmd);\n let positions;\n try {\n const { client } = await buildClient({ requireAuth: true, globals });\n positions = await client.portfolio.positions(\n options.market === undefined ? {} : { marketId: options.market }\n );\n } catch (cause) {\n throw toCliError(cause);\n }\n\n if (globals.json) {\n // Canonical list-envelope shape `{data, pagination, count}` —\n // matches `markets list / trade list / webhooks list /\n // markets predictions`. Positions is non-paginated server-side\n // (full set returned in one call), so pagination always carries\n // terminal values; the field is present for shape parity so\n // agents can pin one schema across every list-shaped command.\n printJson({\n data: positions,\n pagination: { hasMore: false, cursor: null },\n count: positions.length,\n });\n return;\n }\n\n if (positions.length === 0) {\n log.info('No positions found.');\n return;\n }\n\n const table = createTable(['Market', 'Out#', 'Shares (WAD)', 'Cost basis', 'Trades', 'Last']);\n for (const p of positions) {\n table.push([\n shortId(p.marketId),\n String(p.outcomeIndex),\n formatWad(p.shares),\n formatUsdcAtomic(p.costBasisAtomic),\n String(p.tradeCount),\n formatDate(p.lastTradeAt),\n ]);\n }\n print(table.toString());\n });\n","/**\n * `kash portfolio show` — aggregate summary for the authenticating\n * user's smart account.\n */\n\nimport { Command } from 'commander';\n\nimport { toCliError } from '../../errors.js';\nimport { buildClient } from '../../utils/client.js';\nimport { formatAddress, formatUsdcAtomic } from '../../utils/formatting.js';\nimport { readGlobals } from '../../utils/global-options.js';\nimport { print, printJson, style } from '../../utils/output.js';\n\nexport const showPortfolioCommand = new Command('show')\n .description('Show the aggregate portfolio summary.')\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash portfolio show\n $ kash portfolio show --json --quiet | jq -r '.smartAccountAddress'\n`\n )\n .action(async (_opts, cmd: Command) => {\n const globals = readGlobals(cmd);\n let portfolio;\n try {\n const { client } = await buildClient({ requireAuth: true, globals });\n portfolio = await client.portfolio.get();\n } catch (cause) {\n throw toCliError(cause);\n }\n\n if (globals.json) {\n printJson(portfolio);\n return;\n }\n\n print('');\n // An EVM smart account, or a base58 Solana wallet for a user whose\n // funds live on Solana.\n print(\n ` ${style.dim('Wallet ')} ${formatAddress(portfolio.smartAccountAddress, 10, 8)}`\n );\n print(` ${style.dim('Active ')} ${String(portfolio.activePositions)} positions`);\n print(` ${style.dim('Cost basis ')} ${formatUsdcAtomic(portfolio.totalCostBasisAtomic)}`);\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,WAAAA,gBAAe;;;ACAxB,SAAS,eAAe;AAkBjB,IAAM,mBAAmB,IAAI,QAAQ,WAAW,EACpD,YAAY,wBAAwB,EACpC,OAAO,qBAAqB,qBAAq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AACJ,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,YAAY,EAAE,aAAa,MAAM,QAAQ,CAAC;AACnE,gBAAY,MAAM,OAAO,UAAU,IAAI;AAAA,EACzC,SAAS,OAAO;AACd,UAAM,WAAW,KAAK;AAAA,EACxB;AAEA,MAAI,QAAQ,MAAM;AAChB,cAAU,SAAS;AACnB;AAAA,EACF;AAEA,QAAM,EAAE;AAGR;AAAA,IACE,KAAK,MAAM,IAAI,gBAAgB,CAAC,IAAI,cAAc,UAAU,qBAAqB,IAAI,CAAC,CAAC;AAAA,EACzF;AACA,QAAM,KAAK,MAAM,IAAI,gBAAgB,CAAC,IAAI,OAAO,UAAU,eAAe,CAAC,YAAY;AACvF,QAAM,KAAK,MAAM,IAAI,gBAAgB,CAAC,IAAI,iBAAiB,UAAU,oBAAoB,CAAC,EAAE;AAC9F,CAAC;;;AFpCI,IAAM,mBAAmB,IAAIC,SAAQ,WAAW,EACpD,YAAY,sBAAsB,EAClC,WAAW,oBAAoB,EAC/B,WAAW,gBAAgB;","names":["Command","Command","Command","Command"]}
@@ -2,17 +2,19 @@
2
2
  import {
3
3
  loadRawPrivateKey,
4
4
  resolveCliCustomChain
5
- } from "./chunk-L4AFV2HK.js";
5
+ } from "./chunk-IOLKGV45.js";
6
6
  import {
7
7
  formatAddress,
8
8
  formatBigDecimal,
9
9
  formatGwei,
10
10
  formatUsdcAtomic,
11
11
  formatWad
12
- } from "./chunk-R4NGUZKN.js";
12
+ } from "./chunk-6UU43MF5.js";
13
13
  import {
14
+ isEvmChain,
15
+ protocolEvmChainId,
14
16
  readConfig
15
- } from "./chunk-N26VGVGB.js";
17
+ } from "./chunk-ZSMI63N3.js";
16
18
  import {
17
19
  DEFAULT_SLIPPAGE_BPS,
18
20
  HEX_HASH_REGEX,
@@ -26,13 +28,13 @@ import {
26
28
  parseUppercaseSide,
27
29
  validateAddress,
28
30
  validateAddressOptional
29
- } from "./chunk-BVFDUI73.js";
31
+ } from "./chunk-2SR77BYA.js";
30
32
  import {
31
33
  parseOptionalPositiveFloat,
32
34
  parseOptionalPositiveInt,
33
35
  parsePositiveInt,
34
36
  readGlobals
35
- } from "./chunk-A3IH5HUV.js";
37
+ } from "./chunk-AROIP4EQ.js";
36
38
  import {
37
39
  isQuiet,
38
40
  log,
@@ -40,14 +42,14 @@ import {
40
42
  printJson,
41
43
  style,
42
44
  writeNdjson
43
- } from "./chunk-MQUJG224.js";
44
- import "./chunk-KADB3OKE.js";
45
+ } from "./chunk-2HFKULGG.js";
46
+ import "./chunk-VFBQVUL4.js";
45
47
  import {
46
48
  CliError,
47
49
  CliValidationError,
48
50
  EXIT_CODES,
49
51
  toCliError
50
- } from "./chunk-X2VM6VKM.js";
52
+ } from "./chunk-WL7XUYPH.js";
51
53
 
52
54
  // src/commands/protocol/index.ts
53
55
  import { Command as Command13 } from "commander";
@@ -83,7 +85,7 @@ async function buildDirectClient(opts) {
83
85
  );
84
86
  }
85
87
  const client = createSmartAccountClient({
86
- chainId: config.defaultChainId,
88
+ chainId: protocolEvmChainId(config.defaultChain),
87
89
  rpc,
88
90
  signer,
89
91
  ...bundlerConfig === void 0 ? {} : { bundler: bundlerConfig },
@@ -91,7 +93,7 @@ async function buildDirectClient(opts) {
91
93
  });
92
94
  return {
93
95
  client,
94
- chainId: config.defaultChainId,
96
+ chainId: protocolEvmChainId(config.defaultChain),
95
97
  smartAccount: config.smartAccount
96
98
  };
97
99
  }
@@ -137,15 +139,15 @@ function resolveBundlerConfig(config) {
137
139
  }
138
140
  async function maybeBuildCustomChain(config, rpc) {
139
141
  if (config.customChain === void 0) return void 0;
140
- if (config.defaultChainId === void 0) {
142
+ if (!isEvmChain(config.defaultChain)) {
141
143
  throw missingDirectConfig(
142
- "defaultChainId",
143
- "`kash config set defaultChainId <id>` (required when customChain is set so the CLI can construct the viem chain)"
144
+ "defaultChain",
145
+ "`kash config set defaultChain evm:<id>` (a customChain describes an EVM network, so the profile must name an EVM chain for the CLI to construct the viem chain)"
144
146
  );
145
147
  }
146
148
  return resolveCliCustomChain({
147
149
  customChain: config.customChain,
148
- chainId: config.defaultChainId,
150
+ chainId: protocolEvmChainId(config.defaultChain),
149
151
  rpc
150
152
  });
151
153
  }
@@ -1564,9 +1566,9 @@ function formatEventHuman(event) {
1564
1566
 
1565
1567
  // src/commands/protocol/index.ts
1566
1568
  var protocolCommand = new Command13("protocol").description(
1567
- "Self-orchestrated direct-to-chain operations (uses @kashdao/protocol-sdk). Like the default Kash-orchestrated mode, this path is non-custodial \u2014 the difference is who builds and submits trades."
1569
+ "EVM/Base only: self-orchestrated direct-to-chain operations via ERC-4337 smart accounts (uses @kashdao/protocol-sdk). For Solana markets \u2014 Kash's canonical chain \u2014 use the API-backed commands (kash markets, kash trade, kash redeem). Non-custodial either way; the difference is who builds and submits trades."
1568
1570
  ).addCommand(balanceCommand).addCommand(marketCommand).addCommand(quoteCommand).addCommand(positionCommand).addCommand(allowanceCommand).addCommand(smartAccountCommand).addCommand(feesCommand).addCommand(tokenIdCommand).addCommand(decodeRevertCommand).addCommand(tradeCommand).addCommand(useropCommand).addCommand(watchCommand);
1569
1571
  export {
1570
1572
  protocolCommand
1571
1573
  };
1572
- //# sourceMappingURL=protocol-ZB6R25IM.js.map
1574
+ //# sourceMappingURL=protocol-WYQAKN6N.js.map