tenjin-cli 0.1.0-alpha.5 → 0.1.0-alpha.8

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 (121) hide show
  1. package/README.md +169 -199
  2. package/dist/{buy-YMXXVNFH.js → buy-K2G6XQY2.js} +20 -18
  3. package/dist/{candidate-H7FR4AU5.js → candidate-DJB2NNTG.js} +7 -8
  4. package/dist/{chunk-ZW3B5LWX.js → chunk-2YX6LTCD.js} +5 -5
  5. package/dist/{chunk-4WVKXKDK.js → chunk-6OE2IJMH.js} +29 -238
  6. package/dist/chunk-6OE2IJMH.js.map +1 -0
  7. package/dist/{chunk-ADJYSM45.js → chunk-6ZBZCBR7.js} +27 -13
  8. package/dist/chunk-6ZBZCBR7.js.map +1 -0
  9. package/dist/{chunk-HTDALK7M.js → chunk-B7YB4MMU.js} +15 -12
  10. package/dist/{chunk-HTDALK7M.js.map → chunk-B7YB4MMU.js.map} +1 -1
  11. package/dist/{chunk-NFSOVL3C.js → chunk-BBUYCDSG.js} +12 -3
  12. package/dist/chunk-BBUYCDSG.js.map +1 -0
  13. package/dist/chunk-C3S6725N.js +337 -0
  14. package/dist/chunk-C3S6725N.js.map +1 -0
  15. package/dist/chunk-CYRYVZPN.js +213 -0
  16. package/dist/chunk-CYRYVZPN.js.map +1 -0
  17. package/dist/{chunk-MDDGEGSW.js → chunk-DAJ56EUU.js} +3 -3
  18. package/dist/{chunk-IOPWPMT2.js → chunk-DH6D6QIO.js} +5 -5
  19. package/dist/{chunk-NJF2WENW.js → chunk-DQDGBWWH.js} +4 -2
  20. package/dist/chunk-DQDGBWWH.js.map +1 -0
  21. package/dist/chunk-EDENZN2Q.js +614 -0
  22. package/dist/chunk-EDENZN2Q.js.map +1 -0
  23. package/dist/chunk-GABYDXWL.js +190 -0
  24. package/dist/chunk-GABYDXWL.js.map +1 -0
  25. package/dist/{chunk-LAM66WFJ.js → chunk-GM4RZUVU.js} +6 -8
  26. package/dist/{chunk-LAM66WFJ.js.map → chunk-GM4RZUVU.js.map} +1 -1
  27. package/dist/{chunk-PAUXMRSF.js → chunk-J6CVKC4M.js} +73 -2
  28. package/dist/chunk-J6CVKC4M.js.map +1 -0
  29. package/dist/chunk-L6AV2Q73.js +105 -0
  30. package/dist/chunk-L6AV2Q73.js.map +1 -0
  31. package/dist/{chunk-PYNSGYBE.js → chunk-NVHQCTIC.js} +249 -552
  32. package/dist/chunk-NVHQCTIC.js.map +1 -0
  33. package/dist/{chunk-CVX6JNGD.js → chunk-OTDI5FXG.js} +3 -5
  34. package/dist/{chunk-CVX6JNGD.js.map → chunk-OTDI5FXG.js.map} +1 -1
  35. package/dist/{chunk-3IRDP7TN.js → chunk-P3FBESBB.js} +6 -4
  36. package/dist/{chunk-3IRDP7TN.js.map → chunk-P3FBESBB.js.map} +1 -1
  37. package/dist/{chunk-FU6MCSLG.js → chunk-PCLPVJ3J.js} +16 -78
  38. package/dist/chunk-PCLPVJ3J.js.map +1 -0
  39. package/dist/chunk-QB2NNV6C.js +143 -0
  40. package/dist/chunk-QB2NNV6C.js.map +1 -0
  41. package/dist/{chunk-C444K6MI.js → chunk-RGFBBNGP.js} +42 -17
  42. package/dist/{chunk-C444K6MI.js.map → chunk-RGFBBNGP.js.map} +1 -1
  43. package/dist/{chunk-TXPPMK4L.js → chunk-RGTTACP3.js} +5 -5
  44. package/dist/chunk-SGK2B724.js +67 -0
  45. package/dist/chunk-SGK2B724.js.map +1 -0
  46. package/dist/{chunk-ZDY2KY5X.js → chunk-URSGGRO4.js} +28 -11
  47. package/dist/chunk-URSGGRO4.js.map +1 -0
  48. package/dist/{chunk-5SCU253N.js → chunk-UYP7G3GZ.js} +2 -2
  49. package/dist/{chunk-ZIYVN4CD.js → chunk-VZ3AJCO5.js} +3 -5
  50. package/dist/{chunk-ZIYVN4CD.js.map → chunk-VZ3AJCO5.js.map} +1 -1
  51. package/dist/{chunk-QONTBYQW.js → chunk-WRWCDLVK.js} +4 -6
  52. package/dist/{chunk-QONTBYQW.js.map → chunk-WRWCDLVK.js.map} +1 -1
  53. package/dist/chunk-XBJ3VLWX.js +35 -0
  54. package/dist/chunk-XBJ3VLWX.js.map +1 -0
  55. package/dist/{chunk-RTJLLPFA.js → chunk-XFHZWORF.js} +123 -24
  56. package/dist/chunk-XFHZWORF.js.map +1 -0
  57. package/dist/{chunk-BIKAUVC2.js → chunk-ZA3RFDAV.js} +40 -6
  58. package/dist/chunk-ZA3RFDAV.js.map +1 -0
  59. package/dist/{cli-IW76QTN3.js → cli-KNCYWMAG.js} +237 -25
  60. package/dist/cli-KNCYWMAG.js.map +1 -0
  61. package/dist/{config-VCOS7P5K.js → config-SAQEQRFB.js} +5 -6
  62. package/dist/dist-U4M6QCKE.js +2842 -0
  63. package/dist/dist-U4M6QCKE.js.map +1 -0
  64. package/dist/{doctor-WS65JG3V.js → doctor-FBRQNOUQ.js} +10 -9
  65. package/dist/{publish-DSFWQRUN.js → edit-IZZ2HIMR.js} +20 -18
  66. package/dist/index.js +1 -1
  67. package/dist/{inspect-SFJWUQHO.js → inspect-BFWZ5XOP.js} +17 -16
  68. package/dist/{install-RVPQPCKH.js → install-QXZCHIBT.js} +400 -166
  69. package/dist/install-QXZCHIBT.js.map +1 -0
  70. package/dist/outcome-VXCBEGNC.js +20 -0
  71. package/dist/publish-5NTCRF2V.js +40 -0
  72. package/dist/read-T6OTMU72.js +158 -0
  73. package/dist/read-T6OTMU72.js.map +1 -0
  74. package/dist/{run-OMPKA43G.js → run-5OGX64IY.js} +106 -32
  75. package/dist/{run-OMPKA43G.js.map → run-5OGX64IY.js.map} +1 -1
  76. package/dist/search-LIIWUMWV.js +24 -0
  77. package/dist/{send-3G4C64HJ.js → send-ENE47KQE.js} +7 -7
  78. package/dist/session-HY4QIWHV.js +87 -0
  79. package/dist/session-HY4QIWHV.js.map +1 -0
  80. package/dist/{wallet-PP22LAX7.js → wallet-OCCGEH6H.js} +7 -7
  81. package/dist/{wallet-B7KJS2R5.js → wallet-RBDVNZVR.js} +5 -5
  82. package/dist/wallet-RBDVNZVR.js.map +1 -0
  83. package/docs/agent-permissions.md +255 -0
  84. package/package.json +3 -1
  85. package/skills/tenjin/SKILL.md +57 -13
  86. package/skills/tenjin-publish/SKILL.md +12 -4
  87. package/skills/tenjin-search/SKILL.md +68 -12
  88. package/dist/chunk-2JQ5JSG6.js +0 -68
  89. package/dist/chunk-2JQ5JSG6.js.map +0 -1
  90. package/dist/chunk-4WVKXKDK.js.map +0 -1
  91. package/dist/chunk-ADJYSM45.js.map +0 -1
  92. package/dist/chunk-BIKAUVC2.js.map +0 -1
  93. package/dist/chunk-FU6MCSLG.js.map +0 -1
  94. package/dist/chunk-L4IHCN6B.js +0 -63
  95. package/dist/chunk-L4IHCN6B.js.map +0 -1
  96. package/dist/chunk-NFSOVL3C.js.map +0 -1
  97. package/dist/chunk-NJF2WENW.js.map +0 -1
  98. package/dist/chunk-PAUXMRSF.js.map +0 -1
  99. package/dist/chunk-PYNSGYBE.js.map +0 -1
  100. package/dist/chunk-RTJLLPFA.js.map +0 -1
  101. package/dist/chunk-ZDY2KY5X.js.map +0 -1
  102. package/dist/cli-IW76QTN3.js.map +0 -1
  103. package/dist/install-RVPQPCKH.js.map +0 -1
  104. package/dist/outcome-GNYCSZ7J.js +0 -20
  105. package/dist/search-KOI6Y7P6.js +0 -24
  106. /package/dist/{buy-YMXXVNFH.js.map → buy-K2G6XQY2.js.map} +0 -0
  107. /package/dist/{candidate-H7FR4AU5.js.map → candidate-DJB2NNTG.js.map} +0 -0
  108. /package/dist/{chunk-ZW3B5LWX.js.map → chunk-2YX6LTCD.js.map} +0 -0
  109. /package/dist/{chunk-MDDGEGSW.js.map → chunk-DAJ56EUU.js.map} +0 -0
  110. /package/dist/{chunk-IOPWPMT2.js.map → chunk-DH6D6QIO.js.map} +0 -0
  111. /package/dist/{chunk-TXPPMK4L.js.map → chunk-RGTTACP3.js.map} +0 -0
  112. /package/dist/{chunk-5SCU253N.js.map → chunk-UYP7G3GZ.js.map} +0 -0
  113. /package/dist/{config-VCOS7P5K.js.map → config-SAQEQRFB.js.map} +0 -0
  114. /package/dist/{doctor-WS65JG3V.js.map → doctor-FBRQNOUQ.js.map} +0 -0
  115. /package/dist/{inspect-SFJWUQHO.js.map → edit-IZZ2HIMR.js.map} +0 -0
  116. /package/dist/{outcome-GNYCSZ7J.js.map → inspect-BFWZ5XOP.js.map} +0 -0
  117. /package/dist/{publish-DSFWQRUN.js.map → outcome-VXCBEGNC.js.map} +0 -0
  118. /package/dist/{search-KOI6Y7P6.js.map → publish-5NTCRF2V.js.map} +0 -0
  119. /package/dist/{wallet-B7KJS2R5.js.map → search-LIIWUMWV.js.map} +0 -0
  120. /package/dist/{send-3G4C64HJ.js.map → send-ENE47KQE.js.map} +0 -0
  121. /package/dist/{wallet-PP22LAX7.js.map → wallet-OCCGEH6H.js.map} +0 -0
