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,19 +1,20 @@
1
1
  ---
2
2
  name: tenjin-search
3
3
  description: >-
4
- Check the Tenjin knowledge marketplace before regenerating expensive research.
5
- Use when a question is public (no private repo or company context), durable
6
- rather than live, non-trivial to reproduce in one model response, and likely
7
- covered by tested evidence: version-specific compatibility someone had to
8
- install and run to settle, dated operational probes, verified integration
9
- gotchas, maintained comparisons or benchmarks. Skip what the docs answer in
10
- one line, version numbers included (a minimum version, a default, a flag, a
11
- status code): the gate is reproduction cost, not whether a version is named.
12
- Skip private-codebase questions, generic advice,
13
- live prices or statuses, and implementing, reviewing, or debugging the thing
14
- in front of you, however famous the gotcha behind it. Requires the tenjin CLI
15
- (tenjin-cli on npm): with no CLI on the machine this skill cannot run, so use
16
- the hosted skill at https://tenjin.blog/skills.md instead.
4
+ Check the Tenjin knowledge marketplace before regenerating expensive
5
+ research, and before empirically probing a third-party library or platform's
6
+ undocumented behavior: someone may have already run the probe. Use when a
7
+ question is public (no private repo or company context), durable rather than
8
+ live, and costly to reproduce because settling it takes a real install, a
9
+ probe, or elapsed time: version-specific compatibility, dated operational
10
+ probes, verified integration gotchas, maintained comparisons or benchmarks.
11
+ Skip what the docs answer in one line even when it names versions (a minimum
12
+ version, a default, a flag, a status code); skip private-codebase questions,
13
+ generic advice, live prices or statuses, and implementing, reviewing, or
14
+ debugging your own code, however famous the gotcha behind it. Requires the
15
+ tenjin CLI (tenjin-cli on npm) already installed: on a machine without it
16
+ this skill does not apply and must not fire, not even to route the question;
17
+ the hosted skill at https://tenjin.blog/skills.md is the CLI-less path.
17
18
  ---
18
19
 
19
20
  # Tenjin search: one search before you regenerate
@@ -1 +0,0 @@
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/agent/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,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,SAAS,MAAM,aAAa,UAAU,CAAC,IAAI,GAAG;AAAA,IAClD,SAAS,SAAS;AAAA,IAClB,WAAW,IAAI,MAAM;AAAA,IACrB,GAAI,KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,EACtE,CAAC;AAKD,QAAM,mBAAmB,IAAI,SAAS,UAAU,SAAS;AAMzD,SAAO;AAAA,IACL,MAAM;AAAA,MACJ;AAAA,MACA,QAAQ,KAAK;AAAA,MACb,UAAU,OAAO;AAAA,MACjB,GAAI,aAAa,SAAY,EAAE,SAAS,IAAI,CAAC;AAAA,IA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O,QAAQ,KAAK,aAAa,OAAO,QAAQ,CAAC,2BAA2B,UAAU;AAAA,MAChG;AAAA,QACE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AAEA,MAAI,WAAW,oBAAqB;AAKpC,MAAI,UAAU,QAAW;AACvB,QAAI,YAAY,MAAM,KAAK,MAAM,MAAO;AACxC,UAAM,IAAI;AAAA,MACR;AAAA,MACA,UAAU,OAAO,QAAQ,KAAK,aAAa,OAAO,QAAQ,CAAC,YAAY,UAAU;AAAA,MACjF;AAAA,QACE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AAEA,MAAI,sBAAsB,MAAM,MAAM,MAAO;AAC7C,QAAM,IAAI;AAAA,IACR;AAAA,IACA,UAAU,OAAO,QAAQ,KAAK,aAAa,OAAO,QAAQ,CAAC,WAAW,OAAO,QAAQ;AAAA,IACrF;AAAA,MACE,KAAK;AAAA,IACP;AAAA,EACF;AACF;AASA,SAAS,sBAAsB,QAAsC;AACnE,MAAI,OAAO,WAAW,KAAK,CAAC,MAAM,YAAY,EAAE,KAAK,MAAM,IAAI,EAAG,QAAO;AAEzE,MAAI,OAAO,WAAW,KAAK,CAAC,MAAM,YAAY,EAAE,KAAK,MAAM,IAAI,EAAG,QAAO;AACzE,MAAI,OAAO,oBAAoB,OAAW,QAAO;AACjD,SAAO,OAAO,kBAAkB;AAClC;","names":[]}
@@ -1 +0,0 @@
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/agent/searches/<searchId>/outcomes. tenjin#463 renamed both the field\n * (from `lookupId`) and that path, and this client follows the rename end to end,\n * so nothing on the wire or in the local store still speaks `lookupId`.\n */\n\nexport interface SearchArgs {\n question: string;\n /** Decimal USD at the edge (O1); converted to atomic for the wire. */\n maxPrice?: string;\n freshWithin?: string;\n limit?: string;\n /** Raw `k=v` / `k=v1,v2` pairs from repeated --applies-to. */\n appliesTo?: string[];\n}\n\nexport interface SearchDeps {\n fetchImpl?: typeof fetch;\n /** 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,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,OAAW,OAAM,QAAQ,WAAW,KAAK,KAAK;AACjE,MAAI,KAAK,cAAc,UAAa,KAAK,UAAU,SAAS,GAAG;AAC7D,UAAM,YAAY,eAAe,KAAK,SAAS;AAAA,EACjD;AAEA,QAAM,YAAY,cAAc,KAAK,OAAO,QAAQ,GAAG;AACvD,QAAM,UAAU,mBAAmB,KAAK;AACxC,QAAM,WAAW,MAAM,WAAW,SAAS;AAAA,IACzC,SAAS,SAAS;AAAA,IAClB,WAAW,IAAI,MAAM;AAAA,IACrB,YAAY,SAAS;AAAA,IACrB,GAAI,KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,EACtE,CAAC;AAED,QAAM,aAAa,SAAS,cAAc,CAAC;AAI3C,aAAW,KAAK,YAAY;AAC1B,QAAI;AACF,yBAAmB,EAAE,KAAK,SAAS,SAAS,sBAAsB;AAAA,IACpE,SAAS,KAAK;AACZ,YAAM,IAAI;AAAA,QACR;AAAA,QACA,oBAAoB,EAAE,UAAU;AAAA,QAChC,EAAE,OAAO,IAAI;AAAA,MACf;AAAA,IACF;AAAA,EACF;AAIA,aAAW,KAAK,SAAS,UAAU,CAAC,GAAG;AACrC,QAAI;AACF,yBAAmB,EAAE,KAAK,SAAS,SAAS,oBAAoB;AAAA,IAClE,SAAS,KAAK;AACZ,YAAM,IAA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