tenjin-cli 0.1.0-alpha.11 → 0.1.0-alpha.12

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 (61) hide show
  1. package/README.md +235 -596
  2. package/dist/{buy-THMVOPUH.js → buy-3DTBFZ4B.js} +6 -6
  3. package/dist/{chunk-VWY3U732.js → chunk-6RMEX74N.js} +2 -2
  4. package/dist/{chunk-2SDUV6MQ.js → chunk-7MJVNALU.js} +2 -2
  5. package/dist/{chunk-OCN27NJV.js → chunk-CBNXUQGM.js} +2 -2
  6. package/dist/{chunk-GUUAYR3K.js → chunk-CLOEU7RA.js} +2 -2
  7. package/dist/chunk-CLOEU7RA.js.map +1 -0
  8. package/dist/{chunk-UY6CGULW.js → chunk-HWHYPCCH.js} +2 -2
  9. package/dist/{chunk-UY6CGULW.js.map → chunk-HWHYPCCH.js.map} +1 -1
  10. package/dist/{chunk-IAFYUFIC.js → chunk-ILDVGY7K.js} +3 -3
  11. package/dist/{chunk-XWHXX2BI.js → chunk-L3I2MVKR.js} +2 -2
  12. package/dist/{chunk-O25VWJCG.js → chunk-MBKFZBB2.js} +2 -2
  13. package/dist/{chunk-ZE7KOO7A.js → chunk-ROAK2DOX.js} +3 -3
  14. package/dist/{chunk-3GSZUADW.js → chunk-TUXKOIOU.js} +2 -2
  15. package/dist/{chunk-GKV6VZSZ.js → chunk-V5UHKC46.js} +2 -2
  16. package/dist/chunk-V5UHKC46.js.map +1 -0
  17. package/dist/{chunk-IXTENA2H.js → chunk-WWIKAJFO.js} +2 -2
  18. package/dist/{chunk-EDVI7RRD.js → chunk-X2WZPGCF.js} +3 -3
  19. package/dist/{chunk-EDVI7RRD.js.map → chunk-X2WZPGCF.js.map} +1 -1
  20. package/dist/{cli-Y2HBOSGK.js → cli-3WZGLZDP.js} +13 -13
  21. package/dist/{doctor-CSIWKWM2.js → doctor-EKVCP7JP.js} +4 -4
  22. package/dist/{edit-E7N6F3OY.js → edit-4UZQVFCK.js} +6 -6
  23. package/dist/{fund-OKK627GL.js → fund-JAPOFTUG.js} +4 -4
  24. package/dist/index.js +1 -1
  25. package/dist/{inspect-573WHEV4.js → inspect-IEV75A42.js} +6 -6
  26. package/dist/{install-SQAYMNQC.js → install-WXTOHDWC.js} +4 -4
  27. package/dist/{outcome-W3KYGF23.js → outcome-FYOFDOUK.js} +5 -5
  28. package/dist/{publish-N5U4XYVA.js → publish-6QNARH7E.js} +6 -6
  29. package/dist/{read-PJ7Z6UGF.js → read-UAZGZ4UL.js} +5 -5
  30. package/dist/{run-FSO3MMXN.js → run-AJNCOT5R.js} +13 -13
  31. package/dist/{search-ZWOP4EGK.js → search-EEKTW6VK.js} +5 -5
  32. package/docs/agent-permissions.md +2 -2
  33. package/docs/command-reference.md +204 -0
  34. package/docs/safety-model.md +45 -0
  35. package/package.json +1 -1
  36. package/skills/tenjin/SKILL.md +3 -3
  37. package/skills/tenjin-publish/SKILL.md +14 -11
  38. package/skills/tenjin-search/SKILL.md +14 -13
  39. package/dist/chunk-GKV6VZSZ.js.map +0 -1
  40. package/dist/chunk-GUUAYR3K.js.map +0 -1
  41. /package/dist/{buy-THMVOPUH.js.map → buy-3DTBFZ4B.js.map} +0 -0
  42. /package/dist/{chunk-VWY3U732.js.map → chunk-6RMEX74N.js.map} +0 -0
  43. /package/dist/{chunk-2SDUV6MQ.js.map → chunk-7MJVNALU.js.map} +0 -0
  44. /package/dist/{chunk-OCN27NJV.js.map → chunk-CBNXUQGM.js.map} +0 -0
  45. /package/dist/{chunk-IAFYUFIC.js.map → chunk-ILDVGY7K.js.map} +0 -0
  46. /package/dist/{chunk-XWHXX2BI.js.map → chunk-L3I2MVKR.js.map} +0 -0
  47. /package/dist/{chunk-O25VWJCG.js.map → chunk-MBKFZBB2.js.map} +0 -0
  48. /package/dist/{chunk-ZE7KOO7A.js.map → chunk-ROAK2DOX.js.map} +0 -0
  49. /package/dist/{chunk-3GSZUADW.js.map → chunk-TUXKOIOU.js.map} +0 -0
  50. /package/dist/{chunk-IXTENA2H.js.map → chunk-WWIKAJFO.js.map} +0 -0
  51. /package/dist/{cli-Y2HBOSGK.js.map → cli-3WZGLZDP.js.map} +0 -0
  52. /package/dist/{doctor-CSIWKWM2.js.map → doctor-EKVCP7JP.js.map} +0 -0
  53. /package/dist/{edit-E7N6F3OY.js.map → edit-4UZQVFCK.js.map} +0 -0
  54. /package/dist/{fund-OKK627GL.js.map → fund-JAPOFTUG.js.map} +0 -0
  55. /package/dist/{inspect-573WHEV4.js.map → inspect-IEV75A42.js.map} +0 -0
  56. /package/dist/{install-SQAYMNQC.js.map → install-WXTOHDWC.js.map} +0 -0
  57. /package/dist/{outcome-W3KYGF23.js.map → outcome-FYOFDOUK.js.map} +0 -0
  58. /package/dist/{publish-N5U4XYVA.js.map → publish-6QNARH7E.js.map} +0 -0
  59. /package/dist/{read-PJ7Z6UGF.js.map → read-UAZGZ4UL.js.map} +0 -0
  60. /package/dist/{run-FSO3MMXN.js.map → run-AJNCOT5R.js.map} +0 -0
  61. /package/dist/{search-ZWOP4EGK.js.map → search-EEKTW6VK.js.map} +0 -0
@@ -1,22 +1,22 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  runBuy
4
- } from "./chunk-O25VWJCG.js";
4
+ } from "./chunk-MBKFZBB2.js";
5
5
  import "./chunk-QW2Q2KAH.js";
6
6
  import "./chunk-OZHJ3FLR.js";
7
- import "./chunk-ZE7KOO7A.js";
7
+ import "./chunk-ROAK2DOX.js";
8
8
  import "./chunk-SGK2B724.js";
9
9
  import "./chunk-6UY2UQMY.js";
10
10
  import "./chunk-4NTZETIL.js";