@@ -1,22 +1,22 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  fetchRead
4
- } from "./chunk-BIKAUVC2.js";
4
+ } from "./chunk-ZA3RFDAV.js";
5
5
  import {
6
6
  headingOutline
7
- } from "./chunk-FU6MCSLG.js";
7
+ } from "./chunk-SGK2B724.js";
8
8
  import {
9
9
  resolveResourceRef
10
- } from "./chunk-L4IHCN6B.js";
10
+ } from "./chunk-CYRYVZPN.js";
11
11
  import {
12
12
  sanitizeForTerminal
13
- } from "./chunk-NFSOVL3C.js";
13
+ } from "./chunk-BBUYCDSG.js";
14
14
  import {
15
15
  resolveContextSettings
16
- } from "./chunk-MDDGEGSW.js";
16
+ } from "./chunk-DAJ56EUU.js";
17
17
  import {
18
18
  toMoney
19
- } from "./chunk-5SCU253N.js";
19
+ } from "./chunk-UYP7G3GZ.js";
20
20
 
21
21
  // src/commands/inspect.ts
22
22
  async function runInspect(args, ctx, deps = {}) {
@@ -35,10 +35,14 @@ async function runInspect(args, ctx, deps = {}) {
35
35
  access: "free",
36
36
  title: body.title,
37
37
  price: toMoney(body.price),
38
- headings: headingOutline(body.bodyMd)
38
+ headings: headingOutline(body.bodyMd),
39
+ // The free/owned half of the verb split (#42): delivery here costs nothing,
40
+ // so point at the free-only verb, not at the paying one. Machine consumers
41
+ // read this; the human line below says the same thing.
42
+ nextCommand: `tenjin read ${ref.url}`
39
43
  },
40
44
  humanLines: [
41
- `${sanitizeForTerminal(body.title)}, free (${body.price} atomic). Read it with \`tenjin buy\`.`
45
+ `${sanitizeForTerminal(body.title)}, free (${body.price} atomic). Read it with \`tenjin read ${sanitizeForTerminal(ref.url)}\`.`
42
46
  ]
43
47
  };
44
48
  }
@@ -64,7 +68,10 @@ async function runInspect(args, ctx, deps = {}) {
64
68
  // hoisted copy would double every inspect payload to save one key of
65
69
  // depth.
66
70
  preview: result.preview,
67
- ...result.cardError === true ? { cardError: true } : {}
71
+ ...result.cardError === true ? { cardError: true } : {},
72
+ // Paid and unowned: this one really does cost money, so it keeps pointing at
73
+ // `buy`. `tenjin read` would refuse it with exit 3.
74
+ nextCommand: `tenjin buy ${ref.url}`
68
75
  },
69
76
  humanLines: [
70
77
  `Paid resource${price !== void 0 ? `, ${price.usd} USD (${price.atomic} atomic)` : ""}.`,
@@ -79,13 +86,20 @@ async function runInspect(args, ctx, deps = {}) {
79
86
  ...result.cardError === true ? [
80
87
  "The server sent an answer card this CLI could not parse; judging on price and preview only."
81
88
  ] : [],
82
- "This is the pre-purchase card; run `tenjin buy` to pay and read."
89
+ "This is the pre-purchase card; run `tenjin buy` to pay and read (`tenjin read` refuses paid pieces)."
83
90
  ]
84
91
  };
85
92
  }
86
93
  return {
87
- data: { url: ref.url, access: "entitled", message: result.message },
88
- humanLines: [sanitizeForTerminal(result.message)]
94
+ data: {
95
+ url: ref.url,
96
+ access: "entitled",
97
+ message: result.message,
98
+ nextCommand: `tenjin read ${ref.url}`
99
+ },
100
+ humanLines: [
101
+ `${sanitizeForTerminal(result.message)} Read it with \`tenjin read ${sanitizeForTerminal(ref.url)}\`.`
102
+ ]
89
103
  };
