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

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 (116) hide show
  1. package/README.md +107 -33
  2. package/dist/{buy-YMXXVNFH.js → buy-XVOMNWKN.js} +18 -16
  3. package/dist/{candidate-H7FR4AU5.js → candidate-DJB2NNTG.js} +7 -8
  4. package/dist/{chunk-TXPPMK4L.js → chunk-2KIDDWQO.js} +5 -5
  5. package/dist/{chunk-3IRDP7TN.js → chunk-2L73UI6T.js} +6 -4
  6. package/dist/{chunk-3IRDP7TN.js.map → chunk-2L73UI6T.js.map} +1 -1
  7. package/dist/{chunk-ZW3B5LWX.js → chunk-2YX6LTCD.js} +5 -5
  8. package/dist/{chunk-HTDALK7M.js → chunk-5X4EBGGU.js} +15 -12
  9. package/dist/{chunk-HTDALK7M.js.map → chunk-5X4EBGGU.js.map} +1 -1
  10. package/dist/{chunk-RTJLLPFA.js → chunk-6S44OLND.js} +123 -23
  11. package/dist/chunk-6S44OLND.js.map +1 -0
  12. package/dist/{chunk-FU6MCSLG.js → chunk-7WDY4AXV.js} +2 -64
  13. package/dist/chunk-7WDY4AXV.js.map +1 -0
  14. package/dist/{chunk-NFSOVL3C.js → chunk-BBUYCDSG.js} +12 -3
  15. package/dist/chunk-BBUYCDSG.js.map +1 -0
  16. package/dist/chunk-CYRYVZPN.js +213 -0
  17. package/dist/chunk-CYRYVZPN.js.map +1 -0
  18. package/dist/{chunk-MDDGEGSW.js → chunk-DAJ56EUU.js} +3 -3
  19. package/dist/{chunk-IOPWPMT2.js → chunk-DH6D6QIO.js} +5 -5
  20. package/dist/chunk-E6BNARCS.js +614 -0
  21. package/dist/chunk-E6BNARCS.js.map +1 -0
  22. package/dist/chunk-GABYDXWL.js +190 -0
  23. package/dist/chunk-GABYDXWL.js.map +1 -0
  24. package/dist/{chunk-LAM66WFJ.js → chunk-GM4RZUVU.js} +6 -8
  25. package/dist/{chunk-LAM66WFJ.js.map → chunk-GM4RZUVU.js.map} +1 -1
  26. package/dist/{chunk-ZDY2KY5X.js → chunk-GXYNLMUQ.js} +28 -11
  27. package/dist/chunk-GXYNLMUQ.js.map +1 -0
  28. package/dist/{chunk-PAUXMRSF.js → chunk-J6CVKC4M.js} +73 -2
  29. package/dist/chunk-J6CVKC4M.js.map +1 -0
  30. package/dist/{chunk-BIKAUVC2.js → chunk-KT2DGKFT.js} +40 -6
  31. package/dist/chunk-KT2DGKFT.js.map +1 -0
  32. package/dist/chunk-L6AV2Q73.js +105 -0
  33. package/dist/chunk-L6AV2Q73.js.map +1 -0
  34. package/dist/{chunk-CVX6JNGD.js → chunk-OTDI5FXG.js} +3 -5
  35. package/dist/{chunk-CVX6JNGD.js.map → chunk-OTDI5FXG.js.map} +1 -1
  36. package/dist/chunk-PIIWLEEG.js +337 -0
  37. package/dist/chunk-PIIWLEEG.js.map +1 -0
  38. package/dist/{chunk-PYNSGYBE.js → chunk-PLU3E63S.js} +249 -552
  39. package/dist/chunk-PLU3E63S.js.map +1 -0
  40. package/dist/{chunk-C444K6MI.js → chunk-RGFBBNGP.js} +42 -17
  41. package/dist/{chunk-C444K6MI.js.map → chunk-RGFBBNGP.js.map} +1 -1
  42. package/dist/chunk-SGK2B724.js +67 -0
  43. package/dist/chunk-SGK2B724.js.map +1 -0
  44. package/dist/{chunk-5SCU253N.js → chunk-UYP7G3GZ.js} +2 -2
  45. package/dist/{chunk-ZIYVN4CD.js → chunk-VZ3AJCO5.js} +3 -5
  46. package/dist/{chunk-ZIYVN4CD.js.map → chunk-VZ3AJCO5.js.map} +1 -1
  47. package/dist/{chunk-NJF2WENW.js → chunk-WDJTGVKN.js} +2 -2
  48. package/dist/{chunk-NJF2WENW.js.map → chunk-WDJTGVKN.js.map} +1 -1
  49. package/dist/{chunk-4WVKXKDK.js → chunk-WI5EOAQQ.js} +29 -238
  50. package/dist/chunk-WI5EOAQQ.js.map +1 -0
  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-ADJYSM45.js → chunk-ZEWY3RJ3.js} +27 -13
  56. package/dist/chunk-ZEWY3RJ3.js.map +1 -0
  57. package/dist/chunk-ZFE7STX7.js +143 -0
  58. package/dist/chunk-ZFE7STX7.js.map +1 -0
  59. package/dist/{cli-IW76QTN3.js → cli-7B2QNJG3.js} +231 -23
  60. package/dist/cli-7B2QNJG3.js.map +1 -0
  61. package/dist/{config-VCOS7P5K.js → config-SAQEQRFB.js} +5 -6
  62. package/dist/{doctor-WS65JG3V.js → doctor-ENJ22XWN.js} +10 -9
  63. package/dist/{publish-DSFWQRUN.js → edit-2QO5GQDU.js} +18 -16
  64. package/dist/index.js +1 -1
  65. package/dist/{inspect-SFJWUQHO.js → inspect-IPKKQB2S.js} +15 -14
  66. package/dist/{install-RVPQPCKH.js → install-7ZIYISQ7.js} +17 -17
  67. package/dist/outcome-NSDE2KAJ.js +20 -0
  68. package/dist/publish-7WIFFNFG.js +40 -0
  69. package/dist/read-5TQR7LCF.js +158 -0
  70. package/dist/read-5TQR7LCF.js.map +1 -0
  71. package/dist/{run-OMPKA43G.js → run-NPKIP26Y.js} +102 -28
  72. package/dist/{run-OMPKA43G.js.map → run-NPKIP26Y.js.map} +1 -1
  73. package/dist/search-63ELMRZH.js +24 -0
  74. package/dist/{send-3G4C64HJ.js → send-ENE47KQE.js} +7 -7
  75. package/dist/session-FZU4VFFE.js +87 -0
  76. package/dist/session-FZU4VFFE.js.map +1 -0
  77. package/dist/{wallet-PP22LAX7.js → wallet-OCCGEH6H.js} +7 -7
  78. package/dist/{wallet-B7KJS2R5.js → wallet-RBDVNZVR.js} +5 -5
  79. package/dist/wallet-RBDVNZVR.js.map +1 -0
  80. package/package.json +1 -1
  81. package/skills/tenjin/SKILL.md +2 -2
  82. package/skills/tenjin-publish/SKILL.md +12 -4
  83. package/skills/tenjin-search/SKILL.md +68 -12
  84. package/dist/chunk-2JQ5JSG6.js +0 -68
  85. package/dist/chunk-2JQ5JSG6.js.map +0 -1
  86. package/dist/chunk-4WVKXKDK.js.map +0 -1
  87. package/dist/chunk-ADJYSM45.js.map +0 -1
  88. package/dist/chunk-BIKAUVC2.js.map +0 -1
  89. package/dist/chunk-FU6MCSLG.js.map +0 -1
  90. package/dist/chunk-L4IHCN6B.js +0 -63
  91. package/dist/chunk-L4IHCN6B.js.map +0 -1
  92. package/dist/chunk-NFSOVL3C.js.map +0 -1
  93. package/dist/chunk-PAUXMRSF.js.map +0 -1
  94. package/dist/chunk-PYNSGYBE.js.map +0 -1
  95. package/dist/chunk-RTJLLPFA.js.map +0 -1
  96. package/dist/chunk-ZDY2KY5X.js.map +0 -1
  97. package/dist/cli-IW76QTN3.js.map +0 -1
  98. package/dist/outcome-GNYCSZ7J.js +0 -20
  99. package/dist/search-KOI6Y7P6.js +0 -24
  100. /package/dist/{buy-YMXXVNFH.js.map → buy-XVOMNWKN.js.map} +0 -0
  101. /package/dist/{candidate-H7FR4AU5.js.map → candidate-DJB2NNTG.js.map} +0 -0
  102. /package/dist/{chunk-TXPPMK4L.js.map → chunk-2KIDDWQO.js.map} +0 -0
  103. /package/dist/{chunk-ZW3B5LWX.js.map → chunk-2YX6LTCD.js.map} +0 -0
  104. /package/dist/{chunk-MDDGEGSW.js.map → chunk-DAJ56EUU.js.map} +0 -0
  105. /package/dist/{chunk-IOPWPMT2.js.map → chunk-DH6D6QIO.js.map} +0 -0
  106. /package/dist/{chunk-5SCU253N.js.map → chunk-UYP7G3GZ.js.map} +0 -0
  107. /package/dist/{config-VCOS7P5K.js.map → config-SAQEQRFB.js.map} +0 -0
  108. /package/dist/{doctor-WS65JG3V.js.map → doctor-ENJ22XWN.js.map} +0 -0
  109. /package/dist/{inspect-SFJWUQHO.js.map → edit-2QO5GQDU.js.map} +0 -0
  110. /package/dist/{outcome-GNYCSZ7J.js.map → inspect-IPKKQB2S.js.map} +0 -0
  111. /package/dist/{install-RVPQPCKH.js.map → install-7ZIYISQ7.js.map} +0 -0
  112. /package/dist/{publish-DSFWQRUN.js.map → outcome-NSDE2KAJ.js.map} +0 -0
  113. /package/dist/{search-KOI6Y7P6.js.map → publish-7WIFFNFG.js.map} +0 -0
  114. /package/dist/{wallet-B7KJS2R5.js.map → search-63ELMRZH.js.map} +0 -0
  115. /package/dist/{send-3G4C64HJ.js.map → send-ENE47KQE.js.map} +0 -0
  116. /package/dist/{wallet-PP22LAX7.js.map → wallet-OCCGEH6H.js.map} +0 -0
