tenjin-cli 0.1.0-alpha.4 → 0.1.0-alpha.5
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.
- package/README.md +168 -11
- package/dist/{buy-OOOLUDND.js → buy-YMXXVNFH.js} +18 -17
- package/dist/{candidate-TWCWTFGA.js → candidate-H7FR4AU5.js} +8 -8
- package/dist/{chunk-MUBUQVC3.js → chunk-2JQ5JSG6.js} +3 -2
- package/dist/{chunk-MUBUQVC3.js.map → chunk-2JQ5JSG6.js.map} +1 -1
- package/dist/{chunk-NXCJN2FJ.js → chunk-3IRDP7TN.js} +48 -41
- package/dist/chunk-3IRDP7TN.js.map +1 -0
- package/dist/{chunk-4GR7DGD6.js → chunk-4WVKXKDK.js} +14 -28
- package/dist/chunk-4WVKXKDK.js.map +1 -0
- package/dist/chunk-5SCU253N.js +412 -0
- package/dist/chunk-5SCU253N.js.map +1 -0
- package/dist/chunk-ADJYSM45.js +135 -0
- package/dist/chunk-ADJYSM45.js.map +1 -0
- package/dist/{chunk-5JH7ZB6Z.js → chunk-BIKAUVC2.js} +40 -8
- package/dist/chunk-BIKAUVC2.js.map +1 -0
- package/dist/{chunk-S3KZ3PPK.js → chunk-C444K6MI.js} +254 -47
- package/dist/chunk-C444K6MI.js.map +1 -0
- package/dist/{chunk-XNNOR7F7.js → chunk-CVX6JNGD.js} +3 -3
- package/dist/{chunk-H5ETJRQD.js → chunk-HTDALK7M.js} +16 -11
- package/dist/chunk-HTDALK7M.js.map +1 -0
- package/dist/chunk-IOPWPMT2.js +239 -0
- package/dist/chunk-IOPWPMT2.js.map +1 -0
- package/dist/{chunk-MM4TGTST.js → chunk-L4IHCN6B.js} +8 -4
- package/dist/chunk-L4IHCN6B.js.map +1 -0
- package/dist/{chunk-EUQN3L5X.js → chunk-LAM66WFJ.js} +20 -6
- package/dist/chunk-LAM66WFJ.js.map +1 -0
- package/dist/{chunk-FHB3VKZW.js → chunk-MDDGEGSW.js} +5 -3
- package/dist/chunk-MDDGEGSW.js.map +1 -0
- package/dist/{chunk-333FOTUJ.js → chunk-MJZZTKCC.js} +108 -2
- package/dist/chunk-MJZZTKCC.js.map +1 -0
- package/dist/{chunk-VV4P5RVK.js → chunk-NFSOVL3C.js} +6 -3
- package/dist/{chunk-VV4P5RVK.js.map → chunk-NFSOVL3C.js.map} +1 -1
- package/dist/{chunk-QH6677FJ.js → chunk-NJF2WENW.js} +2 -2
- package/dist/{chunk-QH6677FJ.js.map → chunk-NJF2WENW.js.map} +1 -1
- package/dist/{chunk-6WWVYYSB.js → chunk-PAUXMRSF.js} +14 -3
- package/dist/{chunk-6WWVYYSB.js.map → chunk-PAUXMRSF.js.map} +1 -1
- package/dist/{chunk-ULLWHHIT.js → chunk-PYNSGYBE.js} +244 -32
- package/dist/chunk-PYNSGYBE.js.map +1 -0
- package/dist/{chunk-DPET3TW5.js → chunk-QONTBYQW.js} +12 -9
- package/dist/chunk-QONTBYQW.js.map +1 -0
- package/dist/chunk-QW2Q2KAH.js +27 -0
- package/dist/chunk-QW2Q2KAH.js.map +1 -0
- package/dist/chunk-RTJLLPFA.js +599 -0
- package/dist/chunk-RTJLLPFA.js.map +1 -0
- package/dist/{chunk-KXIX7YDV.js → chunk-TXPPMK4L.js} +5 -5
- package/dist/{chunk-C4TIWOAM.js → chunk-ZDY2KY5X.js} +2 -2
- package/dist/{chunk-DPUMEMGM.js → chunk-ZIYVN4CD.js} +3 -3
- package/dist/{chunk-OJD54DIU.js → chunk-ZW3B5LWX.js} +5 -5
- package/dist/{cli-AFSLAKR6.js → cli-IW76QTN3.js} +38 -25
- package/dist/{cli-AFSLAKR6.js.map → cli-IW76QTN3.js.map} +1 -1
- package/dist/{config-DBEEM3UA.js → config-VCOS7P5K.js} +8 -6
- package/dist/{doctor-XDA3YU6H.js → doctor-WS65JG3V.js} +9 -8
- package/dist/index.js +1 -1
- package/dist/{inspect-YBGDAG47.js → inspect-SFJWUQHO.js} +14 -14
- package/dist/{install-7J6KKEEP.js → install-RVPQPCKH.js} +177 -130
- package/dist/install-RVPQPCKH.js.map +1 -0
- package/dist/outcome-GNYCSZ7J.js +20 -0
- package/dist/{publish-IH7RJXGB.js → publish-DSFWQRUN.js} +14 -14
- package/dist/{run-DCZFEW2C.js → run-OMPKA43G.js} +29 -28
- package/dist/{run-DCZFEW2C.js.map → run-OMPKA43G.js.map} +1 -1
- package/dist/search-KOI6Y7P6.js +24 -0
- package/dist/send-3G4C64HJ.js +222 -0
- package/dist/send-3G4C64HJ.js.map +1 -0
- package/dist/{usdc-AU6ZIKA6.js → usdc-4VCDHFWX.js} +20 -4
- package/dist/{wallet-HKG3GSTX.js → wallet-B7KJS2R5.js} +17 -7
- package/dist/{wallet-UWHSHWC6.js → wallet-PP22LAX7.js} +8 -8
- package/package.json +1 -1
- package/skills/tenjin/SKILL.md +32 -7
- package/skills/tenjin-publish/SKILL.md +97 -12
- package/skills/tenjin-search/SKILL.md +115 -12
- package/dist/chunk-333FOTUJ.js.map +0 -1
- package/dist/chunk-4GR7DGD6.js.map +0 -1
- package/dist/chunk-5JH7ZB6Z.js.map +0 -1
- package/dist/chunk-BXUS5UCT.js +0 -212
- package/dist/chunk-BXUS5UCT.js.map +0 -1
- package/dist/chunk-CJU555P5.js +0 -333
- package/dist/chunk-CJU555P5.js.map +0 -1
- package/dist/chunk-DPET3TW5.js.map +0 -1
- package/dist/chunk-EUQN3L5X.js.map +0 -1
- package/dist/chunk-FHB3VKZW.js.map +0 -1
- package/dist/chunk-H5ETJRQD.js.map +0 -1
- package/dist/chunk-MM4TGTST.js.map +0 -1
- package/dist/chunk-NXCJN2FJ.js.map +0 -1
- package/dist/chunk-R7BMDJZM.js +0 -167
- package/dist/chunk-R7BMDJZM.js.map +0 -1
- package/dist/chunk-S3KZ3PPK.js.map +0 -1
- package/dist/chunk-ULLWHHIT.js.map +0 -1
- package/dist/chunk-YFREUEUI.js +0 -78
- package/dist/chunk-YFREUEUI.js.map +0 -1
- package/dist/install-7J6KKEEP.js.map +0 -1
- package/dist/outcome-ZFGHX2XW.js +0 -20
- package/dist/search-R6NIQFXI.js +0 -24
- /package/dist/{buy-OOOLUDND.js.map → buy-YMXXVNFH.js.map} +0 -0
- /package/dist/{candidate-TWCWTFGA.js.map → candidate-H7FR4AU5.js.map} +0 -0
- /package/dist/{chunk-XNNOR7F7.js.map → chunk-CVX6JNGD.js.map} +0 -0
- /package/dist/{chunk-KXIX7YDV.js.map → chunk-TXPPMK4L.js.map} +0 -0
- /package/dist/{chunk-C4TIWOAM.js.map → chunk-ZDY2KY5X.js.map} +0 -0
- /package/dist/{chunk-DPUMEMGM.js.map → chunk-ZIYVN4CD.js.map} +0 -0
- /package/dist/{chunk-OJD54DIU.js.map → chunk-ZW3B5LWX.js.map} +0 -0
- /package/dist/{config-DBEEM3UA.js.map → config-VCOS7P5K.js.map} +0 -0
- /package/dist/{doctor-XDA3YU6H.js.map → doctor-WS65JG3V.js.map} +0 -0
- /package/dist/{inspect-YBGDAG47.js.map → inspect-SFJWUQHO.js.map} +0 -0
- /package/dist/{outcome-ZFGHX2XW.js.map → outcome-GNYCSZ7J.js.map} +0 -0
- /package/dist/{publish-IH7RJXGB.js.map → publish-DSFWQRUN.js.map} +0 -0
- /package/dist/{search-R6NIQFXI.js.map → search-KOI6Y7P6.js.map} +0 -0
- /package/dist/{usdc-AU6ZIKA6.js.map → usdc-4VCDHFWX.js.map} +0 -0
- /package/dist/{wallet-HKG3GSTX.js.map → wallet-B7KJS2R5.js.map} +0 -0
- /package/dist/{wallet-UWHSHWC6.js.map → wallet-PP22LAX7.js.map} +0 -0
package/README.md
CHANGED
|
@@ -38,7 +38,7 @@ tenjin search "what actually changed in <library> v3's public API" # your firs
|
|
|
38
38
|
| Command | Purpose |
|
|
39
39
|
| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
|
40
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, and wallet checks
|
|
41
|
+
| `tenjin doctor` | Environment, API reachability, contract, skill-wiring, and wallet checks |
|
|
42
42
|
| `tenjin config [get\|set]` | Spend policy (`maxAutoSpend`, `sessionBudget`, `confirm`, allowlists) and `publish.mode` / `publish.defaultPrice` |
|
|
43
43
|
| `tenjin wallet [create\|show\|balance]` | Local Base wallet; the key never leaves the machine |
|
|
44
44
|
| `tenjin search "<question>"` | Ask for payable candidates or an honest MISS; prints the compact JSON verbatim |
|
|
@@ -48,6 +48,19 @@ tenjin search "what actually changed in <library> v3's public API" # your firs
|
|
|
48
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
49
|
| `tenjin publish --candidate <id>` | Publish a parked candidate (its `draft.md`); clears it on success |
|
|
50
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) |
|
|
52
|
+
|
|
53
|
+
`send` is human-invoked only: it is deliberately absent from the MCP toolset and
|
|
54
|
+
the harness skills, and nothing is signed until the previewed (checksummed)
|
|
55
|
+
recipient, amount, and network fee are confirmed, interactively at a TTY or
|
|
56
|
+
explicitly with `--yes` when headless. It refuses when the active wallet's
|
|
57
|
+
passphrase entry is missing. The `sendMaxAmount` hard per-send cap has no
|
|
58
|
+
default: `tenjin send` refuses until you run `tenjin config set sendMaxAmount
|
|
59
|
+
<usd|0|none>` (`0` disables the verb, `none` opts in to uncapped), and `--yes`
|
|
60
|
+
can never bypass the cap or the unset refusal.
|
|
61
|
+
For routing FUTURE revenue away from the agent wallet entirely, connect the
|
|
62
|
+
agent to your own Tenjin account instead (delegation); `send` exists for funds
|
|
63
|
+
already sitting on the agent key.
|
|
51
64
|
|
|
52
65
|
`buy` re-reads an entitled resource for free before ever paying, re-delivers
|
|
53
66
|
already-bought content from the local library without paying again, and refuses to
|
|
@@ -104,13 +117,107 @@ Pricing: `--price` (or a frontmatter `price:`) wins, otherwise `publish.defaultP
|
|
|
104
117
|
(default $0.10). A card never auto-prices; the `tenjin-publish` skill's rubric is
|
|
105
118
|
what actually chooses a price before it calls the command.
|
|
106
119
|
|
|
120
|
+
## Auto-mode permission allowlist
|
|
121
|
+
|
|
122
|
+
Coding harnesses running unattended ("auto mode", "full auto", YOLO) classify each
|
|
123
|
+
shell command before running it, and an unknown binary is denied by default. That
|
|
124
|
+
denies the free verbs too, which breaks the whole marketplace loop: the skills
|
|
125
|
+
forbid working around a denial, so a denied `tenjin search` just stops.
|
|
126
|
+
|
|
127
|
+
Pre-clear the free verbs once. In Claude Code these go in the `permissions.allow`
|
|
128
|
+
array of `.claude/settings.json`:
|
|
129
|
+
|
|
130
|
+
```
|
|
131
|
+
Bash(tenjin search:*)
|
|
132
|
+
Bash(tenjin inspect:*)
|
|
133
|
+
Bash(tenjin outcome:*)
|
|
134
|
+
Bash(tenjin doctor:*)
|
|
135
|
+
Bash(tenjin wallet show:*)
|
|
136
|
+
Bash(tenjin wallet balance:*)
|
|
137
|
+
Bash(tenjin config get:*)
|
|
138
|
+
Bash(tenjin candidate list:*)
|
|
139
|
+
```
|
|
140
|
+
|
|
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.
|
|
146
|
+
|
|
147
|
+
`tenjin install` prints this block, and `tenjin doctor` reprints it on every run
|
|
148
|
+
(including in `doctor --json` under `permissions`, on the failure envelope as well
|
|
149
|
+
as the success one), so an agent that just got denied can point you at the exact
|
|
150
|
+
line.
|
|
151
|
+
|
|
152
|
+
**A prefix rule pins the verb, not the flags.** Every line above also clears
|
|
153
|
+
`--base-url <url>` on that verb, because the CLI accepts the global flags on every
|
|
154
|
+
subcommand. `--base-url` is validated as a URL and nothing more, and it wins
|
|
155
|
+
settings precedence, so it moves where the question goes, where `doctor` probes,
|
|
156
|
+
and (with the `buy` line below) where a SIWX signature and an EIP-3009 payment
|
|
157
|
+
authorization are sent. The origin pin only checks that a resource URL shares an
|
|
158
|
+
origin with the _configured_ base, so an attacker-controlled pair satisfies it.
|
|
159
|
+
There is no prefix syntax for "this verb but not that flag", so treat this as a
|
|
160
|
+
disclosed limit: set your base URL in config, and allowlist these verbs only if
|
|
161
|
+
you are content for an agent to be able to choose the destination host. The
|
|
162
|
+
skills tell agents never to pass `--base-url` on an allowlisted verb, but that is
|
|
163
|
+
a convention rather than an enforced boundary.
|
|
164
|
+
|
|
165
|
+
Purchases are a **separate, explicit opt-in**:
|
|
166
|
+
|
|
167
|
+
```
|
|
168
|
+
Bash(tenjin buy:*)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Read this before pasting it: **on the default config that line authorizes
|
|
172
|
+
unattended spending up to your wallet balance.** `--yes` is an ordinary flag on
|
|
173
|
+
the same allowlisted verb and it clears the confirm gate outright, so `confirm:
|
|
174
|
+
always` does not put a human on every purchase once the agent can pass `--yes`.
|
|
175
|
+
Walking the defaults: `allowlistCreators` is empty (gate off), `maxAutoSpend` is
|
|
176
|
+
`0` and `confirm` is `always`, which together only ask for a confirmation that
|
|
177
|
+
`--yes` satisfies, and `sessionBudget` is `0`, which the policy reads as **no
|
|
178
|
+
ceiling at all**, not a zero one. Set real values first:
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
tenjin config set maxAutoSpend 0.25
|
|
182
|
+
tenjin config set sessionBudget 2.00
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
The allowlist line itself never raises a spend cap. That is true, and it is not
|
|
186
|
+
the same as saying the caps stop an allowlisted `buy`.
|
|
187
|
+
|
|
188
|
+
Deliberately **never** recommended, because each is a human decision: `tenjin send`
|
|
189
|
+
(moves USDC out of the wallet, and is not bounded by the buy spend policy), `tenjin
|
|
190
|
+
publish`, `tenjin wallet create`, `tenjin config set` (it can widen the agent's own
|
|
191
|
+
spend policy), `tenjin candidate add` / `tenjin candidate drop`, `tenjin install`,
|
|
192
|
+
and `tenjin mcp`
|
|
193
|
+
(it re-exposes every command core, so clearing it clears everything). For the same
|
|
194
|
+
reason, prefer the narrow rules above over a broad `Bash(tenjin:*)`, `Bash(tenjin
|
|
195
|
+
wallet:*)`, or `Bash(tenjin config:*)`, which would swallow them.
|
|
196
|
+
|
|
197
|
+
Two gaps worth knowing, both of which fail closed (denied, never wrongly allowed):
|
|
198
|
+
bare `tenjin config` is as read-only as `config get` but no prefix rule reaches it
|
|
199
|
+
without also covering `config set`, so use `tenjin config get <key>`; and group-level
|
|
200
|
+
flag forms like `tenjin wallet --json show` are not covered, so put global flags
|
|
201
|
+
after the leaf verb (`tenjin wallet show --json`).
|
|
202
|
+
|
|
203
|
+
**Running the local MCP server instead?** That is a different permission surface:
|
|
204
|
+
the harness gates tools there, and these Bash rules do not apply. If you follow
|
|
205
|
+
the [MCP section](#local-stdio-mcp-server) as well, leave
|
|
206
|
+
`mcp__tenjin__tenjin_publish` and `mcp__tenjin__tenjin_wallet` gated, treat
|
|
207
|
+
`mcp__tenjin__tenjin_candidate` as gated for its add/drop actions, and treat
|
|
208
|
+
`mcp__tenjin__tenjin_buy` as the same opt-in decision as the `buy` line above.
|
|
209
|
+
|
|
210
|
+
This harness allowlist is unrelated to the `allowlistCreators` spend-policy key:
|
|
211
|
+
that one gates **who you may pay**, this one gates **which commands may run**.
|
|
212
|
+
|
|
107
213
|
## Skills (installed by `tenjin install`)
|
|
108
214
|
|
|
109
215
|
`tenjin install` auto-detects your harness, copies the three Tenjin skills into
|
|
110
216
|
place, wires the pointers each harness needs, and runs the `doctor` checks as its
|
|
111
217
|
last step. It is idempotent: re-run any time, `--dry-run` previews the changes
|
|
112
218
|
without writing, and `--harness claude|codex|shared` (repeatable) targets a
|
|
113
|
-
specific one
|
|
219
|
+
specific one, which is remembered so `doctor` keeps checking it. `--publish-mode
|
|
220
|
+
<mode>` sets your consent mode non-interactively.
|
|
114
221
|
|
|
115
222
|
Where the skills land:
|
|
116
223
|
|
|
@@ -137,8 +244,29 @@ The three skills:
|
|
|
137
244
|
- **`tenjin-search`**: thin adapter over `tenjin search/inspect/buy/outcome`
|
|
138
245
|
with a deliberately narrow trigger (public, durable, costly-to-reproduce
|
|
139
246
|
questions).
|
|
140
|
-
- **`tenjin-publish`**:
|
|
141
|
-
|
|
247
|
+
- **`tenjin-publish`**: publishing rubric and `tenjin publish` adapter, with a
|
|
248
|
+
narrow trigger (an explicit ask, or the after-a-MISS reflex). Consent is
|
|
249
|
+
`publish.mode`, backed by the local **secret-shape** scan. Its blocking tier —
|
|
250
|
+
structured provider token formats, private keys, connection URIs with an
|
|
251
|
+
embedded password — is what no mode and no `--yes` can clear. Everything else
|
|
252
|
+
is a warning, which `review` shows you and `--yes`/`full-auto` clear:
|
|
253
|
+
generically named `API_KEY=`-style assignments, PII, wallet addresses,
|
|
254
|
+
internal hostnames, confidential markers, long verbatim quotes,
|
|
255
|
+
paid/licensed-content legends, the caller's own project references, and
|
|
256
|
+
labeled customer/account identifiers. So rights and employer-internal
|
|
257
|
+
content have no _blocking_ detector — those are warn-tier only — and the
|
|
258
|
+
skill's draft rules put that judgment on the author.
|
|
259
|
+
|
|
260
|
+
All three land on every run, including on a machine that already carries the
|
|
261
|
+
hosted `tenjin` skill: that install wires the CLI skills rather than skipping.
|
|
262
|
+
The hosted skill is kept as the zero-install fallback and the two CLI skills
|
|
263
|
+
take precedence while the CLI is installed. `tenjin doctor`'s `skills` check
|
|
264
|
+
reports that state per skills directory (which skills are wired, where) so a
|
|
265
|
+
half-wired machine is diagnosable without a screen recording. It judges each
|
|
266
|
+
directory a harness it detected here reads, plus any directory you named with
|
|
267
|
+
`--harness` — an explicit choice is recorded, because detection cannot see a
|
|
268
|
+
harness Tenjin does not probe for. A leftover directory that is neither is
|
|
269
|
+
described, not warned about.
|
|
142
270
|
|
|
143
271
|
A funded wallet is only needed for paid reads and publishing.
|
|
144
272
|
|
|
@@ -244,17 +372,36 @@ approval.
|
|
|
244
372
|
is never written to disk. The wallet address stays readable, so `show`,
|
|
245
373
|
`balance`, and `doctor` work without a passphrase; only signing decrypts.
|
|
246
374
|
Signing is local and the CLI talks only to the configured base URL.
|
|
375
|
+
- There is exactly **one active wallet**. `wallet create` refuses when one
|
|
376
|
+
exists; the explicit `wallet create --replace` first verifies the outgoing
|
|
377
|
+
wallet's passphrase against its keystore, preserves it under the wallet's own
|
|
378
|
+
address in the OS store, parks the keystore beside the new one
|
|
379
|
+
(`wallet.<address>.json.bak`), and only then creates the new wallet — a
|
|
380
|
+
replace can never strand the old wallet's funds. `wallet show` lists archived
|
|
381
|
+
addresses as a recovery hint. To make an archived wallet active again: move
|
|
382
|
+
the current `wallet.json` aside (e.g. with another `--replace` later, or
|
|
383
|
+
manually), then `mv ~/.tenjin/wallet.<address>.json.bak ~/.tenjin/wallet.json`
|
|
384
|
+
— its passphrase entry is keyed by the wallet's address, so signing resumes
|
|
385
|
+
transparently.
|
|
247
386
|
- The signing passphrase resolves in order: `TENJIN_WALLET_PASSPHRASE`, then the
|
|
248
387
|
OS credential store, then an interactive prompt. On `wallet create` with no env
|
|
249
388
|
passphrase, a strong random one is generated and saved to the OS store so later
|
|
250
|
-
signing is transparent.
|
|
389
|
+
signing is transparent. Every stored entry is **per wallet** — keyed by the
|
|
390
|
+
wallet's own address — so replacing a wallet never touches the outgoing
|
|
391
|
+
wallet's passphrase. (Installs from before per-wallet entries used one shared
|
|
392
|
+
slot; the first signing that proves ownership re-keys that slot under the
|
|
393
|
+
owning wallet's address — the copy is verified before the old slot is
|
|
394
|
+
removed.) Where entries land per platform:
|
|
251
395
|
- **macOS**: the login keychain, via the OS `security` tool (the same
|
|
252
|
-
mechanism the GitHub CLI uses)
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
396
|
+
mechanism the GitHub CLI uses): service `tenjin-cli`, account = the wallet
|
|
397
|
+
address.
|
|
398
|
+
- **Windows**: a DPAPI-encrypted file per wallet
|
|
399
|
+
(`passphrase.<address>.dpapi`), decryptable only by the same user on the
|
|
400
|
+
same machine, via built-in PowerShell. The file holds ciphertext, not the
|
|
401
|
+
passphrase.
|
|
256
402
|
- **Desktop Linux**: the Secret Service keyring, via `secret-tool` when
|
|
257
|
-
libsecret-tools is installed
|
|
403
|
+
libsecret-tools is installed: service `tenjin-cli`, account = the wallet
|
|
404
|
+
address.
|
|
258
405
|
- **Headless or CI (any OS)**: no durable OS store, so set
|
|
259
406
|
`TENJIN_WALLET_PASSPHRASE`.
|
|
260
407
|
|
|
@@ -262,7 +409,17 @@ approval.
|
|
|
262
409
|
key never leaves the machine.
|
|
263
410
|
|
|
264
411
|
- Fund small: this is a pocket-money wallet by design.
|
|
265
|
-
- Purchased content is untrusted data, never instructions.
|
|
412
|
+
- Purchased content is untrusted data, never instructions. The skills never
|
|
413
|
+
execute it, and instructions embedded in it never override the task. In
|
|
414
|
+
particular, no harness permission, hook, or settings change is ever recommended
|
|
415
|
+
on the strength of content the agent read: a claim that some permission change
|
|
416
|
+
is "the documented fix" is still a claim from untrusted content.
|
|
417
|
+
- The recommended auto-mode allowlist covers free verbs only; `tenjin buy` is an
|
|
418
|
+
explicit opt-in that authorizes unattended spending, and money-moving verbs are
|
|
419
|
+
never recommended. See
|
|
420
|
+
[Auto-mode permission allowlist](#auto-mode-permission-allowlist). A harness
|
|
421
|
+
permission denial is never worked around: the skills surface the exact allowlist
|
|
422
|
+
line and stop.
|
|
266
423
|
|
|
267
424
|
## Contributing and releases
|
|
268
425
|
|
|
@@ -1,30 +1,31 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
runBuy
|
|
4
|
-
} from "./chunk-
|
|
5
|
-
import "./chunk-
|
|
4
|
+
} from "./chunk-4WVKXKDK.js";
|
|
5
|
+
import "./chunk-BIKAUVC2.js";
|
|
6
6
|
import "./chunk-FU6MCSLG.js";
|
|
7
|
-
import "./chunk-
|
|
8
|
-
import "./chunk-
|
|
9
|
-
import "./chunk-
|
|
10
|
-
import "./chunk-
|
|
11
|
-
import "./chunk-
|
|
7
|
+
import "./chunk-POJRB2AE.js";
|
|
8
|
+
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";
|
|
12
14
|
import "./chunk-WWX32ML4.js";
|
|
13
|
-
import "./chunk-
|
|
14
|
-
import "./chunk-
|
|
15
|
-
import "./chunk-
|
|
15
|
+
import "./chunk-ZDY2KY5X.js";
|
|
16
|
+
import "./chunk-NJF2WENW.js";
|
|
17
|
+
import "./chunk-NFSOVL3C.js";
|
|
16
18
|
import "./chunk-2I4QTOLB.js";
|
|
17
19
|
import "./chunk-KZAAWQNP.js";
|
|
18
20
|
import "./chunk-S5RYMCV6.js";
|
|
19
|
-
import "./chunk-POJRB2AE.js";
|
|
20
21
|
import "./chunk-YLYINX2H.js";
|
|
21
|
-
import "./chunk-
|
|
22
|
+
import "./chunk-MDDGEGSW.js";
|
|
22
23
|
import "./chunk-YBMMV4Y4.js";
|
|
23
24
|
import "./chunk-UO22YNY4.js";
|
|
24
|
-
import "./chunk-
|
|
25
|
-
import "./chunk-
|
|
26
|
-
import "./chunk-
|
|
27
|
-
import "./chunk-
|
|
25
|
+
import "./chunk-5SCU253N.js";
|
|
26
|
+
import "./chunk-2JQ5JSG6.js";
|
|
27
|
+
import "./chunk-PAUXMRSF.js";
|
|
28
|
+
import "./chunk-MJZZTKCC.js";
|
|
28
29
|
import "./chunk-7FK2UN2T.js";
|
|
29
30
|
import "./chunk-M2O56UK7.js";
|
|
30
31
|
import "./chunk-UHTVXQ2O.js";
|
|
@@ -38,4 +39,4 @@ import "./chunk-ZXTAQYNA.js";
|
|
|
38
39
|
export {
|
|
39
40
|
runBuy
|
|
40
41
|
};
|
|
41
|
-
//# sourceMappingURL=buy-
|
|
42
|
+
//# sourceMappingURL=buy-YMXXVNFH.js.map
|
|
@@ -3,20 +3,20 @@ import {
|
|
|
3
3
|
runCandidateAdd,
|
|
4
4
|
runCandidateDrop,
|
|
5
5
|
runCandidateList
|
|
6
|
-
} from "./chunk-
|
|
7
|
-
import "./chunk-
|
|
6
|
+
} from "./chunk-ZW3B5LWX.js";
|
|
7
|
+
import "./chunk-ZIYVN4CD.js";
|
|
8
8
|
import "./chunk-WWX32ML4.js";
|
|
9
|
-
import "./chunk-
|
|
9
|
+
import "./chunk-NFSOVL3C.js";
|
|
10
10
|
import "./chunk-2I4QTOLB.js";
|
|
11
|
-
import "./chunk-
|
|
11
|
+
import "./chunk-MDDGEGSW.js";
|
|
12
12
|
import "./chunk-UO22YNY4.js";
|
|
13
|
-
import "./chunk-
|
|
14
|
-
import "./chunk-
|
|
15
|
-
import "./chunk-
|
|
13
|
+
import "./chunk-5SCU253N.js";
|
|
14
|
+
import "./chunk-2JQ5JSG6.js";
|
|
15
|
+
import "./chunk-PAUXMRSF.js";
|
|
16
16
|
import "./chunk-ZXTAQYNA.js";
|
|
17
17
|
export {
|
|
18
18
|
runCandidateAdd,
|
|
19
19
|
runCandidateDrop,
|
|
20
20
|
runCandidateList
|
|
21
21
|
};
|
|
22
|
-
//# sourceMappingURL=candidate-
|
|
22
|
+
//# sourceMappingURL=candidate-H7FR4AU5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/atomic-json.ts"],"sourcesContent":["import { chmod, link, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { basename, dirname, join } from 'node:path';\n\n/** fs modes are no-ops on Windows; the 0600/0700 custody story does not apply. */\nconst isWindows = process.platform === 'win32';\n\nexport interface AtomicWriteOptions {\n /** Mode for the written file (ignored on win32). Default 0o644. */\n mode?: number;\n /** Mode for the parent dir when this call creates it (ignored on win32). Default 0o755. */\n dirMode?: number;\n}\n\n/**\n * Write `data` to `targetPath` atomically: a uniquely-named temp file is created\n * in the SAME directory (so the rename is atomic — a cross-filesystem rename is\n * not), given the final mode at open time, then renamed over the target. A\n * reader therefore sees either the old file or the fully-written new one, never\n * a partial write.\n *\n * The temp file is born with the caller's `mode` (0o600 for a wallet key) so the\n * bytes are never written through a world-readable descriptor; the follow-up\n * chmod only makes the mode exact under an unusual umask and only ever touches\n * the temp path, so the live target still appears atomically at its final mode.\n */\nexport async function writeFileAtomic(\n targetPath: string,\n data: string | Buffer,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n await writeFile(tmpPath, data, isWindows ? undefined : { mode: fileMode });\n if (!isWindows) await chmod(tmpPath, fileMode);\n await rename(tmpPath, targetPath);\n } catch (err) {\n await rm(tmpPath, { force: true }).catch(() => undefined);\n throw err;\n }\n}\n\n/**\n * Like {@link writeFileAtomic} but NO-CLOBBER and crash-durable: the commit fails\n * with `EEXIST` when `targetPath` already exists instead of replacing it, and the\n * new entry is fsynced before returning. This is what a wallet key needs — two\n * concurrent `create`/`import` runs must not both \"succeed\" and silently lose one\n * key; the loser gets a distinguishable EEXIST the wallet layer maps to\n * WALLET_EXISTS.\n *\n * The temp file is fsynced, then `link()` commits it — link is atomic and throws\n * EEXIST if the target already exists, so the check-then-write race is closed at\n * the filesystem, not by an earlier stat. The parent dir is then fsynced so the\n * new entry survives a crash. On win32, link semantics differ and a directory\n * cannot be fsynced, so we fall back to an exclusive `wx` open (still atomic\n * create-or-EEXIST, just not crash-durable — win32 has no 0600 custody story to\n * protect anyway).\n */\nexport async function writeFileAtomicExclusive(\n targetPath: string,\n data: string,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n if (isWindows) {\n const handle = await open(targetPath, 'wx');\n try {\n await handle.writeFile(data);\n await handle.sync();\n } finally {\n await handle.close();\n }\n return;\n }\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n const handle = await open(tmpPath, 'wx', fileMode);\n try {\n await handle.writeFile(data);\n await handle.chmod(fileMode); // exact mode even under an unusual umask\n await handle.sync();\n } finally {\n await handle.close();\n }\n await link(tmpPath, targetPath); // atomic; throws EEXIST when the target exists\n await fsyncDir(dir);\n } finally {\n // On success the temp is now a redundant link to the target; on EEXIST it is\n // the orphaned write. Either way remove it before returning/throwing.\n await rm(tmpPath, { force: true }).catch(() => undefined);\n }\n}\n\n/** fsync a directory so a freshly linked entry is durable. Never
|
|
1
|
+
{"version":3,"sources":["../src/lib/atomic-json.ts"],"sourcesContent":["import { chmod, link, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { basename, dirname, join } from 'node:path';\n\n/** fs modes are no-ops on Windows; the 0600/0700 custody story does not apply. */\nconst isWindows = process.platform === 'win32';\n\nexport interface AtomicWriteOptions {\n /** Mode for the written file (ignored on win32). Default 0o644. */\n mode?: number;\n /** Mode for the parent dir when this call creates it (ignored on win32). Default 0o755. */\n dirMode?: number;\n}\n\n/**\n * Write `data` to `targetPath` atomically: a uniquely-named temp file is created\n * in the SAME directory (so the rename is atomic — a cross-filesystem rename is\n * not), given the final mode at open time, then renamed over the target. A\n * reader therefore sees either the old file or the fully-written new one, never\n * a partial write.\n *\n * The temp file is born with the caller's `mode` (0o600 for a wallet key) so the\n * bytes are never written through a world-readable descriptor; the follow-up\n * chmod only makes the mode exact under an unusual umask and only ever touches\n * the temp path, so the live target still appears atomically at its final mode.\n */\nexport async function writeFileAtomic(\n targetPath: string,\n data: string | Buffer,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n await writeFile(tmpPath, data, isWindows ? undefined : { mode: fileMode });\n if (!isWindows) await chmod(tmpPath, fileMode);\n await rename(tmpPath, targetPath);\n } catch (err) {\n await rm(tmpPath, { force: true }).catch(() => undefined);\n throw err;\n }\n}\n\n/**\n * Like {@link writeFileAtomic} but NO-CLOBBER and crash-durable: the commit fails\n * with `EEXIST` when `targetPath` already exists instead of replacing it, and the\n * new entry is fsynced before returning. This is what a wallet key needs — two\n * concurrent `create`/`import` runs must not both \"succeed\" and silently lose one\n * key; the loser gets a distinguishable EEXIST the wallet layer maps to\n * WALLET_EXISTS.\n *\n * The temp file is fsynced, then `link()` commits it — link is atomic and throws\n * EEXIST if the target already exists, so the check-then-write race is closed at\n * the filesystem, not by an earlier stat. The parent dir is then fsynced so the\n * new entry survives a crash. On win32, link semantics differ and a directory\n * cannot be fsynced, so we fall back to an exclusive `wx` open (still atomic\n * create-or-EEXIST, just not crash-durable — win32 has no 0600 custody story to\n * protect anyway).\n */\nexport async function writeFileAtomicExclusive(\n targetPath: string,\n data: string,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n if (isWindows) {\n const handle = await open(targetPath, 'wx');\n try {\n await handle.writeFile(data);\n await handle.sync();\n } finally {\n await handle.close();\n }\n return;\n }\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n const handle = await open(tmpPath, 'wx', fileMode);\n try {\n await handle.writeFile(data);\n await handle.chmod(fileMode); // exact mode even under an unusual umask\n await handle.sync();\n } finally {\n await handle.close();\n }\n await link(tmpPath, targetPath); // atomic; throws EEXIST when the target exists\n await fsyncDir(dir);\n } finally {\n // On success the temp is now a redundant link to the target; on EEXIST it is\n // the orphaned write. Either way remove it before returning/throwing.\n await rm(tmpPath, { force: true }).catch(() => undefined);\n }\n}\n\n/** fsync a directory so a freshly linked entry is durable. Never call on win32. */\nexport async function fsyncDir(dir: string): Promise<void> {\n const handle = await open(dir, 'r');\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n}\n"],"mappings":";;;AAAA,SAAS,OAAO,MAAM,OAAO,MAAM,QAAQ,IAAI,iBAAiB;AAChE,SAAS,mBAAmB;AAC5B,SAAS,UAAU,SAAS,YAAY;AAGxC,IAAM,YAAY,QAAQ,aAAa;AAqBvC,eAAsB,gBACpB,YACA,MACA,OAA2B,CAAC,GACb;AACf,QAAM,MAAM,QAAQ,UAAU;AAC9B,QAAM,WAAW,KAAK,QAAQ;AAC9B,QAAM,UAAU,KAAK,WAAW;AAEhC,QAAM,MAAM,KAAK,EAAE,WAAW,MAAM,GAAI,YAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,EAAG,CAAC;AAE7E,QAAM,UAAU,KAAK,KAAK,IAAI,SAAS,UAAU,CAAC,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,MAAM;AAC1F,MAAI;AACF,UAAM,UAAU,SAAS,MAAM,YAAY,SAAY,EAAE,MAAM,SAAS,CAAC;AACzE,QAAI,CAAC,UAAW,OAAM,MAAM,SAAS,QAAQ;AAC7C,UAAM,OAAO,SAAS,UAAU;AAA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
|
|
|
7
7
|
CLIENT_HEADER,
|
|
8
8
|
httpRequest,
|
|
9
9
|
trimSlash
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-ZDY2KY5X.js";
|
|
11
11
|
import {
|
|
12
12
|
CliError,
|
|
13
13
|
external_exports
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-PAUXMRSF.js";
|
|
15
15
|
|
|
16
16
|
// src/lib/agent-api.ts
|
|
17
17
|
var FRESH_WITHIN_RE = /^P(\d+)[DWMY]$/;
|
|
18
18
|
var CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;
|
|
19
|
+
var MAX_LIMIT = 10;
|
|
19
20
|
function buildSearchRequest(input) {
|
|
20
21
|
const question = input.question.trim();
|
|
21
22
|
if (question.length === 0 || question.length > 512) {
|
|
@@ -37,9 +38,9 @@ function buildSearchRequest(input) {
|
|
|
37
38
|
});
|
|
38
39
|
}
|
|
39
40
|
const limit = input.limit ?? 5;
|
|
40
|
-
if (!Number.isInteger(limit) || limit < 1 || limit >
|
|
41
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
41
42
|
throw new CliError("USAGE", `Invalid --limit: ${JSON.stringify(input.limit)}`, {
|
|
42
|
-
fix:
|
|
43
|
+
fix: `Pass an integer between 1 and ${MAX_LIMIT}.`
|
|
43
44
|
});
|
|
44
45
|
}
|
|
45
46
|
if (input.appliesTo !== void 0) {
|
|
@@ -72,7 +73,7 @@ function buildSearchRequest(input) {
|
|
|
72
73
|
}
|
|
73
74
|
}
|
|
74
75
|
return {
|
|
75
|
-
schemaVersion:
|
|
76
|
+
schemaVersion: 2,
|
|
76
77
|
question,
|
|
77
78
|
...input.freshWithin !== void 0 ? { freshWithin: input.freshWithin } : {},
|
|
78
79
|
...input.maxPrice !== void 0 ? { maxPrice: input.maxPrice } : {},
|
|
@@ -83,17 +84,12 @@ function buildSearchRequest(input) {
|
|
|
83
84
|
var searchCandidateSchema = external_exports.object({
|
|
84
85
|
resourceId: external_exports.string().regex(UUID_RE, "resourceId must be a uuid"),
|
|
85
86
|
url: external_exports.string(),
|
|
87
|
+
slug: external_exports.string(),
|
|
86
88
|
title: external_exports.string(),
|
|
87
89
|
artifactType: external_exports.string(),
|
|
88
90
|
price: external_exports.string().regex(ATOMIC_RE, "price must be an atomic integer string"),
|
|
89
91
|
asOf: external_exports.string().nullable(),
|
|
90
92
|
validUntil: external_exports.string().nullable(),
|
|
91
|
-
temporalMode: external_exports.string(),
|
|
92
|
-
appliesTo: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
|
|
93
|
-
questionsAnswered: external_exports.array(external_exports.string()),
|
|
94
|
-
tasksSupported: external_exports.array(external_exports.string()),
|
|
95
|
-
scope: external_exports.string().nullable(),
|
|
96
|
-
exclusions: external_exports.string().nullable(),
|
|
97
93
|
matchReasons: external_exports.array(external_exports.string()),
|
|
98
94
|
estimatedTokens: external_exports.number(),
|
|
99
95
|
creator: external_exports.object({ handle: external_exports.string() }).passthrough()
|
|
@@ -107,11 +103,18 @@ var searchBrowseSchema = external_exports.object({
|
|
|
107
103
|
creator: external_exports.object({ handle: external_exports.string() }).passthrough()
|
|
108
104
|
}).passthrough();
|
|
109
105
|
var searchResponseSchema = external_exports.object({
|
|
110
|
-
schemaVersion: external_exports.literal(
|
|
106
|
+
schemaVersion: external_exports.literal(2),
|
|
111
107
|
searchId: external_exports.string().regex(UUID_RE, "searchId must be a uuid"),
|
|
112
108
|
decision: external_exports.enum(["CANDIDATES", "MISS"]),
|
|
113
109
|
calibration: external_exports.string(),
|
|
114
110
|
candidates: external_exports.array(searchCandidateSchema).optional(),
|
|
111
|
+
// Set only when the server's size backstop dropped trailing candidates the
|
|
112
|
+
// requested limit had room for; omitted entirely otherwise. There is no cursor,
|
|
113
|
+
// so a retry at a SMALLER limit returns strictly fewer rows; the ceiling scales
|
|
114
|
+
// with the candidates returned, so a LARGER limit (up to MAX_LIMIT) is what
|
|
115
|
+
// recovers the tail, and at MAX_LIMIT the tail is unrecoverable and narrowing the
|
|
116
|
+
// question is the remedy. `runSearch` picks the half that applies.
|
|
117
|
+
truncated: external_exports.literal(true).optional(),
|
|
115
118
|
// Omitted entirely by the server when empty, and only ever present on a MISS.
|
|
116
119
|
// Not enforced here (a stricter schema would reject an otherwise-usable
|
|
117
120
|
// response); truncateResponse drops it on a CANDIDATES decision instead.
|
|
@@ -120,7 +123,7 @@ var searchResponseSchema = external_exports.object({
|
|
|
120
123
|
function apiFailure(url, result) {
|
|
121
124
|
const code = result.kind === "network" || result.kind === "timeout" ? "NETWORK_ERROR" : "API_UNREACHABLE";
|
|
122
125
|
return new CliError(code, `${url}: ${result.message}`, {
|
|
123
|
-
fix: "Check
|
|
126
|
+
fix: "Check your network and the configured base URL (`tenjin config get baseUrl`), then retry."
|
|
124
127
|
});
|
|
125
128
|
}
|
|
126
129
|
function rateLimitError(url, header) {
|
|
@@ -161,6 +164,11 @@ async function postSearch(body, opts) {
|
|
|
161
164
|
if (!res.ok) throw apiFailure(url, res);
|
|
162
165
|
if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));
|
|
163
166
|
if (res.status !== 200) {
|
|
167
|
+
if (res.status === 400 && rejectedSchemaVersion(res.json)) {
|
|
168
|
+
throw outdatedServerError("The server rejected schemaVersion 2: it predates search v2.", {
|
|
169
|
+
details: res.json
|
|
170
|
+
});
|
|
171
|
+
}
|
|
164
172
|
throw new CliError(
|
|
165
173
|
"API_UNREACHABLE",
|
|
166
174
|
serverErrorMessage(res.json) ?? `Search failed (${res.status})`,
|
|
@@ -172,6 +180,13 @@ async function postSearch(body, opts) {
|
|
|
172
180
|
}
|
|
173
181
|
const parsed = searchResponseSchema.safeParse(res.json);
|
|
174
182
|
if (!parsed.success) {
|
|
183
|
+
const served = serverSchemaVersion(res.json);
|
|
184
|
+
if (served !== void 0 && served !== 2) {
|
|
185
|
+
throw outdatedServerError(
|
|
186
|
+
`Search response is schemaVersion ${served}; this CLI requires 2 (search v2).`,
|
|
187
|
+
{ details: parsed.error.issues }
|
|
188
|
+
);
|
|
189
|
+
}
|
|
175
190
|
throw new CliError("CONTRACT_MISMATCH", "Search response did not match the expected contract", {
|
|
176
191
|
fix: "Update tenjin-cli; the server contract may have changed.",
|
|
177
192
|
details: parsed.error.issues
|
|
@@ -179,17 +194,26 @@ async function postSearch(body, opts) {
|
|
|
179
194
|
}
|
|
180
195
|
return truncateResponse(parsed.data);
|
|
181
196
|
}
|
|
197
|
+
function outdatedServerError(message, opts) {
|
|
198
|
+
return new CliError("CONTRACT_MISMATCH", message, {
|
|
199
|
+
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.",
|
|
200
|
+
details: opts.details
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
function rejectedSchemaVersion(json) {
|
|
204
|
+
const record = (v) => typeof v === "object" && v !== null ? v : void 0;
|
|
205
|
+
const fieldErrors = record(record(record(json)?.error)?.details)?.fieldErrors;
|
|
206
|
+
return Array.isArray(record(fieldErrors)?.schemaVersion);
|
|
207
|
+
}
|
|
208
|
+
function serverSchemaVersion(json) {
|
|
209
|
+
if (typeof json !== "object" || json === null) return void 0;
|
|
210
|
+
const v = json.schemaVersion;
|
|
211
|
+
return typeof v === "number" ? v : void 0;
|
|
212
|
+
}
|
|
182
213
|
var CAND_BOUNDS = {
|
|
183
214
|
title: 200,
|
|
184
|
-
scope: 240,
|
|
185
|
-
exclusions: 240,
|
|
186
|
-
listItems: 4,
|
|
187
|
-
listItemChars: 160,
|
|
188
215
|
matchReasons: 3,
|
|
189
|
-
matchReasonChars: 80
|
|
190
|
-
appliesToKeys: 6,
|
|
191
|
-
appliesToValues: 5,
|
|
192
|
-
appliesToValueChars: 80
|
|
216
|
+
matchReasonChars: 80
|
|
193
217
|
};
|
|
194
218
|
var cap = (s, n) => s.length > n ? s.slice(0, n) : s;
|
|
195
219
|
function truncateResponse(res) {
|
|
@@ -212,28 +236,10 @@ function truncateResponse(res) {
|
|
|
212
236
|
}
|
|
213
237
|
var BROWSE_MAX = 3;
|
|
214
238
|
function truncateCandidate(c) {
|
|
215
|
-
const capList = (list, items, chars) => list.slice(0, items).map((s) => cap(s, chars));
|
|
216
|
-
const appliesTo = {};
|
|
217
|
-
for (const key of Object.keys(c.appliesTo).slice(0, CAND_BOUNDS.appliesToKeys)) {
|
|
218
|
-
appliesTo[cap(key, CAND_BOUNDS.appliesToValueChars)] = capList(
|
|
219
|
-
c.appliesTo[key] ?? [],
|
|
220
|
-
CAND_BOUNDS.appliesToValues,
|
|
221
|
-
CAND_BOUNDS.appliesToValueChars
|
|
222
|
-
);
|
|
223
|
-
}
|
|
224
239
|
return {
|
|
225
240
|
...c,
|
|
226
241
|
title: cap(c.title, CAND_BOUNDS.title),
|
|
227
|
-
|
|
228
|
-
exclusions: c.exclusions === null ? null : cap(c.exclusions, CAND_BOUNDS.exclusions),
|
|
229
|
-
questionsAnswered: capList(
|
|
230
|
-
c.questionsAnswered,
|
|
231
|
-
CAND_BOUNDS.listItems,
|
|
232
|
-
CAND_BOUNDS.listItemChars
|
|
233
|
-
),
|
|
234
|
-
tasksSupported: capList(c.tasksSupported, CAND_BOUNDS.listItems, CAND_BOUNDS.listItemChars),
|
|
235
|
-
matchReasons: capList(c.matchReasons, CAND_BOUNDS.matchReasons, CAND_BOUNDS.matchReasonChars),
|
|
236
|
-
appliesTo
|
|
242
|
+
matchReasons: c.matchReasons.slice(0, CAND_BOUNDS.matchReasons).map((r) => cap(r, CAND_BOUNDS.matchReasonChars))
|
|
237
243
|
};
|
|
238
244
|
}
|
|
239
245
|
var OUTCOME_STATUSES = [
|
|
@@ -304,10 +310,11 @@ async function postOutcomes(searchId, items, opts) {
|
|
|
304
310
|
}
|
|
305
311
|
|
|
306
312
|
export {
|
|
313
|
+
MAX_LIMIT,
|
|
307
314
|
buildSearchRequest,
|
|
308
315
|
rateLimitError,
|
|
309
316
|
postSearch,
|
|
310
317
|
buildOutcomeItem,
|
|
311
318
|
postOutcomes
|
|
312
319
|
};
|
|
313
|
-
//# sourceMappingURL=chunk-
|
|
320
|
+
//# sourceMappingURL=chunk-3IRDP7TN.js.map
|
|
@@ -0,0 +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":";;;;;;;;;;;;;;;;AAiB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