90
104
  }
91
105
  var CARD_BOUNDS = {
@@ -132,4 +146,4 @@ function freshness(card) {
132
146
  export {
133
147
  runInspect
134
148
  };
135
- //# sourceMappingURL=chunk-ADJYSM45.js.map
149
+ //# sourceMappingURL=chunk-6ZBZCBR7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/inspect.ts"],"sourcesContent":["import { resolveResourceRef } from '../lib/resource-ref';\nimport { resolveContextSettings } from '../lib/settings';\nimport { fetchRead, type PreviewCard } from '../lib/read-client';\nimport { toMoney } from '../lib/money';\nimport { headingOutline } from '../lib/markdown';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin inspect <resource-url-or-id>`, fetch the pre-purchase answer card /\n * preview from the read route's 402 body WITHOUT paying (spec 10). A free\n * resource returns 200 with the whole body; a paid one returns the leak-safe\n * preview plus the advertised price/network, and the answer card when the piece\n * carries one. Never signs, never pays, never saves.\n *\n * The card is the depth half of the search/inspect split: search v2 candidates are\n * lean, so this free call is where an agent gets what it answers, what it applies\n * to, what it excludes, and how it is dated, before spending anything.\n */\n\nexport interface InspectArgs {\n ref: string;\n}\n\nexport interface InspectDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runInspect(\n args: InspectArgs,\n ctx: CommandContext,\n deps: InspectDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const ref = await resolveResourceRef(args.ref, ctx.dataDir, settings.baseUrl);\n\n const result = await fetchRead(ref.url, {\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n if (result.kind === 'entitled') {\n // Free (or already-entitled) resource: the body is readable now, no payment.\n const body = result.body;\n return {\n data: {\n url: ref.url,\n resourceId: body.id,\n access: 'free',\n title: body.title,\n price: toMoney(body.price),\n headings: headingOutline(body.bodyMd),\n // The free/owned half of the verb split (#42): delivery here costs nothing,\n // so point at the free-only verb, not at the paying one. Machine consumers\n // read this; the human line below says the same thing.\n nextCommand: `tenjin read ${ref.url}`,\n },\n humanLines: [\n `${sanitizeForTerminal(body.title)}, free (${body.price} atomic). Read it with \\`tenjin read ${sanitizeForTerminal(ref.url)}\\`.`,\n ],\n };\n }\n\n if (result.kind === 'payment_required') {\n const requirement = result.paymentRequired.accepts[0];\n const price = requirement !== undefined ? toMoney(requirement.amount) : undefined;\n const card = result.preview.card;\n return {\n data: {\n url: ref.url,\n ...(ref.resourceId !== undefined ? { resourceId: ref.resourceId } : {}),\n access: 'paid',\n ...(price !== undefined ? { price } : {}),\n payment:\n requirement !== undefined\n ? {\n scheme: requirement.scheme,\n network: requirement.network,\n asset: requirement.asset,\n payTo: requirement.payTo,\n amount: requirement.amount,\n }\n : undefined,\n // The card stays where the wire puts it, inside `preview`, and is emitted\n // exactly once: it is the largest object in this envelope, and a second\n // hoisted copy would double every inspect payload to save one key of\n // depth.\n preview: result.preview,\n ...(result.cardError === true ? { cardError: true } : {}),\n // Paid and unowned: this one really does cost money, so it keeps pointing at\n // `buy`. `tenjin read` would refuse it with exit 3.\n nextCommand: `tenjin buy ${ref.url}`,\n },\n humanLines: [\n `Paid resource${price !== undefined ? `, ${price.usd} USD (${price.atomic} atomic)` : ''}.`,\n ...cardLines(card),\n // Three distinct states behind an absent card, and they call for three\n // different actions: the piece attests nothing (a signal, judge on that),\n // the server could not load a card it has (transient, retry), or this CLI\n // could not parse what arrived (a client-side bug or server drift). Only\n // the last is ours. `cardUnavailable` is server-sent and never rides\n // alongside a card, so it is only worth saying when there is no card.\n ...(card === undefined && result.preview.cardUnavailable === true\n ? ['The piece has a card the server could not load; retry later.']\n : []),\n ...(result.cardError === true\n ? [\n 'The server sent an answer card this CLI could not parse; judging on price and preview only.',\n ]\n : []),\n 'This is the pre-purchase card; run `tenjin buy` to pay and read (`tenjin read` refuses paid pieces).',\n ],\n };\n }\n\n // already_purchased without a payment header is unexpected; report it plainly.\n // Owned means delivery is free, so this branch points at `read` too.\n return {\n data: {\n url: ref.url,\n access: 'entitled',\n message: result.message,\n nextCommand: `tenjin read ${ref.url}`,\n },\n humanLines: [\n `${sanitizeForTerminal(result.message)} Read it with \\`tenjin read ${sanitizeForTerminal(ref.url)}\\`.`,\n ],\n };\n}\n\n/**\n * Per-line caps for the rendered card, each derived from the server's write-time\n * bound for that field, so a VALID card is never clipped: the two lists are 10\n * items x 200 chars joined with '; '; appliesTo is 8 keys (<=32 chars) x 20\n * values x 120 chars; the prose fields have a 500-char column bound and cadence\n * 120. Exceeding one means a server that broke its own bounds.\n *\n * When that happens the clip is MARKED. A silently shortened claim reads as a\n * whole one, and \"applies to Postgres 14, 15\" is a different promise from\n * \"applies to Postgres 14, 15, 16\". The `--json` payload stays verbatim either\n * way, because that copy is what an agent decides a non-refundable purchase on.\n */\nconst CARD_BOUNDS = {\n list: 10 * 200 + 9 * 2,\n appliesTo: 8 * (32 + 1 + 20 * 120 + 19 * 2) + 7 * 2,\n prose: 500,\n cadence: 120,\n // artifactType and temporalMode are open strings on the wire, so the composed\n // freshness line gets a bound of its own rather than trusting them.\n freshness: 200,\n} as const;\n\nconst CLIP_MARKER = '...';\n\nfunction cardLine(label: string, value: string | null, max: number): string[] {\n if (value === null) return [];\n const text = sanitizeForTerminal(value).trim();\n if (text.length === 0) return [];\n return [`${label}: ${text.length > max ? `${text.slice(0, max)}${CLIP_MARKER}` : text}`];\n}\n\n/**\n * The answer card off the 402 body, as human lines. This is the depth half of the\n * search/inspect split: search v2 returns lean hits, and the card an agent judges\n * fit on arrives here, for free. Empty when the piece carries no card, so an\n * uncarded inspect renders exactly as it did before.\n */\nfunction cardLines(card: PreviewCard | undefined): string[] {\n if (card === undefined) return [];\n const list = (items: string[]): string | null => (items.length > 0 ? items.join('; ') : null);\n const appliesTo = Object.entries(card.appliesTo).map(\n ([key, values]) => `${key}=${values.join(', ')}`,\n );\n return [\n ...cardLine('Answers', list(card.questionsAnswered), CARD_BOUNDS.list),\n ...cardLine('Tasks', list(card.tasksSupported), CARD_BOUNDS.list),\n ...cardLine('Applies to', list(appliesTo), CARD_BOUNDS.appliesTo),\n ...cardLine('Scope', card.scope, CARD_BOUNDS.prose),\n ...cardLine('Excludes', card.exclusions, CARD_BOUNDS.prose),\n ...cardLine('Freshness', freshness(card), CARD_BOUNDS.freshness),\n ...cardLine('Provenance', card.provenanceSummary, CARD_BOUNDS.prose),\n ...cardLine('Method', card.methodologySummary, CARD_BOUNDS.prose),\n ...cardLine('Maintenance', card.maintenanceCadence, CARD_BOUNDS.cadence),\n ];\n}\n\n/** Type, temporal mode and the two dates on one line: they answer the single\n * question a buyer asks of freshness, which is whether this is still true here.\n *\n * Both labels are open strings on the wire, so an empty one is dropped rather\n * than joined: otherwise the line leads with a comma and reads as a rendering\n * bug. All four empty yields '', and cardLine then omits the line entirely. */\nfunction freshness(card: PreviewCard): string {\n const parts = [card.artifactType, card.temporalMode].filter((s) => s.trim().length > 0);\n if (card.asOf !== null) parts.push(`as of ${card.asOf}`);\n if (card.validUntil !== null) parts.push(`valid until ${card.validUntil}`);\n return parts.join(', ');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsB,WACpB,MACA,KACA,OAAoB,CAAC,GACG;AACxB,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,MAAM,MAAM,mBAAmB,KAAK,KAAK,IAAI,SAAS,SAAS,OAAO;AAE5E,QAAM,SAAS,MAAM,UAAU,IAAI,KAAK;AAAA,IACtC,WAAW,IAAI,MAAM;AAAA,IACrB,GAAI,KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,EACtE,CAAC;AAED,MAAI,OAAO,SAAS,YAAY;AAE9B,UAAM,OAAO,OAAO;AACpB,WAAO;AAAA,MACL,MAAM;AAAA,QACJ,KAAK,IAAI;AAAA,QACT,YAAY,KAAK;AAAA,QACjB,QAAQ;AAAA,QACR,OAAO,KAAK;AAAA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GAAG,YAAY,IAAI;AAAA,IACrE,GAAG,SAAS,SAAS,KAAK,KAAK,cAAc,GAAG,YAAY,IAAI;AAAA,IAChE,GAAG,SAAS,cAAc,KAAK,SAAS,GAAG,YAAY,SAAS;AAAA,IAChE,GAAG,SAAS,SAAS,KAAK,OAAO,YAAY,KAAK;AAAA,IAClD,GAAG,SAAS,YAAY,KAAK,YAAY,YAAY,KAAK;AAAA,IAC1D,GAAG,SAAS,aAAa,UAAU,IAAI,GAAG,YAAY,SAAS;AAAA,IAC/D,GAAG,SAAS,cAAc,KAAK,mBAAmB,YAAY,KAAK;AAAA,IACnE,GAAG,SAAS,UAAU,KAAK,oBAAoB,YAAY,KAAK;AAAA,IAChE,GAAG,SAAS,eAAe,KAAK,oBAAoB,YAAY,OAAO;AAAA,EACzE;AACF;AAQA,SAAS,UAAU,MAA2B;AAC5C,QAAM,QAAQ,CAAC,KAAK,cAAc,KAAK,YAAY,EAAE,OAAO,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC;AACtF,MAAI,KAAK,SAAS,KAAM,OAAM,KAAK,SAAS,KAAK,IAAI,EAAE;AACvD,MAAI,KAAK,eAAe,KAAM,OAAM,KAAK,eAAe,KAAK,UAAU,EAAE;AACzE,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
@@ -1,31 +1,31 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  assertOnBaseOrigin
4
- } from "./chunk-L4IHCN6B.js";
4
+ } from "./chunk-CYRYVZPN.js";
5
5
  import {
6
6
  recordSearch
7
- } from "./chunk-CVX6JNGD.js";
7
+ } from "./chunk-OTDI5FXG.js";
8
+ import {
9
+ listCandidates
10
+ } from "./chunk-VZ3AJCO5.js";
8
11
  import {
9
12
  MAX_LIMIT,
10
13
  buildSearchRequest,
11
14
  postSearch
12
- } from "./chunk-3IRDP7TN.js";
13
- import {
14
- listCandidates
15
- } from "./chunk-ZIYVN4CD.js";
15
+ } from "./chunk-P3FBESBB.js";
16
16
  import {
17
17
  sanitizeForTerminal
18
- } from "./chunk-NFSOVL3C.js";
18
+ } from "./chunk-BBUYCDSG.js";
19
19
  import {
20
20
  resolveContextSettings
21
- } from "./chunk-MDDGEGSW.js";
21
+ } from "./chunk-DAJ56EUU.js";
22
22
  import {
23
23
  formatUsdDisplay,
24
24
  parseUsdToAtomic
25
- } from "./chunk-5SCU253N.js";
25
+ } from "./chunk-UYP7G3GZ.js";
26
26
  import {
27
27
  CliError
28
- } from "./chunk-PAUXMRSF.js";
28
+ } from "./chunk-J6CVKC4M.js";
29
29
 