package/README.md CHANGED
@@ -35,20 +35,23 @@ tenjin search "what actually changed in <library> v3's public API" # your firs
35
35
 
36
36
  ## Commands
37
37
 
38
- | Command | Purpose |
39
- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
40
- | `tenjin install` | Walk you through harness skills, your publish consent mode, and wallet setup, then run the doctor checks |
41
- | `tenjin doctor` | Environment, API reachability, contract, skill-wiring, and wallet checks |
42
- | `tenjin config [get\|set]` | Spend policy (`maxAutoSpend`, `sessionBudget`, `confirm`, allowlists) and `publish.mode` / `publish.defaultPrice` |
43
- | `tenjin wallet [create\|show\|balance]` | Local Base wallet; the key never leaves the machine |
44
- | `tenjin search "<question>"` | Ask for payable candidates or an honest MISS; prints the compact JSON verbatim |
45
- | `tenjin inspect <url-or-id>` | Show a candidate's pre-purchase card from the 402 body; never pays |
46
- | `tenjin buy <url-or-id> [--max-price <usd>] [--yes]` | Entitlement re-check (free re-read if owned), then x402 exact payment |
47
- | `tenjin outcome --search-id <id> --status <s>` | Report `used` / `partially_used` / `rejected` / `regenerated` / `purchase_declined` |
48
- | `tenjin publish <file.md> [--price <usd>] [--mode <m>]` | Publish a Markdown piece with an optional answer card, gated by a local scan and your consent mode |
49
- | `tenjin publish --candidate <id>` | Publish a parked candidate (its `draft.md`); clears it on success |
50
- | `tenjin candidate [add\|list\|drop]` | Park, list, or discard local publish drafts; a search MISS nudges you about parked ones |
51
- | `tenjin send <amount> usdc <to> [--yes]` | **Escape hatch:** move USDC on Base out of the agent wallet (preview, explicit confirm, then the tx hash) |
38
+ | Command | Purpose |
39
+ | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
40
+ | `tenjin install` | Walk you through harness skills, your publish consent mode, and wallet setup, then run the doctor checks |
41
+ | `tenjin doctor` | Environment, API reachability, contract, skill-wiring, and wallet checks |
42
+ | `tenjin config [get\|set]` | Spend policy (`maxAutoSpend`, `sessionBudget`, `confirm`, allowlists) and `publish.mode` / `publish.defaultPrice` |
43
+ | `tenjin wallet [create\|show\|balance]` | Local Base wallet; the key never leaves the machine |
44
+ | `tenjin search "<question>"` | Ask for payable candidates or an honest MISS; prints the compact JSON verbatim |
45
+ | `tenjin inspect <url-or-id>` | Show a candidate's pre-purchase card from the 402 body; never pays |
46
+ | `tenjin read <url-or-id>` | Deliver a free piece, re-deliver from the local library, or recover one you own with a cached session key (never a payment); refuses with exit 3 if it would cost |
47
+ | `tenjin session start [--scope read]` | Open the wallet once to mint a ≤24h read-scoped session key, so `read` can recover owned pieces unattended; spends nothing |
48
+ | `tenjin buy <url-or-id> [--max-price <usd>] [--yes]` | Entitlement re-check (free re-read if owned), then x402 exact payment |
49
+ | `tenjin outcome --search-id <id> --status <s>` | Report `used` / `partially_used` / `rejected` / `regenerated` / `purchase_declined` |
50
+ | `tenjin publish <file.md> [--price <usd>] [--mode <m>]` | Publish a Markdown piece with an optional answer card, gated by a local scan and your consent mode |
51
+ | `tenjin publish --candidate <id>` | Publish a parked candidate (its `draft.md`); clears it on success |
52
+ | `tenjin edit <postId> [flags] [--yes]` | Show one of your posts and its card, or merge-update it: omitted fields are kept, `--clear <field>` clears one |
53
+ | `tenjin candidate [add\|list\|drop]` | Park, list, or discard local publish drafts; a search MISS nudges you about parked ones |
54
+ | `tenjin send <amount> usdc <to> [--yes]` | **Escape hatch:** move USDC on Base out of the agent wallet (preview, explicit confirm, then the tx hash) |
52
55
 
53
56
  `send` is human-invoked only: it is deliberately absent from the MCP toolset and
54
57
  the harness skills, and nothing is signed until the previewed (checksummed)
@@ -62,10 +65,44 @@ For routing FUTURE revenue away from the agent wallet entirely, connect the
62
65
  agent to your own Tenjin account instead (delegation); `send` exists for funds
63
66
  already sitting on the agent key.
64
67
 
65
- `buy` re-reads an entitled resource for free before ever paying, re-delivers
66
- already-bought content from the local library without paying again, and refuses to
67
- sign if the price rose since it first saw the 402. Spend policy is enforced in the
68
- wallet provider layer before any payment.
68
+ `read` and `buy` split delivery by whether money can move, not by how much work is
69
+ involved. `read` is free-only and tries three things in order: the local library,
70
+ then an unauthenticated fetch (which delivers free pieces), then — only if a
71
+ read-scoped session key is already cached — one signed GET presenting that
72
+ delegation, which delivers a piece this wallet already bought. A paid piece that
73
+ none of the three reaches hard-refuses (exit 3) with the price and a pointer at
74
+ `buy`; the refusal's `entitlementCheck` says whether a session was actually
75
+ presented (`session`) or there was none to present (`not_performed`).
76
+
77
+ `tenjin session start --scope read` is what mints that key: one wallet signature,
78
+ ≤24h, spends nothing. It is a separate opt-in verb precisely so `read` never needs
79
+ the wallet — `read` imports no wallet, payment, or session-MINTING module, and its
80
+ import graph is test-pinned to stay clear of all three. It cannot unlock a
81
+ keystore at all and never consults the spend policy. The key it may present is
82
+ P-256: the wrong curve for the EIP-712/secp256k1 signature an EIP-3009 transfer
83
+ authorization needs, so `read` cannot pay however it is refactored.
84
+
85
+ The session file itself is a **wallet-derived credential** — treat it like one.
86
+ Its scope is not a containment boundary, so do not read "read-scoped" as a limit
87
+ on what a copied file is worth. What actually bounds it: it expires within 24h
88
+ (server-clamped), it is stored 0600, and it records the origin it was minted for
89
+ and is never presented anywhere else. That last one is why a stray `--base-url`
90
+ cannot redirect it to a host an agent picked.
91
+
92
+ `buy` is the paying verb: it re-reads an entitled resource for free before ever
93
+ paying, re-delivers already-bought content from the local library without paying
94
+ again, and refuses to sign if the price rose since it first saw the 402. Spend
95
+ policy is enforced in the wallet provider layer before any payment.
96
+
97
+ `edit` sends only the fields you pass, so an omitted field is kept; `--clear
98
+ <field>` is the one way to empty a card field, and `--question` / `--task`
99
+ replace the stored list while `--add-question` / `--add-task` append to it. The
100
+ append flags read the post and then write it back, with no concurrency guard (the
101
+ API offers no `If-Match`), so a web-panel edit landing between the two calls can
102
+ be overwritten. Reading your own post is owner-scoped, so even the no-flag show
103
+ signs with your wallet on first use, minting a read-scoped 24h session; only a run
104
+ that intends to write asks for a write-capable one. An edit sends only what
105
+ actually changes, so re-running the same command writes nothing.
69
106
 
70
107
  Read output defaults to a heading outline, not the body: `--print-body` includes
71
108
  the full body, and `--sections <tokens>` includes the leading sections within a
@@ -130,6 +167,7 @@ array of `.claude/settings.json`:
130
167
  ```
131
168
  Bash(tenjin search:*)
132
169
  Bash(tenjin inspect:*)
170
+ Bash(tenjin read:*)
133
171
  Bash(tenjin outcome:*)
134
172
  Bash(tenjin doctor:*)
135
173
  Bash(tenjin wallet show:*)
@@ -138,11 +176,22 @@ Bash(tenjin config get:*)
138
176
  Bash(tenjin candidate list:*)
139
177
  ```
140
178
 