11
- import "./chunk-EDVI7RRD.js";
11
+ import "./chunk-X2WZPGCF.js";
12
12
  import "./chunk-6BGYHARE.js";
13
13
  import "./chunk-S5RYMCV6.js";
14
14
  import "./chunk-POJRB2AE.js";
15
15
  import "./chunk-YLYINX2H.js";
16
16
  import "./chunk-MJZZTKCC.js";
17
17
  import "./chunk-CNUXRXI2.js";
18
- import "./chunk-3GSZUADW.js";
19
- import "./chunk-UY6CGULW.js";
18
+ import "./chunk-TUXKOIOU.js";
19
+ import "./chunk-HWHYPCCH.js";
20
20
  import "./chunk-PZSUWDF2.js";
21
21
  import "./chunk-Y7ERTA7D.js";
22
22
  import "./chunk-KZAAWQNP.js";
@@ -41,4 +41,4 @@ import "./chunk-ZXTAQYNA.js";
41
41
  export {
42
42
  runBuy
43
43
  };
44
- //# sourceMappingURL=buy-THMVOPUH.js.map
44
+ //# sourceMappingURL=buy-3DTBFZ4B.js.map
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-4TCU3YRD.js";
6
6
  import {
7
7
  fetchJson
8
- } from "./chunk-3GSZUADW.js";
8
+ } from "./chunk-TUXKOIOU.js";
9
9
  import {
10
10
  isSessionPresentable,
11
11
  readSessionFile,
@@ -671,4 +671,4 @@ export {
671
671
  isNoWalletCheck,
672
672
  renderDoctorHuman
673
673
  };
674
- //# sourceMappingURL=chunk-VWY3U732.js.map
674
+ //# sourceMappingURL=chunk-6RMEX74N.js.map
@@ -16,7 +16,7 @@ import {
16
16
  resolveWriteAuth,
17
17
  scan,
18
18
  writeModeNotices
19
- } from "./chunk-IAFYUFIC.js";
19
+ } from "./chunk-ILDVGY7K.js";
20
20
  import {
21
21
  headingOutline
22
22
  } from "./chunk-SGK2B724.js";