30
30
  // src/commands/search.ts
31
31
  async function runSearch(args, ctx, deps = {}) {
@@ -89,8 +89,11 @@ async function runSearch(args, ctx, deps = {}) {
89
89
  ] : [];
90
90
  const humanLines = response.decision === "MISS" ? [`MISS, no candidates (searchId ${response.searchId})`, ...browseHint, ...truncatedHint] : [
91
91
  `${candidates.length} candidate(s) (searchId ${response.searchId}):`,
92
+ // Dollars for the same reason the browse hint uses them: this is the
93
+ // human's cue to size the spend against gates they entered in decimal
94
+ // USD. The machine `candidates` array in --json keeps atomic.
92
95
  ...candidates.map(
93
- (c, i) => ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${c.price} atomic, ${sanitizeForTerminal(c.url)}`
96
+ (c, i) => ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${formatUsdDisplay(c.price)} USD, ${sanitizeForTerminal(c.url)}`
94
97
  ),
95
98
  ...truncatedHint
96
99
  ];
@@ -140,4 +143,4 @@ function parseAppliesTo(pairs) {
140
143
  export {
141
144
  runSearch
142
145
  };
143
- //# sourceMappingURL=chunk-HTDALK7M.js.map
146
+ //# sourceMappingURL=chunk-B7YB4MMU.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/search.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { formatUsdDisplay, parseUsdToAtomic } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildSearchRequest, postSearch, MAX_LIMIT, type SearchInput } from '../lib/agent-api';\nimport { recordSearch } from '../lib/search-store';\nimport { listCandidates } from '../lib/candidate-store';\nimport { assertOnBaseOrigin } from '../lib/resource-ref';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin search \"<question>\"`, one POST to /api/agent/search. Prints the compact\n * CANDIDATES/MISS response verbatim (spec 10), and records the searchId +\n * candidates locally so `outcome --last` and `buy <resourceId>` can use them. No\n * wallet, no signing: search is anonymous.\n *\n * Search is the breadth step: a candidate is a lean hit (identity, price,\n * freshness, why it matched), and the full answer card comes from `tenjin inspect`,\n * which is free. So a candidate line stays short on purpose.\n *\n * The response's `searchId` is the outcome-reporting capability for\n * POST /api/agent/searches/<searchId>/outcomes. tenjin#463 renamed both the field\n * (from `lookupId`) and that path, and this client follows the rename end to end,\n * so nothing on the wire or in the local store still speaks `lookupId`.\n */\n\nexport interface SearchArgs {\n question: string;\n /** Decimal USD at the edge (O1); converted to atomic for the wire. */\n maxPrice?: string;\n freshWithin?: string;\n limit?: string;\n /** Raw `k=v` / `k=v1,v2` pairs from repeated --applies-to. */\n appliesTo?: string[];\n}\n\nexport interface SearchDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runSearch(\n args: SearchArgs,\n ctx: CommandContext,\n deps: SearchDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const input: SearchInput = { question: args.question };\n if (args.maxPrice !== undefined) input.maxPrice = parseUsdToAtomic(args.maxPrice);\n if (args.freshWithin !== undefined) input.freshWithin = args.freshWithin;\n if (args.limit !== undefined) input.limit = parseLimit(args.limit);\n if (args.appliesTo !== undefined && args.appliesTo.length > 0) {\n input.appliesTo = parseAppliesTo(args.appliesTo);\n }\n\n const request = buildSearchRequest(input);\n const response = await postSearch(request, {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n evalCohort: settings.evalCohort,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const candidates = response.candidates ?? [];\n // Ingest trust boundary: a candidate url that points off the configured origin\n // would later route a wallet-signed SIWX header and payment to that host via\n // `buy <resourceId>`. Refuse the whole response as a contract violation.\n for (const c of candidates) {\n try {\n assertOnBaseOrigin(c.url, settings.baseUrl, 'search candidate URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Search candidate ${c.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n // Browse pointers are never buyable through `buy <resourceId>` (they are not\n // recorded), but their urls are still emitted into the agent's transcript, so\n // they get the same origin check rather than a weaker one.\n for (const b of response.browse ?? []) {\n try {\n assertOnBaseOrigin(b.url, settings.baseUrl, 'browse pointer URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Browse pointer ${b.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n await recordSearch(ctx.dataDir, {\n searchId: response.searchId,\n at: new Date().toISOString(),\n question: request.question,\n decision: response.decision,\n candidates: candidates.map((c) => ({\n resourceId: c.resourceId,\n url: c.url,\n title: c.title,\n price: c.price,\n })),\n });\n\n // A parked-candidate nudge on stderr (not in the machine JSON), MISS only: a\n // MISS is the moment to publish the answer you are about to derive, and stale\n // drafts should not rot unseen. A HIT is not a publish moment, and hot search\n // paths should not get advisory noise every call. One line, only when parked.\n if (response.decision === 'MISS') await emitCandidateNudge(ctx);\n\n // A MISS may carry up to 3 browse pointers from the broad corpus. They are\n // pointers, NOT candidates: rendered as ONE hint line with no scores and no\n // per-item detail, so a MISS still reads as a MISS and an agent is never\n // nudged to treat a browse pointer as an answer. The machine JSON keeps the\n // full `browse` array; this line is only the human tail.\n //\n // The price rides this line because a browse url IS payable: it is the read\n // endpoint that answers a 402, and `buy <url>` resolves the URL arm by origin\n // without consulting the search store, so a browse pointer can be bought even\n // though `buy <resourceId>` can never reach one. All spend gates (price cap,\n // session budget, allowlist, confirm) still run; showing the price keeps the\n // only human-visible surface from being a blind spend.\n //\n // It renders in DOLLARS, not atomic units, because the whole point of the line\n // is that a human can size the spend against the gates they set, and every gate\n // is entered in decimal USD (`--max-price 0.10`, the `maxAutoSpend` config).\n // `formatUsdDisplay` is the canonical human-copy form (always two decimals, so\n // a dime reads \"0.10\" and not \"0.1\"); the machine `browse` array in --json still\n // carries the exact atomic string, per the money-units contract in the README.\n const browse = response.browse ?? [];\n const browseHint =\n browse.length > 0\n ? [\n `no match, ${browse.length} piece(s) you could browse: ${browse\n .map((b) => `${sanitizeForTerminal(b.title)} (${formatUsdDisplay(b.price)} USD)`)\n .join('; ')}`,\n ]\n : [];\n\n // `truncated` means the server's size backstop dropped candidates, either a\n // trailing few the limit had room for or a single oversized one. The response\n // ceiling GROWS with the number of candidates returned (tenjin#501), so the\n // remedy is counter-intuitive and worth stating outright: a larger --limit\n // recovers the tail, a smaller one returns strictly fewer. Only at the maximum\n // is the tail unrecoverable and narrowing the question the answer.\n //\n // The CLI knows the limit it sent, so it names the next step instead of\n // restating the rule and leaving the reader to work out which half applies.\n // The flag stays in the machine envelope (--json) untouched, where it is\n // omitted rather than false when it did not fire.\n //\n // Rendering it on a MISS too is DEFENSIVE, not wire behavior: the server only\n // ever sets the flag alongside candidates it dropped. Handling both keeps the\n // flag from going unrendered if that ever changes.\n const truncatedHint =\n response.truncated === true\n ? [\n request.limit < MAX_LIMIT\n ? `some candidates were dropped for size; retry with --limit ${MAX_LIMIT} (the size ceiling grows with the number of candidates returned)`\n : `some candidates were dropped for size; at --limit ${MAX_LIMIT} the dropped tail cannot be recovered, so narrow the question`,\n ]\n : [];\n\n const humanLines =\n response.decision === 'MISS'\n ? [`MISS, no candidates (searchId ${response.searchId})`, ...browseHint, ...truncatedHint]\n : [\n `${candidates.length} candidate(s) (searchId ${response.searchId}):`,\n ...candidates.map(\n (c, i) =>\n ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${c.price} atomic, ${sanitizeForTerminal(c.url)}`,\n ),\n ...truncatedHint,\n ];\n\n return { data: response, humanLines };\n}\n\nconst STALE_MS = 7 * 24 * 60 * 60 * 1000;\n\n/** One stderr line naming parked candidates (and how many are stale >7d), so a\n * search is a reminder to publish/tidy the local pen. Silent when none parked. */\nasync function emitCandidateNudge(ctx: CommandContext): Promise<void> {\n const records = await listCandidates(ctx.dataDir);\n if (records.length === 0) return;\n const now = Date.now();\n const stale = records.filter((r) => now - Date.parse(r.meta.created) > STALE_MS).length;\n ctx.io.stderr.write(\n `${records.length} candidate(s) parked (${stale} stale >7d) - tenjin candidate list\\n`,\n );\n}\n\nfunction parseLimit(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n)) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(raw)}`, {\n fix: 'Pass an integer between 1 and 10.',\n });\n }\n return n;\n}\n\n/** `products=Vercel` or `products=Vercel,Next` → { products: [\"Vercel\",\"Next\"] }. Repeated\n * keys merge their values. */\nfunction parseAppliesTo(pairs: string[]): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const pair of pairs) {\n const eq = pair.indexOf('=');\n if (eq <= 0) {\n throw new CliError('USAGE', `Invalid --applies-to: ${JSON.stringify(pair)}`, {\n fix: 'Use key=value, e.g. --applies-to products=Vercel.',\n });\n }\n const key = pair.slice(0, eq).trim();\n const values = pair\n .slice(eq + 1)\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v.length > 0);\n if (values.length === 0) {\n throw new CliError('USAGE', `--applies-to ${JSON.stringify(key)} has no values`, {\n fix: 'Give each key at least one value, e.g. products=Vercel.',\n });\n }\n out[key] = [...(out[key] ?? []), ...values];\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,eAAsB,UACpB,MACA,KACA,OAAmB,CAAC,GACI;AACxB,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,QAAqB,EAAE,UAAU,KAAK,SAAS;AACrD,MAAI,KAAK,aA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G,QAAQ,MAAM,yBAAyB,KAAK;AAAA;AAAA,EACjD;AACF;AAEA,SAAS,WAAW,KAAqB;AACvC,QAAM,IAAI,OAAO,GAAG;AACpB,MAAI,CAAC,OAAO,UAAU,CAAC,GAAG;AACxB,UAAM,IAAI,SAAS,SAAS,oBAAoB,KAAK,UAAU,GAAG,CAAC,IAAI;AAAA,MACrE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAIA,SAAS,eAAe,OAA2C;AACjE,QAAM,MAAgC,CAAC;AACvC,aAAW,QAAQ,OAAO;AACxB,UAAM,KAAK,KAAK,QAAQ,GAAG;AAC3B,QAAI,MAAM,GAAG;AACX,YAAM,IAAI,SAAS,SAAS,yBAAyB,KAAK,UAAU,IAAI,CAAC,IAAI;AAAA,QAC3E,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,UAAM,MAAM,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK;AACnC,UAAM,SAAS,KACZ,MAAM,KAAK,CAAC,EACZ,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAC7B,QAAI,OAAO,WAAW,GAAG;AACvB,YAAM,IAAI,SAAS,SAAS,gBAAgB,KAAK,UAAU,GAAG,CAAC,kBAAkB;AAAA,QAC/E,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,QAAI,GAAG,IAAI,CAAC,GAAI,IAAI,GAAG,KAAK,CAAC,GAAI,GAAG,MAAM;AAAA,EAC5C;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/commands/search.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { formatUsdDisplay, parseUsdToAtomic } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildSearchRequest, postSearch, MAX_LIMIT, type SearchInput } from '../lib/agent-api';\nimport { recordSearch } from '../lib/search-store';\nimport { listCandidates } from '../lib/candidate-store';\nimport { assertOnBaseOrigin } from '../lib/resource-ref';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin search \"<question>\"`, one POST to /api/agent/search. Prints the compact\n * CANDIDATES/MISS response verbatim (spec 10), and records the searchId +\n * candidates locally so `outcome --last` and `buy <resourceId>` can use them. No\n * wallet, no signing: search is anonymous.\n *\n * Search is the breadth step: a candidate is a lean hit (identity, price,\n * freshness, why it matched), and the full answer card comes from `tenjin inspect`,\n * which is free. So a candidate line stays short on purpose.\n *\n * The response's `searchId` is the outcome-reporting capability for\n * POST /api/agent/searches/<searchId>/outcomes. tenjin#463 renamed both the field\n * (from `lookupId`) and that path, and this client follows the rename end to end,\n * so nothing on the wire or in the local store still speaks `lookupId`.\n */\n\nexport interface SearchArgs {\n question: string;\n /** Decimal USD at the edge (O1); converted to atomic for the wire. */\n maxPrice?: string;\n freshWithin?: string;\n limit?: string;\n /** Raw `k=v` / `k=v1,v2` pairs from repeated --applies-to. */\n appliesTo?: string[];\n}\n\nexport interface SearchDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runSearch(\n args: SearchArgs,\n ctx: CommandContext,\n deps: SearchDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const input: SearchInput = { question: args.question };\n if (args.maxPrice !== undefined) input.maxPrice = parseUsdToAtomic(args.maxPrice);\n if (args.freshWithin !== undefined) input.freshWithin = args.freshWithin;\n if (args.limit !== undefined) input.limit = parseLimit(args.limit);\n if (args.appliesTo !== undefined && args.appliesTo.length > 0) {\n input.appliesTo = parseAppliesTo(args.appliesTo);\n }\n\n const request = buildSearchRequest(input);\n const response = await postSearch(request, {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n evalCohort: settings.evalCohort,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const candidates = response.candidates ?? [];\n // Ingest trust boundary: a candidate url that points off the configured origin\n // would later route a wallet-signed SIWX header and payment to that host via\n // `buy <resourceId>`. Refuse the whole response as a contract violation.\n for (const c of candidates) {\n try {\n assertOnBaseOrigin(c.url, settings.baseUrl, 'search candidate URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Search candidate ${c.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n // Browse pointers are never buyable through `buy <resourceId>` (they are not\n // recorded), but their urls are still emitted into the agent's transcript, so\n // they get the same origin check rather than a weaker one.\n for (const b of response.browse ?? []) {\n try {\n assertOnBaseOrigin(b.url, settings.baseUrl, 'browse pointer URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Browse pointer ${b.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n await recordSearch(ctx.dataDir, {\n searchId: response.searchId,\n at: new Date().toISOString(),\n question: request.question,\n decision: response.decision,\n candidates: candidates.map((c) => ({\n resourceId: c.resourceId,\n url: c.url,\n title: c.title,\n price: c.price,\n })),\n });\n\n // A parked-candidate nudge on stderr (not in the machine JSON), MISS only: a\n // MISS is the moment to publish the answer you are about to derive, and stale\n // drafts should not rot unseen. A HIT is not a publish moment, and hot search\n // paths should not get advisory noise every call. One line, only when parked.\n if (response.decision === 'MISS') await emitCandidateNudge(ctx);\n\n // A MISS may carry up to 3 browse pointers from the broad corpus. They are\n // pointers, NOT candidates: rendered as ONE hint line with no scores and no\n // per-item detail, so a MISS still reads as a MISS and an agent is never\n // nudged to treat a browse pointer as an answer. The machine JSON keeps the\n // full `browse` array; this line is only the human tail.\n //\n // The price rides this line because a browse url IS payable: it is the read\n // endpoint that answers a 402, and `buy <url>` resolves the URL arm by origin\n // without consulting the search store, so a browse pointer can be bought even\n // though `buy <resourceId>` can never reach one. All spend gates (price cap,\n // session budget, allowlist, confirm) still run; showing the price keeps the\n // only human-visible surface from being a blind spend.\n //\n // It renders in DOLLARS, not atomic units, because the whole point of the line\n // is that a human can size the spend against the gates they set, and every gate\n // is entered in decimal USD (`--max-price 0.10`, the `maxAutoSpend` config).\n // `formatUsdDisplay` is the canonical human-copy form (always two decimals, so\n // a dime reads \"0.10\" and not \"0.1\"); the machine `browse` array in --json still\n // carries the exact atomic string, per the money-units contract in the README.\n const browse = response.browse ?? [];\n const browseHint =\n browse.length > 0\n ? [\n `no match, ${browse.length} piece(s) you could browse: ${browse\n .map((b) => `${sanitizeForTerminal(b.title)} (${formatUsdDisplay(b.price)} USD)`)\n .join('; ')}`,\n ]\n : [];\n\n // `truncated` means the server's size backstop dropped candidates, either a\n // trailing few the limit had room for or a single oversized one. The response\n // ceiling GROWS with the number of candidates returned (tenjin#501), so the\n // remedy is counter-intuitive and worth stating outright: a larger --limit\n // recovers the tail, a smaller one returns strictly fewer. Only at the maximum\n // is the tail unrecoverable and narrowing the question the answer.\n //\n // The CLI knows the limit it sent, so it names the next step instead of\n // restating the rule and leaving the reader to work out which half applies.\n // The flag stays in the machine envelope (--json) untouched, where it is\n // omitted rather than false when it did not fire.\n //\n // Rendering it on a MISS too is DEFENSIVE, not wire behavior: the server only\n // ever sets the flag alongside candidates it dropped. Handling both keeps the\n // flag from going unrendered if that ever changes.\n const truncatedHint =\n response.truncated === true\n ? [\n request.limit < MAX_LIMIT\n ? `some candidates were dropped for size; retry with --limit ${MAX_LIMIT} (the size ceiling grows with the number of candidates returned)`\n : `some candidates were dropped for size; at --limit ${MAX_LIMIT} the dropped tail cannot be recovered, so narrow the question`,\n ]\n : [];\n\n const humanLines =\n response.decision === 'MISS'\n ? [`MISS, no candidates (searchId ${response.searchId})`, ...browseHint, ...truncatedHint]\n : [\n `${candidates.length} candidate(s) (searchId ${response.searchId}):`,\n // Dollars for the same reason the browse hint uses them: this is the\n // human's cue to size the spend against gates they entered in decimal\n // USD. The machine `candidates` array in --json keeps atomic.\n ...candidates.map(\n (c, i) =>\n ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${formatUsdDisplay(c.price)} USD, ${sanitizeForTerminal(c.url)}`,\n ),\n ...truncatedHint,\n ];\n\n return { data: response, humanLines };\n}\n\nconst STALE_MS = 7 * 24 * 60 * 60 * 1000;\n\n/** One stderr line naming parked candidates (and how many are stale >7d), so a\n * search is a reminder to publish/tidy the local pen. Silent when none parked. */\nasync function emitCandidateNudge(ctx: CommandContext): Promise<void> {\n const records = await listCandidates(ctx.dataDir);\n if (records.length === 0) return;\n const now = Date.now();\n const stale = records.filter((r) => now - Date.parse(r.meta.created) > STALE_MS).length;\n ctx.io.stderr.write(\n `${records.length} candidate(s) parked (${stale} stale >7d) - tenjin candidate list\\n`,\n );\n}\n\nfunction parseLimit(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n)) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(raw)}`, {\n fix: 'Pass an integer between 1 and 10.',\n });\n }\n return n;\n}\n\n/** `products=Vercel` or `products=Vercel,Next` → { products: [\"Vercel\",\"Next\"] }. Repeated\n * keys merge their values. */\nfunction parseAppliesTo(pairs: string[]): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const pair of pairs) {\n const eq = pair.indexOf('=');\n if (eq <= 0) {\n throw new CliError('USAGE', `Invalid --applies-to: ${JSON.stringify(pair)}`, {\n fix: 'Use key=value, e.g. --applies-to products=Vercel.',\n });\n }\n const key = pair.slice(0, eq).trim();\n const values = pair\n .slice(eq + 1)\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v.length > 0);\n if (values.length === 0) {\n throw new CliError('USAGE', `--applies-to ${JSON.stringify(key)} has no values`, {\n fix: 'Give each key at least one value, e.g. products=Vercel.',\n });\n }\n out[key] = [...(out[key] ?? []), ...values];\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,eAAsB,UACpB,MACA,KACA,OAAmB,CAAC,GACI;AACxB,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,QAAqB,EAAE,UAAU,KAAK,SAAS;AACrD,MAAI,KAAK,aAAa,OAAW,OAAM,WA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AAAA,IACZ,GAAG,QAAQ,MAAM,yBAAyB,KAAK;AAAA;AAAA,EACjD;AACF;AAEA,SAAS,WAAW,KAAqB;AACvC,QAAM,IAAI,OAAO,GAAG;AACpB,MAAI,CAAC,OAAO,UAAU,CAAC,GAAG;AACxB,UAAM,IAAI,SAAS,SAAS,oBAAoB,KAAK,UAAU,GAAG,CAAC,IAAI;AAAA,MACrE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAIA,SAAS,eAAe,OAA2C;AACjE,QAAM,MAAgC,CAAC;AACvC,aAAW,QAAQ,OAAO;AACxB,UAAM,KAAK,KAAK,QAAQ,GAAG;AAC3B,QAAI,MAAM,GAAG;AACX,YAAM,IAAI,SAAS,SAAS,yBAAyB,KAAK,UAAU,IAAI,CAAC,IAAI;AAAA,QAC3E,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,UAAM,MAAM,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK;AACnC,UAAM,SAAS,KACZ,MAAM,KAAK,CAAC,EACZ,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAC7B,QAAI,OAAO,WAAW,GAAG;AACvB,YAAM,IAAI,SAAS,SAAS,gBAAgB,KAAK,UAAU,GAAG,CAAC,kBAAkB;AAAA,QAC/E,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,QAAI,GAAG,IAAI,CAAC,GAAI,IAAI,GAAG,KAAK,CAAC,GAAI,GAAG,MAAM;AAAA,EAC5C;AACA,SAAO;AACT;","names":[]}
@@ -2,7 +2,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  CliError,
4
4
  external_exports
5
- } from "./chunk-PAUXMRSF.js";
5
+ } from "./chunk-J6CVKC4M.js";
6
6
 