141
- None of those touches the wallet, signs anything, or moves money. Two are not
142
- read-only, which is worth knowing before you pre-clear them: `tenjin search` POSTs
143
- your generalized question off-machine, and `tenjin outcome` POSTs a report that
144
- moves the marketplace's reuse signal. Both are unauthenticated and free; neither
145
- carries a credential.
179
+ None of those can spend, and none can open the keystore. That is the definition of
180
+ this tier, and it is deliberately narrower than "signs nothing": `tenjin read` can
181
+ present a session key that already exists (below), which is a signature — a P-256
182
+ delegation, the wrong curve to authorize a USDC transfer. It cannot mint one; that
183
+ needs the wallet.
184
+
185
+ Worth knowing before you paste the `read` line: once a session key exists, `read`
186
+ **transmits that wallet-derived credential** to the origin it was minted for. That
187
+ origin binding is what keeps a stray `--base-url` from redirecting it, and it is
188
+ the reason the binding exists rather than a nicety.
189
+
190
+ Three are not read-only, which is worth knowing before you pre-clear them:
191
+ `tenjin search` POSTs your generalized question off-machine, and `tenjin outcome`
192
+ POSTs a report that moves the marketplace's reuse signal — both unauthenticated
193
+ and free, neither carrying a credential — while `tenjin read` writes locally,
194
+ saving a delivered piece to your library.
146
195
 
147
196
  `tenjin install` prints this block, and `tenjin doctor` reprints it on every run
148
197
  (including in `doctor --json` under `permissions`, on the failure envelope as well
@@ -185,6 +234,31 @@ tenjin config set sessionBudget 2.00
185
234
  The allowlist line itself never raises a spend cap. That is true, and it is not
186
235
  the same as saying the caps stop an allowlisted `buy`.
187
236
 
237
+ Minting a session key is the **other** explicit opt-in — it spends nothing and
238
+ cannot spend, but it opens the keystore:
239
+
240
+ ```
241
+ Bash(tenjin session start:*)
242
+ ```
243
+
244
+ `tenjin session start --scope read` takes one wallet signature and leaves a ≤24h
245
+ P-256 delegation in `~/.tenjin/session.json` (0600), which `tenjin read` then
246
+ presents to recover pieces you already own. The key is the wrong curve to sign an
247
+ EIP-3009 payment authorization, so the line can never become a spend grant.
248
+
249
+ Do not read the `read` scope as more than that. The scope is enforced only on the
250
+ request shape that carries a session signature alongside the delegation header; a
251
+ copy of the same delegation presented differently is not scope-checked, so treat
252
+ the file as a credential carrying your wallet's authority. Its real bounds are the
253
+ 24h expiry, the 0600 mode, and the origin binding.
254
+
255
+ What you are clearing is **unattended keystore access**: on an encrypted wallet
256
+ the passphrase comes from the environment rather than from you, and the
257
+ `--base-url` caveat above bites hardest here, because a mint against a host an
258
+ agent chose is a wallet signature you did not intend to make. `tenjin doctor`
259
+ reports whether a session exists, for which origin, at what scope, and when it
260
+ expires.
261
+
188
262
  Deliberately **never** recommended, because each is a human decision: `tenjin send`
189
263
  (moves USDC out of the wallet, and is not bounded by the buy spend policy), `tenjin
190
264
  publish`, `tenjin wallet create`, `tenjin config set` (it can widen the agent's own
@@ -324,16 +398,16 @@ server the CLI ships (see [Local stdio MCP server](#local-stdio-mcp-server)).
324
398
  ## Local stdio MCP server
325
399
 
326
400
  `tenjin mcp` runs a local MCP server over stdio backed by the same command cores
327
- as the CLI (`search`, `inspect`, `buy`, `outcome`, `publish`, `candidate`, and
328
- `wallet`), in-process, no shelling out. It exposes seven tools (`tenjin_search`,
329
- `tenjin_inspect`, `tenjin_buy`, `tenjin_outcome`, `tenjin_publish`,
330
- `tenjin_candidate`, `tenjin_wallet`), each returning the machine JSON envelope as
331
- `structuredContent` with a short text summary. The consent gates carry over
332
- exactly: the spend policy gates `tenjin_buy`, `publish.mode` gates
333
- `tenjin_publish` (the client renders the `needs_confirmation` payload as its own
334
- confirm UI, then re-calls with `yes:true`), and a hard content block is never
335
- bypassable. The wallet stays local: the key never leaves the machine and appears
336
- in no tool result.
401
+ as the CLI (`search`, `inspect`, `buy`, `outcome`, `publish`, `edit`,
402
+ `candidate`, and `wallet`), in-process, no shelling out. It exposes eight tools
403
+ (`tenjin_search`, `tenjin_inspect`, `tenjin_buy`, `tenjin_outcome`,
404
+ `tenjin_publish`, `tenjin_edit`, `tenjin_candidate`, `tenjin_wallet`), each
405
+ returning the machine JSON envelope as `structuredContent` with a short text
406
+ summary. The consent gates carry over exactly: the spend policy gates
407
+ `tenjin_buy`, `publish.mode` gates `tenjin_publish` and `tenjin_edit` (the client
408
+ renders the `needs_confirmation` payload as its own confirm UI, then re-calls
409
+ with `yes:true`), and a hard content block is never bypassable. The wallet stays
410
+ local: the key never leaves the machine and appears in no tool result.
337
411
 
338
412
  **Claude Code**
339
413
 
@@ -1,30 +1,32 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  runBuy
4
- } from "./chunk-4WVKXKDK.js";
5
- import "./chunk-BIKAUVC2.js";
6
- import "./chunk-FU6MCSLG.js";
4
+ } from "./chunk-WI5EOAQQ.js";
5
+ import "./chunk-L6AV2Q73.js";
6
+ import "./chunk-KT2DGKFT.js";
7
+ import "./chunk-SGK2B724.js";
8
+ import "./chunk-7WDY4AXV.js";
7
9
  import "./chunk-POJRB2AE.js";
8
10
  import "./chunk-QW2Q2KAH.js";
9
- import "./chunk-C444K6MI.js";
10
- import "./chunk-QONTBYQW.js";
11
- import "./chunk-L4IHCN6B.js";
12
- import "./chunk-CVX6JNGD.js";
13
- import "./chunk-3IRDP7TN.js";
11
+ import "./chunk-RGFBBNGP.js";
12
+ import "./chunk-WRWCDLVK.js";
13
+ import "./chunk-CYRYVZPN.js";
14
+ import "./chunk-OTDI5FXG.js";
15
+ import "./chunk-2L73UI6T.js";
14
16
  import "./chunk-WWX32ML4.js";
15
- import "./chunk-ZDY2KY5X.js";
16
- import "./chunk-NJF2WENW.js";
17
- import "./chunk-NFSOVL3C.js";
17
+ import "./chunk-GXYNLMUQ.js";
18
+ import "./chunk-WDJTGVKN.js";
19
+ import "./chunk-XBJ3VLWX.js";
18
20
  import "./chunk-2I4QTOLB.js";
21
+ import "./chunk-BBUYCDSG.js";
19
22
  import "./chunk-KZAAWQNP.js";
20
23
  import "./chunk-S5RYMCV6.js";
21
24
  import "./chunk-YLYINX2H.js";
22
- import "./chunk-MDDGEGSW.js";
25
+ import "./chunk-DAJ56EUU.js";
23
26
  import "./chunk-YBMMV4Y4.js";
24
27
  import "./chunk-UO22YNY4.js";
25
- import "./chunk-5SCU253N.js";
26
- import "./chunk-2JQ5JSG6.js";
27
- import "./chunk-PAUXMRSF.js";
28
+ import "./chunk-UYP7G3GZ.js";
29
+ import "./chunk-J6CVKC4M.js";
28
30
  import "./chunk-MJZZTKCC.js";
29
31
  import "./chunk-7FK2UN2T.js";
30
32
  import "./chunk-M2O56UK7.js";
@@ -39,4 +41,4 @@ import "./chunk-ZXTAQYNA.js";
39
41
  export {
40
42
  runBuy
41
43
  };
42
- //# sourceMappingURL=buy-YMXXVNFH.js.map
44
+ //# sourceMappingURL=buy-XVOMNWKN.js.map
@@ -3,20 +3,19 @@ import {
3
3
  runCandidateAdd,
4
4
  runCandidateDrop,
5
5
  runCandidateList
6
- } from "./chunk-ZW3B5LWX.js";
7
- import "./chunk-ZIYVN4CD.js";
6
+ } from "./chunk-2YX6LTCD.js";
7
+ import "./chunk-VZ3AJCO5.js";
8
8
  import "./chunk-WWX32ML4.js";
9
- import "./chunk-NFSOVL3C.js";
10
9
  import "./chunk-2I4QTOLB.js";
11
- import "./chunk-MDDGEGSW.js";
10
+ import "./chunk-BBUYCDSG.js";
11
+ import "./chunk-DAJ56EUU.js";
12
12
  import "./chunk-UO22YNY4.js";
13
- import "./chunk-5SCU253N.js";
14
- import "./chunk-2JQ5JSG6.js";
15
- import "./chunk-PAUXMRSF.js";
13
+ import "./chunk-UYP7G3GZ.js";
14
+ import "./chunk-J6CVKC4M.js";
16
15
  import "./chunk-ZXTAQYNA.js";
17
16
  export {
18
17
  runCandidateAdd,
19
18
  runCandidateDrop,
20
19
  runCandidateList
21
20
  };
22
- //# sourceMappingURL=candidate-H7FR4AU5.js.map
21
+ //# sourceMappingURL=candidate-DJB2NNTG.js.map
@@ -1,17 +1,17 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  latestSearch
4
- } from "./chunk-CVX6JNGD.js";
4
+ } from "./chunk-OTDI5FXG.js";
5
5
  import {
6
6
  buildOutcomeItem,
7
7
  postOutcomes
8
- } from "./chunk-3IRDP7TN.js";
8
+ } from "./chunk-2L73UI6T.js";
9
9
  import {
10
10
  resolveContextSettings
11
- } from "./chunk-MDDGEGSW.js";
11
+ } from "./chunk-DAJ56EUU.js";
12
12
  import {
13
13
  CliError
14
- } from "./chunk-PAUXMRSF.js";
14
+ } from "./chunk-J6CVKC4M.js";
15
15
 