@@ -349,4 +349,4 @@ function confirmMessage(warnCount, priceUsd) {
349
349
  export {
350
350
  runPublish
351
351
  };
352
- //# sourceMappingURL=chunk-2SDUV6MQ.js.map
352
+ //# sourceMappingURL=chunk-7MJVNALU.js.map
@@ -15,7 +15,7 @@ import {
15
15
  scan,
16
16
  updatePost,
17
17
  writeModeNotices
18
- } from "./chunk-IAFYUFIC.js";
18
+ } from "./chunk-ILDVGY7K.js";
19
19
  import {
20
20
  describeWallet,
21
21
  resolveWalletProvider
@@ -609,4 +609,4 @@ function hasText(value) {
609
609
  export {
610
610
  runEdit
611
611
  };
612
- //# sourceMappingURL=chunk-OCN27NJV.js.map
612
+ //# sourceMappingURL=chunk-CBNXUQGM.js.map
@@ -9,7 +9,7 @@ import {
9
9
  MAX_LIMIT,
10
10
  buildSearchRequest,
11
11
  postSearch
12
- } from "./chunk-EDVI7RRD.js";
12
+ } from "./chunk-X2WZPGCF.js";
13
13
  import {
14
14
  sanitizeForTerminal
15
15
  } from "./chunk-IB63U6BM.js";
@@ -172,4 +172,4 @@ function parseAppliesTo(pairs) {
172
172
  export {
173
173
  runSearch
174
174
  };
175
- //# sourceMappingURL=chunk-GUUAYR3K.js.map
175
+ //# sourceMappingURL=chunk-CLOEU7RA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/search.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { formatUsdDisplay, isPaidPrice, parseUsdToAtomic } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildSearchRequest, postSearch, MAX_LIMIT, type SearchInput } from '../lib/agent-api';\nimport { recordSearch } from '../lib/search-store';\nimport { assertOnBaseOrigin } from '../lib/resource-ref';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin search \"<question>\"`, one POST to /api/agent/search. Prints the compact\n * CANDIDATES/MISS response (spec 10) and records the searchId + candidates\n * locally so `outcome --last` and `buy <resourceId>` can use them. No wallet, no\n * signing: search is anonymous.\n *\n * The machine envelope is the server's response verbatim plus exactly one\n * CLI-owned key, `publishBack`, and only on a MISS. It carries no server data: it\n * is the local searchId and the two commands that close the loop, which is\n * information the CLI owns and the contract does not describe.\n *\n * Search is the breadth step: a candidate is a lean hit (identity, price,\n * freshness, why it matched), and the full answer card comes from `tenjin inspect`,\n * which is free. So a candidate line stays short on purpose.\n *\n * The response's `searchId` is the outcome-reporting capability for\n * POST /api/searches/<searchId>/outcomes. tenjin#463 renamed the field (from\n * `lookupId`) and tenjin#616 dropped the `/agent` prefix from the path; this\n * client follows both end to end, so nothing on the wire or in the local store\n * still speaks `lookupId` or the prefixed spelling.\n */\n\nexport interface SearchArgs {\n question: string;\n /** Decimal USD at the edge (O1); converted to atomic for the wire. */\n maxPrice?: string;\n freshWithin?: string;\n limit?: string;\n /** Raw `k=v` / `k=v1,v2` pairs from repeated --applies-to. */\n appliesTo?: string[];\n}\n\nexport interface SearchDeps {\n fetchImpl?: typeof fetch;\n /** Environment seam (TENJIN_SESSION_ID); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runSearch(\n args: SearchArgs,\n ctx: CommandContext,\n deps: SearchDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const input: SearchInput = { question: args.question };\n if (args.maxPrice !== undefined) input.maxPrice = parseUsdToAtomic(args.maxPrice);\n if (args.freshWithin !== undefined) input.freshWithin = args.freshWithin;\n if (args.limit !== undefined) input.limit = parseLimit(args.limit);\n if (args.appliesTo !== undefined && args.appliesTo.length > 0) {\n input.appliesTo = parseAppliesTo(args.appliesTo);\n }\n\n const sessionId = readSessionId(deps.env ?? process.env);\n const request = buildSearchRequest(input);\n const response = await postSearch(request, {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n evalCohort: settings.evalCohort,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const candidates = response.candidates ?? [];\n // Ingest trust boundary: a candidate url that points off the configured origin\n // would later route a wallet-signed SIWX header and payment to that host via\n // `buy <resourceId>`. Refuse the whole response as a contract violation.\n for (const c of candidates) {\n try {\n assertOnBaseOrigin(c.url, settings.baseUrl, 'search candidate URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Search candidate ${c.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n // Browse pointers are never buyable through `buy <resourceId>` (they are not\n // recorded), but their urls are still emitted into the agent's transcript, so\n // they get the same origin check rather than a weaker one.\n for (const b of response.browse ?? []) {\n try {\n assertOnBaseOrigin(b.url, settings.baseUrl, 'browse pointer URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Browse pointer ${b.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n await recordSearch(ctx.dataDir, {\n searchId: response.searchId,\n at: new Date().toISOString(),\n question: request.question,\n decision: response.decision,\n // A deliberate search, as opposed to one the WebSearch hook rode along with.\n // The Stop hook nags on the two differently, so the tag has to be written\n // here rather than inferred later from anything.\n source: 'cli',\n // Usually absent; see readSessionId. An unstamped entry is raised in every\n // session, which is the safe direction for a reminder.\n ...(sessionId !== undefined ? { sessionId } : {}),\n candidates: candidates.map((c) => ({\n resourceId: c.resourceId,\n url: c.url,\n title: c.title,\n price: c.price,\n })),\n // The pointers stay unrecorded on purpose (see below); only how many of them\n // cost money, so `outcome` can tell a MISS that offered a payable browse tail\n // from one that offered nothing to buy. A zero-priced pointer does not count:\n // `read` delivers it for nothing, so there was no purchase to decline. Zero on\n // a CANDIDATES decision, where the contract carries no browse array and the\n // parser drops any that appears.\n paidBrowseCount: (response.browse ?? []).filter((b) => isPaidPrice(b.price) === true).length,\n });\n\n // One stderr line on a MISS (never in the machine JSON): a MISS is the moment\n // to publish the answer you are about to derive. There is deliberately no\n // second line about drafts waiting somewhere — a reminder that re-raises work\n // nobody chose to come back to is the class this CLI stopped emitting.\n if (response.decision === 'MISS') {\n ctx.io.stderr.write(`${publishBackLine(response.searchId)}\\n`);\n }\n\n // A MISS may carry up to 3 browse pointers from the broad corpus. They are\n // pointers, NOT candidates: rendered as ONE hint line with no scores and no\n // per-item detail, so a MISS still reads as a MISS and an agent is never\n // nudged to treat a browse pointer as an answer. The machine JSON keeps the\n // full `browse` array; this line is only the human tail.\n //\n // The price rides this line because a browse url IS payable: it is the read\n // endpoint that answers a 402, and `buy <url>` resolves the URL arm by origin\n // without consulting the search store, so a browse pointer can be bought even\n // though `buy <resourceId>` can never reach one. All spend gates (price cap,\n // session budget, allowlist, confirm) still run; showing the price keeps the\n // only human-visible surface from being a blind spend.\n //\n // It renders in DOLLARS, not atomic units, because the whole point of the line\n // is that a human can size the spend against the gates they set, and every gate\n // is entered in decimal USD (`--max-price 0.10`, the `maxAutoSpend` config).\n // `formatUsdDisplay` is the canonical human-copy form (always two decimals, so\n // a dime reads \"0.10\" and not \"0.1\"); the machine `browse` array in --json still\n // carries the exact atomic string, per the money-units contract in the README.\n const browse = response.browse ?? [];\n const browseHint =\n browse.length > 0\n ? [\n `no match, ${browse.length} piece(s) you could browse: ${browse\n .map((b) => `${sanitizeForTerminal(b.title)} (${formatUsdDisplay(b.price)} USD)`)\n .join('; ')}`,\n ]\n : [];\n\n // `truncated` means the server's size backstop dropped candidates, either a\n // trailing few the limit had room for or a single oversized one. The response\n // ceiling GROWS with the number of candidates returned (tenjin#501), so the\n // remedy is counter-intuitive and worth stating outright: a larger --limit\n // recovers the tail, a smaller one returns strictly fewer. Only at the maximum\n // is the tail unrecoverable and narrowing the question the answer.\n //\n // The CLI knows the limit it sent, so it names the next step instead of\n // restating the rule and leaving the reader to work out which half applies.\n // The flag stays in the machine envelope (--json) untouched, where it is\n // omitted rather than false when it did not fire.\n //\n // Rendering it on a MISS too is DEFENSIVE, not wire behavior: the server only\n // ever sets the flag alongside candidates it dropped. Handling both keeps the\n // flag from going unrendered if that ever changes.\n const truncatedHint =\n response.truncated === true\n ? [\n request.limit < MAX_LIMIT\n ? `some candidates were dropped for size; retry with --limit ${MAX_LIMIT} (the size ceiling grows with the number of candidates returned)`\n : `some candidates were dropped for size; at --limit ${MAX_LIMIT} the dropped tail cannot be recovered, so narrow the question`,\n ]\n : [];\n\n const humanLines =\n response.decision === 'MISS'\n ? [`MISS, no candidates (searchId ${response.searchId})`, ...browseHint, ...truncatedHint]\n : [\n `${candidates.length} candidate(s) (searchId ${response.searchId}):`,\n // Dollars for the same reason the browse hint uses them: this is the\n // human's cue to size the spend against gates they entered in decimal\n // USD. The machine `candidates` array in --json keeps atomic.\n ...candidates.map(\n (c, i) =>\n ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${formatUsdDisplay(c.price)} USD, ${sanitizeForTerminal(c.url)}`,\n ),\n ...truncatedHint,\n ];\n\n // The one CLI-owned field in this envelope. Everything else is the server's\n // response verbatim (spec 10), so the addition is namespaced under a key the\n // contract does not define and is present ONLY on a MISS: a MISS is the moment\n // the demand this searcher just expressed can still be met, and the searchId is\n // what ties the answer they are about to derive back to it. A CANDIDATES\n // response is byte-identical to what it was.\n const data =\n response.decision === 'MISS'\n ? { ...response, publishBack: publishBackHint(response.searchId) }\n : response;\n\n return { data, humanLines };\n}\n\n/**\n * The session to stamp this search with, so the Stop hook can tell one session's\n * open loops from a sibling's, or undefined when nothing can say.\n *\n * Two sources, in precedence order. TENJIN_SESSION_ID is the explicit operator\n * override and wins. CLAUDE_CODE_SESSION_ID is what Claude Code exports to Bash\n * tool subprocesses, which is what a `tenjin search` runs as; its value is the\n * same `session_id` the hook scripts are handed on stdin, so a CLI search and a\n * WebSearch-hook search in one session stamp identically. It is verified against\n * a live session rather than documented, hence the fallback rather than a\n * requirement: on a harness that does not export it this stays undefined, and\n * undefined is the safe answer — the hook raises an unstamped entry in every\n * session rather than in none.\n */\nfunction readSessionId(env: NodeJS.ProcessEnv): string | undefined {\n return firstNonEmpty(env.TENJIN_SESSION_ID) ?? firstNonEmpty(env.CLAUDE_CODE_SESSION_ID);\n}\n\nfunction firstNonEmpty(raw: string | undefined): string | undefined {\n if (typeof raw !== 'string') return undefined;\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/** The publish-back hint, as machine fields rather than prose to re-parse. */\nfunction publishBackHint(searchId: string): {\n searchId: string;\n reason: string;\n publish: string;\n decline: string;\n} {\n return {\n searchId,\n reason: 'Nothing on the marketplace answered this. If you solve it, publish it back.',\n // Both arms carry the searchId, because both are commands to run verbatim and\n // a publish without it leaves this very loop open (see publish's --search-id).\n // The second arm is DECLINE, not park: nothing is saved to come back to, and\n // reporting the outcome is what closes the loop so it never raises again.\n publish: `tenjin publish <file.md> --json --search-id ${searchId}`,\n decline: `tenjin outcome --search-id ${searchId} --status regenerated --json`,\n };\n}\n\n/** The same hint as one stderr line for a human. */\nfunction publishBackLine(searchId: string): string {\n return `Nobody has published this yet - if you solve it, publish it back (tenjin publish <file.md> --search-id ${searchId}); if you will not, close the loop: tenjin outcome --search-id ${searchId} --status regenerated`;\n}\n\nfunction parseLimit(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n)) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(raw)}`, {\n fix: 'Pass an integer between 1 and 10.',\n });\n }\n return n;\n}\n\n/** `products=Vercel` or `products=Vercel,Next` → { products: [\"Vercel\",\"Next\"] }. Repeated\n * keys merge their values. */\nfunction parseAppliesTo(pairs: string[]): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const pair of pairs) {\n const eq = pair.indexOf('=');\n if (eq <= 0) {\n throw new CliError('USAGE', `Invalid --applies-to: ${JSON.stringify(pair)}`, {\n fix: 'Use key=value, e.g. --applies-to products=Vercel.',\n });\n }\n const key = pair.slice(0, eq).trim();\n const values = pair\n .slice(eq + 1)\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v.length > 0);\n if (values.length === 0) {\n throw new CliError('USAGE', `--applies-to ${JSON.stringify(key)} has no values`, {\n fix: 'Give each key at least one value, e.g. products=Vercel.',\n });\n }\n out[key] = [...(out[key] ?? []), ...values];\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,eAAsB,UACpB,MACA,KACA,OAAmB,CAAC,GACI;AACxB,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,QAAqB,EAAE,UAAU,KAAK,SAAS;AACrD,MAAI,KAAK,aAAa,OAAW,OAAM,WAAW,iBAAiB,KAAK,QAAQ;AAChF,MAAI,KAAK,gBAAgB,OAAW,OAAM,cAAc,KAAK;AAC7D,MAAI,KAAK,UAAU,OAA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vB,YAAM,IAAI,SAAS,SAAS,gBAAgB,KAAK,UAAU,GAAG,CAAC,kBAAkB;AAAA,QAC/E,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,QAAI,GAAG,IAAI,CAAC,GAAI,IAAI,GAAG,KAAK,CAAC,GAAI,GAAG,MAAM;AAAA,EAC5C;AACA,SAAO;AACT;","names":[]}
@@ -3,7 +3,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
3
3
  // package.json
4
4
  var package_default = {
5
5
  name: "tenjin-cli",
6
- version: "0.1.0-alpha.11",
6
+ version: "0.1.0-alpha.12",
7
7
  mcpName: "blog.tenjin/tenjin",
8
8
  type: "module",
9
9
  description: "Tenjin agent CLI for the x402 knowledge marketplace.",
@@ -80,4 +80,4 @@ var package_default = {
80
80
  export {
81
81
  package_default
82
82
  };
83
- //# sourceMappingURL=chunk-UY6CGULW.js.map
83
+ //# sourceMappingURL=chunk-HWHYPCCH.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.11\",\n \"mcpName\": \"blog.tenjin/tenjin\",\n \"type\": \"module\",\n \"description\": \"Tenjin agent CLI for the x402 knowledge marketplace.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/BackTrackCo/tenjin-agent.git\"\n },\n \"homepage\": \"https://tenjin.blog/agents\",\n \"bugs\": \"https://github.com/BackTrackCo/tenjin-agent/issues\",\n \"keywords\": [\n \"x402\",\n \"usdc\",\n \"base\",\n \"ai-agents\",\n \"agent-payments\",\n \"mcp\",\n \"knowledge-marketplace\",\n \"micropayments\",\n \"claude\",\n \"codex\",\n \"cli\"\n ],\n \"bin\": {\n \"tenjin\": \"dist/index.js\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"dist\",\n \"docs\",\n \"skills\",\n \"NOTICE.md\"\n ],\n \"packageManager\": \"pnpm@11.11.0\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format\": \"prettier --write .\",\n \"format:check\": \"prettier --check .\",\n \"check\": \"pnpm run build && pnpm run test\",\n \"sync:skill\": \"node scripts/sync-skill.mjs\",\n \"pack-smoke\": \"bash scripts/pack-smoke.sh\",\n \"changeset\": \"changeset\",\n \"prepublishOnly\": \"pnpm run build\",\n \"prepare\": \"git config core.hooksPath .githooks || true\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.31.1\",\n \"@clack/prompts\": \"^1.7.0\",\n \"@eslint/js\": \"^10\",\n \"@modelcontextprotocol/sdk\": \"1.29.0\",\n \"@types/node\": \"^25\",\n \"@x402/core\": \"2.17.0\",\n \"@x402/evm\": \"2.17.0\",\n \"@x402/extensions\": \"2.17.0\",\n \"commander\": \"^14.0.1\",\n \"eslint\": \"^10\",\n \"eslint-config-prettier\": \"^10\",\n \"ox\": \"0.14.30\",\n \"prettier\": \"^3\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6\",\n \"typescript-eslint\": \"^8\",\n \"viem\": \"^2.53.1\",\n \"vitest\": \"^4.1.9\",\n \"zod\": \"^4.4.3\"\n }\n}\n"],"mappings":";;;AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,aAAe;AAAA,EACf,SAAW;AAAA,EACX,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,EACR,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,KAAO;AAAA,IACL,QAAU;AAAA,EACZ;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,gBAAkB;AAAA,EAClB,SAAW;AAAA,IACT,OAAS;AAAA,IACT,MAAQ;AAAA,IACR,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,QAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,OAAS;AAAA,IACT,cAAc;AAAA,IACd,cAAc;AAAA,IACd,WAAa;AAAA,IACb,gBAAkB;AAAA,IAClB,SAAW;AAAA,EACb;AAAA,EACA,iBAAmB;AAAA,IACjB,mBAAmB;AAAA,IACnB,kBAAkB;AAAA,IAClB,cAAc;AAAA,IACd,6BAA6B;AAAA,IAC7B,eAAe;AAAA,IACf,cAAc;AAAA,IACd,aAAa;AAAA,IACb,oBAAoB;AAAA,IACpB,WAAa;AAAA,IACb,QAAU;AAAA,IACV,0BAA0B;AAAA,IAC1B,IAAM;AAAA,IACN,UAAY;AAAA,IACZ,MAAQ;AAAA,IACR,YAAc;AAAA,IACd,qBAAqB;AAAA,IACrB,MAAQ;AAAA,IACR,QAAU;AAAA,IACV,KAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.12\",\n \"mcpName\": \"blog.tenjin/tenjin\",\n \"type\": \"module\",\n \"description\": \"Tenjin agent CLI for the x402 knowledge marketplace.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/BackTrackCo/tenjin-agent.git\"\n },\n \"homepage\": \"https://tenjin.blog/agents\",\n \"bugs\": \"https://github.com/BackTrackCo/tenjin-agent/issues\",\n \"keywords\": [\n \"x402\",\n \"usdc\",\n \"base\",\n \"ai-agents\",\n \"agent-payments\",\n \"mcp\",\n \"knowledge-marketplace\",\n \"micropayments\",\n \"claude\",\n \"codex\",\n \"cli\"\n ],\n \"bin\": {\n \"tenjin\": \"dist/index.js\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"dist\",\n \"docs\",\n \"skills\",\n \"NOTICE.md\"\n ],\n \"packageManager\": \"pnpm@11.11.0\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format\": \"prettier --write .\",\n \"format:check\": \"prettier --check .\",\n \"check\": \"pnpm run build && pnpm run test\",\n \"sync:skill\": \"node scripts/sync-skill.mjs\",\n \"pack-smoke\": \"bash scripts/pack-smoke.sh\",\n \"changeset\": \"changeset\",\n \"prepublishOnly\": \"pnpm run build\",\n \"prepare\": \"git config core.hooksPath .githooks || true\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.31.1\",\n \"@clack/prompts\": \"^1.7.0\",\n \"@eslint/js\": \"^10\",\n \"@modelcontextprotocol/sdk\": \"1.29.0\",\n \"@types/node\": \"^25\",\n \"@x402/core\": \"2.17.0\",\n \"@x402/evm\": \"2.17.0\",\n \"@x402/extensions\": \"2.17.0\",\n \"commander\": \"^14.0.1\",\n \"eslint\": \"^10\",\n \"eslint-config-prettier\": \"^10\",\n \"ox\": \"0.14.30\",\n \"prettier\": \"^3\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6\",\n \"typescript-eslint\": \"^8\",\n \"viem\": \"^2.53.1\",\n \"vitest\": \"^4.1.9\",\n \"zod\": \"^4.4.3\"\n }\n}\n"],"mappings":";;;AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,aAAe;AAAA,EACf,SAAW;AAAA,EACX,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,EACR,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,KAAO;AAAA,IACL,QAAU;AAAA,EACZ;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,gBAAkB;AAAA,EAClB,SAAW;AAAA,IACT,OAAS;AAAA,IACT,MAAQ;AAAA,IACR,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,QAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,OAAS;AAAA,IACT,cAAc;AAAA,IACd,cAAc;AAAA,IACd,WAAa;AAAA,IACb,gBAAkB;AAAA,IAClB,SAAW;AAAA,EACb;AAAA,EACA,iBAAmB;AAAA,IACjB,mBAAmB;AAAA,IACnB,kBAAkB;AAAA,IAClB,cAAc;AAAA,IACd,6BAA6B;AAAA,IAC7B,eAAe;AAAA,IACf,cAAc;AAAA,IACd,aAAa;AAAA,IACb,oBAAoB;AAAA,IACpB,WAAa;AAAA,IACb,QAAU;AAAA,IACV,0BAA0B;AAAA,IAC1B,IAAM;AAAA,IACN,UAAY;AAAA,IACZ,MAAQ;AAAA,IACR,YAAc;AAAA,IACd,qBAAqB;AAAA,IACrB,MAAQ;AAAA,IACR,QAAU;AAAA,IACV,KAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  rateLimitError
4
- } from "./chunk-EDVI7RRD.js";
4
+ } from "./chunk-X2WZPGCF.js";
5
5
  import {
6
6
  SESSION_CHAIN_ID,
7
7
  createSessionKeyAuth,
@@ -9,7 +9,7 @@ import {
9
9
  } from "./chunk-TDDN5GXR.js";
10
10
  import {
11
11
  httpRequest
12
- } from "./chunk-3GSZUADW.js";
12
+ } from "./chunk-TUXKOIOU.js";
13
13
  import {
14
14
  trimSlash
15
15
  } from "./chunk-PZSUWDF2.js";
@@ -1405,4 +1405,4 @@ export {
1405
1405
  dedupeFindings,
1406
1406
  describeFindings
1407
1407
  };
1408
- //# sourceMappingURL=chunk-IAFYUFIC.js.map
1408
+ //# sourceMappingURL=chunk-ILDVGY7K.js.map
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  fetchRead
4
- } from "./chunk-ZE7KOO7A.js";
4
+ } from "./chunk-ROAK2DOX.js";
5
5
  import {
6
6
  headingOutline
7
7
  } from "./chunk-SGK2B724.js";