7
7
  // src/lib/output.ts
8
8
  import { styleText } from "util";
@@ -116,8 +116,16 @@ function emitFailure(io, command, err, opts = {}) {
116
116
  writeJson(io.stdout, buildFailureEnvelope(command, cliErr));
117
117
  return cliErr;
118
118
  }
119
+ function emitNotice(io, text, opts = {}) {
120
+ if (!humanMode(io, opts)) return;
121
+ io.stderr.write(`${paint(io, "dim", sanitizeForTerminal(text))}
122
+ `);
123
+ }
119
124
  function sanitizeForTerminal(text) {
120
- return text.replace(/\x1b(?:\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g, "").replace(/[\x00-\x08\x0a-\x1f\x7f-\x9f]/g, "");
125
+ return text.replace(/\x1b(?:\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g, "").replace(/[\x00-\x08\x0a-\x1f\x7f-\x9f]/g, "").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "").replace(
126
+ /(\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F})|[\u{E0000}-\u{E007F}\u{FEFF}]/gu,
127
+ (_match, rgiFlag) => rgiFlag ?? ""
128
+ );
121
129
  }
122
130
  function normalizeError(err) {
123
131
  if (err instanceof CliError) return err;
@@ -161,7 +169,8 @@ export {
161
169
  buildFailureEnvelope,
162
170
  emitSuccess,
163
171
  emitFailure,
172
+ emitNotice,
164
173
  sanitizeForTerminal,
165
174
  normalizeError
166
175
  };
167
- //# sourceMappingURL=chunk-NFSOVL3C.js.map
176
+ //# sourceMappingURL=chunk-BBUYCDSG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/output.ts","../src/schemas.ts"],"sourcesContent":["import { styleText } from 'node:util';\nimport { Stream } from 'node:stream';\nimport { CliError } from './errors';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { FailureEnvelope, OutputError, SuccessEnvelope } from '../schemas';\n\n/**\n * Injected streams + TTY fact. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` is the real terminal fact; the separate `--json` flag (passed to the\n * emit functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output.\n */\nexport interface Io {\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, the JSON envelope is emitted even at a TTY. */\n json?: boolean;\n}\n\n/**\n * The two pure envelope builders, shared by the CLI's emit functions and the MCP\n * adapter so both surfaces produce the identical wire object by construction. They\n * hold no I/O and no --json branching: they turn a (command, data) or a normalized\n * CliError into the exact object that goes to stdout / structuredContent.\n */\nexport function buildSuccessEnvelope(command: string, data: unknown): SuccessEnvelope {\n return { schemaVersion: SCHEMA_VERSION, command, ok: true, data };\n}\n\nexport function buildFailureEnvelope(command: string, err: CliError): FailureEnvelope {\n const error: OutputError = {\n code: err.code,\n message: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n return { schemaVersion: SCHEMA_VERSION, command, ok: false, error };\n}\n\n/**\n * Output contract (human-first): at a TTY without `--json`, print ONLY the human\n * rendering to stdout, no JSON envelope. With `--json`, or when stdout is not a\n * TTY (a pipe, an agent), print exactly one JSON envelope to stdout and nothing\n * else. Exit codes are identical on both paths; only the stdout shape differs.\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n if (humanMode(io, opts)) {\n writeLines(io.stdout, humanLines);\n return;\n }\n writeJson(io.stdout, buildSuccessEnvelope(command, data));\n}\n\n/**\n * The failure half of the same contract: at a TTY without `--json`, a red error\n * line plus a `fix` line to stdout and no envelope; otherwise exactly one failure\n * envelope to stdout. Accepts a CliError or any thrown value (non-CliError\n * normalizes to INTERNAL). Returns the normalized CliError so the caller reads its\n * `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n if (humanMode(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n // Scan findings are the one detail shape a human needs inline: without them an\n // interactive publish hitting NEEDS_CONFIRMATION / PUBLISH_BLOCKED sees the\n // count but not WHICH lines tripped. Every other details shape stays machine-only.\n lines.push(...findingLines(io, cliErr.details));\n writeLines(io.stdout, lines);\n return cliErr;\n }\n writeJson(io.stdout, buildFailureEnvelope(command, cliErr));\n return cliErr;\n}\n\n/**\n * One dim advisory line on stderr, human mode only. This is for facts that belong\n * to NO command's result — an unreadable spend ledger, a newer release on npm —\n * so they can never join the envelope on stdout or reach a machine consumer at\n * all. Sanitized here rather than by each caller: what these lines quote (a\n * registry version string, a parse error) is not the command's own prose.\n */\nexport function emitNotice(io: Io, text: string, opts: EmitOptions = {}): void {\n if (!humanMode(io, opts)) return;\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * Strip ANSI escape sequences, C0/C1 control characters, Unicode bidirectional\n * formatting, and invisible tag/BOM characters from a string headed for a\n * terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm, a right-to-left override to reorder\n * that same line on screen into one that reads as a different price, or tag\n * characters to carry a payload that draws as nothing at all. It is not\n * applied to whole human lines here because trusted callers (doctor) paint\n * their own ANSI colors. JSON stdout is untouched: JSON.stringify escapes C0\n * controls itself, but the bidi and tag/BOM sets ride through it raw, and that\n * is deliberate rather than covered — the envelope is machine-read data whose\n * bytes must be what the server said, and a consumer reading codepoints is not\n * deceived by rendering order the way a human reading a drawn line is.\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n // eslint-disable-next-line no-control-regex\n .replace(/\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n // The UAX#9 directional formatting set: the marks (LRM/RLM/ALM), the\n // embeddings and overrides (U+202A-U+202E), and the isolates\n // (U+2066-U+2069). Removed, not escaped, so what a human reads is the\n // order the bytes are in. Deliberately this set and NOT all of category\n // Cf: U+200D (ZWJ) joins legitimate emoji sequences, and dropping it\n // would corrupt honest titles to defend against dishonest ones.\n .replace(/[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n // The Unicode tag block (U+E0000-U+E007F) and the BOM/ZWNBSP, neither of\n // which has a legitimate mid-title use. Tag characters render as nothing\n // at all, so a payload spelled in them is invisible in the line a human\n // is reading and in the line they would paste back to report it.\n //\n // The three RGI subdivision flags are the exception and survive\n // byte-identical: they are ordinary title content. The whitelist is those\n // three sequences and NOT \"any well-formed tag sequence\", because a\n // non-RGI sequence draws as a bare black flag with the payload hidden\n // behind it, which is the exact channel this closes.\n //\n // Kept for the same reason as ZWJ above: U+200B (ZWSP) hints line breaks\n // in CJK and U+200C (ZWNJ) is orthographically required in Persian, so\n // stripping them would corrupt honest titles to defend against dishonest\n // ones.\n .replace(\n /(\\u{1F3F4}\\u{E0067}\\u{E0062}(?:\\u{E0065}\\u{E006E}\\u{E0067}|\\u{E0073}\\u{E0063}\\u{E0074}|\\u{E0077}\\u{E006C}\\u{E0073})\\u{E007F})|[\\u{E0000}-\\u{E007F}\\u{FEFF}]/gu,\n (_match, rgiFlag: string | undefined) => rgiFlag ?? '',\n )\n );\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\n/** True in human-first mode: a TTY without --json. Otherwise the JSON envelope wins. */\nfunction humanMode(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\n/**\n * Render `details.findings` (the scan-finding projection publish attaches to\n * NEEDS_CONFIRMATION / PUBLISH_BLOCKED) as one dim line per finding:\n * ` <check> (line N): <excerpt>`. The excerpt is already masked for secret\n * findings at the source; sanitize it anyway since it can echo file content.\n * Returns [] for any other details shape, so no other error leaks a detail dump.\n */\nfunction findingLines(io: Io, details: unknown): string[] {\n if (typeof details !== 'object' || details === null || !('findings' in details)) return [];\n const { findings } = details as { findings: unknown };\n if (!Array.isArray(findings) || findings.length === 0) return [];\n const rendered: string[] = [];\n for (const f of findings) {\n if (typeof f !== 'object' || f === null) continue;\n const { check, line, excerpt } = f as { check?: unknown; line?: unknown; excerpt?: unknown };\n if (typeof check !== 'string' || typeof line !== 'number' || typeof excerpt !== 'string') {\n continue;\n }\n rendered.push(paint(io, 'dim', ` ${check} (line ${line}): ${sanitizeForTerminal(excerpt)}`));\n }\n return rendered;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\n/**\n * Color a human line for stdout (the human surface now). styleText emits ANSI only\n * when the target stream is color-capable (a real TTY with color depth) and honors\n * NO_COLOR/FORCE_COLOR natively. The `stream` option is passed only when stdout is\n * a genuine Stream; a test/redirected sink is not one, so it falls back to the\n * default capability check and comes out plain.\n */\nfunction paint(io: Io, format: Parameters<typeof styleText>[0], text: string): string {\n if (io.stdout instanceof Stream) return styleText(format, text, { stream: io.stdout });\n return styleText(format, text);\n}\n","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'SEARCH_NOT_FOUND',\n // A 429 from the anonymous search/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n // A send that reverted or produced no receipt AFTER the human approved it and\n // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.\n 'SEND_FAILED',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discriminatedUnion('ok', [\n SuccessEnvelopeSchema,\n FailureEnvelopeSchema,\n]);\nexport type OutputEnvelope = z.infer<typeof OutputEnvelopeSchema>;\n"],"mappings":";;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,cAAc;;;ACMhB,IAAM,iBAAiB;AAQvB,IAAM,kBAAkB,iBAAE,KAAK;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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