16
16
  // src/commands/outcome.ts
17
17
  async function runOutcome(args, ctx, deps = {}) {
@@ -56,4 +56,4 @@ async function resolveSearchId(args, ctx) {
56
56
  export {
57
57
  runOutcome
58
58
  };
59
- //# sourceMappingURL=chunk-TXPPMK4L.js.map
59
+ //# sourceMappingURL=chunk-2KIDDWQO.js.map
@@ -5,13 +5,15 @@ import {
5
5
  } from "./chunk-WWX32ML4.js";
6
6
  import {
7
7
  CLIENT_HEADER,
8
- httpRequest,
8
+ httpRequest
9
+ } from "./chunk-GXYNLMUQ.js";
10
+ import {
9
11
  trimSlash
10
- } from "./chunk-ZDY2KY5X.js";
12
+ } from "./chunk-XBJ3VLWX.js";
11
13
  import {
12
14
  CliError,
13
15
  external_exports
14
- } from "./chunk-PAUXMRSF.js";
16
+ } from "./chunk-J6CVKC4M.js";
15
17
 
16
18
  // src/lib/agent-api.ts
17
19
  var FRESH_WITHIN_RE = /^P(\d+)[DWMY]$/;
@@ -317,4 +319,4 @@ export {
317
319
  buildOutcomeItem,
318
320
  postOutcomes
319
321
  };