@@ -146,4 +146,4 @@ function freshness(card) {
146
146
  export {
147
147
  runInspect
148
148
  };
149
- //# sourceMappingURL=chunk-XWHXX2BI.js.map
149
+ //# sourceMappingURL=chunk-L3I2MVKR.js.map
@@ -9,7 +9,7 @@ import {
9
9
  } from "./chunk-OZHJ3FLR.js";
10
10
  import {
11
11
  fetchRead
12
- } from "./chunk-ZE7KOO7A.js";
12
+ } from "./chunk-ROAK2DOX.js";
13
13
  import {
14
14
  findDelivered,
15
15
  findDeliveredByUrl,
@@ -1354,4 +1354,4 @@ async function confirmSpend(ctx, deps, yes, amountAtomic, creator) {
1354
1354
  export {
1355
1355
  runBuy
1356
1356
  };
1357
- //# sourceMappingURL=chunk-O25VWJCG.js.map
1357
+ //# sourceMappingURL=chunk-MBKFZBB2.js.map
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  rateLimitError
4
- } from "./chunk-EDVI7RRD.js";
4
+ } from "./chunk-X2WZPGCF.js";
5
5
  import {
6
6
  SIWX_HEADER,
7
7
  decodePaymentRequiredHeader,
@@ -9,7 +9,7 @@ import {
9
9
  } from "./chunk-6BGYHARE.js";
10
10
  import {
11
11
  httpRequest
12
- } from "./chunk-3GSZUADW.js";
12
+ } from "./chunk-TUXKOIOU.js";
13
13
  import {
14
14
  SLUG_RE,
15
15
  UUID_RE
@@ -230,4 +230,4 @@ function readMessage(json) {
230
230
  export {
231
231
  fetchRead
232
232
  };
233
- //# sourceMappingURL=chunk-ZE7KOO7A.js.map
233
+ //# sourceMappingURL=chunk-ROAK2DOX.js.map
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  package_default
4
- } from "./chunk-UY6CGULW.js";
4
+ } from "./chunk-HWHYPCCH.js";
5
5
  import {
6
6
  CliError
7
7
  } from "./chunk-PZRAAAY2.js";
