tenjin-cli 0.1.0-alpha.2 → 0.1.0-alpha.4

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 (135) hide show
  1. package/README.md +156 -185
  2. package/dist/{_esm-FEASBWRP.js → _esm-N4KAVXQR.js} +9 -9
  3. package/dist/buy-OOOLUDND.js +41 -0
  4. package/dist/candidate-TWCWTFGA.js +22 -0
  5. package/dist/{ccip-XR5NE5QK.js → ccip-RPPPKTJR.js} +5 -5
  6. package/dist/{ccip-NQXCEK2U.js → ccip-ZGGWQN4X.js} +4 -4
  7. package/dist/{chunk-XJIW7USF.js → chunk-333FOTUJ.js} +5 -5
  8. package/dist/{chunk-YALGASEU.js → chunk-47PP7TAG.js} +1610 -1610
  9. package/dist/chunk-47PP7TAG.js.map +1 -0
  10. package/dist/{buy-U35DQ6XM.js → chunk-4GR7DGD6.js} +23 -41
  11. package/dist/{buy-U35DQ6XM.js.map → chunk-4GR7DGD6.js.map} +1 -1
  12. package/dist/{chunk-27ONARHV.js → chunk-5JH7ZB6Z.js} +7 -7
  13. package/dist/{chunk-27ONARHV.js.map → chunk-5JH7ZB6Z.js.map} +1 -1
  14. package/dist/{chunk-OYMYCW7J.js → chunk-6WWVYYSB.js} +32 -2
  15. package/dist/{chunk-OYMYCW7J.js.map → chunk-6WWVYYSB.js.map} +1 -1
  16. package/dist/{chunk-UGX7YPX2.js → chunk-7FK2UN2T.js} +65 -65
  17. package/dist/{chunk-UGX7YPX2.js.map → chunk-7FK2UN2T.js.map} +1 -1
  18. package/dist/{chunk-IYLHQMT5.js → chunk-BXUS5UCT.js} +5 -4
  19. package/dist/chunk-BXUS5UCT.js.map +1 -0
  20. package/dist/{chunk-QNP7H47L.js → chunk-C4TIWOAM.js} +2 -2
  21. package/dist/{chunk-QNP7H47L.js.map → chunk-C4TIWOAM.js.map} +1 -1
  22. package/dist/{chunk-7PHSZKQS.js → chunk-CJU555P5.js} +24 -24
  23. package/dist/{chunk-7PHSZKQS.js.map → chunk-CJU555P5.js.map} +1 -1
  24. package/dist/{chunk-YN5SHIXQ.js → chunk-DPET3TW5.js} +2 -2
  25. package/dist/{chunk-TLCMMYLY.js → chunk-DPUMEMGM.js} +5 -5
  26. package/dist/chunk-DPUMEMGM.js.map +1 -0
  27. package/dist/{chunk-TFGSOPWR.js → chunk-EUQN3L5X.js} +9 -9
  28. package/dist/{chunk-TFGSOPWR.js.map → chunk-EUQN3L5X.js.map} +1 -1
  29. package/dist/{chunk-UPIEAMGH.js → chunk-FHB3VKZW.js} +6 -6
  30. package/dist/{chunk-UPIEAMGH.js.map → chunk-FHB3VKZW.js.map} +1 -1
  31. package/dist/{chunk-S3IGX57D.js → chunk-FU6MCSLG.js} +9 -9
  32. package/dist/{lookup-WYVTOMVY.js → chunk-H5ETJRQD.js} +54 -29
  33. package/dist/chunk-H5ETJRQD.js.map +1 -0
  34. package/dist/chunk-KXIX7YDV.js +59 -0
  35. package/dist/chunk-KXIX7YDV.js.map +1 -0
  36. package/dist/{chunk-5CLSD5YN.js → chunk-KYQVEKP5.js} +7 -7
  37. package/dist/{chunk-RRN3YTK7.js → chunk-KZAAWQNP.js} +3 -3
  38. package/dist/{chunk-NCE5NSN6.js → chunk-M2O56UK7.js} +158 -158
  39. package/dist/chunk-M2O56UK7.js.map +1 -0
  40. package/dist/{chunk-7KUW4MJD.js → chunk-MM4TGTST.js} +6 -6
  41. package/dist/{chunk-7KUW4MJD.js.map → chunk-MM4TGTST.js.map} +1 -1
  42. package/dist/{chunk-YIYQ2ZNT.js → chunk-NXCJN2FJ.js} +55 -28
  43. package/dist/chunk-NXCJN2FJ.js.map +1 -0
  44. package/dist/{candidate-RLYCQMF5.js → chunk-OJD54DIU.js} +15 -19
  45. package/dist/{candidate-RLYCQMF5.js.map → chunk-OJD54DIU.js.map} +1 -1
  46. package/dist/{chunk-ZABPQJ3M.js → chunk-POJRB2AE.js} +2 -2
  47. package/dist/{chunk-N62ROTMC.js → chunk-QH6677FJ.js} +5 -4
  48. package/dist/chunk-QH6677FJ.js.map +1 -0
  49. package/dist/{wallet-6QKS6UHW.js → chunk-R7BMDJZM.js} +15 -27
  50. package/dist/{wallet-6QKS6UHW.js.map → chunk-R7BMDJZM.js.map} +1 -1
  51. package/dist/{chunk-Z6MFJV5Z.js → chunk-S3KZ3PPK.js} +15 -11
  52. package/dist/{chunk-Z6MFJV5Z.js.map → chunk-S3KZ3PPK.js.map} +1 -1
  53. package/dist/{chunk-CYOF7ROH.js → chunk-S5RYMCV6.js} +3 -3
  54. package/dist/{chunk-ZMHYXMO6.js → chunk-U5S527PP.js} +3 -3
  55. package/dist/{chunk-RY4XKNV3.js → chunk-UHTVXQ2O.js} +3 -3
  56. package/dist/{publish-D76B3MBK.js → chunk-ULLWHHIT.js} +25 -42
  57. package/dist/chunk-ULLWHHIT.js.map +1 -0
  58. package/dist/{chunk-Z52RA3NC.js → chunk-VV4P5RVK.js} +47 -20
  59. package/dist/chunk-VV4P5RVK.js.map +1 -0
  60. package/dist/{chunk-QVX5MWJZ.js → chunk-W6R3HAAG.js} +2 -2
  61. package/dist/{chunk-3OV7E5G5.js → chunk-WWX32ML4.js} +1 -1
  62. package/dist/{chunk-3OV7E5G5.js.map → chunk-WWX32ML4.js.map} +1 -1
  63. package/dist/{chunk-HIVZG55D.js → chunk-XJN5WUKL.js} +2 -2
  64. package/dist/{chunk-JPHG2JW3.js → chunk-XNNOR7F7.js} +25 -25
  65. package/dist/chunk-XNNOR7F7.js.map +1 -0
  66. package/dist/{inspect-JGYJWFDP.js → chunk-YFREUEUI.js} +8 -26
  67. package/dist/{inspect-JGYJWFDP.js.map → chunk-YFREUEUI.js.map} +1 -1
  68. package/dist/{chunk-HSDCI7OV.js → chunk-YLYINX2H.js} +3 -3
  69. package/dist/{cli-4NNBEQYH.js → cli-AFSLAKR6.js} +47 -36
  70. package/dist/{cli-4NNBEQYH.js.map → cli-AFSLAKR6.js.map} +1 -1
  71. package/dist/{config-2VSXWWHK.js → config-DBEEM3UA.js} +5 -5
  72. package/dist/{doctor-JJPNIBYH.js → doctor-XDA3YU6H.js} +7 -7
  73. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-WHYKB6HA.js} +5 -5
  74. package/dist/index.js +1 -1
  75. package/dist/inspect-YBGDAG47.js +33 -0
  76. package/dist/install-7J6KKEEP.js +542 -0
  77. package/dist/install-7J6KKEEP.js.map +1 -0
  78. package/dist/outcome-ZFGHX2XW.js +20 -0
  79. package/dist/publish-IH7RJXGB.js +36 -0
  80. package/dist/publish-IH7RJXGB.js.map +1 -0
  81. package/dist/run-DCZFEW2C.js +16806 -0
  82. package/dist/run-DCZFEW2C.js.map +1 -0
  83. package/dist/search-R6NIQFXI.js +24 -0
  84. package/dist/search-R6NIQFXI.js.map +1 -0
  85. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-XRPVBC6V.js} +3 -3
  86. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  87. package/dist/usdc-AU6ZIKA6.js +22 -0
  88. package/dist/usdc-AU6ZIKA6.js.map +1 -0
  89. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-TUQJBMHM.js} +5 -5
  90. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  91. package/dist/{wallet-PA54CRBL.js → wallet-HKG3GSTX.js} +10 -10
  92. package/dist/wallet-HKG3GSTX.js.map +1 -0
  93. package/dist/wallet-UWHSHWC6.js +31 -0
  94. package/dist/wallet-UWHSHWC6.js.map +1 -0
  95. package/package.json +4 -3
  96. package/skills/tenjin/SKILL.md +56 -13
  97. package/skills/tenjin-publish/SKILL.md +57 -27
  98. package/skills/tenjin-search/SKILL.md +57 -31
  99. package/dist/chunk-IYLHQMT5.js.map +0 -1
  100. package/dist/chunk-JPHG2JW3.js.map +0 -1
  101. package/dist/chunk-N62ROTMC.js.map +0 -1
  102. package/dist/chunk-NCE5NSN6.js.map +0 -1
  103. package/dist/chunk-TLCMMYLY.js.map +0 -1
  104. package/dist/chunk-YALGASEU.js.map +0 -1
  105. package/dist/chunk-YIYQ2ZNT.js.map +0 -1
  106. package/dist/chunk-Z52RA3NC.js.map +0 -1
  107. package/dist/install-ZQRMSRGW.js +0 -378
  108. package/dist/install-ZQRMSRGW.js.map +0 -1
  109. package/dist/lookup-WYVTOMVY.js.map +0 -1
  110. package/dist/outcome-HKKT6QIA.js +0 -66
  111. package/dist/outcome-HKKT6QIA.js.map +0 -1
  112. package/dist/publish-D76B3MBK.js.map +0 -1
  113. package/dist/usdc-JIAJW4SV.js +0 -22
  114. /package/dist/{_esm-FEASBWRP.js.map → _esm-N4KAVXQR.js.map} +0 -0
  115. /package/dist/{ccip-NQXCEK2U.js.map → buy-OOOLUDND.js.map} +0 -0
  116. /package/dist/{ccip-XR5NE5QK.js.map → candidate-TWCWTFGA.js.map} +0 -0
  117. /package/dist/{config-2VSXWWHK.js.map → ccip-RPPPKTJR.js.map} +0 -0
  118. /package/dist/{doctor-JJPNIBYH.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  119. /package/dist/{chunk-XJIW7USF.js.map → chunk-333FOTUJ.js.map} +0 -0
  120. /package/dist/{chunk-YN5SHIXQ.js.map → chunk-DPET3TW5.js.map} +0 -0
  121. /package/dist/{chunk-S3IGX57D.js.map → chunk-FU6MCSLG.js.map} +0 -0
  122. /package/dist/{chunk-5CLSD5YN.js.map → chunk-KYQVEKP5.js.map} +0 -0
  123. /package/dist/{chunk-RRN3YTK7.js.map → chunk-KZAAWQNP.js.map} +0 -0
  124. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POJRB2AE.js.map} +0 -0
  125. /package/dist/{chunk-CYOF7ROH.js.map → chunk-S5RYMCV6.js.map} +0 -0
  126. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-U5S527PP.js.map} +0 -0
  127. /package/dist/{chunk-RY4XKNV3.js.map → chunk-UHTVXQ2O.js.map} +0 -0
  128. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-W6R3HAAG.js.map} +0 -0
  129. /package/dist/{chunk-HIVZG55D.js.map → chunk-XJN5WUKL.js.map} +0 -0
  130. /package/dist/{chunk-HSDCI7OV.js.map → chunk-YLYINX2H.js.map} +0 -0
  131. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → config-DBEEM3UA.js.map} +0 -0
  132. /package/dist/{secp256k1-N3ZHU7LB.js.map → doctor-XDA3YU6H.js.map} +0 -0
  133. /package/dist/{usdc-JIAJW4SV.js.map → ethersCompat-Df4a6QIZ-WHYKB6HA.js.map} +0 -0
  134. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → inspect-YBGDAG47.js.map} +0 -0
  135. /package/dist/{wallet-PA54CRBL.js.map → outcome-ZFGHX2XW.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/agent-api.ts"],"sourcesContent":["import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResult } from './http';\nimport { CLIENT_HEADER } from './client-meta';\nimport { ATOMIC_RE, UUID_RE } from './ids';\nimport { trimSlash } from './url';\n\n/**\n * The lookup + outcome HTTP contract (A2, tenjin#370). Request building and\n * response validation live here; the wire shape is validated defensively, an\n * unknown `schemaVersion` degrades to a parse refusal rather than a guess, and\n * unrecognized candidate fields are ignored (forward-compatible), per spec 10.\n *\n * These endpoints are anonymous: no wallet, no SIWX. The only header of note is\n * `X-Tenjin-Client`, which attributes a later purchase back to the lookup flow.\n */\n\nconst FRESH_WITHIN_RE = /^P(\\d+)[DWMY]$/;\nconst CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;\n\n/** Client-side lookup request (mirrors lib/lookup.ts lookupRequestSchema bounds\n * so a malformed flag fails locally as USAGE, before a round trip). */\nexport interface LookupInput {\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit?: number;\n}\n\nexport interface LookupRequestBody {\n schemaVersion: 1;\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit: number;\n}\n\nexport function buildLookupRequest(input: LookupInput): LookupRequestBody {\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 > 10) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(input.limit)}`, {\n fix: 'Pass an integer between 1 and 10.',\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: 1,\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.\nexport const lookupCandidateSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: 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 temporalMode: z.string(),\n appliesTo: z.record(z.string(), z.array(z.string())),\n questionsAnswered: z.array(z.string()),\n tasksSupported: z.array(z.string()),\n scope: z.string().nullable(),\n exclusions: 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 LookupCandidate = z.infer<typeof lookupCandidateSchema>;\n\nexport const lookupResponseSchema = z.object({\n schemaVersion: z.literal(1),\n lookupId: z.string().regex(UUID_RE, 'lookupId must be a uuid'),\n decision: z.enum(['CANDIDATES', 'MISS']),\n calibration: z.string(),\n candidates: z.array(lookupCandidateSchema).optional(),\n});\n\nexport type LookupResponse = z.infer<typeof lookupResponseSchema>;\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 --base-url and your network, 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 postLookup(\n body: LookupRequestBody,\n opts: AgentApiOptions,\n): Promise<LookupResponse> {\n const url = `${trimSlash(opts.baseUrl)}/api/agent/lookup`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: {\n 'x-tenjin-client': CLIENT_HEADER,\n ...(opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {}),\n },\n jsonBody: body,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Lookup failed (${res.status})`,\n {\n fix: 'Retry; if it persists the lookup endpoint may be unavailable.',\n details: res.json,\n },\n );\n }\n const parsed = lookupResponseSchema.safeParse(res.json);\n if (!parsed.success) {\n throw new CliError('CONTRACT_MISMATCH', 'Lookup 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/**\n * The server bounds every card string (response budget ~1k tokens, spec 09);\n * re-apply the same caps defensively so a misbehaving server cannot blow up an\n * agent transcript through the CLI (spec 10 response-size discipline).\n */\nconst CAND_BOUNDS = {\n title: 200,\n scope: 240,\n exclusions: 240,\n listItems: 4,\n listItemChars: 160,\n matchReasons: 3,\n matchReasonChars: 80,\n appliesToKeys: 6,\n appliesToValues: 5,\n appliesToValueChars: 80,\n} as const;\n\nfunction truncateResponse(res: LookupResponse): LookupResponse {\n if (res.candidates === undefined) return res;\n return { ...res, candidates: res.candidates.map(truncateCandidate) };\n}\n\nfunction truncateCandidate(c: LookupCandidate): LookupCandidate {\n const cap = (s: string, n: number): string => (s.length > n ? s.slice(0, n) : s);\n const capList = (list: string[], items: number, chars: number): string[] =>\n list.slice(0, items).map((s) => cap(s, chars));\n const appliesTo: Record<string, string[]> = {};\n for (const key of Object.keys(c.appliesTo).slice(0, CAND_BOUNDS.appliesToKeys)) {\n appliesTo[cap(key, CAND_BOUNDS.appliesToValueChars)] = capList(\n c.appliesTo[key] ?? [],\n CAND_BOUNDS.appliesToValues,\n CAND_BOUNDS.appliesToValueChars,\n );\n }\n return {\n ...c,\n title: cap(c.title, CAND_BOUNDS.title),\n scope: c.scope === null ? null : cap(c.scope, CAND_BOUNDS.scope),\n exclusions: c.exclusions === null ? null : cap(c.exclusions, CAND_BOUNDS.exclusions),\n questionsAnswered: capList(\n c.questionsAnswered,\n CAND_BOUNDS.listItems,\n CAND_BOUNDS.listItemChars,\n ),\n tasksSupported: capList(c.tasksSupported, CAND_BOUNDS.listItems, CAND_BOUNDS.listItemChars),\n matchReasons: capList(c.matchReasons, CAND_BOUNDS.matchReasons, CAND_BOUNDS.matchReasonChars),\n appliesTo,\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 lookup 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 LOOKUP_ID_RE = UUID_RE;\n\nexport async function postOutcomes(\n lookupId: string,\n items: OutcomeBodyItem[],\n opts: AgentApiOptions,\n): Promise<{ accepted: number }> {\n if (!LOOKUP_ID_RE.test(lookupId)) {\n throw new CliError('USAGE', `Invalid lookup id: ${JSON.stringify(lookupId)}`, {\n fix: 'Pass the lookupId from a prior lookup (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/lookups/${lookupId}/outcomes`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n jsonBody: items.length === 1 ? items[0] : items,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n // 202 is the only success; the body is a uniform { accepted } regardless of\n // whether the lookupId 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 lookup id, then retry.',\n details: res.json,\n },\n );\n }\n const accepted =\n typeof res.json === 'object' && res.json !== null && 'accepted' in res.json\n ? Number((res.json as { accepted: unknown }).accepted)\n : items.length;\n return { accepted: Number.isFinite(accepted) ? accepted : items.length };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAqBlB,SAAS,mBAAmB,OAAuC;AACxE,QAAM,WAAW,MAAM,SAAS,KAAK;AACrC,MAAI,SAAS,WAAW,KAAK,SAAS,SAAS,KAAK;AAClD,UAAM,IAAI,SAAS,SAAS,wCAAwC;AAAA,MAClE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,MAAI,MAAM,gBAAgB,QAAW;AAGnC,UAAM,SAAS,gBAAgB,KAAK,MAAM,WAAW,IAAI,CAAC;AAC1D,QAAI,WAAW,UAAa,OAAO,MAAM,MAAM,GAAG;AAChD,YAAM,IAAI,SAAS,SAAS,2BAA2B,KAAK,UAAU,MAAM,WAAW,CAAC,IAAI;AAAA,QAC1F,KAAK;AAAA,MACP,CAAC;AAAA,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Ae,KAAK,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC;AAGtE,MAAI,IAAI,WAAW,KAAK;AACtB,UAAM,IAAI;AAAA,MACR;AAAA,MACA,mBAAmB,IAAI,IAAI,KAAK,0BAA0B,IAAI,MAAM;AAAA,MACpE;AAAA,QACE,KAAK;AAAA,QACL,SAAS,IAAI;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACA,QAAM,WACJ,OAAO,IAAI,SAAS,YAAY,IAAI,SAAS,QAAQ,cAAc,IAAI,OACnE,OAAQ,IAAI,KAA+B,QAAQ,IACnD,MAAM;AACZ,SAAO,EAAE,UAAU,OAAO,SAAS,QAAQ,IAAI,WAAW,MAAM,OAAO;AACzE;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/output.ts","../src/schemas.ts"],"sourcesContent":["import { styleText } from 'node:util';\nimport { Stream } from 'node:stream';\nimport { CliError } from './errors';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { OutputError } from '../schemas';\n\n/**\n * Injected streams + TTY fact. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` is the real terminal fact; the separate `--json` flag (passed to the\n * emit functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output.\n */\nexport interface Io {\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, all stderr human rendering is suppressed. */\n json?: boolean;\n}\n\n/**\n * Emit exactly one pretty-printed success envelope to stdout. When on a TTY and\n * --json is off, the optional human lines are rendered to stderr (never stdout —\n * stdout stays a clean single JSON object for the agent that piped us).\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n writeJson(io.stdout, { schemaVersion: SCHEMA_VERSION, command, ok: true, data });\n if (shouldRenderHuman(io, opts) && humanLines.length > 0) {\n writeLines(io.stderr, humanLines);\n }\n}\n\n/**\n * Emit exactly one pretty-printed failure envelope to stdout and (on a TTY, with\n * --json off) a red error line plus a `fix` line to stderr. Accepts a CliError or\n * any thrown value; anything that is not a CliError normalizes to INTERNAL.\n * Returns the normalized CliError so the caller can read its `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n const error: OutputError = {\n code: cliErr.code,\n message: cliErr.message,\n ...(cliErr.fix !== undefined ? { fix: cliErr.fix } : {}),\n ...(cliErr.details !== undefined ? { details: cliErr.details } : {}),\n };\n writeJson(io.stdout, { schemaVersion: SCHEMA_VERSION, command, ok: false, error });\n if (shouldRenderHuman(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n writeLines(io.stderr, lines);\n }\n return cliErr;\n}\n\n/**\n * Strip C0/C1 control characters and ANSI escape sequences from a string headed\n * for a terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm. It is not applied to whole human\n * lines here because trusted callers (doctor) paint their own ANSI colors. JSON\n * stdout is untouched (JSON.stringify escapes control characters itself).\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n // eslint-disable-next-line no-control-regex\n .replace(/\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n );\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\nfunction shouldRenderHuman(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\n/**\n * Color the human line for stderr. styleText emits ANSI only when the target\n * stream is color-capable (a real TTY with color depth) and honors\n * NO_COLOR/FORCE_COLOR natively (verified on Node 22/23). The `stream` option is\n * passed only when stderr is a genuine Stream — styleText throws on anything\n * else, and a test/redirected sink is not one, so it falls back to the default\n * (process.stdout) capability check and simply comes out plain.\n */\nfunction paint(io: Io, format: Parameters<typeof styleText>[0], text: string): string {\n if (io.stderr instanceof Stream) return styleText(format, text, { stream: io.stderr });\n return styleText(format, text);\n}\n","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (lookup/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'LOOKUP_NOT_FOUND',\n // A 429 from the anonymous lookup/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discriminatedUnion('ok', [\n SuccessEnvelopeSchema,\n FailureEnvelopeSchema,\n]);\nexport type OutputEnvelope = z.infer<typeof OutputEnvelopeSchema>;\n"],"mappings":";;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,cAAc;;;ACMhB,IAAM,iBAAiB;AAQvB,IAAM,kBAAkB,iBAAE,KAAK;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AASM,IAAM,cAAc,iBAAE,OAAO;AAAA,EAClC,QAAQ,iBAAE,OAAO;AAAA,EACjB,KAAK,iBAAE,OAAO;AAChB,CAAC;AAGM,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACxC,MAAM;AAAA,EACN,SAAS,iBAAE,OAAO;AAAA,EAClB,KAAK,iBAAE,OAAO,EAAE,SAAS;AAAA,EACzB,SAAS,iBAAE,QAAQ,EAAE,SAAS;AAChC,CAAC;AAGM,IAAM,wBAAwB,iBAAE,OAAO;AAAA,EAC5C,eAAe,iBAAE,QAAQ,cAAc;AAAA,EACvC,SAAS,iBAAE,OAAO;AAAA,EAClB,IAAI,iBAAE,QAAQ,IAAI;AAAA,EAClB,M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K,MAAM,IAAI,OAAO,QAAQ,oBAAoB,OAAO,GAAG,CAAC,EAAE,CAAC;AAAA,IACxE;AACA,eAAW,GAAG,QAAQ,KAAK;AAAA,EAC7B;AACA,SAAO;AACT;AAWO,SAAS,oBAAoB,MAAsB;AACxD,SACE,KAIG,QAAQ,0EAA0E,EAAE,EAEpF,QAAQ,kCAAkC,EAAE;AAEnD;AAGO,SAAS,eAAe,KAAwB;AACrD,MAAI,eAAe,SAAU,QAAO;AACpC,MAAI,eAAe,MAAO,QAAO,IAAI,SAAS,YAAY,IAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AACrF,SAAO,IAAI,SAAS,YAAY,oBAAoB,EAAE,SAAS,IAAI,CAAC;AACtE;AAEA,SAAS,kBAAkB,IAAQ,MAA4B;AAC7D,SAAO,GAAG,SAAS,KAAK,SAAS;AACnC;AAEA,SAAS,UAAU,QAA+B,OAAsB;AACtE,SAAO,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,CAAI;AACpD;AAEA,SAAS,WAAW,QAA+B,OAAuB;AACxE,MAAI,MAAM,SAAS,EAAG,QAAO,MAAM,GAAG,MAAM,KAAK,IAAI,CAAC;AAAA,CAAI;AAC5D;AAUA,SAAS,MAAM,IAAQ,QAAyC,MAAsB;AACpF,MAAI,GAAG,kBAAkB,OAAQ,QAAO,UAAU,QAAQ,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC;AACrF,SAAO,UAAU,QAAQ,IAAI;AAC/B;","names":[]}
@@ -1,378 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- collectDoctorChecks,
4
- renderDoctorHuman
5
- } from "./chunk-7PHSZKQS.js";
6
- import "./chunk-QNP7H47L.js";
7
- import "./chunk-N62ROTMC.js";
8
- import {
9
- persistPublishMode
10
- } from "./chunk-TFGSOPWR.js";
11
- import "./chunk-UPIEAMGH.js";
12
- import {
13
- PublishModeSchema,
14
- loadRawConfig,
15
- parsePublishModeFlag
16
- } from "./chunk-IYLHQMT5.js";
17
- import "./chunk-YN5SHIXQ.js";
18
- import "./chunk-2I4QTOLB.js";
19
- import "./chunk-YBMMV4Y4.js";
20
- import "./chunk-UO22YNY4.js";
21
- import {
22
- writeFileAtomic
23
- } from "./chunk-MUBUQVC3.js";
24
- import {
25
- CliError,
26
- external_exports
27
- } from "./chunk-OYMYCW7J.js";
28
- import "./chunk-ZXTAQYNA.js";
29
-
30
- // src/commands/install.ts
31
- import { existsSync as existsSync2, statSync } from "fs";
32
- import { readFile, readdir, rm } from "fs/promises";
33
- import { createInterface } from "readline";
34
- import { fileURLToPath } from "url";
35
- import { delimiter, join as join2, relative } from "path";
36
- import { homedir } from "os";
37
- import { styleText } from "util";
38
- import { Stream } from "stream";
39
-
40
- // src/lib/skills-source.ts
41
- import { existsSync } from "fs";
42
- import { dirname, join } from "path";
43
- var SKILL_NAMES = ["tenjin-search", "tenjin-publish", "tenjin"];
44
- var SENTINEL = join("tenjin", "SKILL.md");
45
- function resolveSkillsSource(startDir) {
46
- let dir = startDir;
47
- for (let i = 0; i < 8; i += 1) {
48
- const candidate = join(dir, "skills");
49
- if (existsSync(join(candidate, SENTINEL))) return candidate;
50
- const parent = dirname(dir);
51
- if (parent === dir) break;
52
- dir = parent;
53
- }
54
- throw new CliError("INTERNAL", "Could not locate the packaged Tenjin skills directory", {
55
- fix: "Reinstall tenjin-cli; the published package must ship the skills/ directory (files array).",
56
- details: { startDir }
57
- });
58
- }
59
-
60
- // src/commands/install.ts
61
- var HARNESSES = ["claude", "codex", "shared"];
62
- var InstallInputSchema = external_exports.object({
63
- harness: external_exports.array(external_exports.string()).optional(),
64
- dryRun: external_exports.boolean().optional(),
65
- publishMode: external_exports.string().optional()
66
- });
67
- var AGENTS_MARKER = "<!-- tenjin-cli:skills -->";
68
- var CODEX_NETWORK_RULE = "[sandbox_workspace_write]\nnetwork_access = true";
69
- async function runInstall(input, ctx, deps = {}) {
70
- const parsed = InstallInputSchema.safeParse(input);
71
- if (!parsed.success) {
72
- throw new CliError("USAGE", "Invalid install options", {
73
- fix: "Run `tenjin install --help`.",
74
- details: parsed.error.issues
75
- });
76
- }
77
- const dryRun = parsed.data.dryRun === true;
78
- const publishModeFlag = parsed.data.publishMode !== void 0 ? parseModeFlag(parsed.data.publishMode) : void 0;
79
- const env = deps.env ?? process.env;
80
- const home = deps.homeDir ?? homedir();
81
- const which = deps.which ?? ((bin) => onPath(bin, env));
82
- const skillsSource = deps.skillsSourceDir ?? resolveSkillsSource(fileURLToPath(new URL(".", import.meta.url)));
83
- await assertSkillsSource(skillsSource);
84
- const plans = resolvePlans(parsed.data.harness, home, which);
85
- const harnesses = [];
86
- for (const plan of plans) {
87
- harnesses.push(await applyPlan(plan, skillsSource, dryRun));
88
- }
89
- const collect = deps.collectChecks ?? ((c) => collectDoctorChecks(c, deps.doctorDeps ?? {}));
90
- const doctor = await collect(ctx);
91
- const doctorStatus = doctor.failure !== void 0 ? "fail" : "pass";
92
- const publishMode = await selectPublishMode(publishModeFlag, ctx, deps, dryRun);
93
- const data = {
94
- dryRun,
95
- skillsSource,
96
- harnesses,
97
- doctor: { status: doctorStatus, checks: doctor.checks },
98
- publishMode
99
- };
100
- const humanLines = renderHuman(ctx.io, harnesses, doctor, dryRun);
101
- humanLines.push(publishModeLine(ctx.io, publishMode, dryRun));
102
- return { data, humanLines };
103
- }
104
- var PUBLISH_MODE_PROMPT = "Publish consent mode? review = always ask / auto = ask only on findings / full-auto = only hard blocks stop it [auto]: ";
105
- async function selectPublishMode(flag, ctx, deps, dryRun) {
106
- if (flag !== void 0) {
107
- if (!dryRun) await persistPublishMode(ctx.dataDir, flag);
108
- return { value: flag, source: "flag" };
109
- }
110
- const config = await loadRawConfig(ctx.dataDir);
111
- if (config.publish?.mode !== void 0) {
112
- return { value: config.publish.mode, source: "existing" };
113
- }
114
- const interactive = ctx.flags.json !== true && (deps.isInteractive ?? (ctx.io.isTTY && Boolean(process.stdin.isTTY)));
115
- if (dryRun || !interactive) return { value: "auto", source: "default-skipped" };
116
- const prompt = deps.promptMode ?? defaultPromptMode;
117
- for (let attempt = 0; attempt < 2; attempt++) {
118
- const answer = (await prompt(PUBLISH_MODE_PROMPT)).trim();
119
- if (answer.length === 0) return { value: "auto", source: "default-skipped" };
120
- const parsed = PublishModeSchema.safeParse(answer);
121
- if (parsed.success) {
122
- await persistPublishMode(ctx.dataDir, parsed.data);
123
- return { value: parsed.data, source: "prompt" };
124
- }
125
- }
126
- ctx.io.stderr.write(
127
- "Unrecognized mode; keeping the default (auto). Change it with `tenjin config set publish.mode`.\n"
128
- );
129
- return { value: "auto", source: "default-skipped" };
130
- }
131
- function parseModeFlag(value) {
132
- return parsePublishModeFlag(value, "--publish-mode");
133
- }
134
- function defaultPromptMode(label) {
135
- return new Promise((resolve) => {
136
- const rl = createInterface({ input: process.stdin, output: process.stderr });
137
- let settled = false;
138
- const settle = (value) => {
139
- if (settled) return;
140
- settled = true;
141
- rl.close();
142
- resolve(value);
143
- };
144
- rl.once("close", () => settle(""));
145
- rl.question(label, (answer) => settle(answer));
146
- });
147
- }
148
- function publishModeLine(io, selection, dryRun) {
149
- const detail = {
150
- flag: dryRun ? "would set from --publish-mode" : "set from --publish-mode",
151
- existing: "already configured",
152
- prompt: "saved",
153
- "default-skipped": "default; run interactively or pass --publish-mode to change"
154
- };
155
- return paint(io, "bold", `publish mode: ${selection.value} (${detail[selection.source]})`);
156
- }
157
- function resolvePlans(override, home, which) {
158
- const claudeDir = join2(home, ".claude", "skills");
159
- const sharedDir = join2(home, ".agents", "skills");
160
- if (override !== void 0 && override.length > 0) {
161
- const plans2 = override.map(
162
- (v) => planFor(validateHarness(v), ["override"], true, home, claudeDir, sharedDir)
163
- );
164
- return dedupeBySkillsDir(plans2);
165
- }
166
- const plans = [];
167
- const claudeBy = detectReasons(existsSync2(join2(home, ".claude")), which("claude"));
168
- const codexBy = detectReasons(existsSync2(join2(home, ".codex")), which("codex"));
169
- if (claudeBy.length > 0)
170
- plans.push(planFor("claude", claudeBy, true, home, claudeDir, sharedDir));
171
- if (codexBy.length > 0) plans.push(planFor("codex", codexBy, true, home, claudeDir, sharedDir));
172
- if (plans.length === 0) {
173
- plans.push(planFor("shared", ["fallback"], false, home, claudeDir, sharedDir));
174
- }
175
- return dedupeBySkillsDir(plans);
176
- }
177
- function detectReasons(homeDirPresent, onPathPresent) {
178
- const reasons = [];
179
- if (homeDirPresent) reasons.push("home-dir");
180
- if (onPathPresent) reasons.push("binary");
181
- return reasons;
182
- }
183
- function planFor(harness, detectedBy, detected, home, claudeDir, sharedDir) {
184
- const skillsDir = harness === "claude" ? claudeDir : sharedDir;
185
- return { harness, detected, detectedBy, skillsDir, wiresAgentsMd: harness !== "claude", home };
186
- }
187
- function dedupeBySkillsDir(plans) {
188
- const seen = /* @__PURE__ */ new Set();
189
- const out = [];
190
- for (const p of plans) {
191
- if (seen.has(p.skillsDir)) continue;
192
- seen.add(p.skillsDir);
193
- out.push(p);
194
- }
195
- return out;
196
- }
197
- function validateHarness(value) {
198
- if (HARNESSES.includes(value)) return value;
199
- throw new CliError("USAGE", `Unknown harness "${value}"`, {
200
- fix: `--harness must be one of: ${HARNESSES.join(", ")}.`
201
- });
202
- }
203
- async function applyPlan(plan, skillsSource, dryRun) {
204
- const skills = [];
205
- const warnings = [];
206
- for (const name of SKILL_NAMES) {
207
- const { status, warning } = await installSkill(
208
- join2(skillsSource, name),
209
- join2(plan.skillsDir, name),
210
- dryRun
211
- );
212
- skills.push({ name, status });
213
- if (warning !== void 0) warnings.push(warning);
214
- }
215
- const result = {
216
- harness: plan.harness,
217
- detected: plan.detected,
218
- detectedBy: plan.detectedBy,
219
- skillsDir: plan.skillsDir,
220
- skills,
221
- notes: notesFor(plan),
222
- warnings
223
- };
224
- if (plan.wiresAgentsMd) {
225
- result.agentsMd = await wireAgentsMd(plan, dryRun);
226
- result.codexNetworkRule = CODEX_NETWORK_RULE;
227
- }
228
- return result;
229
- }
230
- function notesFor(plan) {
231
- if (plan.harness === "claude") {
232
- return [
233
- "Installed at the user level (~/.claude/skills). The Claude Code plugin marketplace (roadmap C3) will supersede this path for Claude users."
234
- ];
235
- }
236
- return [
237
- "Copied into the shared Agent Skills location (~/.agents/skills). Codex and any Agent-Skills-compatible harness read it there."
238
- ];
239
- }
240
- async function installSkill(srcDir, destDir, dryRun) {
241
- const src = await readTree(srcDir);
242
- const dest = await readTree(destDir);
243
- if (src === null) {
244
- throw new CliError("INTERNAL", `Packaged skill source ${srcDir} is empty`);
245
- }
246
- const change = dest === null ? "create" : treesEqual(src, dest) ? "none" : "update";
247
- if (!dryRun && change !== "none") {
248
- await rm(destDir, { recursive: true, force: true });
249
- for (const [rel, content] of src) {
250
- await writeFileAtomic(join2(destDir, rel), content);
251
- }
252
- }
253
- if (change === "create") return { status: dryRun ? "would-install" : "installed" };
254
- if (change === "none") return { status: "up-to-date" };
255
- return {
256
- status: dryRun ? "would-update" : "updated",
257
- warning: `${destDir}: local skill copy differed and was ${dryRun ? "would be " : ""}overwritten (the packaged copy is canonical).`
258
- };
259
- }
260
- async function readTree(dir) {
261
- if (!existsSync2(dir)) return null;
262
- const entries = await readdir(dir, { recursive: true, withFileTypes: true });
263
- const files = /* @__PURE__ */ new Map();
264
- for (const entry of entries) {
265
- if (!entry.isFile()) continue;
266
- const full = join2(entry.parentPath, entry.name);
267
- files.set(relative(dir, full), await readFile(full));
268
- }
269
- return files;
270
- }
271
- function treesEqual(a, b) {
272
- if (b === null) return false;
273
- if (a.size !== b.size) return false;
274
- for (const [k, v] of a) {
275
- const other = b.get(k);
276
- if (other === void 0 || !v.equals(other)) return false;
277
- }
278
- return true;
279
- }
280
- async function wireAgentsMd(plan, dryRun) {
281
- const shared = join2(plan.home, ".agents", "AGENTS.md");
282
- const codex = join2(plan.home, ".codex", "AGENTS.md");
283
- const line = `${AGENTS_MARKER} Tenjin agent skills are installed at ${plan.skillsDir} (tenjin-search, tenjin-publish, tenjin). Read the relevant SKILL.md before using the tenjin CLI.`;
284
- for (const path2 of [shared, codex]) {
285
- if (existsSync2(path2) && (await readFile(path2, "utf8")).includes(AGENTS_MARKER)) {
286
- return { path: path2, status: "already-present" };
287
- }
288
- }
289
- const path = chooseAgentsMdPath(plan.home);
290
- if (dryRun) return { path, status: "would-append" };
291
- const existing = existsSync2(path) ? await readFile(path, "utf8") : null;
292
- const prefix = existing === null || existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
293
- await writeFileAtomic(path, `${existing ?? ""}${prefix}${line}
294
- `);
295
- return { path, status: "appended" };
296
- }
297
- function chooseAgentsMdPath(home) {
298
- const shared = join2(home, ".agents", "AGENTS.md");
299
- const codex = join2(home, ".codex", "AGENTS.md");
300
- if (existsSync2(shared)) return shared;
301
- if (existsSync2(codex)) return codex;
302
- if (existsSync2(join2(home, ".codex"))) return codex;
303
- return shared;
304
- }
305
- function onPath(bin, env) {
306
- const raw = env.PATH ?? "";
307
- const exts = process.platform === "win32" ? ["", ...(env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter((e) => e.length > 0)] : [""];
308
- for (const part of raw.split(delimiter)) {
309
- if (part.length === 0) continue;
310
- for (const ext of exts) {
311
- if (isFile(join2(part, bin + ext))) return true;
312
- }
313
- }
314
- return false;
315
- }
316
- function isFile(p) {
317
- try {
318
- return statSync(p).isFile();
319
- } catch {
320
- return false;
321
- }
322
- }
323
- function renderHuman(io, harnesses, doctor, dryRun) {
324
- const lines = [];
325
- if (dryRun) lines.push(paint(io, "yellow", "dry run: no files written"));
326
- for (const h of harnesses) {
327
- const how = h.detectedBy.length > 0 ? ` (${h.detectedBy.join(", ")})` : "";
328
- lines.push(paint(io, "bold", `${h.harness}${how} -> ${h.skillsDir}`));
329
- for (const s of h.skills) {
330
- lines.push(` ${skillIcon(io, s.status)} ${s.name.padEnd(14)} ${paint(io, "dim", s.status)}`);
331
- }
332
- if (h.agentsMd !== void 0) {
333
- lines.push(` ${paint(io, "dim", `AGENTS.md ${h.agentsMd.status}: ${h.agentsMd.path}`)}`);
334
- }
335
- for (const w of h.warnings) lines.push(` ${paint(io, "yellow", `! ${w}`)}`);
336
- for (const n of h.notes) lines.push(` ${paint(io, "dim", n)}`);
337
- if (h.codexNetworkRule !== void 0) {
338
- lines.push(
339
- paint(
340
- io,
341
- "dim",
342
- " Codex's default workspace-write sandbox blocks network, which breaks paid x402 calls."
343
- )
344
- );
345
- lines.push(paint(io, "dim", " Add this to ~/.codex/config.toml:"));
346
- for (const rl of h.codexNetworkRule.split("\n")) lines.push(` ${rl}`);
347
- }
348
- }
349
- lines.push("");
350
- lines.push(paint(io, "bold", "doctor (final checks):"));
351
- lines.push(...renderDoctorHuman(io, doctor.checks));
352
- if (doctor.failure !== void 0) {
353
- lines.push(paint(io, "yellow", "doctor reported a problem above; the skills are still wired."));
354
- }
355
- return lines;
356
- }
357
- function skillIcon(io, status) {
358
- if (status === "up-to-date") return paint(io, "green", "=");
359
- if (status === "updated" || status === "would-update") return paint(io, "yellow", "~");
360
- return paint(io, "green", "+");
361
- }
362
- function paint(io, format, text) {
363
- if (io.stderr instanceof Stream) return styleText(format, text, { stream: io.stderr });
364
- return styleText(format, text);
365
- }
366
- async function assertSkillsSource(dir) {
367
- for (const name of SKILL_NAMES) {
368
- if (!existsSync2(join2(dir, name, "SKILL.md"))) {
369
- throw new CliError("INTERNAL", `Packaged skill "${name}" is missing under ${dir}`, {
370
- fix: "Reinstall tenjin-cli; the published package must ship every skill under skills/."
371
- });
372
- }
373
- }
374
- }
375
- export {
376
- runInstall
377
- };
378
- //# sourceMappingURL=install-ZQRMSRGW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/install.ts","../src/lib/skills-source.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport { readFile, readdir, rm } from 'node:fs/promises';\nimport { createInterface } from 'node:readline';\nimport { fileURLToPath } from 'node:url';\nimport { delimiter, join, relative } from 'node:path';\nimport { homedir } from 'node:os';\nimport { z } from 'zod';\nimport { styleText } from 'node:util';\nimport { Stream } from 'node:stream';\nimport { CliError } from '../lib/errors';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { resolveSkillsSource, SKILL_NAMES } from '../lib/skills-source';\nimport { loadRawConfig, PublishModeSchema, parsePublishModeFlag } from '../lib/config';\nimport type { PublishMode } from '../lib/config';\nimport { persistPublishMode } from './config';\nimport { collectDoctorChecks, renderDoctorHuman } from './doctor';\nimport type { DoctorDeps, DoctorChecks } from './doctor';\nimport type { Io } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\nconst HARNESSES = ['claude', 'codex', 'shared'] as const;\ntype Harness = (typeof HARNESSES)[number];\n\nconst InstallInputSchema = z.object({\n harness: z.array(z.string()).optional(),\n dryRun: z.boolean().optional(),\n publishMode: z.string().optional(),\n});\nexport type InstallInput = z.infer<typeof InstallInputSchema>;\n\n/** A visible text-prompt seam (like passphrase's PromptFn); injected in tests. */\nexport type PromptFn = (label: string) => Promise<string>;\n\ntype PublishModeSource = 'flag' | 'existing' | 'prompt' | 'default-skipped';\ninterface PublishModeSelection {\n value: PublishMode;\n source: PublishModeSource;\n}\n\n/**\n * The one line `install` keeps in an AGENTS.md so Codex (which reads AGENTS.md as\n * global guidance, not the raw ~/.agents/skills scan) knows the skills are there.\n * The HTML-comment marker is how re-runs stay idempotent: its presence means the\n * line is already written, so we never append a second copy.\n */\nconst AGENTS_MARKER = '<!-- tenjin-cli:skills -->';\n\n/**\n * The Codex config.toml rule the user must add by hand. We PRINT it, never edit\n * config.toml: Codex's default workspace-write sandbox blocks network, which would\n * make every paid x402 call fail (or prompt) until this is set.\n */\nconst CODEX_NETWORK_RULE = '[sandbox_workspace_write]\\nnetwork_access = true';\n\n/** Per-skill install outcome for one harness target. */\ninterface SkillResult {\n name: string;\n status: 'installed' | 'updated' | 'up-to-date' | 'would-install' | 'would-update';\n}\n\ninterface AgentsMdResult {\n path: string;\n status: 'appended' | 'already-present' | 'would-append';\n}\n\ninterface HarnessResult {\n harness: Harness;\n detected: boolean;\n detectedBy: string[];\n skillsDir: string;\n skills: SkillResult[];\n agentsMd?: AgentsMdResult;\n codexNetworkRule?: string;\n notes: string[];\n warnings: string[];\n}\n\nexport interface InstallDeps {\n /** Home directory root for harness detection + skill destinations. Tests inject a temp dir. */\n homeDir?: string;\n /** The packaged skills source directory. Defaults to resolving it from this module's location. */\n skillsSourceDir?: string;\n /** PATH probe for `claude`/`codex` binaries. Injectable so tests never depend on the real PATH. */\n which?: (bin: string) => boolean;\n /** Environment (PATH for the default `which`). Defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Doctor check collector; defaults to the real one. Injected in tests to avoid the network. */\n collectChecks?: (ctx: CommandContext) => Promise<DoctorChecks>;\n /** Deps forwarded to the default doctor collector (e.g. a canned fetch). */\n doctorDeps?: DoctorDeps;\n /** Interactive text-prompt seam for the publish-mode question; defaults to a stdin reader. */\n promptMode?: PromptFn;\n /** Whether an interactive prompt is possible; defaults to the TTY facts. */\n isInteractive?: boolean;\n}\n\n/**\n * `tenjin install`: detect the installed harness(es), copy the packaged skills into\n * each one's skills directory, wire the AGENTS.md pointer + print the Codex sandbox\n * rule where relevant, THEN run the doctor checks as the final step (D39: doctor is\n * diagnostics run last, never a required first hop; a doctor problem is surfaced but\n * never fails the wiring that already succeeded). Idempotent: a re-run reports\n * up-to-date and never duplicates the AGENTS.md line. `--dry-run` writes nothing.\n */\nexport async function runInstall(\n input: InstallInput,\n ctx: CommandContext,\n deps: InstallDeps = {},\n): Promise<CommandResult> {\n const parsed = InstallInputSchema.safeParse(input);\n if (!parsed.success) {\n throw new CliError('USAGE', 'Invalid install options', {\n fix: 'Run `tenjin install --help`.',\n details: parsed.error.issues,\n });\n }\n const dryRun = parsed.data.dryRun === true;\n // Validate --publish-mode UP FRONT so a bad value fails before any wiring, even\n // though the mode is only settled (and persisted) after the doctor phase below.\n const publishModeFlag =\n parsed.data.publishMode !== undefined ? parseModeFlag(parsed.data.publishMode) : undefined;\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n\n const skillsSource =\n deps.skillsSourceDir ?? resolveSkillsSource(fileURLToPath(new URL('.', import.meta.url)));\n await assertSkillsSource(skillsSource);\n\n const plans = resolvePlans(parsed.data.harness, home, which);\n\n const harnesses: HarnessResult[] = [];\n for (const plan of plans) {\n harnesses.push(await applyPlan(plan, skillsSource, dryRun));\n }\n\n const collect = deps.collectChecks ?? ((c) => collectDoctorChecks(c, deps.doctorDeps ?? {}));\n const doctor = await collect(ctx);\n const doctorStatus = doctor.failure !== undefined ? 'fail' : 'pass';\n\n // After wiring + doctor, settle the publish consent mode: a flag sets it, an\n // already-configured mode is left alone, and an interactive setup asks once\n // (plain enter keeps the default WITHOUT writing, so `config get` stays truthful).\n const publishMode = await selectPublishMode(publishModeFlag, ctx, deps, dryRun);\n\n const data = {\n dryRun,\n skillsSource,\n harnesses,\n doctor: { status: doctorStatus, checks: doctor.checks },\n publishMode,\n };\n const humanLines = renderHuman(ctx.io, harnesses, doctor, dryRun);\n humanLines.push(publishModeLine(ctx.io, publishMode, dryRun));\n return { data, humanLines };\n}\n\n// --- Publish-mode selection (D38 setup) ------------------------------------------\n\nconst PUBLISH_MODE_PROMPT =\n 'Publish consent mode? review = always ask / auto = ask only on findings / full-auto = only hard blocks stop it [auto]: ';\n\n/**\n * Resolve (and, for an explicit choice, persist) the publish consent mode at\n * install time. Precedence: `--publish-mode` flag > an already-configured global\n * mode > an interactive prompt > the untouched default. Only an explicit choice\n * writes: a plain enter, a non-interactive run, `--dry-run`, or an unrecognized\n * answer all leave `publish.mode` unset so its provenance stays `default`.\n */\nasync function selectPublishMode(\n flag: PublishMode | undefined,\n ctx: CommandContext,\n deps: InstallDeps,\n dryRun: boolean,\n): Promise<PublishModeSelection> {\n if (flag !== undefined) {\n if (!dryRun) await persistPublishMode(ctx.dataDir, flag); // --dry-run: would-set only\n return { value: flag, source: 'flag' };\n }\n\n // Only the GLOBAL config file counts as \"already configured\" for setup: env/flag\n // are per-run and a project `.tenjin.json` is not this machine's global choice.\n const config = await loadRawConfig(ctx.dataDir);\n if (config.publish?.mode !== undefined) {\n return { value: config.publish.mode, source: 'existing' };\n }\n\n // --json implies non-interactive: a machine consumer must never sit behind a\n // prompt, even one on stderr. It overrides an injected isInteractive too, so the\n // only ways to set the mode under --json are --publish-mode or a prior config.\n const interactive =\n ctx.flags.json !== true &&\n (deps.isInteractive ?? (ctx.io.isTTY && Boolean(process.stdin.isTTY)));\n if (dryRun || !interactive) return { value: 'auto', source: 'default-skipped' };\n\n const prompt = deps.promptMode ?? defaultPromptMode;\n // Ask, allow ONE reprompt on an unrecognized answer, then fall back to auto.\n for (let attempt = 0; attempt < 2; attempt++) {\n const answer = (await prompt(PUBLISH_MODE_PROMPT)).trim();\n if (answer.length === 0) return { value: 'auto', source: 'default-skipped' }; // enter: no write\n const parsed = PublishModeSchema.safeParse(answer);\n if (parsed.success) {\n await persistPublishMode(ctx.dataDir, parsed.data);\n return { value: parsed.data, source: 'prompt' };\n }\n }\n ctx.io.stderr.write(\n 'Unrecognized mode; keeping the default (auto). Change it with `tenjin config set publish.mode`.\\n',\n );\n return { value: 'auto', source: 'default-skipped' };\n}\n\nfunction parseModeFlag(value: string): PublishMode {\n return parsePublishModeFlag(value, '--publish-mode');\n}\n\n/** A visible line-reader (prompt on stderr so stdout stays a single JSON object). */\nfunction defaultPromptMode(label: string): Promise<string> {\n return new Promise((resolve) => {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n let settled = false;\n const settle = (value: string): void => {\n if (settled) return;\n settled = true;\n rl.close();\n resolve(value);\n };\n rl.once('close', () => settle('')); // ctrl-D mid-prompt reads as the default\n rl.question(label, (answer) => settle(answer));\n });\n}\n\nfunction publishModeLine(io: Io, selection: PublishModeSelection, dryRun: boolean): string {\n const detail: Record<PublishModeSource, string> = {\n flag: dryRun ? 'would set from --publish-mode' : 'set from --publish-mode',\n existing: 'already configured',\n prompt: 'saved',\n 'default-skipped': 'default; run interactively or pass --publish-mode to change',\n };\n return paint(io, 'bold', `publish mode: ${selection.value} (${detail[selection.source]})`);\n}\n\n// --- Detection + planning --------------------------------------------------------\n\ninterface HarnessPlan {\n harness: Harness;\n detected: boolean;\n detectedBy: string[];\n skillsDir: string;\n wiresAgentsMd: boolean;\n home: string;\n}\n\n/**\n * Turn detection (or an explicit --harness override) into the ordered, de-duped\n * list of targets to write. Codex and the shared fallback both land in\n * ~/.agents/skills (the harness-shared Agent Skills location), so a request for\n * both collapses to one target keyed by that directory.\n */\nfunction resolvePlans(\n override: string[] | undefined,\n home: string,\n which: (bin: string) => boolean,\n): HarnessPlan[] {\n const claudeDir = join(home, '.claude', 'skills');\n const sharedDir = join(home, '.agents', 'skills');\n\n if (override !== undefined && override.length > 0) {\n const plans = override.map((v) =>\n planFor(validateHarness(v), ['override'], true, home, claudeDir, sharedDir),\n );\n return dedupeBySkillsDir(plans);\n }\n\n const plans: HarnessPlan[] = [];\n const claudeBy = detectReasons(existsSync(join(home, '.claude')), which('claude'));\n const codexBy = detectReasons(existsSync(join(home, '.codex')), which('codex'));\n if (claudeBy.length > 0)\n plans.push(planFor('claude', claudeBy, true, home, claudeDir, sharedDir));\n if (codexBy.length > 0) plans.push(planFor('codex', codexBy, true, home, claudeDir, sharedDir));\n if (plans.length === 0) {\n // Nothing detected: the shared Agent Skills location is the fallback target, so\n // a harness installed later still finds the skills.\n plans.push(planFor('shared', ['fallback'], false, home, claudeDir, sharedDir));\n }\n return dedupeBySkillsDir(plans);\n}\n\nfunction detectReasons(homeDirPresent: boolean, onPathPresent: boolean): string[] {\n const reasons: string[] = [];\n if (homeDirPresent) reasons.push('home-dir');\n if (onPathPresent) reasons.push('binary');\n return reasons;\n}\n\nfunction planFor(\n harness: Harness,\n detectedBy: string[],\n detected: boolean,\n home: string,\n claudeDir: string,\n sharedDir: string,\n): HarnessPlan {\n const skillsDir = harness === 'claude' ? claudeDir : sharedDir;\n return { harness, detected, detectedBy, skillsDir, wiresAgentsMd: harness !== 'claude', home };\n}\n\nfunction dedupeBySkillsDir(plans: HarnessPlan[]): HarnessPlan[] {\n const seen = new Set<string>();\n const out: HarnessPlan[] = [];\n for (const p of plans) {\n if (seen.has(p.skillsDir)) continue;\n seen.add(p.skillsDir);\n out.push(p);\n }\n return out;\n}\n\nfunction validateHarness(value: string): Harness {\n if ((HARNESSES as readonly string[]).includes(value)) return value as Harness;\n throw new CliError('USAGE', `Unknown harness \"${value}\"`, {\n fix: `--harness must be one of: ${HARNESSES.join(', ')}.`,\n });\n}\n\n// --- Applying a plan -------------------------------------------------------------\n\nasync function applyPlan(\n plan: HarnessPlan,\n skillsSource: string,\n dryRun: boolean,\n): Promise<HarnessResult> {\n const skills: SkillResult[] = [];\n const warnings: string[] = [];\n for (const name of SKILL_NAMES) {\n const { status, warning } = await installSkill(\n join(skillsSource, name),\n join(plan.skillsDir, name),\n dryRun,\n );\n skills.push({ name, status });\n if (warning !== undefined) warnings.push(warning);\n }\n\n const result: HarnessResult = {\n harness: plan.harness,\n detected: plan.detected,\n detectedBy: plan.detectedBy,\n skillsDir: plan.skillsDir,\n skills,\n notes: notesFor(plan),\n warnings,\n };\n\n if (plan.wiresAgentsMd) {\n result.agentsMd = await wireAgentsMd(plan, dryRun);\n result.codexNetworkRule = CODEX_NETWORK_RULE;\n }\n return result;\n}\n\nfunction notesFor(plan: HarnessPlan): string[] {\n if (plan.harness === 'claude') {\n return [\n 'Installed at the user level (~/.claude/skills). The Claude Code plugin marketplace (roadmap C3) will supersede this path for Claude users.',\n ];\n }\n return [\n 'Copied into the shared Agent Skills location (~/.agents/skills). Codex and any Agent-Skills-compatible harness read it there.',\n ];\n}\n\n/**\n * Copy one skill directory. The packaged copy is canonical: an absent target is\n * `installed`, an identical target is `up-to-date`, and any local drift is\n * overwritten and reported as `updated` with a warning. On --dry-run nothing is\n * written and the status reads `would-*`.\n */\nasync function installSkill(\n srcDir: string,\n destDir: string,\n dryRun: boolean,\n): Promise<{ status: SkillResult['status']; warning?: string }> {\n const src = await readTree(srcDir);\n const dest = await readTree(destDir);\n if (src === null) {\n // assertSkillsSource already guards SKILL.md; this is defensive for an empty dir.\n throw new CliError('INTERNAL', `Packaged skill source ${srcDir} is empty`);\n }\n\n const change = dest === null ? 'create' : treesEqual(src, dest) ? 'none' : 'update';\n\n if (!dryRun && change !== 'none') {\n // Overwrite wholesale so the packaged copy is exactly what lands, with no stray\n // local files left behind. rm is a no-op when the dir is absent.\n await rm(destDir, { recursive: true, force: true });\n for (const [rel, content] of src) {\n await writeFileAtomic(join(destDir, rel), content);\n }\n }\n\n if (change === 'create') return { status: dryRun ? 'would-install' : 'installed' };\n if (change === 'none') return { status: 'up-to-date' };\n return {\n status: dryRun ? 'would-update' : 'updated',\n warning: `${destDir}: local skill copy differed and was ${dryRun ? 'would be ' : ''}overwritten (the packaged copy is canonical).`,\n };\n}\n\n/**\n * Read a directory tree into a rel-path -> content map, or null when it does not\n * exist. Reads as raw `Buffer`, not `utf8`: today's skills are markdown-only, but\n * this is a general recursive dir-copy, and decoding to a string here would\n * silently corrupt a future non-text asset (an image, a font) on write, or worse,\n * make two different corrupted binaries both decode to U+FFFD and compare equal.\n */\nasync function readTree(dir: string): Promise<Map<string, Buffer> | null> {\n if (!existsSync(dir)) return null;\n const entries = await readdir(dir, { recursive: true, withFileTypes: true });\n const files = new Map<string, Buffer>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const full = join(entry.parentPath, entry.name);\n files.set(relative(dir, full), await readFile(full));\n }\n return files;\n}\n\nfunction treesEqual(a: Map<string, Buffer>, b: Map<string, Buffer> | null): boolean {\n if (b === null) return false;\n if (a.size !== b.size) return false;\n for (const [k, v] of a) {\n const other = b.get(k);\n if (other === undefined || !v.equals(other)) return false;\n }\n return true;\n}\n\n/**\n * Ensure the AGENTS.md pointer line is present exactly once. Append-once is GLOBAL\n * across both locations Codex/harnesses read (~/.agents/AGENTS.md and Codex's own\n * ~/.codex/AGENTS.md): if either already carries the marker we stop, so a pointer\n * already in ~/.codex/AGENTS.md is never duplicated into a later-created\n * ~/.agents/AGENTS.md. When neither has it, target selection follows what Codex\n * actually reads: prefer an existing ~/.agents/AGENTS.md, else an existing\n * ~/.codex/AGENTS.md, else create the one whose home dir exists, else fall back to\n * ~/.agents/AGENTS.md alongside the shared skills.\n */\nasync function wireAgentsMd(plan: HarnessPlan, dryRun: boolean): Promise<AgentsMdResult> {\n const shared = join(plan.home, '.agents', 'AGENTS.md');\n const codex = join(plan.home, '.codex', 'AGENTS.md');\n const line = `${AGENTS_MARKER} Tenjin agent skills are installed at ${plan.skillsDir} (tenjin-search, tenjin-publish, tenjin). Read the relevant SKILL.md before using the tenjin CLI.`;\n\n for (const path of [shared, codex]) {\n if (existsSync(path) && (await readFile(path, 'utf8')).includes(AGENTS_MARKER)) {\n return { path, status: 'already-present' };\n }\n }\n\n const path = chooseAgentsMdPath(plan.home);\n if (dryRun) return { path, status: 'would-append' };\n\n const existing = existsSync(path) ? await readFile(path, 'utf8') : null;\n const prefix = existing === null || existing.length === 0 || existing.endsWith('\\n') ? '' : '\\n';\n await writeFileAtomic(path, `${existing ?? ''}${prefix}${line}\\n`);\n return { path, status: 'appended' };\n}\n\nfunction chooseAgentsMdPath(home: string): string {\n const shared = join(home, '.agents', 'AGENTS.md');\n const codex = join(home, '.codex', 'AGENTS.md');\n if (existsSync(shared)) return shared;\n if (existsSync(codex)) return codex;\n if (existsSync(join(home, '.codex'))) return codex;\n return shared;\n}\n\n// --- PATH probe ------------------------------------------------------------------\n\n/**\n * Is `bin` a real executable file on PATH? Gates on statSync().isFile() so a\n * same-named DIRECTORY on PATH never false-positives as the binary, and probes the\n * PATHEXT extensions on win32 where the real binary is `claude.cmd`/`claude.exe`\n * rather than a bare `claude`.\n */\nfunction onPath(bin: string, env: NodeJS.ProcessEnv): boolean {\n const raw = env.PATH ?? '';\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of raw.split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (isFile(join(part, bin + ext))) return true;\n }\n }\n return false;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\n// --- Human rendering -------------------------------------------------------------\n\nfunction renderHuman(\n io: Io,\n harnesses: HarnessResult[],\n doctor: DoctorChecks,\n dryRun: boolean,\n): string[] {\n const lines: string[] = [];\n if (dryRun) lines.push(paint(io, 'yellow', 'dry run: no files written'));\n for (const h of harnesses) {\n const how = h.detectedBy.length > 0 ? ` (${h.detectedBy.join(', ')})` : '';\n lines.push(paint(io, 'bold', `${h.harness}${how} -> ${h.skillsDir}`));\n for (const s of h.skills) {\n lines.push(` ${skillIcon(io, s.status)} ${s.name.padEnd(14)} ${paint(io, 'dim', s.status)}`);\n }\n if (h.agentsMd !== undefined) {\n lines.push(` ${paint(io, 'dim', `AGENTS.md ${h.agentsMd.status}: ${h.agentsMd.path}`)}`);\n }\n for (const w of h.warnings) lines.push(` ${paint(io, 'yellow', `! ${w}`)}`);\n for (const n of h.notes) lines.push(` ${paint(io, 'dim', n)}`);\n if (h.codexNetworkRule !== undefined) {\n lines.push(\n paint(\n io,\n 'dim',\n \" Codex's default workspace-write sandbox blocks network, which breaks paid x402 calls.\",\n ),\n );\n lines.push(paint(io, 'dim', ' Add this to ~/.codex/config.toml:'));\n for (const rl of h.codexNetworkRule.split('\\n')) lines.push(` ${rl}`);\n }\n }\n lines.push('');\n lines.push(paint(io, 'bold', 'doctor (final checks):'));\n lines.push(...renderDoctorHuman(io, doctor.checks));\n if (doctor.failure !== undefined) {\n lines.push(paint(io, 'yellow', 'doctor reported a problem above; the skills are still wired.'));\n }\n return lines;\n}\n\nfunction skillIcon(io: Io, status: SkillResult['status']): string {\n if (status === 'up-to-date') return paint(io, 'green', '=');\n if (status === 'updated' || status === 'would-update') return paint(io, 'yellow', '~');\n return paint(io, 'green', '+');\n}\n\nfunction paint(io: Io, format: Parameters<typeof styleText>[0], text: string): string {\n if (io.stderr instanceof Stream) return styleText(format, text, { stream: io.stderr });\n return styleText(format, text);\n}\n\n// --- Skills source guard ---------------------------------------------------------\n\nasync function assertSkillsSource(dir: string): Promise<void> {\n for (const name of SKILL_NAMES) {\n if (!existsSync(join(dir, name, 'SKILL.md'))) {\n throw new CliError('INTERNAL', `Packaged skill \"${name}\" is missing under ${dir}`, {\n fix: 'Reinstall tenjin-cli; the published package must ship every skill under skills/.',\n });\n }\n }\n}\n","import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * The packaged skills `install` copies into every target harness. All three go to\n * every target: `tenjin` (the zero-install curriculum, works with no CLI),\n * `tenjin-search` and `tenjin-publish` (thin CLI adapters). Order is the install\n * order and the human-render order.\n */\nexport const SKILL_NAMES = ['tenjin-search', 'tenjin-publish', 'tenjin'] as const;\nexport type SkillName = (typeof SKILL_NAMES)[number];\n\n// A `skills/` directory is the real one iff it holds `tenjin/SKILL.md`; a bare\n// `skills/` created for some other reason up the tree can't false-positive.\nconst SENTINEL = join('tenjin', 'SKILL.md');\n\n/**\n * Locate the packaged `skills/` directory by walking up from `startDir`. This has\n * to work in two layouts from one resolver: a global npm install where the module\n * lives in `dist/` with `skills/` a sibling (the `files` array ships it), and a\n * repo/source run where the module is under `src/` and `skills/` sits at the repo\n * root. Walking up until a `skills/` with the sentinel appears covers both without\n * hard-coding either depth. Sync (existsSync) on purpose: this is one-shot path\n * resolution at command start, the same shape as `require.resolve`.\n */\nexport function resolveSkillsSource(startDir: string): string {\n let dir = startDir;\n for (let i = 0; i < 8; i += 1) {\n const candidate = join(dir, 'skills');\n if (existsSync(join(candidate, SENTINEL))) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new CliError('INTERNAL', 'Could not locate the packaged Tenjin skills directory', {\n fix: 'Reinstall tenjin-cli; the published package must ship the skills/ directory (files array).',\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KAA4B;AAC5D,aAAW,QAAQ,aAAa;AAC9B,QAAI,CAACE,YAAWF,MAAK,KAAK,MAAM,UAAU,CAAC,GAAG;AAC5C,YAAM,IAAI,SAAS,YAAY,mBAAmB,IAAI,sBAAsB,GAAG,IAAI;AAAA,QACjF,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["existsSync","join","join","plans","existsSync","path"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/lookup.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { parseUsdToAtomic } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildLookupRequest, postLookup, type LookupInput } from '../lib/agent-api';\nimport { recordLookup } from '../lib/lookup-store';\nimport { assertOnBaseOrigin } from '../lib/resource-ref';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin lookup \"<question>\"`, one POST to /api/agent/lookup. Prints the compact\n * CANDIDATES/MISS response verbatim (spec 10), and records the lookupId +\n * candidates locally so `outcome --last` and `buy <resourceId>` can use them. No\n * wallet, no signing: lookup is anonymous.\n */\n\nexport interface LookupArgs {\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 LookupDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runLookup(\n args: LookupArgs,\n ctx: CommandContext,\n deps: LookupDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const input: LookupInput = { question: args.question };\n if (args.maxPrice !== undefined) input.maxPrice = parseUsdToAtomic(args.maxPrice);\n if (args.freshWithin !== undefined) input.freshWithin = args.freshWithin;\n if (args.limit !== undefined) input.limit = parseLimit(args.limit);\n if (args.appliesTo !== undefined && args.appliesTo.length > 0) {\n input.appliesTo = parseAppliesTo(args.appliesTo);\n }\n\n const request = buildLookupRequest(input);\n const response = await postLookup(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, 'lookup candidate URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Lookup candidate ${c.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n await recordLookup(ctx.dataDir, {\n lookupId: response.lookupId,\n at: new Date().toISOString(),\n question: request.question,\n decision: response.decision,\n candidates: candidates.map((c) => ({\n resourceId: c.resourceId,\n url: c.url,\n title: c.title,\n price: c.price,\n })),\n });\n\n const humanLines =\n response.decision === 'MISS'\n ? [`MISS, no candidates (lookupId ${response.lookupId})`]\n : [\n `${candidates.length} candidate(s) (lookupId ${response.lookupId}):`,\n ...candidates.map(\n (c, i) =>\n ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${c.price} atomic, ${sanitizeForTerminal(c.url)}`,\n ),\n ];\n\n return { data: response, humanLines };\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,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,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;A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AC,EACZ,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAC7B,QAAI,OAAO,WAAW,GAAG;AACvB,YAAM,IAAI,SAAS,SAAS,gBAAgB,KAAK,UAAU,GAAG,CAAC,kBAAkB;AAAA,QAC/E,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,QAAI,GAAG,IAAI,CAAC,GAAI,IAAI,GAAG,KAAK,CAAC,GAAI,GAAG,MAAM;AAAA,EAC5C;AACA,SAAO;AACT;","names":[]}
@@ -1,66 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- latestLookup
4
- } from "./chunk-JPHG2JW3.js";
5
- import {
6
- buildOutcomeItem,
7
- postOutcomes
8
- } from "./chunk-YIYQ2ZNT.js";
9
- import "./chunk-3OV7E5G5.js";
10
- import "./chunk-QNP7H47L.js";
11
- import "./chunk-N62ROTMC.js";
12
- import {
13
- resolveContextSettings
14
- } from "./chunk-UPIEAMGH.js";
15
- import "./chunk-IYLHQMT5.js";
16
- import "./chunk-YBMMV4Y4.js";
17
- import "./chunk-UO22YNY4.js";
18
- import "./chunk-MUBUQVC3.js";
19
- import {
20
- CliError
21
- } from "./chunk-OYMYCW7J.js";
22
- import "./chunk-ZXTAQYNA.js";
23
-
24
- // src/commands/outcome.ts
25
- async function runOutcome(args, ctx, deps = {}) {
26
- const lookupId = await resolveLookupId(args, ctx);
27
- const item = buildOutcomeItem({
28
- status: args.status,
29
- ...args.resource !== void 0 ? { resourceId: args.resource } : {},
30
- ...args.contentHash !== void 0 ? { contentHash: args.contentHash } : {}
31
- });
32
- const settings = await resolveContextSettings(ctx);
33
- const result = await postOutcomes(lookupId, [item], {
34
- baseUrl: settings.baseUrl,
35
- timeoutMs: ctx.flags.timeout,
36
- ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
37
- });
38
- return {
39
- data: { lookupId, status: item.status, accepted: result.accepted },
40
- humanLines: [`Reported ${item.status} for lookup ${lookupId} (accepted ${result.accepted}).`]
41
- };
42
- }
43
- async function resolveLookupId(args, ctx) {
44
- if (args.lookupId !== void 0 && args.last === true) {
45
- throw new CliError("USAGE", "Pass either --lookup-id or --last, not both.", {
46
- fix: "Use --lookup-id <id> for a specific lookup, or --last for the most recent."
47
- });
48
- }
49
- if (args.lookupId !== void 0) return args.lookupId;
50
- if (args.last === true) {
51
- const latest = await latestLookup(ctx.dataDir);
52
- if (latest === null) {
53
- throw new CliError("LOOKUP_NOT_FOUND", "No local lookup to target with --last.", {
54
- fix: "Run `tenjin lookup` first, or pass --lookup-id <id>."
55
- });
56
- }
57
- return latest.lookupId;
58
- }
59
- throw new CliError("USAGE", "An outcome needs a lookup to report against.", {
60
- fix: "Pass --lookup-id <id> or --last."
61
- });
62
- }
63
- export {
64
- runOutcome
65
- };
66
- //# sourceMappingURL=outcome-HKKT6QIA.js.map
@@ -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 { latestLookup } from '../lib/lookup-store';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin outcome --lookup-id <id> --status <s>`, POST to\n * /api/agent/lookups/:id/outcomes, closing the reuse loop (used / partially_used\n * / rejected / regenerated / purchase_declined). The lookupId is the capability,\n * so no wallet is needed; `--last` sugar targets the most recent local lookup.\n */\n\nexport interface OutcomeArgs {\n lookupId?: 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 lookupId = await resolveLookupId(args, ctx);\n const item = buildOutcomeItem({\n status: args.status,\n ...(args.resource !== undefined ? { resourceId: args.resource } : {}),\n ...(args.contentHash !== undefined ? { contentHash: args.contentHash } : {}),\n });\n\n const settings = await resolveContextSettings(ctx);\n const result = await postOutcomes(lookupId, [item], {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n return {\n data: { lookupId, status: item.status, accepted: result.accepted },\n humanLines: [`Reported ${item.status} for lookup ${lookupId} (accepted ${result.accepted}).`],\n };\n}\n\nasync function resolveLookupId(args: OutcomeArgs, ctx: CommandContext): Promise<string> {\n if (args.lookupId !== undefined && args.last === true) {\n throw new CliError('USAGE', 'Pass either --lookup-id or --last, not both.', {\n fix: 'Use --lookup-id <id> for a specific lookup, or --last for the most recent.',\n });\n }\n if (args.lookupId !== undefined) return args.lookupId;\n if (args.last === true) {\n const latest = await latestLookup(ctx.dataDir);\n if (latest === null) {\n throw new CliError('LOOKUP_NOT_FOUND', 'No local lookup to target with --last.', {\n fix: 'Run `tenjin lookup` first, or pass --lookup-id <id>.',\n });\n }\n return latest.lookupId;\n }\n throw new CliError('USAGE', 'An outcome needs a lookup to report against.', {\n fix: 'Pass --lookup-id <id> or --last.',\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,eAAsB,WACpB,MACA,KACA,OAAoB,CAAC,GACG;AACxB,QAAM,WAAW,MAAM,gBAAgB,MAAM,GAAG;AAChD,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;AAED,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,SAAS,MAAM,aAAa,UAAU,CAAC,IAAI,GAAG;AA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