320
- //# sourceMappingURL=chunk-3IRDP7TN.js.map
322
+ //# sourceMappingURL=chunk-2L73UI6T.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/agent-api.ts"],"sourcesContent":["import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResult } from './http';\nimport { CLIENT_HEADER } from './client-meta';\nimport { ATOMIC_RE, UUID_RE } from './ids';\nimport { trimSlash } from './url';\n\n/**\n * The search + outcome HTTP contract (A2, tenjin#370). Request building and\n * response validation live here; the wire shape is validated defensively, an\n * unknown `schemaVersion` degrades to a parse refusal rather than a guess, and\n * unrecognized candidate fields are ignored (forward-compatible), per spec 10.\n *\n * These endpoints are anonymous: no wallet, no SIWX. The only header of note is\n * `X-Tenjin-Client`, which attributes a later purchase back to the search flow.\n */\n\nconst FRESH_WITHIN_RE = /^P(\\d+)[DWMY]$/;\nconst CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;\n\n/** The server's `limit` ceiling. Exported because the truncation advice in\n * `search` has to name it: past search v2 the response budget scales with the\n * candidates returned, so a truncated page is recovered by asking for MORE, and\n * this is the value to ask for. One definition, so the cap the CLI enforces and\n * the number it tells the operator to retry with cannot drift apart. */\nexport const MAX_LIMIT = 10;\n\n/** Client-side search request (mirrors the server lookupRequestSchema bounds\n * so a malformed flag fails locally as USAGE, before a round trip). */\nexport interface SearchInput {\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit?: number;\n}\n\nexport interface SearchRequestBody {\n schemaVersion: 2;\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit: number;\n}\n\nexport function buildSearchRequest(input: SearchInput): SearchRequestBody {\n const question = input.question.trim();\n if (question.length === 0 || question.length > 512) {\n throw new CliError('USAGE', 'question must be 1 to 512 characters', {\n fix: 'Pass a non-empty question under 512 characters.',\n });\n }\n if (input.freshWithin !== undefined) {\n // The server rejects ANY zero-valued duration (P0D, P0W, P00M, ...), so a\n // zero window fails here as USAGE instead of a remote 400.\n const digits = FRESH_WITHIN_RE.exec(input.freshWithin)?.[1];\n if (digits === undefined || Number(digits) === 0) {\n throw new CliError('USAGE', `Invalid --fresh-within: ${JSON.stringify(input.freshWithin)}`, {\n fix: 'Use a nonzero ISO-like window P<n>[DWMY], e.g. P30D, P2W, P1Y.',\n });\n }\n }\n if (input.maxPrice !== undefined && !ATOMIC_RE.test(input.maxPrice)) {\n throw new CliError('USAGE', `Invalid --max-price: ${JSON.stringify(input.maxPrice)}`, {\n fix: 'Pass an atomic USDC integer, e.g. 100000 for $0.10.',\n });\n }\n const limit = input.limit ?? 5;\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(input.limit)}`, {\n fix: `Pass an integer between 1 and ${MAX_LIMIT}.`,\n });\n }\n if (input.appliesTo !== undefined) {\n // Mirror the server's strictObject bounds (<=8 keys, <=20 values/key,\n // 1..120 chars/value) so a bad filter fails locally, never as a remote 400.\n const keys = Object.keys(input.appliesTo);\n if (keys.length > 8) {\n throw new CliError('USAGE', 'Too many --applies-to keys (max 8).');\n }\n for (const [key, values] of Object.entries(input.appliesTo)) {\n if (!CANONICAL_KEY_RE.test(key)) {\n throw new CliError('USAGE', `Invalid appliesTo key: ${JSON.stringify(key)}`, {\n fix: 'Keys must be canonical lowercase identifiers, e.g. products=Vercel.',\n });\n }\n if (values.length === 0) {\n throw new CliError('USAGE', `appliesTo key ${JSON.stringify(key)} has no values`, {\n fix: 'Give each --applies-to key at least one value.',\n });\n }\n if (values.length > 20) {\n throw new CliError('USAGE', `Too many --applies-to values for ${key} (max 20).`);\n }\n for (const value of values) {\n if (value.length === 0 || value.length > 120) {\n throw new CliError(\n 'USAGE',\n `Invalid --applies-to value for ${key}: must be 1 to 120 characters.`,\n );\n }\n }\n }\n }\n return {\n schemaVersion: 2,\n question,\n ...(input.freshWithin !== undefined ? { freshWithin: input.freshWithin } : {}),\n ...(input.maxPrice !== undefined ? { maxPrice: input.maxPrice } : {}),\n ...(input.appliesTo !== undefined ? { appliesTo: input.appliesTo } : {}),\n limit,\n };\n}\n\n// Response schemas. `.passthrough()` on the candidate keeps unknown future fields\n// instead of stripping them (forward-compatible), while still requiring the\n// contract fields this CLI reads. `decision` is uppercase on the wire.\n//\n// A candidate is a LEAN hit (search v2): identity, price, freshness and why it\n// matched, and nothing more. The full answer card is one free unpaid GET of `url`\n// away, which is what `tenjin inspect` does, so breadth here costs no depth there.\nexport const searchCandidateSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string(),\n slug: z.string(),\n title: z.string(),\n artifactType: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n matchReasons: z.array(z.string()),\n estimatedTokens: z.number(),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchCandidate = z.infer<typeof searchCandidateSchema>;\n\n/** Per-field caps for a browse pointer's free-form strings. `url` gets its own,\n * looser bound so a legitimate read URL is never mangled while an invented one\n * still cannot run away. Declared above the schema because the schema enforces\n * the `url` bound at parse time (see below). */\nconst BROWSE_BOUNDS = { title: 200, url: 512, handle: 64 } as const;\n\n// A browse pointer, carried ONLY on a MISS (tenjin#460): a piece from the broad\n// discoverable corpus with deliberately NO matchReasons, NO estimatedTokens and\n// no confidence field. It is a \"you might browse this\" hint, never a scored\n// answer candidate, so it is kept strictly out of `candidates` and never\n// recorded in the local search store.\n//\n// That store exclusion makes `inspect`/`buy`/`outcome` unreachable BY\n// `resourceId` (resolveResourceRef's uuid arm needs a store hit and fails with\n// RESOURCE_NOT_FOUND), but NOT by url: resolveResourceRef's URL arm is gated on\n// origin alone and never consults the store, so `tenjin buy <browse url>` does\n// pay. That is by design here, since the url is the payable read endpoint and\n// the contract re-emits it verbatim, but it is a real spend path, so the human\n// hint line carries the price and every spend gate still applies. Do not\n// restate the old \"never reachable by inspect/buy/outcome\" claim: it was false.\n//\n// A malformed pointer fails the WHOLE response into CONTRACT_MISMATCH rather\n// than being dropped. Deliberate: this client is fail-closed on every other\n// contract deviation, and silently swallowing a bad tail would hide server\n// drift that contract.test.ts exists to catch. Pinned in agent-api.test.ts.\n//\n// The `url` bound is enforced HERE rather than by truncation in the projection\n// below, and that asymmetry with `title`/`handle` is deliberate. Those two are\n// display strings: clipping one degrades gracefully and the human still reads\n// something true. `url` is an actionable payable pointer, and a clipped url is\n// not a shorter url, it is a DIFFERENT and broken one that still looks payable\n// in `--json`. Refusing is also the only ordering-independent answer: capping\n// first would hand the origin assertion in `runSearch` a string the server never\n// sent. 512 is far above any real read endpoint, so exceeding it is server drift.\nexport const searchBrowseSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string().max(BROWSE_BOUNDS.url, `url must be at most ${BROWSE_BOUNDS.url} characters`),\n title: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchBrowse = z.infer<typeof searchBrowseSchema>;\n\nexport const searchResponseSchema = z.object({\n schemaVersion: z.literal(2),\n searchId: z.string().regex(UUID_RE, 'searchId must be a uuid'),\n decision: z.enum(['CANDIDATES', 'MISS']),\n calibration: z.string(),\n candidates: z.array(searchCandidateSchema).optional(),\n // Set only when the server's size backstop dropped trailing candidates the\n // requested limit had room for; omitted entirely otherwise. There is no cursor,\n // so a retry at a SMALLER limit returns strictly fewer rows; the ceiling scales\n // with the candidates returned, so a LARGER limit (up to MAX_LIMIT) is what\n // recovers the tail, and at MAX_LIMIT the tail is unrecoverable and narrowing the\n // question is the remedy. `runSearch` picks the half that applies.\n truncated: z.literal(true).optional(),\n // Omitted entirely by the server when empty, and only ever present on a MISS.\n // Not enforced here (a stricter schema would reject an otherwise-usable\n // response); truncateResponse drops it on a CANDIDATES decision instead.\n browse: z.array(searchBrowseSchema).optional(),\n});\n\nexport type SearchResponse = z.infer<typeof searchResponseSchema>;\n\nexport interface AgentApiOptions {\n baseUrl: string;\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** Spec 09 §3 evaluation-cohort opt-in: sends X-Tenjin-Eval-Cohort: 1. */\n evalCohort?: boolean;\n}\n\n/** Turn a non-2xx / transport HttpResult into the CLI error contract. */\nfunction apiFailure(url: string, result: Exclude<HttpResult, { ok: true }>): CliError {\n const code =\n result.kind === 'network' || result.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n return new CliError(code, `${url}: ${result.message}`, {\n fix: 'Check your network and the configured base URL (`tenjin config get baseUrl`), then retry.',\n });\n}\n\n/** 429 with Retry-After: a recoverable pause, not an outage; agents branch on it. */\nexport function rateLimitError(\n url: string,\n header: (name: string) => string | undefined,\n): CliError {\n const retryAfter = header('retry-after');\n const seconds = retryAfter !== undefined ? Number(retryAfter) : undefined;\n return new CliError('RATE_LIMITED', `${url}: rate limited by the server.`, {\n fix:\n seconds !== undefined && Number.isFinite(seconds)\n ? `Retry after ${seconds}s.`\n : 'Back off and retry shortly.',\n details: {\n ...(seconds !== undefined && Number.isFinite(seconds) ? { retryAfterSeconds: seconds } : {}),\n },\n });\n}\n\nfunction serverErrorMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n const err = rec.error;\n if (typeof err === 'string') return err;\n if (typeof err === 'object' && err !== null) {\n const m = (err as Record<string, unknown>).message;\n if (typeof m === 'string') return m;\n }\n if (typeof rec.message === 'string') return rec.message;\n }\n return undefined;\n}\n\nexport async function postSearch(\n body: SearchRequestBody,\n opts: AgentApiOptions,\n): Promise<SearchResponse> {\n const url = `${trimSlash(opts.baseUrl)}/api/agent/search`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: {\n 'x-tenjin-client': CLIENT_HEADER,\n ...(opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {}),\n },\n jsonBody: body,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) {\n // The REQUEST gate is where a pre-v2 server actually refuses us, and it is\n // the arm that fires in practice. Old tenjin declares `schemaVersion:\n // z.literal(1)` inside a strictObject, so a v2 request never reaches the\n // handler: it comes back 400 \"Invalid request body\" with the zod flatten in\n // `error.details`, and the response check further down can never see it.\n // Without this the operator is told to retry a request that cannot succeed.\n if (res.status === 400 && rejectedSchemaVersion(res.json)) {\n throw outdatedServerError('The server rejected schemaVersion 2: it predates search v2.', {\n details: res.json,\n });\n }\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Search failed (${res.status})`,\n {\n fix: 'Retry; if it persists the search endpoint may be unavailable.',\n details: res.json,\n },\n );\n }\n const parsed = searchResponseSchema.safeParse(res.json);\n if (!parsed.success) {\n // The other way a stale server surfaces: it answered 200 with a v1 body.\n // Unreachable against today's old tenjin (the request gate above refuses\n // first), but correct for anything that accepts the request and replies v1.\n const served = serverSchemaVersion(res.json);\n if (served !== undefined && served !== 2) {\n throw outdatedServerError(\n `Search response is schemaVersion ${served}; this CLI requires 2 (search v2).`,\n { details: parsed.error.issues },\n );\n }\n throw new CliError('CONTRACT_MISMATCH', 'Search response did not match the expected contract', {\n fix: 'Update tenjin-cli; the server contract may have changed.',\n details: parsed.error.issues,\n });\n }\n return truncateResponse(parsed.data);\n}\n\n/** One wording for both ways a pre-v2 server refuses this CLI, so the request-gate\n * arm and the response arm can never drift apart. */\nfunction outdatedServerError(message: string, opts: { details: unknown }): CliError {\n return new CliError('CONTRACT_MISMATCH', message, {\n fix: 'The server predates search v2. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.',\n details: opts.details,\n });\n}\n\n/** True when a 400 body is the old server's request-gate refusal of our\n * `schemaVersion`: an ApiError envelope whose zod `flatten()` details carry a\n * `schemaVersion` fieldError. Keyed on the field, never the message text. */\nfunction rejectedSchemaVersion(json: unknown): boolean {\n const record = (v: unknown): Record<string, unknown> | undefined =>\n typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : undefined;\n const fieldErrors = record(record(record(json)?.error)?.details)?.fieldErrors;\n return Array.isArray(record(fieldErrors)?.schemaVersion);\n}\n\n/** The `schemaVersion` an unparsed body claims, when it claims a number at all. */\nfunction serverSchemaVersion(json: unknown): number | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const v = (json as { schemaVersion?: unknown }).schemaVersion;\n return typeof v === 'number' ? v : undefined;\n}\n\n/**\n * The server bounds every free-form candidate string (spec 09); re-apply the same\n * caps defensively so a misbehaving server cannot blow up an agent transcript\n * through the CLI (spec 10 response-size discipline).\n *\n * `slug` is deliberately absent: it is an identifier, not display text, so\n * clipping it would not shorten it but change it into a slug that resolves to\n * nothing while still looking usable in `--json`. The server tolerates an\n * uncapped slug for the same reason (that is the one case its `truncated` flag\n * exists for), so capping here would fail on a response the server calls valid.\n */\nconst CAND_BOUNDS = {\n title: 200,\n matchReasons: 3,\n matchReasonChars: 80,\n} as const;\n\nconst cap = (s: string, n: number): string => (s.length > n ? s.slice(0, n) : s);\n\nfunction truncateResponse(res: SearchResponse): SearchResponse {\n const out: SearchResponse = { ...res };\n if (res.candidates !== undefined) out.candidates = res.candidates.map(truncateCandidate);\n // Browse pointers ride the same defensive discipline, and then some. The\n // schema is `.passthrough()` so a server-invented key would otherwise survive\n // at unbounded length into `--json` and MCP structuredContent; we rebuild each\n // pointer explicitly from the five contract fields instead of spreading, which\n // drops unknown keys and is what makes the contract.test.ts \"no score-like\n // field\" pin hold at runtime and not just against the fixture. Count is capped\n // at the server's BROWSE_MAX, and every free-form string (title, url, handle)\n // at its own bound.\n //\n // `browse` is MISS-only by contract; drop it outright on a CANDIDATES decision\n // rather than trust the server, since humanLines renders no hint line there and\n // it would otherwise be an unrendered channel of server text and payable urls.\n if (res.browse !== undefined && res.decision === 'MISS') {\n out.browse = res.browse.slice(0, BROWSE_MAX).map((b) => ({\n resourceId: b.resourceId,\n // Not capped: the schema already refused anything over BROWSE_BOUNDS.url,\n // so this is the url the server sent, verbatim and payable.\n url: b.url,\n title: cap(b.title, BROWSE_BOUNDS.title),\n price: b.price,\n creator: { handle: cap(b.creator.handle, BROWSE_BOUNDS.handle) },\n }));\n } else {\n delete out.browse;\n }\n return out;\n}\n\n/** Mirrors the server's BROWSE_MAX (lib/search-browse.ts): a MISS carries at\n * most three browse pointers. */\nconst BROWSE_MAX = 3;\n\nfunction truncateCandidate(c: SearchCandidate): SearchCandidate {\n return {\n ...c,\n title: cap(c.title, CAND_BOUNDS.title),\n matchReasons: c.matchReasons\n .slice(0, CAND_BOUNDS.matchReasons)\n .map((r) => cap(r, CAND_BOUNDS.matchReasonChars)),\n };\n}\n\nconst OUTCOME_STATUSES = [\n 'used',\n 'partially_used',\n 'rejected',\n 'regenerated',\n 'purchase_declined',\n] as const;\nexport type OutcomeStatus = (typeof OUTCOME_STATUSES)[number];\nexport const OUTCOME_STATUS_VALUES: readonly string[] = OUTCOME_STATUSES;\n\nconst CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\n\nexport interface OutcomeInput {\n status: string;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeBodyItem {\n status: OutcomeStatus;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport function buildOutcomeItem(input: OutcomeInput): OutcomeBodyItem {\n if (!OUTCOME_STATUS_VALUES.includes(input.status)) {\n throw new CliError('USAGE', `Invalid outcome status: ${JSON.stringify(input.status)}`, {\n fix: `Use one of: ${OUTCOME_STATUSES.join(', ')}.`,\n });\n }\n if (input.resourceId !== undefined && !UUID_RE.test(input.resourceId)) {\n throw new CliError('USAGE', `Invalid --resource id: ${JSON.stringify(input.resourceId)}`, {\n fix: 'Pass the resourceId (a uuid) from a search candidate.',\n });\n }\n if (input.contentHash !== undefined && !CONTENT_HASH_RE.test(input.contentHash)) {\n throw new CliError('USAGE', `Invalid content hash: ${JSON.stringify(input.contentHash)}`, {\n fix: 'A content hash is \"sha256:<64 hex>\".',\n });\n }\n return {\n status: input.status as OutcomeStatus,\n ...(input.resourceId !== undefined ? { resourceId: input.resourceId } : {}),\n ...(input.contentHash !== undefined ? { contentHash: input.contentHash } : {}),\n };\n}\n\nconst SEARCH_ID_RE = UUID_RE;\n\nexport async function postOutcomes(\n searchId: string,\n items: OutcomeBodyItem[],\n opts: AgentApiOptions,\n): Promise<{ accepted: number }> {\n if (!SEARCH_ID_RE.test(searchId)) {\n throw new CliError('USAGE', `Invalid search id: ${JSON.stringify(searchId)}`, {\n fix: 'Pass the searchId from a prior search (or use --last).',\n });\n }\n if (items.length === 0 || items.length > 10) {\n throw new CliError('USAGE', 'An outcome report carries 1 to 10 items', {\n fix: 'Report between 1 and 10 outcomes per call.',\n });\n }\n const url = `${trimSlash(opts.baseUrl)}/api/agent/searches/${searchId}/outcomes`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n jsonBody: items.length === 1 ? items[0] : items,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n // 202 is the only success; the body is a uniform { accepted } regardless of\n // whether the searchId existed (no existence oracle, by design).\n if (res.status !== 202) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Outcome report failed (${res.status})`,\n {\n fix: 'Check the status vocabulary and search id, then retry.',\n details: res.json,\n },\n );\n }\n const accepted =\n typeof res.json === 'object' && res.json !== null && 'accepted' in res.json\n ? Number((res.json as { accepted: unknown }).accepted)\n : items.length;\n return { accepted: Number.isFinite(accepted) ? accepted : items.length };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAOlB,IAAM,YAAY;AAqBlB,SAAS,mBAAmB,OAAuC;AACxE,QAAM,WAAW,MAAM,SAAS,KAAK;AACrC,MAAI,SAAS,WAAW,KAAK,SAAS,SAAS,KAAK;AAClD,UAAM,IAAI,SAAS,SAAS,wCAAwC;AAAA,MAClE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,MAAI,MAAM,gBAAgB,QAAW;AAGnC,UAAM,SAAS,gBAAgB,KAAK,MAAM,WAAW,IAAI,CAAC;AAC1D,QAAI,WAAW,UAAa,OAAO,MAAM,MAAM,GAAG;AAChD,YAAM,IAAI,SAAS,SAAS,2BAA2B,KAAK,UAAU,MAAM,WAAW,CAAC,IAAI;AAAA,QAC1F,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,MAAM,aAAa,UAAa,CAAC,UAAU,KAAK,MAAM,QAAQ,GAAG;AACnE,UAAM,IAAI,SAAS,SAAS,wBAAwB,KAAK,UAAU,MAAM,QAAQ,CAAC,IAAI;AAAA,MACpF,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,QAAM,QAAQ,MAAM,SAAS;AAC7B,MAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,QAAQ,WAAW;AAC9D,UAAM,IAAI,SAAS,SAAS,oBAAoB,KAA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,IAAI;AAC3C,UAAM,IAAI,SAAS,SAAS,2CAA2C;AAAA,MACrE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,QAAM,MAAM,GAAG,UAAU,KAAK,OAAO,CAAC,uBAAuB,QAAQ;AACrE,QAAM,MAAM,MAAM,YAAY,KAAK;AAAA,IACjC,QAAQ;AAAA,IACR,WAAW,KAAK;AAAA,IAChB,SAAS,EAAE,mBAAmB,cAAc;AAAA,IAC5C,UAAU,MAAM,WAAW,IAAI,MAAM,CAAC,IAAI;AAAA,IAC1C,WAAW,KAAK;AAAA,EAClB,CAAC;AACD,MAAI,CAAC,IAAI,GAAI,OAAM,WAAW,KAAK,GAAG;AACtC,MAAI,IAAI,WAAW,IAAK,OAAM,eAAe,KAAK,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC;AAGtE,MAAI,IAAI,WAAW,KAAK;AACtB,UAAM,IAAI;AAAA,MACR;AAAA,MACA,mBAAmB,IAAI,IAAI,KAAK,0BAA0B,IAAI,MAAM;AAAA,MACpE;AAAA,QACE,KAAK;AAAA,QACL,SAAS,IAAI;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACA,QAAM,WACJ,OAAO,IAAI,SAAS,YAAY,IAAI,SAAS,QAAQ,cAAc,IAAI,OACnE,OAAQ,IAAI,KAA+B,QAAQ,IACnD,MAAM;AACZ,SAAO,EAAE,UAAU,OAAO,SAAS,QAAQ,IAAI,WAAW,MAAM,OAAO;AACzE;","names":[]}
1
+ {"version":3,"sources":["../src/lib/agent-api.ts"],"sourcesContent":["import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResult } from './http';\nimport { CLIENT_HEADER } from './client-meta';\nimport { ATOMIC_RE, UUID_RE } from './ids';\nimport { trimSlash } from './url';\n\n/**\n * The search + outcome HTTP contract (A2, tenjin#370). Request building and\n * response validation live here; the wire shape is validated defensively, an\n * unknown `schemaVersion` degrades to a parse refusal rather than a guess, and\n * unrecognized candidate fields are ignored (forward-compatible), per spec 10.\n *\n * These endpoints are anonymous: no wallet, no SIWX. The only header of note is\n * `X-Tenjin-Client`, which attributes a later purchase back to the search flow.\n */\n\nconst FRESH_WITHIN_RE = /^P(\\d+)[DWMY]$/;\nconst CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;\n\n/** The server's `limit` ceiling. Exported because the truncation advice in\n * `search` has to name it: past search v2 the response budget scales with the\n * candidates returned, so a truncated page is recovered by asking for MORE, and\n * this is the value to ask for. One definition, so the cap the CLI enforces and\n * the number it tells the operator to retry with cannot drift apart. */\nexport const MAX_LIMIT = 10;\n\n/** Client-side search request (mirrors the server lookupRequestSchema bounds\n * so a malformed flag fails locally as USAGE, before a round trip). */\nexport interface SearchInput {\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit?: number;\n}\n\nexport interface SearchRequestBody {\n schemaVersion: 2;\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit: number;\n}\n\nexport function buildSearchRequest(input: SearchInput): SearchRequestBody {\n const question = input.question.trim();\n if (question.length === 0 || question.length > 512) {\n throw new CliError('USAGE', 'question must be 1 to 512 characters', {\n fix: 'Pass a non-empty question under 512 characters.',\n });\n }\n if (input.freshWithin !== undefined) {\n // The server rejects ANY zero-valued duration (P0D, P0W, P00M, ...), so a\n // zero window fails here as USAGE instead of a remote 400.\n const digits = FRESH_WITHIN_RE.exec(input.freshWithin)?.[1];\n if (digits === undefined || Number(digits) === 0) {\n throw new CliError('USAGE', `Invalid --fresh-within: ${JSON.stringify(input.freshWithin)}`, {\n fix: 'Use a nonzero ISO-like window P<n>[DWMY], e.g. P30D, P2W, P1Y.',\n });\n }\n }\n if (input.maxPrice !== undefined && !ATOMIC_RE.test(input.maxPrice)) {\n throw new CliError('USAGE', `Invalid --max-price: ${JSON.stringify(input.maxPrice)}`, {\n fix: 'Pass an atomic USDC integer, e.g. 100000 for $0.10.',\n });\n }\n const limit = input.limit ?? 5;\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(input.limit)}`, {\n fix: `Pass an integer between 1 and ${MAX_LIMIT}.`,\n });\n }\n if (input.appliesTo !== undefined) {\n // Mirror the server's strictObject bounds (<=8 keys, <=20 values/key,\n // 1..120 chars/value) so a bad filter fails locally, never as a remote 400.\n const keys = Object.keys(input.appliesTo);\n if (keys.length > 8) {\n throw new CliError('USAGE', 'Too many --applies-to keys (max 8).');\n }\n for (const [key, values] of Object.entries(input.appliesTo)) {\n if (!CANONICAL_KEY_RE.test(key)) {\n throw new CliError('USAGE', `Invalid appliesTo key: ${JSON.stringify(key)}`, {\n fix: 'Keys must be canonical lowercase identifiers, e.g. products=Vercel.',\n });\n }\n if (values.length === 0) {\n throw new CliError('USAGE', `appliesTo key ${JSON.stringify(key)} has no values`, {\n fix: 'Give each --applies-to key at least one value.',\n });\n }\n if (values.length > 20) {\n throw new CliError('USAGE', `Too many --applies-to values for ${key} (max 20).`);\n }\n for (const value of values) {\n if (value.length === 0 || value.length > 120) {\n throw new CliError(\n 'USAGE',\n `Invalid --applies-to value for ${key}: must be 1 to 120 characters.`,\n );\n }\n }\n }\n }\n return {\n schemaVersion: 2,\n question,\n ...(input.freshWithin !== undefined ? { freshWithin: input.freshWithin } : {}),\n ...(input.maxPrice !== undefined ? { maxPrice: input.maxPrice } : {}),\n ...(input.appliesTo !== undefined ? { appliesTo: input.appliesTo } : {}),\n limit,\n };\n}\n\n// Response schemas. `.passthrough()` on the candidate keeps unknown future fields\n// instead of stripping them (forward-compatible), while still requiring the\n// contract fields this CLI reads. `decision` is uppercase on the wire.\n//\n// A candidate is a LEAN hit (search v2): identity, price, freshness and why it\n// matched, and nothing more. The full answer card is one free unpaid GET of `url`\n// away, which is what `tenjin inspect` does, so breadth here costs no depth there.\nexport const searchCandidateSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string(),\n slug: z.string(),\n title: z.string(),\n artifactType: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n matchReasons: z.array(z.string()),\n estimatedTokens: z.number(),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchCandidate = z.infer<typeof searchCandidateSchema>;\n\n/** Per-field caps for a browse pointer's free-form strings. `url` gets its own,\n * looser bound so a legitimate read URL is never mangled while an invented one\n * still cannot run away. Declared above the schema because the schema enforces\n * the `url` bound at parse time (see below). */\nconst BROWSE_BOUNDS = { title: 200, url: 512, handle: 64 } as const;\n\n// A browse pointer, carried ONLY on a MISS (tenjin#460): a piece from the broad\n// discoverable corpus with deliberately NO matchReasons, NO estimatedTokens and\n// no confidence field. It is a \"you might browse this\" hint, never a scored\n// answer candidate, so it is kept strictly out of `candidates` and never\n// recorded in the local search store.\n//\n// That store exclusion makes `inspect`/`buy`/`outcome` unreachable BY\n// `resourceId` (resolveResourceRef's uuid arm needs a store hit and fails with\n// RESOURCE_NOT_FOUND), but NOT by url: resolveResourceRef's URL arm is gated on\n// origin alone and never consults the store, so `tenjin buy <browse url>` does\n// pay. That is by design here, since the url is the payable read endpoint and\n// the contract re-emits it verbatim, but it is a real spend path, so the human\n// hint line carries the price and every spend gate still applies. Do not\n// restate the old \"never reachable by inspect/buy/outcome\" claim: it was false.\n//\n// A malformed pointer fails the WHOLE response into CONTRACT_MISMATCH rather\n// than being dropped. Deliberate: this client is fail-closed on every other\n// contract deviation, and silently swallowing a bad tail would hide server\n// drift that contract.test.ts exists to catch. Pinned in agent-api.test.ts.\n//\n// The `url` bound is enforced HERE rather than by truncation in the projection\n// below, and that asymmetry with `title`/`handle` is deliberate. Those two are\n// display strings: clipping one degrades gracefully and the human still reads\n// something true. `url` is an actionable payable pointer, and a clipped url is\n// not a shorter url, it is a DIFFERENT and broken one that still looks payable\n// in `--json`. Refusing is also the only ordering-independent answer: capping\n// first would hand the origin assertion in `runSearch` a string the server never\n// sent. 512 is far above any real read endpoint, so exceeding it is server drift.\nexport const searchBrowseSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string().max(BROWSE_BOUNDS.url, `url must be at most ${BROWSE_BOUNDS.url} characters`),\n title: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchBrowse = z.infer<typeof searchBrowseSchema>;\n\nexport const searchResponseSchema = z.object({\n schemaVersion: z.literal(2),\n searchId: z.string().regex(UUID_RE, 'searchId must be a uuid'),\n decision: z.enum(['CANDIDATES', 'MISS']),\n calibration: z.string(),\n candidates: z.array(searchCandidateSchema).optional(),\n // Set only when the server's size backstop dropped trailing candidates the\n // requested limit had room for; omitted entirely otherwise. There is no cursor,\n // so a retry at a SMALLER limit returns strictly fewer rows; the ceiling scales\n // with the candidates returned, so a LARGER limit (up to MAX_LIMIT) is what\n // recovers the tail, and at MAX_LIMIT the tail is unrecoverable and narrowing the\n // question is the remedy. `runSearch` picks the half that applies.\n truncated: z.literal(true).optional(),\n // Omitted entirely by the server when empty, and only ever present on a MISS.\n // Not enforced here (a stricter schema would reject an otherwise-usable\n // response); truncateResponse drops it on a CANDIDATES decision instead.\n browse: z.array(searchBrowseSchema).optional(),\n});\n\nexport type SearchResponse = z.infer<typeof searchResponseSchema>;\n\nexport interface AgentApiOptions {\n baseUrl: string;\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** Spec 09 §3 evaluation-cohort opt-in: sends X-Tenjin-Eval-Cohort: 1. */\n evalCohort?: boolean;\n}\n\n/** Turn a non-2xx / transport HttpResult into the CLI error contract. */\nfunction apiFailure(url: string, result: Exclude<HttpResult, { ok: true }>): CliError {\n const code =\n result.kind === 'network' || result.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n return new CliError(code, `${url}: ${result.message}`, {\n fix: 'Check your network and the configured base URL (`tenjin config get baseUrl`), then retry.',\n });\n}\n\n/** 429 with Retry-After: a recoverable pause, not an outage; agents branch on it. */\nexport function rateLimitError(\n url: string,\n header: (name: string) => string | undefined,\n): CliError {\n const retryAfter = header('retry-after');\n const seconds = retryAfter !== undefined ? Number(retryAfter) : undefined;\n return new CliError('RATE_LIMITED', `${url}: rate limited by the server.`, {\n fix:\n seconds !== undefined && Number.isFinite(seconds)\n ? `Retry after ${seconds}s.`\n : 'Back off and retry shortly.',\n details: {\n ...(seconds !== undefined && Number.isFinite(seconds) ? { retryAfterSeconds: seconds } : {}),\n },\n });\n}\n\nfunction serverErrorMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n const err = rec.error;\n if (typeof err === 'string') return err;\n if (typeof err === 'object' && err !== null) {\n const m = (err as Record<string, unknown>).message;\n if (typeof m === 'string') return m;\n }\n if (typeof rec.message === 'string') return rec.message;\n }\n return undefined;\n}\n\nexport async function postSearch(\n body: SearchRequestBody,\n opts: AgentApiOptions,\n): Promise<SearchResponse> {\n const url = `${trimSlash(opts.baseUrl)}/api/agent/search`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: {\n 'x-tenjin-client': CLIENT_HEADER,\n ...(opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {}),\n },\n jsonBody: body,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) {\n // The REQUEST gate is where a pre-v2 server actually refuses us, and it is\n // the arm that fires in practice. Old tenjin declares `schemaVersion:\n // z.literal(1)` inside a strictObject, so a v2 request never reaches the\n // handler: it comes back 400 \"Invalid request body\" with the zod flatten in\n // `error.details`, and the response check further down can never see it.\n // Without this the operator is told to retry a request that cannot succeed.\n if (res.status === 400 && rejectedSchemaVersion(res.json)) {\n throw outdatedServerError('The server rejected schemaVersion 2: it predates search v2.', {\n details: res.json,\n });\n }\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Search failed (${res.status})`,\n {\n fix: 'Retry; if it persists the search endpoint may be unavailable.',\n details: res.json,\n },\n );\n }\n const parsed = searchResponseSchema.safeParse(res.json);\n if (!parsed.success) {\n // The other way a stale server surfaces: it answered 200 with a v1 body.\n // Unreachable against today's old tenjin (the request gate above refuses\n // first), but correct for anything that accepts the request and replies v1.\n const served = serverSchemaVersion(res.json);\n if (served !== undefined && served !== 2) {\n throw outdatedServerError(\n `Search response is schemaVersion ${served}; this CLI requires 2 (search v2).`,\n { details: parsed.error.issues },\n );\n }\n throw new CliError('CONTRACT_MISMATCH', 'Search response did not match the expected contract', {\n fix: 'Update tenjin-cli; the server contract may have changed.',\n details: parsed.error.issues,\n });\n }\n return truncateResponse(parsed.data);\n}\n\n/** One wording for both ways a pre-v2 server refuses this CLI, so the request-gate\n * arm and the response arm can never drift apart. */\nfunction outdatedServerError(message: string, opts: { details: unknown }): CliError {\n return new CliError('CONTRACT_MISMATCH', message, {\n fix: 'The server predates search v2. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.',\n details: opts.details,\n });\n}\n\n/** True when a 400 body is the old server's request-gate refusal of our\n * `schemaVersion`: an ApiError envelope whose zod `flatten()` details carry a\n * `schemaVersion` fieldError. Keyed on the field, never the message text. */\nfunction rejectedSchemaVersion(json: unknown): boolean {\n const record = (v: unknown): Record<string, unknown> | undefined =>\n typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : undefined;\n const fieldErrors = record(record(record(json)?.error)?.details)?.fieldErrors;\n return Array.isArray(record(fieldErrors)?.schemaVersion);\n}\n\n/** The `schemaVersion` an unparsed body claims, when it claims a number at all. */\nfunction serverSchemaVersion(json: unknown): number | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const v = (json as { schemaVersion?: unknown }).schemaVersion;\n return typeof v === 'number' ? v : undefined;\n}\n\n/**\n * The server bounds every free-form candidate string (spec 09); re-apply the same\n * caps defensively so a misbehaving server cannot blow up an agent transcript\n * through the CLI (spec 10 response-size discipline).\n *\n * `slug` is deliberately absent: it is an identifier, not display text, so\n * clipping it would not shorten it but change it into a slug that resolves to\n * nothing while still looking usable in `--json`. The server tolerates an\n * uncapped slug for the same reason (that is the one case its `truncated` flag\n * exists for), so capping here would fail on a response the server calls valid.\n */\nconst CAND_BOUNDS = {\n title: 200,\n matchReasons: 3,\n matchReasonChars: 80,\n} as const;\n\nconst cap = (s: string, n: number): string => (s.length > n ? s.slice(0, n) : s);\n\nfunction truncateResponse(res: SearchResponse): SearchResponse {\n const out: SearchResponse = { ...res };\n if (res.candidates !== undefined) out.candidates = res.candidates.map(truncateCandidate);\n // Browse pointers ride the same defensive discipline, and then some. The\n // schema is `.passthrough()` so a server-invented key would otherwise survive\n // at unbounded length into `--json` and MCP structuredContent; we rebuild each\n // pointer explicitly from the five contract fields instead of spreading, which\n // drops unknown keys and is what makes the contract.test.ts \"no score-like\n // field\" pin hold at runtime and not just against the fixture. Count is capped\n // at the server's BROWSE_MAX, and every free-form string (title, url, handle)\n // at its own bound.\n //\n // `browse` is MISS-only by contract; drop it outright on a CANDIDATES decision\n // rather than trust the server, since humanLines renders no hint line there and\n // it would otherwise be an unrendered channel of server text and payable urls.\n if (res.browse !== undefined && res.decision === 'MISS') {\n out.browse = res.browse.slice(0, BROWSE_MAX).map((b) => ({\n resourceId: b.resourceId,\n // Not capped: the schema already refused anything over BROWSE_BOUNDS.url,\n // so this is the url the server sent, verbatim and payable.\n url: b.url,\n title: cap(b.title, BROWSE_BOUNDS.title),\n price: b.price,\n creator: { handle: cap(b.creator.handle, BROWSE_BOUNDS.handle) },\n }));\n } else {\n delete out.browse;\n }\n return out;\n}\n\n/** Mirrors the server's BROWSE_MAX (lib/search-browse.ts): a MISS carries at\n * most three browse pointers. */\nconst BROWSE_MAX = 3;\n\nfunction truncateCandidate(c: SearchCandidate): SearchCandidate {\n return {\n ...c,\n title: cap(c.title, CAND_BOUNDS.title),\n matchReasons: c.matchReasons\n .slice(0, CAND_BOUNDS.matchReasons)\n .map((r) => cap(r, CAND_BOUNDS.matchReasonChars)),\n };\n}\n\nconst OUTCOME_STATUSES = [\n 'used',\n 'partially_used',\n 'rejected',\n 'regenerated',\n 'purchase_declined',\n] as const;\nexport type OutcomeStatus = (typeof OUTCOME_STATUSES)[number];\nexport const OUTCOME_STATUS_VALUES: readonly string[] = OUTCOME_STATUSES;\n\nconst CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\n\nexport interface OutcomeInput {\n status: string;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeBodyItem {\n status: OutcomeStatus;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport function buildOutcomeItem(input: OutcomeInput): OutcomeBodyItem {\n if (!OUTCOME_STATUS_VALUES.includes(input.status)) {\n throw new CliError('USAGE', `Invalid outcome status: ${JSON.stringify(input.status)}`, {\n fix: `Use one of: ${OUTCOME_STATUSES.join(', ')}.`,\n });\n }\n if (input.resourceId !== undefined && !UUID_RE.test(input.resourceId)) {\n throw new CliError('USAGE', `Invalid --resource id: ${JSON.stringify(input.resourceId)}`, {\n fix: 'Pass the resourceId (a uuid) from a search candidate.',\n });\n }\n if (input.contentHash !== undefined && !CONTENT_HASH_RE.test(input.contentHash)) {\n throw new CliError('USAGE', `Invalid content hash: ${JSON.stringify(input.contentHash)}`, {\n fix: 'A content hash is \"sha256:<64 hex>\".',\n });\n }\n return {\n status: input.status as OutcomeStatus,\n ...(input.resourceId !== undefined ? { resourceId: input.resourceId } : {}),\n ...(input.contentHash !== undefined ? { contentHash: input.contentHash } : {}),\n };\n}\n\nconst SEARCH_ID_RE = UUID_RE;\n\nexport async function postOutcomes(\n searchId: string,\n items: OutcomeBodyItem[],\n opts: AgentApiOptions,\n): Promise<{ accepted: number }> {\n if (!SEARCH_ID_RE.test(searchId)) {\n throw new CliError('USAGE', `Invalid search id: ${JSON.stringify(searchId)}`, {\n fix: 'Pass the searchId from a prior search (or use --last).',\n });\n }\n if (items.length === 0 || items.length > 10) {\n throw new CliError('USAGE', 'An outcome report carries 1 to 10 items', {\n fix: 'Report between 1 and 10 outcomes per call.',\n });\n }\n const url = `${trimSlash(opts.baseUrl)}/api/agent/searches/${searchId}/outcomes`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n jsonBody: items.length === 1 ? items[0] : items,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n // 202 is the only success; the body is a uniform { accepted } regardless of\n // whether the searchId existed (no existence oracle, by design).\n if (res.status !== 202) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Outcome report failed (${res.status})`,\n {\n fix: 'Check the status vocabulary and search id, then retry.',\n details: res.json,\n },\n );\n }\n const accepted =\n typeof res.json === 'object' && res.json !== null && 'accepted' in res.json\n ? Number((res.json as { accepted: unknown }).accepted)\n : items.length;\n return { accepted: Number.isFinite(accepted) ? accepted : items.length };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAOlB,IAAM,YAAY;AAqBlB,SAAS,mBAAmB,OAAuC;AACxE,QAAM,WAAW,MAAM,SAAS,KAAK;AACrC,MAAI,SAAS,WAAW,KAAK,SAAS,SAAS,KAAK;AAClD,UAAM,IAAI,SAAS,SAAS,wCAAwC;AAAA,MAClE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,MAAI,MAAM,gBAAgB,QAAW;AAGnC,UAAM,SAAS,gBAAgB,KAAK,MAAM,WAAW,IAAI,CAAC;AAC1D,QAAI,WAAW,UAAa,OAAO,MAAM,MAAM,GAAG;AAChD,YAAM,IAAI,SAAS,SAAS,2BAA2B,KAAK,UAAU,MAAM,WAAW,CA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SAAO,EAAE,UAAU,OAAO,SAAS,QAAQ,IAAI,WAAW,MAAM,OAAO;AACzE;","names":[]}
@@ -3,19 +3,19 @@ import {
3
3
  createCandidate,
4
4
  dropCandidate,
5
5
  listCandidates
6
- } from "./chunk-ZIYVN4CD.js";
6
+ } from "./chunk-VZ3AJCO5.js";
7
7
  import {
8
8
  UUID_RE
9
9
  } from "./chunk-WWX32ML4.js";
10
10
  import {
11
11
  sanitizeForTerminal
12
- } from "./chunk-NFSOVL3C.js";
12
+ } from "./chunk-BBUYCDSG.js";
13
13
  import {
14
14
  pathExists
15
- } from "./chunk-MDDGEGSW.js";
15
+ } from "./chunk-DAJ56EUU.js";
16
16
  import {
17
17
  CliError
18
- } from "./chunk-PAUXMRSF.js";
18
+ } from "./chunk-J6CVKC4M.js";
19
19
 
20
20
  // src/commands/candidate.ts
21
21
  import { readFile } from "fs/promises";
@@ -120,4 +120,4 @@ export {
120
120
  runCandidateList,
121
121
  runCandidateDrop
122
122
  };
123
- //# sourceMappingURL=chunk-ZW3B5LWX.js.map
123
+ //# sourceMappingURL=chunk-2YX6LTCD.js.map
@@ -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
+ import {
6
+ listCandidates
7
+ } from "./chunk-VZ3AJCO5.js";
5
8
  import {
6
9
  recordSearch
7
- } from "./chunk-CVX6JNGD.js";
10
+ } from "./chunk-OTDI5FXG.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-2L73UI6T.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-5X4EBGGU.js.map