@@ -196,4 +196,4 @@ export {
196
196
  httpRequest,
197
197
  fetchFailureToCliError
198
198
  };
199
- //# sourceMappingURL=chunk-3GSZUADW.js.map
199
+ //# sourceMappingURL=chunk-TUXKOIOU.js.map
@@ -7,7 +7,7 @@ import {
7
7
  import {
8
8
  buildOutcomeItem,
9
9
  postOutcomes
10
- } from "./chunk-EDVI7RRD.js";
10
+ } from "./chunk-X2WZPGCF.js";
11
11
  import {
12
12
  sanitizeForTerminal
13
13
  } from "./chunk-IB63U6BM.js";
@@ -122,4 +122,4 @@ function offeredSomethingToBuy(stored) {
122
122
  export {
123
123
  runOutcome
124
124
  };
125
- //# sourceMappingURL=chunk-GKV6VZSZ.js.map
125
+ //# sourceMappingURL=chunk-V5UHKC46.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/outcome.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildOutcomeItem, postOutcomes } from '../lib/agent-api';\nimport {\n latestSearch,\n loadSearches,\n markSearchResolved,\n type StoredSearch,\n} from '../lib/search-store';\nimport { isPaidPrice } from '../lib/money';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin outcome --search-id <id> --status <s>`, POST to\n * /api/searches/:id/outcomes, closing the reuse loop (used / partially_used\n * / rejected / regenerated / purchase_declined). The searchId is the capability,\n * so no wallet is needed; `--last` sugar targets the most recent DELIBERATE\n * search — entries the WebSearch hook rode along with are skipped, or every web\n * search in auto mode would silently re-aim the report (a hook entry is reached\n * by explicit --search-id, which is what the Stop hook's reminder names).\n *\n * `--last` binds to whatever search ran most recently, which in a multi-search\n * session is often not the one the agent means (issue #100). Two guards, both\n * local: the targeted search's question is echoed back in the success line and in\n * the machine data, so a misfire is visible in the same breath as the report; and\n * an outcome that could not describe that search, whether by its status or by\n * naming a resource the search never surfaced, is refused before the request.\n */\n\nexport interface OutcomeArgs {\n searchId?: string;\n last?: boolean;\n status: string;\n resource?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runOutcome(\n args: OutcomeArgs,\n ctx: CommandContext,\n deps: OutcomeDeps = {},\n): Promise<CommandResult> {\n const target = await resolveTarget(args, ctx);\n // Status name first, so an unknown status still fails as an unknown status\n // rather than as an incoherent one.\n const item = buildOutcomeItem({\n status: args.status,\n ...(args.resource !== undefined ? { resourceId: args.resource } : {}),\n ...(args.contentHash !== undefined ? { contentHash: args.contentHash } : {}),\n });\n if (target.stored !== null) assertOutcomeCoherent(item.status, target.stored, item.resourceId);\n const { searchId } = target;\n const question = target.stored !== null ? echoQuestion(target.stored.question) : undefined;\n\n const settings = await resolveContextSettings(ctx);\n const result = await postOutcomes(searchId, [item], {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n // The loop is closed, so the Stop hook has nothing left to raise about it.\n // AFTER the post, so a refused or failed report leaves the loop open. Local\n // bookkeeping only, and it never throws: see markSearchResolved.\n await markSearchResolved(ctx.dataDir, searchId, 'outcome');\n\n // The question rides both renderings, so the misfire this guards against is\n // visible whether a human is reading the line or an agent is reading the JSON.\n // Sanitized on the human line only: the envelope is machine data and keeps the\n // bytes it was given (see output.ts).\n return {\n data: {\n searchId,\n status: item.status,\n accepted: result.accepted,\n ...(question !== undefined ? { question } : {}),\n },\n humanLines: [\n `Reported ${item.status} for search ${searchId}${\n question !== undefined ? ` \"${sanitizeForTerminal(question)}\"` : ''\n } (accepted ${result.accepted}).`,\n ],\n };\n}\n\n/** The search this report will land on, plus the local record of it when there is\n * one. `stored` is null for a `--search-id` from another machine or an evicted\n * entry: unknown, so neither echoed nor checked. */\ninterface OutcomeTarget {\n searchId: string;\n stored: StoredSearch | null;\n}\n\nasync function resolveTarget(args: OutcomeArgs, ctx: CommandContext): Promise<OutcomeTarget> {\n if (args.searchId !== undefined && args.last === true) {\n throw new CliError('USAGE', 'Pass either --search-id or --last, not both.', {\n fix: 'Use --search-id <id> for a specific search, or --last for the most recent.',\n });\n }\n if (args.searchId !== undefined) {\n const searches = await loadSearches(ctx.dataDir);\n return {\n searchId: args.searchId,\n stored: searches.find((s) => s.searchId === args.searchId) ?? null,\n };\n }\n if (args.last === true) {\n const latest = await latestSearch(ctx.dataDir);\n if (latest === null) {\n throw new CliError('SEARCH_NOT_FOUND', 'No local search to target with --last.', {\n fix: 'Run `tenjin search` first, or pass --search-id <id>.',\n });\n }\n return { searchId: latest.searchId, stored: latest };\n }\n throw new CliError('USAGE', 'An outcome needs a search to report against.', {\n fix: 'Pass --search-id <id> or --last.',\n });\n}\n\n/** Long enough to tell two searches apart on one line, short enough not to bury\n * the searchId next to it. The ellipsis is part of the echo: a question cut with\n * no marker reads as a shorter question that was never asked. */\nconst QUESTION_ECHO_MAX = 80;\n\nfunction echoQuestion(question: string): string {\n return question.length > QUESTION_ECHO_MAX\n ? `${question.slice(0, QUESTION_ECHO_MAX - 1)}…`\n : question;\n}\n\n/**\n * Refuse an outcome that could not describe the search it is aimed at. Two\n * independent checks, because they answer to different rules.\n *\n * MEMBERSHIP, for any status that names a `--resource`: the id has to be one this\n * search surfaced. On a CANDIDATES decision that is provable, since browse\n * pointers are MISS-only by contract AND truncateResponse deletes the array\n * outright on CANDIDATES rather than trust the server, so `candidates` is the\n * entire payable set the agent was shown and `search` records all of it. A uuid\n * outside it is a typo or another search's, and the server drops the item behind\n * its 202 (tenjin#641) whatever the status says, leaving the CLI to report\n * success for an outcome nobody stored. A MISS keeps the fail-open: its browse\n * tail is payable and deliberately unrecorded, so an absent id there is\n * unknowable rather than wrong. So does any other decision value.\n *\n * PAYABILITY, for `purchase_declined` alone. The status matrix is deliberately\n * one-sided: four of the five describe ANY search, so only this one has a\n * precondition.\n *\n * used, partially_used always. A MISS's browse tail is readable, and a free\n * piece is used without any purchase, so \"used\" on a\n * MISS, or on a free candidate, is a real report and not\n * a mistake (issue #100).\n * rejected, regenerated always. \"Nothing here helped, I wrote it myself\" is\n * exactly what a MISS deserves to record.\n * purchase_declined needs the search to have offered something to buy, or,\n * when `--resource` names a candidate the store knows,\n * needs THAT candidate to have cost money. Declining a\n * purchase nobody offered cannot have happened, and that\n * is the shape the dogfooding misfire took: a\n * purchase_declined aimed at a bare MISS.\n *\n * Local knowledge only, and fail-open by construction: an unknown is never a\n * refusal. The server owns the checks this cannot make.\n */\nfunction assertOutcomeCoherent(status: string, stored: StoredSearch, resourceId?: string): void {\n const named =\n resourceId !== undefined\n ? stored.candidates.find((c) => c.resourceId === resourceId)\n : undefined;\n\n if (resourceId !== undefined && named === undefined && stored.decision === 'CANDIDATES') {\n throw new CliError(\n 'USAGE',\n `Search ${stored.searchId} \"${echoQuestion(stored.question)}\" surfaced no candidate ${resourceId}, so an outcome naming it would not be recorded.`,\n {\n fix: 'Pass a resourceId from this search, or drop --resource to report on the search as a whole.',\n },\n );\n }\n\n if (status !== 'purchase_declined') return;\n\n // A named candidate the store knows answers for itself. A piece that was free\n // is not made purchasable by a paid sibling in the same result, so the specific\n // claim is checked against the specific price rather than the search's total.\n if (named !== undefined) {\n if (isPaidPrice(named.price) !== false) return;\n throw new CliError(\n 'USAGE',\n `Search ${stored.searchId} \"${echoQuestion(stored.question)}\" listed ${resourceId} at no cost, so purchase_declined cannot describe it.`,\n {\n fix: 'A free piece is reported as used, partially_used, rejected or regenerated; pass the --resource you actually declined to buy.',\n },\n );\n }\n\n if (offeredSomethingToBuy(stored) !== false) return;\n throw new CliError(\n 'USAGE',\n `Search ${stored.searchId} \"${echoQuestion(stored.question)}\" was a ${stored.decision} that offered nothing to buy, so purchase_declined cannot describe it.`,\n {\n fix: 'Report used, partially_used, rejected or regenerated for this search, or pass --search-id <id> for the search you meant to report against.',\n },\n );\n}\n\n/**\n * Whether the search put anything payable in front of the agent. Priced at zero\n * does not count: `read` delivers a free piece with no payment, so a result that\n * was free end to end offered no purchase to decline, however many rows it had.\n * Null when the stored entry cannot say: it predates `paidBrowseCount`, so an\n * all-free candidate list might still have sat above a payable browse tail.\n */\nfunction offeredSomethingToBuy(stored: StoredSearch): boolean | null {\n if (stored.candidates.some((c) => isPaidPrice(c.price) === true)) return true;\n // A price the store cannot parse is not evidence that the result was free.\n if (stored.candidates.some((c) => isPaidPrice(c.price) === null)) return null;\n if (stored.paidBrowseCount === undefined) return null;\n return stored.paidBrowseCount > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0CA,eAAsB,WACpB,MACA,KACA,OAAoB,CAAC,GACG;AACxB,QAAM,SAAS,MAAM,cAAc,MAAM,GAAG;AAG5C,QAAM,OAAO,iBAAiB;AAAA,IAC5B,QAAQ,KAAK;AAAA,IACb,GAAI,KAAK,aAAa,SAAY,EAAE,YAAY,KAAK,SAAS,IAAI,CAAC;AAAA,IACnE,GAAI,KAAK,gBAAgB,SAAY,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;AAAA,EAC5E,CAAC;AACD,MAAI,OAAO,WAAW,KAAM,uBAAsB,KAAK,QAAQ,OAAO,QAAQ,KAAK,UAAU;AAC7F,QAAM,EAAE,SAAS,IAAI;AACrB,QAAM,WAAW,OAAO,WAAW,OAAO,aAAa,OAAO,OAAO,QAAQ,IAAI;AAEjF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AW,QAAO;AACjD,SAAO,OAAO,kBAAkB;AAClC;","names":[]}
@@ -16,7 +16,7 @@ import {
16
16
  import {
17
17
  fetchFailureToCliError,
18
18
  httpRequest
19
- } from "./chunk-3GSZUADW.js";
19
+ } from "./chunk-TUXKOIOU.js";
20
20
  import {
21
21
  emitNotice,
22
22
  emitWriteNotice
@@ -232,4 +232,4 @@ async function pollForFunds(ctx, desc, rpcUrl, startBalance, opts) {
232
232
  export {
233
233
  runFund
234
234
  };
235
- //# sourceMappingURL=chunk-IXTENA2H.js.map
235
+ //# sourceMappingURL=chunk-WWIKAJFO.js.map
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  httpRequest
4
- } from "./chunk-3GSZUADW.js";
4
+ } from "./chunk-TUXKOIOU.js";
5
5
  import {
6
6
  trimSlash
7
7
  } from "./chunk-PZSUWDF2.js";
@@ -283,7 +283,7 @@ async function postOutcomes(searchId, items, opts) {
283
283
  fix: "Report between 1 and 10 outcomes per call."
284
284
  });
285
285
  }
286
- const url = `${trimSlash(opts.baseUrl)}/api/agent/searches/${searchId}/outcomes`;
286
+ const url = `${trimSlash(opts.baseUrl)}/api/searches/${searchId}/outcomes`;
287
287
  const res = await httpRequest(url, {
288
288
  method: "POST",
289
289
  timeoutMs: opts.timeoutMs,
@@ -314,4 +314,4 @@ export {
314
314
  buildOutcomeItem,
315
315
  postOutcomes
316
316
  };
317
- //# sourceMappingURL=chunk-EDVI7RRD.js.map
317
+ //# sourceMappingURL=chunk-X2WZPGCF.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 { 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 shared transport's\n * User-Agent is what 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: opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {},\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 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":";;;;;;;;;;;;;;;;;AAgBA,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;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lib/agent-api.ts"],"sourcesContent":["import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResult } from './http';\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 shared transport's\n * User-Agent is what 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: opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {},\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/searches/${searchId}/outcomes`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\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":";;;;;;;;;;;;;;;;;AAgBA,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,g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AI,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":[]}
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-4TCU3YRD.js";
5
5
  import {
6
6
  package_default
7
- } from "./chunk-UY6CGULW.js";
7
+ } from "./chunk-HWHYPCCH.js";
8
8
  import {
9
9
  defaultIo,
10
10
  emitFailure,
@@ -3673,7 +3673,7 @@ function buildProgram(io, setExit) {
3673
3673
  const o = this.opts();
3674
3674
  const claudeMdGiven = this.getOptionValueSource("claudeMd") !== "default";
3675
3675
  const allowGiven = this.getOptionValueSource("allowFreeVerbs") !== "default";
3676
- const { runInstall } = await import("./install-SQAYMNQC.js");
3676
+ const { runInstall } = await import("./install-WXTOHDWC.js");
3677
3677
  return runInstall(
3678
3678
  {
3679
3679
  ...Array.isArray(o.harness) && o.harness.length > 0 ? { harness: o.harness } : {},
@@ -3699,7 +3699,7 @@ function buildProgram(io, setExit) {
3699
3699
  });
3700
3700
  addGlobalFlags(program2.command("doctor")).description("Check the local environment and Tenjin API reachability").action(async function() {
3701
3701
  await runCommand("doctor", this, async (ctx) => {
3702
- const { runDoctor } = await import("./doctor-CSIWKWM2.js");
3702
+ const { runDoctor } = await import("./doctor-EKVCP7JP.js");
3703
3703
  return runDoctor(ctx);
3704
3704
  });
3705
3705
  });
@@ -3757,7 +3757,7 @@ function buildProgram(io, setExit) {
3757
3757
  ).action(async function(amountUsd) {
3758
3758
  await runCommand("fund", this, async (ctx) => {
3759
3759
  const o = this.opts();
3760
- const { runFund } = await import("./fund-OKK627GL.js");
3760
+ const { runFund } = await import("./fund-JAPOFTUG.js");
3761
3761
  return runFund(ctx, {
3762
3762
  ...amountUsd !== void 0 ? { amountUsd } : {},
3763
3763
  ...o.open === false ? { open: false } : {},
@@ -3779,7 +3779,7 @@ function buildProgram(io, setExit) {
3779
3779
  ).option("--max-price <usd>", "only candidates at or below this decimal-USD price").option("--fresh-within <window>", "freshness window, e.g. P30D, P2W, P1Y").option("--limit <n>", "maximum candidates (1-10, default 5)").option("--applies-to <pair>", "applicability filter key=value (repeatable)", collect, []).action(async function(question) {
3780
3780
  await runCommand("search", this, async (ctx) => {
3781
3781
  const o = this.opts();
3782
- const { runSearch } = await import("./search-ZWOP4EGK.js");
3782
+ const { runSearch } = await import("./search-EEKTW6VK.js");
3783
3783
  return runSearch(
3784
3784
  {
3785
3785
  question,
@@ -3796,7 +3796,7 @@ function buildProgram(io, setExit) {
3796
3796
  "Show a candidate's pre-purchase card / preview. Use after search, before buy, to check price, scope, and freshness; it never pays"
3797
3797
  ).action(async function(resource) {
3798
3798
  await runCommand("inspect", this, async (ctx) => {
3799
- const { runInspect } = await import("./inspect-573WHEV4.js");
3799
+ const { runInspect } = await import("./inspect-IEV75A42.js");
3800
3800
  return runInspect({ ref: resource }, ctx);
3801
3801
  });
3802
3802
  });
@@ -3808,7 +3808,7 @@ function buildProgram(io, setExit) {
3808
3808
  ).action(async function(resource) {
3809
3809
  await runCommand("read", this, async (ctx) => {
3810
3810
  const o = this.opts();
3811
- const { runRead } = await import("./read-PJ7Z6UGF.js");
3811
+ const { runRead } = await import("./read-UAZGZ4UL.js");
3812
3812
  return runRead(
3813
3813
  {
3814
3814
  ref: resource,
@@ -3841,7 +3841,7 @@ function buildProgram(io, setExit) {
3841
3841
  ).action(async function(resource) {
3842
3842
  await runCommand("buy", this, async (ctx) => {
3843
3843
  const o = this.opts();
3844
- const { runBuy } = await import("./buy-THMVOPUH.js");
3844
+ const { runBuy } = await import("./buy-3DTBFZ4B.js");
3845
3845
  return runBuy(
3846
3846
  {
3847
3847
  ref: resource,
@@ -3865,7 +3865,7 @@ function buildProgram(io, setExit) {
3865
3865
  ).option("--question <text>", "a question this piece answers (repeatable)", collect, []).option("--task <text>", "a task this piece supports (repeatable)", collect, []).option("--scope <text>", "what the piece covers (card scope)").option("--exclusions <text>", "what the piece does not cover (card exclusions)").option("--applies-to <pair>", "applicability key=value (repeatable)", collect, []).option("--as-of <iso>", "as-of timestamp, ISO-8601 with offset").option("--valid-until <iso>", "valid-until timestamp, ISO-8601 with offset").option("--artifact-type <type>", "document | skill | dataset").option("--temporal-mode <mode>", "snapshot | maintained | evergreen").option("--provenance <text>", "provenance summary (card)").option("--methodology <text>", "methodology summary (card)").action(async function(file) {
3866
3866
  await runCommand("publish", this, async (ctx) => {
3867
3867
  const o = this.opts();
3868
- const { runPublish } = await import("./publish-N5U4XYVA.js");
3868
+ const { runPublish } = await import("./publish-6QNARH7E.js");
3869
3869
  return runPublish(
3870
3870
  {
3871
3871
  ...typeof file === "string" ? { file } : {},
@@ -3921,7 +3921,7 @@ function buildProgram(io, setExit) {
3921
3921
  ).action(async function(postId) {
3922
3922
  await runCommand("edit", this, async (ctx) => {
3923
3923
  const o = this.opts();
3924
- const { runEdit } = await import("./edit-E7N6F3OY.js");
3924
+ const { runEdit } = await import("./edit-4UZQVFCK.js");
3925
3925
  return runEdit(
3926
3926
  {
3927
3927
  postId,
@@ -3961,7 +3961,7 @@ function buildProgram(io, setExit) {
3961
3961
  ).option("--resource <id>", "the resourceId the outcome concerns").option("--content-hash <hash>", "sha256:<64hex> of the exact body read").action(async function() {
3962
3962
  await runCommand("outcome", this, async (ctx) => {
3963
3963
  const o = this.opts();
3964
- const { runOutcome } = await import("./outcome-W3KYGF23.js");
3964
+ const { runOutcome } = await import("./outcome-FYOFDOUK.js");
3965
3965
  return runOutcome(
3966
3966
  {
3967
3967
  status: String(o.status),
@@ -3976,7 +3976,7 @@ function buildProgram(io, setExit) {
3976
3976
  });
3977
3977
  addGlobalFlags(program2.command("mcp")).description("Run a local stdio MCP server exposing the Tenjin command cores to an MCP client").action(async function() {
3978
3978
  const ctx = buildContext(this, io);
3979
- const { runMcpServer } = await import("./run-FSO3MMXN.js");
3979
+ const { runMcpServer } = await import("./run-AJNCOT5R.js");
3980
3980
  await runMcpServer({ dataDir: ctx.dataDir, flags: ctx.flags });
3981
3981
  });
3982
3982
  return program2;
@@ -4018,4 +4018,4 @@ export {
4018
4018
  buildProgram,
4019
4019
  main
4020
4020
  };
4021
- //# sourceMappingURL=cli-Y2HBOSGK.js.map
4021
+ //# sourceMappingURL=cli-3WZGLZDP.js.map