tenjin-cli 0.1.0-alpha.29 → 0.1.0-alpha.30

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 +7 -5
  2. package/dist/{chunk-25GGN553.js → chunk-3O2BQIF6.js} +86 -22
  3. package/dist/chunk-3O2BQIF6.js.map +1 -0
  4. package/dist/{chunk-R4AO7GC2.js → chunk-5LJCEMFD.js} +14 -12
  5. package/dist/{chunk-R4AO7GC2.js.map → chunk-5LJCEMFD.js.map} +1 -1
  6. package/dist/{chunk-QTGUDCIR.js → chunk-AEG2PXBP.js} +3 -3
  7. package/dist/{chunk-AMEUXNJT.js → chunk-AWFUPKTM.js} +2 -2
  8. package/dist/{chunk-XJQ6CH7X.js → chunk-EBVIKMCH.js} +2 -2
  9. package/dist/{chunk-XDYKZRLN.js → chunk-HE2MS4QO.js} +6 -6
  10. package/dist/{chunk-RJEPZMYY.js → chunk-IOODYAXL.js} +3 -3
  11. package/dist/{chunk-SBL4THYT.js → chunk-JMM6YE7J.js} +190 -90
  12. package/dist/chunk-JMM6YE7J.js.map +1 -0
  13. package/dist/{chunk-VKQXVCZR.js → chunk-KHE6L6TD.js} +3 -3
  14. package/dist/chunk-KOGZDMHO.js +21 -0
  15. package/dist/chunk-KOGZDMHO.js.map +1 -0
  16. package/dist/{chunk-TROZ6HL4.js → chunk-KYFZTGMC.js} +2 -2
  17. package/dist/{chunk-LX5OT4TQ.js → chunk-NZIP4PA2.js} +2 -2
  18. package/dist/chunk-O2FRQ2L2.js +168 -0
  19. package/dist/chunk-O2FRQ2L2.js.map +1 -0
  20. package/dist/{chunk-3FY5HG7R.js → chunk-OK2TDZQU.js} +4 -4
  21. package/dist/{chunk-ZQNGTLOC.js → chunk-OSYTBCUC.js} +7 -5
  22. package/dist/{chunk-ZQNGTLOC.js.map → chunk-OSYTBCUC.js.map} +1 -1
  23. package/dist/{chunk-MRUPDSUM.js → chunk-PAYV4XUA.js} +3 -5
  24. package/dist/chunk-PAYV4XUA.js.map +1 -0
  25. package/dist/{chunk-USOLCBKC.js → chunk-QUVVWYJW.js} +7 -5
  26. package/dist/{chunk-USOLCBKC.js.map → chunk-QUVVWYJW.js.map} +1 -1
  27. package/dist/{chunk-MOG7PB3A.js → chunk-RAULEAZ6.js} +3 -3
  28. package/dist/{chunk-MG3G644T.js → chunk-SPAVAYSW.js} +3 -3
  29. package/dist/{chunk-4FYMDRD3.js → chunk-TTBKWWTV.js} +22 -20
  30. package/dist/chunk-TTBKWWTV.js.map +1 -0
  31. package/dist/{chunk-OOSRB3OF.js → chunk-U6YQ6FRI.js} +2 -2
  32. package/dist/{chunk-P4LVLFO4.js → chunk-VFMQTSXG.js} +2 -2
  33. package/dist/{chunk-LRCJ2IZ5.js → chunk-VUFAK2LW.js} +2 -2
  34. package/dist/{chunk-LRCJ2IZ5.js.map → chunk-VUFAK2LW.js.map} +1 -1
  35. package/dist/{chunk-WM7TJEBP.js → chunk-VZGAONSJ.js} +7 -5
  36. package/dist/{chunk-WM7TJEBP.js.map → chunk-VZGAONSJ.js.map} +1 -1
  37. package/dist/{chunk-VVAHFCX2.js → chunk-WO5BJNIB.js} +45 -194
  38. package/dist/chunk-WO5BJNIB.js.map +1 -0
  39. package/dist/chunk-WVUSXNIE.js +39 -0
  40. package/dist/chunk-WVUSXNIE.js.map +1 -0
  41. package/dist/chunk-XKESD27X.js +10 -0
  42. package/dist/chunk-XKESD27X.js.map +1 -0
  43. package/dist/{chunk-SFEQGENI.js → chunk-YFQOA5AU.js} +7 -2
  44. package/dist/{chunk-SFEQGENI.js.map → chunk-YFQOA5AU.js.map} +1 -1
  45. package/dist/{cli-JPTDHGRX.js → cli-O5SN7ZJ4.js} +38 -30
  46. package/dist/{cli-JPTDHGRX.js.map → cli-O5SN7ZJ4.js.map} +1 -1
  47. package/dist/{config-YYKDH2TH.js → config-OJQI27LT.js} +13 -12
  48. package/dist/{doctor-SSTXGCHX.js → doctor-IQQJHGGM.js} +36 -62
  49. package/dist/doctor-IQQJHGGM.js.map +1 -0
  50. package/dist/{fund-QWVWRVDK.js → fund-WEV6DMTD.js} +17 -12
  51. package/dist/{fund-QWVWRVDK.js.map → fund-WEV6DMTD.js.map} +1 -1
  52. package/dist/hook-command-D2P3ILRV.js +32 -0
  53. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  54. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  55. package/dist/index.js +4 -4
  56. package/dist/{install-2GXXD4DK.js → install-TUCRF32I.js} +23 -14
  57. package/dist/{install-identity-FK3YF227.js → install-identity-WHPNMNMQ.js} +7 -6
  58. package/dist/{install-wallet-TC22U52X.js → install-wallet-MA27FTQ5.js} +11 -10
  59. package/dist/{install-wallet-TC22U52X.js.map → install-wallet-MA27FTQ5.js.map} +1 -1
  60. package/dist/{mcp-42H2F4NY.js → mcp-QML7ZMPH.js} +33 -40
  61. package/dist/mcp-QML7ZMPH.js.map +1 -0
  62. package/dist/{package-6DJA3Y2O.js → package-LGKYOEPV.js} +2 -2
  63. package/dist/{pay-LSDJBIAZ.js → pay-2C2UBBXJ.js} +14 -13
  64. package/dist/{payments-SPECLBRQ.js → payments-C44QUFXU.js} +10 -9
  65. package/dist/{payments-SPECLBRQ.js.map → payments-C44QUFXU.js.map} +1 -1
  66. package/dist/{send-MHAOLPK3.js → send-KVJX4XIR.js} +9 -8
  67. package/dist/{send-MHAOLPK3.js.map → send-KVJX4XIR.js.map} +1 -1
  68. package/dist/{status-O2RWLPS5.js → status-S7C3WMSH.js} +10 -9
  69. package/dist/{status-O2RWLPS5.js.map → status-S7C3WMSH.js.map} +1 -1
  70. package/dist/{status-line-45TVCRM3.js → status-line-YR2T5HC4.js} +6 -5
  71. package/dist/{status-line-45TVCRM3.js.map → status-line-YR2T5HC4.js.map} +1 -1
  72. package/dist/{uninstall-VOK2Z5M4.js → uninstall-HY6LKIIT.js} +17 -14
  73. package/dist/{uninstall-VOK2Z5M4.js.map → uninstall-HY6LKIIT.js.map} +1 -1
  74. package/dist/{update-FGP3HNLD.js → update-OJV22LR3.js} +17 -14
  75. package/dist/usdc-JK4RRFFQ.js +39 -0
  76. package/dist/{wallet-DA7OFNEW.js → wallet-PD2IMZDU.js} +11 -10
  77. package/dist/wallet-PD2IMZDU.js.map +1 -0
  78. package/docs/agent-permissions.md +16 -4
  79. package/package.json +1 -1
  80. package/dist/chunk-25GGN553.js.map +0 -1
  81. package/dist/chunk-4FYMDRD3.js.map +0 -1
  82. package/dist/chunk-EWLU46J6.js +0 -100
  83. package/dist/chunk-EWLU46J6.js.map +0 -1
  84. package/dist/chunk-MRUPDSUM.js.map +0 -1
  85. package/dist/chunk-SBL4THYT.js.map +0 -1
  86. package/dist/chunk-VVAHFCX2.js.map +0 -1
  87. package/dist/doctor-SSTXGCHX.js.map +0 -1
  88. package/dist/hook-command-VWJXRT7H.js +0 -31
  89. package/dist/mcp-42H2F4NY.js.map +0 -1
  90. /package/dist/{chunk-QTGUDCIR.js.map → chunk-AEG2PXBP.js.map} +0 -0
  91. /package/dist/{chunk-AMEUXNJT.js.map → chunk-AWFUPKTM.js.map} +0 -0
  92. /package/dist/{chunk-XJQ6CH7X.js.map → chunk-EBVIKMCH.js.map} +0 -0
  93. /package/dist/{chunk-XDYKZRLN.js.map → chunk-HE2MS4QO.js.map} +0 -0
  94. /package/dist/{chunk-RJEPZMYY.js.map → chunk-IOODYAXL.js.map} +0 -0
  95. /package/dist/{chunk-VKQXVCZR.js.map → chunk-KHE6L6TD.js.map} +0 -0
  96. /package/dist/{chunk-TROZ6HL4.js.map → chunk-KYFZTGMC.js.map} +0 -0
  97. /package/dist/{chunk-LX5OT4TQ.js.map → chunk-NZIP4PA2.js.map} +0 -0
  98. /package/dist/{chunk-3FY5HG7R.js.map → chunk-OK2TDZQU.js.map} +0 -0
  99. /package/dist/{chunk-MOG7PB3A.js.map → chunk-RAULEAZ6.js.map} +0 -0
  100. /package/dist/{chunk-MG3G644T.js.map → chunk-SPAVAYSW.js.map} +0 -0
  101. /package/dist/{chunk-OOSRB3OF.js.map → chunk-U6YQ6FRI.js.map} +0 -0
  102. /package/dist/{chunk-P4LVLFO4.js.map → chunk-VFMQTSXG.js.map} +0 -0
  103. /package/dist/{config-YYKDH2TH.js.map → config-OJQI27LT.js.map} +0 -0
  104. /package/dist/{hook-command-VWJXRT7H.js.map → hook-command-D2P3ILRV.js.map} +0 -0
  105. /package/dist/{install-2GXXD4DK.js.map → install-TUCRF32I.js.map} +0 -0
  106. /package/dist/{install-identity-FK3YF227.js.map → install-identity-WHPNMNMQ.js.map} +0 -0
  107. /package/dist/{package-6DJA3Y2O.js.map → package-LGKYOEPV.js.map} +0 -0
  108. /package/dist/{pay-LSDJBIAZ.js.map → pay-2C2UBBXJ.js.map} +0 -0
  109. /package/dist/{update-FGP3HNLD.js.map → update-OJV22LR3.js.map} +0 -0
  110. /package/dist/{wallet-DA7OFNEW.js.map → usdc-JK4RRFFQ.js.map} +0 -0
@@ -0,0 +1,39 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/router/names.ts
4
+ var PLUGIN_NAME = "tenjin";
5
+ var MCP_SERVER_NAME = "router";
6
+ var MARKETPLACE_NAME = "tenjin";
7
+ var PLUGIN_ID = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;
8
+ var SKILLS_DIR_PLUGIN_ID = `${PLUGIN_NAME}@skills-dir`;
9
+ var PLUGIN_SERVER = `plugin:${PLUGIN_NAME}:${MCP_SERVER_NAME}`;
10
+ var TOOL_PREFIX = `mcp__plugin_${PLUGIN_NAME}_${MCP_SERVER_NAME}`;
11
+ var REQUEST_TOOL = `${TOOL_PREFIX}__request`;
12
+ var PLUGIN_HOOK_TOOL = `${TOOL_PREFIX}__hook`;
13
+ var LEGACY_MCP_SERVER_NAME = "x402";
14
+ var LEGACY_REQUEST_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__request`;
15
+ var LEGACY_HOOK_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__hook`;
16
+ function launchedByPlugin(env = process.env) {
17
+ const root = env.CLAUDE_PLUGIN_ROOT;
18
+ return typeof root === "string" && root.length > 0;
19
+ }
20
+ function requestToolName(env = process.env) {
21
+ return launchedByPlugin(env) ? REQUEST_TOOL : LEGACY_REQUEST_TOOL;
22
+ }
23
+
24
+ export {
25
+ PLUGIN_NAME,
26
+ MCP_SERVER_NAME,
27
+ MARKETPLACE_NAME,
28
+ PLUGIN_ID,
29
+ SKILLS_DIR_PLUGIN_ID,
30
+ PLUGIN_SERVER,
31
+ REQUEST_TOOL,
32
+ PLUGIN_HOOK_TOOL,
33
+ LEGACY_MCP_SERVER_NAME,
34
+ LEGACY_REQUEST_TOOL,
35
+ LEGACY_HOOK_TOOL,
36
+ launchedByPlugin,
37
+ requestToolName
38
+ };
39
+ //# sourceMappingURL=chunk-WVUSXNIE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/names.ts"],"sourcesContent":["/**\n * THE NAMES THE HARNESS KNOWS THE ROUTER BY, spelled once. `install` registers\n * the Claude Code plugin {@link PLUGIN_NAME}, whose MCP server is\n * {@link MCP_SERVER_NAME}, and Claude Code names a plugin's tools\n * `mcp__plugin_<plugin>_<server>__<tool>`. The plugin's hooks, the server's own\n * name and every hint line the hooks inject read these, so a rename moves them\n * together.\n *\n * A module of its own because the hooks need the tool name and must not load\n * `install` to get it: their chunk graph is the product's floor.\n */\nexport const PLUGIN_NAME = 'tenjin';\nexport const MCP_SERVER_NAME = 'router';\n/** The marketplace `install` adds from the package, so the plugin id is `tenjin@tenjin`. */\nexport const MARKETPLACE_NAME = 'tenjin';\nexport const PLUGIN_ID = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;\n/** The id Claude Code gives the same plugin loaded from a skills-directory folder. */\nexport const SKILLS_DIR_PLUGIN_ID = `${PLUGIN_NAME}@skills-dir`;\n/** How a plugin's `hooks.json` and `claude mcp` name the plugin's own server. */\nexport const PLUGIN_SERVER = `plugin:${PLUGIN_NAME}:${MCP_SERVER_NAME}`;\nconst TOOL_PREFIX = `mcp__plugin_${PLUGIN_NAME}_${MCP_SERVER_NAME}`;\nexport const REQUEST_TOOL = `${TOOL_PREFIX}__request`;\n/** The tool the plugin's hook legs call, which its own deny hook keeps from the model. */\nexport const PLUGIN_HOOK_TOOL = `${TOOL_PREFIX}__hook`;\n\n/**\n * THE SETTINGS-BASED INSTALL'S NAMES, for its migration and nothing else.\n * Releases up to alpha.26 registered the server as `x402` through `claude mcp\n * add` and wrote seven hook entries and two permission rules into settings.json.\n *\n * SHIM: remove on or after 2026-12-01, the first release cut 30 or more days\n * after the plugin PR 2 ships. Doctor keeps naming an unmigrated machine after.\n */\nexport const LEGACY_MCP_SERVER_NAME = 'x402';\nexport const LEGACY_REQUEST_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__request`;\nexport const LEGACY_HOOK_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__hook`;\n\n/**\n * Is this process one Claude Code launched from the plugin? Claude Code sets\n * `CLAUDE_PLUGIN_ROOT` for a plugin's MCP server and its command hooks\n * (checked on 2.1.296), and not for a server registered in `~/.claude.json`.\n */\nexport function launchedByPlugin(env: NodeJS.ProcessEnv = process.env): boolean {\n const root = env.CLAUDE_PLUGIN_ROOT;\n return typeof root === 'string' && root.length > 0;\n}\n\n/**\n * The request tool's name as THIS process's harness exposes it: the plugin's\n * tool for a server the plugin launched, and the `x402` server's tool for one a\n * settings install launched, so an offer line never names a tool the model\n * does not have.\n *\n * SHIM: the second branch goes on or after 2026-12-01 (see\n * {@link LEGACY_MCP_SERVER_NAME}); the name is then always {@link REQUEST_TOOL}.\n */\nexport function requestToolName(env: NodeJS.ProcessEnv = process.env): string {\n return launchedByPlugin(env) ? REQUEST_TOOL : LEGACY_REQUEST_TOOL;\n}\n"],"mappings":";;;AAWO,IAAM,cAAc;AACpB,IAAM,kBAAkB;AAExB,IAAM,mBAAmB;AACzB,IAAM,YAAY,GAAG,WAAW,IAAI,gBAAgB;AAEpD,IAAM,uBAAuB,GAAG,WAAW;AAE3C,IAAM,gBAAgB,UAAU,WAAW,IAAI,eAAe;AACrE,IAAM,cAAc,eAAe,WAAW,IAAI,eAAe;AAC1D,IAAM,eAAe,GAAG,WAAW;AAEnC,IAAM,mBAAmB,GAAG,WAAW;AAUvC,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB,QAAQ,sBAAsB;AAC1D,IAAM,mBAAmB,QAAQ,sBAAsB;AAOvD,SAAS,iBAAiB,MAAyB,QAAQ,KAAc;AAC9E,QAAM,OAAO,IAAI;AACjB,SAAO,OAAO,SAAS,YAAY,KAAK,SAAS;AACnD;AAWO,SAAS,gBAAgB,MAAyB,QAAQ,KAAa;AAC5E,SAAO,iBAAiB,GAAG,IAAI,eAAe;AAChD;","names":[]}
@@ -0,0 +1,10 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/grade.ts
4
+ var ENDED_AFTER_MS = 30 * 6e4;
5
+ var AGENT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
6
+
7
+ export {
8
+ AGENT_ID_RE
9
+ };
10
+ //# sourceMappingURL=chunk-XKESD27X.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/grade.ts"],"sourcesContent":["import { CliError } from './errors';\n\n/**\n * Did the agent USE what a hook arm showed it? The transcript is the only place\n * that answer exists.\n *\n * The arms record what they delivered (`fires`/`legs`), and the shelf records\n * what it served, but neither can see what happened next: the finding lands as\n * additional context in the agent's turn, and from there it is either acted on\n * or it is not. Nobody reports that, so without this the loop has no measure of\n * its own precision.\n *\n * WHAT COUNTS AS EVIDENCE, and why it is only ever a TOOL INPUT. An agent that\n * says \"as the Tenjin note suggests\" in prose has said nothing checkable — the\n * words are cheap, the sentence is generated beside a hundred others, and prose\n * agreeing with an injection is exactly what an injection makes likely whether\n * or not it helped. A tool call is a decision the agent spent something on. So\n * this reads two kinds of row and no others: the `hook_additional_context`\n * attachment that carries the injection (the anchor), and every later\n * `tool_use` block's input, serialized whole so a command, an edit's new text\n * and a written file all read the same way.\n *\n * THREE VERDICTS FOR \"USED\", TWO WEAK. Explicit `tenjin read|inspect <id>`, or\n * the injected url appearing in a tool input, is the agent following the\n * pointer: that is `read`, and it counts anywhere later in the session,\n * because a piece bought twenty tool calls after it was shown is still a piece\n * the injection sold. A backtick span copied out of the injected text is much\n * weaker — it may be a command the agent would have run anyway — so it counts\n * only inside {@link SPAN_WINDOW} tool calls of the anchor, needs at least two\n * words, and is reported to the shelf as `partially_used` rather than `used`.\n * `likely` is weaker again: a command head or file basename named anywhere in\n * the note's prose, with no backticks at all, matched the same way and ranked\n * below `span` — see {@link likelyTokens}.\n *\n * A SPAN OR A LIKELY TOKEN IS EXCLUDED WHEN THE SESSION ALREADY USED IT BEFORE\n * THE INJECTION (tenjin-agent#254a). Boilerplate a machine writes into every\n * subagent work order — `CI=true pnpm format:check` and the like — will always\n * reappear in the next tool call whether or not the injection ran, so a match\n * that cannot see behind the anchor cannot tell \"copied because shown\" from\n * \"was going to type this anyway\". `judge()` is handed the {@link SPAN_WINDOW}\n * tool calls BEFORE the anchor as well as after, and a candidate already\n * present there earns no credit — matched at a token boundary, not by plain\n * substring, so a longer pre-injection token cannot erase credit for a\n * shorter genuine one. This applies to `span` and `likely` only: `read` is a\n * command naming this specific piece, which nothing pre-injection could have\n * done by coincidence.\n *\n * NOTHING IS NOT REJECTION UNTIL THE SESSION IS OVER. A row whose session is\n * still running has simply not been answered yet, and grading it `rejected`\n * would post a verdict the next tool call could contradict. So \"nothing matched\"\n * becomes `rejected` only once the session has ended — `sessions.ended_at`, or a\n * transcript nothing has written to for {@link ENDED_AFTER_MS}.\n *\n * RELAYED ROWS ANCHOR ON THE FIRST TOOL CALL. The subagent arm hands its finding\n * to a child at SubagentStart, and that text reaches no transcript at all: the\n * child is given it as its opening context, and neither the parent's file nor\n * the child's records a `hook_additional_context` row for it. So there is no\n * anchor to find, and there does not need to be — the pointer preceded every\n * call the child ever made, which makes the child's FIRST tool call evidence\n * rather than the row after the anchor. {@link gradeRelayed} judges from there,\n * inclusively, while {@link gradeInjection} keeps its exclusive `anchor + 1`.\n *\n * A relayed row also has no injected text on disk to take spans from — the arm\n * renders a title, a price and possibly a fetched body, and stores none of it —\n * so its span evidence comes from the piece's TITLE alone, which is usually no\n * spans at all. Relayed findings are therefore judged almost entirely on the\n * strong evidence (an explicit read, or the url), which is the right way round.\n * Storing the injected text is a second schema change and is not this one.\n *\n * The functions here are pure over parsed rows, except the two that touch the\n * filesystem at the bottom; the command in commands/grade.ts owns the store.\n */\n\n/** How many tool calls after the anchor a copied span may still be evidence. */\nexport const SPAN_WINDOW = 10;\n\n/** A transcript nothing has appended to for this long belongs to a session that\n * is over, whether or not a Stop hook ever stamped `ended_at` (a crashed or\n * killed harness never does). */\nexport const ENDED_AFTER_MS = 30 * 60_000;\n\n/** How many tool inputs `--explain` shows for a rejected row, and how much of\n * each: enough to see what the agent did instead, not a transcript dump. */\nconst EVIDENCE_ROWS = 3;\nconst EVIDENCE_CHARS = 200;\n\n/** A session id is used as a filename, so it is checked like one. */\nconst SESSION_ID_RE = /^[A-Za-z0-9-]{1,80}$/;\n\n/**\n * An agent id becomes a filename too (`agent-<id>.jsonl`), so it gets the same\n * treatment as a session id.\n *\n * THE ONLY DEFINITION, and every other reader takes it from here rather than\n * restating it: `prelude` interpolates it into the rendered scripts, where\n * `identityOf` and the capture ask's flag splice both read that one declaration,\n * and `publish --agent` tests against this constant directly. The splice and\n * `--agent` used to share a wider `shell-safe` copy admitting `.` and `:` on the\n * reasoning that only shell metacharacters matter in a command line: `:` is the\n * separator `agentKey` joins on, so an id carrying one keys a child's rows into\n * another child's range, and an id one reader accepts and another refuses is a\n * row that can never be graded or reported.\n */\nexport const AGENT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** The only two row kinds that decide anything; see the module note. */\nexport interface TranscriptRow {\n /** 1-based line number in the JSONL, for `--explain`. */\n line: number;\n kind: 'context' | 'tool_use';\n text: string;\n}\n\nexport interface GradeTarget {\n resourceId: string | null;\n url: string | null;\n title: string | null;\n}\n\nexport type Verdict =\n | { outcome: 'used'; by: 'read' | 'span' | 'likely'; evidence: string }\n | { outcome: 'rejected'; by: 'none'; evidence: string[] }\n | { outcome: 'unobserved'; by: 'none' }\n /** Still open: the session may yet answer, so nothing is written. */\n | { outcome: null; evidence: string[] };\n\n/**\n * The transcript, reduced to the rows that can decide a verdict.\n *\n * A malformed line is skipped rather than failing the parse: a transcript being\n * appended to while this runs can end mid-line, and one truncated row is not a\n * reason to refuse to grade a session.\n *\n * `isCompactSummary` rows are dropped. A compaction REPLAYS earlier tool calls\n * into a summary the assistant then carries, so counting them would let one\n * injection be \"used\" by the echo of a call that happened before it was shown.\n */\nexport function parseTranscript(jsonl: string): TranscriptRow[] {\n const rows: TranscriptRow[] = [];\n const lines = jsonl.split('\\n');\n for (let i = 0; i < lines.length; i += 1) {\n const raw = lines[i];\n if (raw === undefined || raw.length === 0) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n continue;\n }\n if (!isRecord(parsed)) continue;\n const line = i + 1;\n const attachment = parsed.attachment;\n if (isRecord(attachment) && attachment.type === 'hook_additional_context') {\n rows.push({ line, kind: 'context', text: contextText(attachment.content) });\n continue;\n }\n if (parsed.type !== 'assistant' || parsed.isCompactSummary === true) continue;\n const message = parsed.message;\n if (!isRecord(message) || !Array.isArray(message.content)) continue;\n for (const block of message.content) {\n if (!isRecord(block) || block.type !== 'tool_use') continue;\n rows.push({ line, kind: 'tool_use', text: JSON.stringify(block.input ?? null) });\n }\n }\n return rows;\n}\n\n/**\n * Where the injection landed, as an index into `rows`, or -1.\n *\n * THE FIRST MATCH, not the nearest one after the row's timestamp. The\n * `injections_shown_once` index makes one injected row per (session,\n * resourceId), so there is only ever one context row naming a given piece, and\n * matching it by content beats matching it by clock: the hook's `at` and the\n * transcript's line order are written by different processes.\n *\n * Id, then url, then title, weakest last: a title is display text that could\n * appear in an unrelated context row, so it is what is tried when the piece has\n * nothing more specific to be found by.\n */\nexport function findAnchor(rows: TranscriptRow[], target: GradeTarget): number {\n for (const needle of [target.resourceId, target.url, target.title]) {\n if (needle === null || needle.length === 0) continue;\n const at = rows.findIndex((row) => row.kind === 'context' && row.text.includes(needle));\n if (at !== -1) return at;\n }\n return -1;\n}\n\n/**\n * The backtick spans in the injected text worth looking for later: at least two\n * whitespace-separated words, deduped.\n *\n * TWO WORDS IS THE FLOOR because one is noise. A note names `pnpm`, `useEffect`\n * or a filename, the agent types the same token in the next command, and a\n * one-word rule calls that reuse — on a machine where the agent was going to\n * type it anyway. Two words is a phrase somebody copied.\n */\nexport function backtickSpans(text: string): string[] {\n const spans = new Set<string>();\n for (const match of text.matchAll(/`([^`\\n]+)`/g)) {\n const span = (match[1] ?? '').trim();\n if (span.split(/\\s+/).filter((w) => w.length > 0).length >= 2) spans.add(span);\n }\n return [...spans];\n}\n\n/** A candidate token has to carry its own punctuation to qualify — see\n * {@link likelyTokens}. */\nconst LIKELY_TOKEN_RE = /\\b[A-Za-z][A-Za-z0-9]*(?:[:_./-][A-Za-z0-9]+)+\\b/g;\nconst LIKELY_MIN_CHARS = 4;\n/** Compounds common enough in ordinary prose to look like a command or a path\n * but never are one. Not a promise of completeness — the punctuation\n * requirement in {@link LIKELY_TOKEN_RE} is what does most of the work; this\n * catches the handful of hyphenated English words that would otherwise slip\n * through it. */\nconst LIKELY_GENERIC = new Set([\n 're-run',\n 're-runs',\n 're-ran',\n 're-executes',\n 're-executed',\n 'up-to-date',\n 'well-known',\n 'self-contained',\n 'read-only',\n 'long-lived',\n 'built-in',\n 'one-word',\n 'two-word',\n 'so-called',\n 'case-by-case',\n 'pre-commit',\n 'post-commit',\n 'e.g',\n 'i.e',\n // The injection's OWN scaffolding, not anything a seller wrote: PUBLIC_OPENER,\n // CLOSING_LINE and the body fence itself (`--- tenjin-body <nonce> ---`) from\n // hooks/prose.ts land in every full-form injection, so without these three\n // `likelyTokens(fullForm(...))` always nets its own boilerplate as a\n // candidate.\n 'third-party',\n 're-verifying',\n 'tenjin-body',\n]);\n\n/**\n * Command heads and file basenames named anywhere in `text`, with no backticks\n * at all — the weaker, single-token net {@link judge} tries below `span` for a\n * note that describes a command in prose instead of quoting it\n * (tenjin-agent#254b: \"gh run rerun\" named only in a title, \"pnpm check\" named\n * only as English words, each with a tool call that actually followed it).\n *\n * CONSERVATIVE ON PURPOSE. A bare English word (\"run\", \"check\", or \"pnpm\" on\n * its own) is exactly what the two-word floor on {@link backtickSpans} already\n * excludes as noise the agent was going to type anyway; a single-token net\n * that took bare words would reopen that hole wider than the floor closes it.\n * So a candidate must carry its own internal structure — a colon, dot, slash,\n * underscore or hyphen joining two word-shaped halves, the way a subcommand\n * (`db:generate`), a filename (`ci.yml`), or a path segment does — which a\n * plain English word essentially never does, and it must be at least\n * {@link LIKELY_MIN_CHARS} long.\n *\n * BACKTICK CONTENT IS STRIPPED FIRST, so a span already tried (and ranked\n * above this) is never re-offered as weaker evidence for the same text.\n *\n * THE PIECE'S OWN ID AND URL ARE EXCLUDED. Those already have a dedicated,\n * stronger `read` verdict; re-crediting them here would rank a followed\n * pointer BELOW a copied identifier instead of above it.\n */\nexport function likelyTokens(text: string, target: GradeTarget): string[] {\n const stripped = text.replace(/`[^`\\n]+`/g, ' ');\n const tokens = new Set<string>();\n for (const match of stripped.matchAll(LIKELY_TOKEN_RE)) {\n const token = match[0];\n if (token.length < LIKELY_MIN_CHARS) continue;\n if (LIKELY_GENERIC.has(token.toLowerCase())) continue;\n // A FRAGMENT counts as the id or the url, not just an exact match: a uuid\n // is all hyphens and hex, so the token regex can walk in from the middle\n // of one (`bbbb-cccc-dddd-...`) and still name nothing but the piece the\n // `read` tier already owns.\n if (target.resourceId !== null && target.resourceId.includes(token)) continue;\n if (target.url !== null && target.url.length > 0 && target.url.includes(token)) continue;\n tokens.add(token);\n }\n return [...tokens];\n}\n\n/**\n * The verdict for one injection, given its transcript and its anchor.\n *\n * Read beats span: both may be present, and \"the agent went and read the piece\"\n * is the stronger claim, so it is the one reported.\n */\nexport function gradeInjection(\n rows: TranscriptRow[],\n anchor: number,\n target: GradeTarget,\n opts: { ended: boolean },\n): Verdict {\n if (anchor < 0 || anchor >= rows.length) return { outcome: 'unobserved', by: 'none' };\n // EXCLUSIVE: the anchor row IS the injection, so the calls that can answer for\n // it are the ones after it. The ones BEFORE it are what a span or a likely\n // token has to clear to earn credit — see the module note on #254a. Bounded\n // to the same SPAN_WINDOW as `after`: a session's first call from an hour\n // before the injection is not \"standing boilerplate\" any more than a session's\n // fiftieth call after it is still \"the injection in view\" — both are the same\n // claim, made symmetrically.\n const before = rows\n .slice(0, anchor)\n .filter((row) => row.kind === 'tool_use')\n .slice(-SPAN_WINDOW);\n const after = rows.slice(anchor + 1).filter((row) => row.kind === 'tool_use');\n const text = rows[anchor]?.text ?? '';\n return judge(after, before, backtickSpans(text), likelyTokens(text, target), target, opts.ended);\n}\n\n/**\n * Where a relayed finding's evidence starts: the first `tool_use` row, or -1.\n *\n * The caller reports it as the anchor line under `--explain`, so a verdict on a\n * child still names the row it was read from.\n */\nexport function firstToolCall(rows: TranscriptRow[]): number {\n return rows.findIndex((row) => row.kind === 'tool_use');\n}\n\n/**\n * The verdict for a finding RELAYED to a subagent, given that child's own\n * transcript.\n *\n * INCLUSIVE OF THE FIRST CALL, and with no anchor at all — see the module note.\n * A child that made no tool calls has done nothing that could be evidence, so it\n * is `rejected` once it is over and open while it runs, exactly as an\n * unanswered main-session row is.\n */\nexport function gradeRelayed(\n rows: TranscriptRow[],\n target: GradeTarget,\n opts: { ended: boolean },\n): Verdict {\n const calls = rows.filter((row) => row.kind === 'tool_use');\n // The title is the only injected text this row left on disk; usually it holds\n // no two-word backtick span at all, and that is the documented limit of what\n // a relayed row can be judged `span` or `likely` on. No pre-injection\n // exclusion here: the pointer preceded the child's first call, so there is no\n // \"before\" inside this transcript for anything to have leaked from.\n const title = target.title ?? '';\n return judge(calls, [], backtickSpans(title), likelyTokens(title, target), target, opts.ended);\n}\n\n/**\n * The evidence rules themselves, over whichever tool calls the caller decided\n * are eligible. Shared byte-for-byte by both verdict functions, so a relayed row\n * and a main-session row can never drift into being judged by different rules.\n *\n * Read beats span beats likely: each may be present alongside a weaker one, and\n * the strongest claim actually supported is the one reported.\n *\n * `before` is up to {@link SPAN_WINDOW} tool calls that happened in this same\n * session BEFORE the injection (empty for a relayed row, which has none). A\n * span or a likely token already present there is boilerplate the session was\n * going to write anyway, so it earns no credit here — tenjin-agent#254a.\n */\nfunction judge(\n after: TranscriptRow[],\n before: TranscriptRow[],\n spans: string[],\n likely: string[],\n target: GradeTarget,\n ended: boolean,\n): Verdict {\n const readRe = target.resourceId === null ? null : readCommandRe(target.resourceId);\n for (const row of after) {\n if (readRe !== null && readRe.test(row.text)) {\n return { outcome: 'used', by: 'read', evidence: cap(row.text) };\n }\n if (target.url !== null && target.url.length > 0 && row.text.includes(target.url)) {\n return { outcome: 'used', by: 'read', evidence: cap(row.text) };\n }\n }\n // A TOKEN BOUNDARY MATCH, not a substring, ON BOTH SIDES: `db:generate` is a\n // plain substring of `db:generate-types`, so a pre-injection call to the\n // latter must not erase credit for a genuine post-injection call to the\n // former (the `before` side) — but by the same logic, a post-injection call\n // to `db:generate-types` must not be credited as a hit for a note that only\n // ever named `db:generate` (the `after` side): that is the identical\n // boilerplate #254a exists to exclude, just spelled with the shorter token\n // as the candidate instead of the longer one. Plain `includes` on one side\n // and a boundary match on the other opens exactly that gap — fixed by\n // sharing one boundary test both directions (tenjin-agent#276 review round\n // 2, major). The class in the lookaround is exactly {@link\n // LIKELY_TOKEN_RE}'s own — a colon, dot, slash, underscore or hyphen still\n // extends a token, so this only rules out landing inside a longer one, not\n // a real reappearance next to punctuation.\n const atBoundary = (haystack: string, candidate: string): boolean =>\n new RegExp(`(?<![A-Za-z0-9:_./-])${escapeRe(candidate)}(?![A-Za-z0-9:_./-])`).test(haystack);\n const seenBefore = (candidate: string): boolean =>\n before.some((row) => atBoundary(row.text, candidate));\n for (const row of after.slice(0, SPAN_WINDOW)) {\n const hit = spans.find((span) => !seenBefore(span) && atBoundary(row.text, span));\n // Capped like every other evidence string here: the span is copied out of\n // injected text, which came off a shelf, and `--explain` prints it.\n if (hit !== undefined) return { outcome: 'used', by: 'span', evidence: cap(hit) };\n }\n for (const row of after.slice(0, SPAN_WINDOW)) {\n const hit = likely.find((token) => !seenBefore(token) && atBoundary(row.text, token));\n if (hit !== undefined) return { outcome: 'used', by: 'likely', evidence: cap(hit) };\n }\n const evidence = after.slice(0, EVIDENCE_ROWS).map(cap);\n return ended ? { outcome: 'rejected', by: 'none', evidence } : { outcome: null, evidence };\n}\n\n/** `7d`, `24h`, `30m` as milliseconds. Anything else is a usage error rather\n * than a silent default, so a typo cannot quietly widen or narrow a sweep. */\nexport function parseSince(text: string): number {\n const match = /^(\\d+)([dhm])$/.exec(text.trim());\n const value = match === null ? 0 : Number(match[1]);\n if (match === null || value <= 0) {\n throw new CliError('USAGE', `Invalid --since window: ${JSON.stringify(text)}`, {\n fix: 'Pass a window like 7d, 24h or 30m.',\n });\n }\n const unit = { d: 24 * 60 * 60_000, h: 60 * 60_000, m: 60_000 }[match[2] as 'd' | 'h' | 'm'];\n return value * unit;\n}\n\n/**\n * Where a session's transcript is, or WHY there is none.\n *\n * `absent` is a FACT ABOUT THE SESSION: the projects directory was listed and\n * holds no file for it. `unreadable` is a fact about this machine right now —\n * no projects directory, a home that is not mounted, a permissions change\n * mid-run — and says nothing about the session at all.\n */\nexport type TranscriptLookup =\n { kind: 'found'; path: string } | { kind: 'absent' } | { kind: 'unreadable'; reason: string };\n\n/**\n * The transcript for a session, or for one subagent of it, or why it was not\n * found.\n *\n * BY READDIR, not by mangling the cwd into a directory name. Claude Code names\n * the project directory from the working directory with a substitution this CLI\n * would have to reimplement and keep in step (and which a worktree, a symlinked\n * home or a renamed checkout each break differently); the session id is a uuid\n * and is unique across them, so one listing finds it wherever it landed.\n *\n * WITH AN AGENT ID IT IS A DIFFERENT FILE, not a different search: a subagent\n * writes to `<session>/subagents/agent-<id>.jsonl` beside the parent's\n * `<session>.jsonl`, under the same project directory. The child's tool calls\n * appear in NO parent file, so a row stamped with an agent id is answered only\n * here.\n *\n * THE TWO NEGATIVE ANSWERS ARE NOT THE SAME ANSWER, and collapsing them to\n * `null` is how a transient fault becomes permanent: the caller turns \"no\n * transcript\" into `unobserved`, `unobserved` is a verdict, and a verdict is\n * never re-graded. One run under a home directory that could not be read would\n * have closed every open row on the machine as never-seen, with no way back.\n */\nexport async function findTranscript(\n homeDir: string,\n sessionId: string,\n agentId: string | null = null,\n): Promise<TranscriptLookup> {\n // An id that cannot be a filename names no transcript in any project\n // directory, now or ever: that is absence, and it is permanent.\n if (!SESSION_ID_RE.test(sessionId)) return { kind: 'absent' };\n if (agentId !== null && !AGENT_ID_RE.test(agentId)) return { kind: 'absent' };\n const { readdir, stat } = await import('node:fs/promises');\n const { join } = await import('node:path');\n const projects = join(homeDir, '.claude', 'projects');\n let dirs: string[];\n try {\n dirs = (await readdir(projects, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch (err) {\n // A missing projects directory included: a machine where the harness has\n // never run, or has not run yet, has not told us anything about this row.\n return { kind: 'unreadable', reason: errorReason(err) };\n }\n let blocked: string | null = null;\n for (const dir of dirs) {\n const path =\n agentId === null\n ? join(projects, dir, `${sessionId}.jsonl`)\n : join(projects, dir, sessionId, 'subagents', `agent-${agentId}.jsonl`);\n try {\n if ((await stat(path)).isFile()) return { kind: 'found', path };\n } catch (err) {\n // ENOENT is the ordinary answer — the session is simply not in THIS\n // project directory, and on the child path its `<session>/` directory may\n // not exist at all (ENOENT, or ENOTDIR where a plain file sits where the\n // directory would be). Anything else is a directory that could be hiding\n // it, so the sweep can no longer claim the file is absent.\n const code = errorCode(err);\n if (code !== 'ENOENT' && code !== 'ENOTDIR') blocked ??= errorReason(err);\n }\n }\n return blocked === null ? { kind: 'absent' } : { kind: 'unreadable', reason: blocked };\n}\n\n/** Has nothing been appended to this transcript for {@link ENDED_AFTER_MS}? The\n * half of \"the session is over\" that survives a harness which never stopped\n * cleanly and so never stamped `ended_at`. Unreadable reads as NOT idle: an\n * unknown must never manufacture a `rejected`. */\nexport async function transcriptIdle(path: string, nowMs: number): Promise<boolean> {\n try {\n const { stat } = await import('node:fs/promises');\n return nowMs - (await stat(path)).mtimeMs > ENDED_AFTER_MS;\n } catch {\n return false;\n }\n}\n\n/** An errno if the platform gave one, else the message: short enough to print\n * on the one `--explain` line that says why a row was left alone. Exported so\n * the caller's own read of the file it was handed reports failures in the same\n * words this one does. */\nexport function errorReason(err: unknown): string {\n const code = errorCode(err);\n if (code !== null) return code;\n return cap(err instanceof Error ? err.message : 'unknown error');\n}\n\nfunction errorCode(err: unknown): string | null {\n return isRecord(err) && typeof err.code === 'string' ? err.code : null;\n}\n\nfunction readCommandRe(resourceId: string): RegExp {\n return new RegExp(`tenjin\\\\s+(?:read|inspect)\\\\s+${escapeRe(resourceId)}`);\n}\n\nfunction escapeRe(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction cap(row: TranscriptRow | string): string {\n const text = typeof row === 'string' ? row : row.text;\n return text.length > EVIDENCE_CHARS ? `${text.slice(0, EVIDENCE_CHARS)}…` : text;\n}\n\n/**\n * The injected text, whatever shape the attachment carried it in: a bare string,\n * an array of strings, or an array of `{ type: 'text', text }` blocks. All three\n * appear, and the anchor match only needs the words.\n */\nfunction contextText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n const parts: string[] = [];\n for (const item of content) {\n if (typeof item === 'string') parts.push(item);\n else if (isRecord(item) && typeof item.text === 'string') parts.push(item.text);\n }\n return parts.join('\\n');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n"],"mappings":";;;AA+EO,IAAM,iBAAiB,KAAK;AAwB5B,IAAM,cAAc;","names":[]}
@@ -27,7 +27,7 @@ import {
27
27
  } from "./chunk-EGELTSPU.js";
28
28
  import {
29
29
  USDC_ADDRESS
30
- } from "./chunk-VVAHFCX2.js";
30
+ } from "./chunk-O2FRQ2L2.js";
31
31
 
32
32
  // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/op-stack/contracts.js
33
33
  var contracts = {
@@ -203,6 +203,7 @@ var basePreconf = /* @__PURE__ */ defineChain({
203
203
 
204
204
  // src/lib/usdc.ts
205
205
  var USDC_ADDRESS2 = USDC_ADDRESS;
206
+ var USDC_DECIMALS = 6;
206
207
  async function getUsdcBalance(address, rpcUrl) {
207
208
  const client = createPublicClient({ chain: base, transport: http(rpcUrl) });
208
209
  return client.readContract({
@@ -311,11 +312,15 @@ function assertUnderCap(field, value, cap) {
311
312
 
312
313
  export {
313
314
  USDC_ADDRESS2 as USDC_ADDRESS,
315
+ USDC_DECIMALS,
314
316
  getUsdcBalance,
317
+ SEND_GAS_CAP,
318
+ SEND_MAX_FEE_PER_GAS_CAP,
319
+ SEND_MAX_PRIORITY_FEE_CAP,
315
320
  FeeCapExceededError,
316
321
  SendRevertedError,
317
322
  SendPendingError,
318
323
  prepareUsdcSend,
319
324
  broadcastUsdcSend
320
325
  };
321
- //# sourceMappingURL=chunk-SFEQGENI.js.map
326
+ //# sourceMappingURL=chunk-YFQOA5AU.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/contracts.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/formatters.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/serializers.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/chainConfig.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/chains/definitions/base.ts","../src/lib/usdc.ts"],"sourcesContent":["import type { Chain } from '../types/chain.js'\n\n/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n} as const satisfies Chain['contracts']\n","import type { ChainFormatters } from '../types/chain.js'\nimport type { RpcTransaction } from '../types/rpc.js'\nimport { hexToBigInt, hexToNumber } from '../utils/encoding/fromHex.js'\nimport { defineBlock } from '../utils/formatters/block.js'\nimport {\n defineTransaction,\n formatTransaction,\n} from '../utils/formatters/transaction.js'\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport type { OpStackBlock, OpStackRpcBlock } from './types/block.js'\nimport type {\n OpStackRpcTransaction,\n OpStackRpcTransactionReceipt,\n OpStackTransaction,\n OpStackTransactionReceipt,\n} from './types/transaction.js'\n\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args: OpStackRpcBlock): OpStackBlock {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string') return transaction\n const formatted = formatTransaction(\n transaction as RpcTransaction,\n ) as OpStackTransaction\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined\n formatted.sourceHash = transaction.sourceHash\n formatted.type = 'deposit'\n }\n return formatted\n })\n return {\n transactions,\n stateRoot: args.stateRoot,\n } as OpStackBlock\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args: OpStackRpcTransaction): OpStackTransaction {\n const transaction = {} as OpStackTransaction\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined\n transaction.sourceHash = args.sourceHash\n transaction.type = 'deposit'\n }\n return transaction\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args: OpStackRpcTransactionReceipt): OpStackTransactionReceipt {\n return {\n ...(args.depositNonce\n ? { depositNonce: hexToBigInt(args.depositNonce) }\n : {}),\n ...(args.depositReceiptVersion\n ? { depositReceiptVersion: hexToNumber(args.depositReceiptVersion) }\n : {}),\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n } as OpStackTransactionReceipt\n },\n }),\n} as const satisfies ChainFormatters\n","import { InvalidAddressError } from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ChainSerializers } from '../types/chain.js'\nimport type { Hex, Signature } from '../types/misc.js'\nimport type { TransactionSerializable } from '../types/transaction.js'\nimport type { RequiredBy } from '../types/utils.js'\nimport { isAddress } from '../utils/address/isAddress.js'\nimport { concatHex } from '../utils/data/concat.js'\nimport { toHex } from '../utils/encoding/toHex.js'\nimport { toRlp } from '../utils/encoding/toRlp.js'\nimport {\n type SerializeTransactionErrorType as SerializeTransactionErrorType_,\n serializeTransaction as serializeTransaction_,\n} from '../utils/transaction/serializeTransaction.js'\nimport type {\n OpStackTransactionSerializable,\n TransactionSerializableDeposit,\n TransactionSerializedDeposit,\n} from './types/transaction.js'\n\nexport type SerializeTransactionReturnType = ReturnType<\n typeof serializeTransaction\n>\n\nexport type SerializeTransactionErrorType =\n | SerializeTransactionErrorType_\n | ErrorType\n\nexport function serializeTransaction(\n transaction: OpStackTransactionSerializable,\n signature?: Signature,\n) {\n if (isDeposit(transaction)) return serializeTransactionDeposit(transaction)\n return serializeTransaction_(\n transaction as TransactionSerializable,\n signature,\n )\n}\n\nexport const serializers = {\n transaction: serializeTransaction,\n} as const satisfies ChainSerializers\n\n//////////////////////////////////////////////////////////////////////////////\n// Serializers\n\nexport type SerializeTransactionDepositReturnType = TransactionSerializedDeposit\n\nfunction serializeTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n): SerializeTransactionDepositReturnType {\n assertTransactionDeposit(transaction)\n\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } =\n transaction\n\n const serializedTransaction: Hex[] = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ]\n\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]) as SerializeTransactionDepositReturnType\n}\n\nfunction isDeposit(\n transaction: OpStackTransactionSerializable,\n): transaction is RequiredBy<TransactionSerializableDeposit, 'type'> {\n if (transaction.type === 'deposit') return true\n if (typeof transaction.sourceHash !== 'undefined') return true\n return false\n}\n\nexport function assertTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n) {\n const { from, to } = transaction\n if (from && !isAddress(from)) throw new InvalidAddressError({ address: from })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n}\n","import { contracts } from './contracts.js'\nimport { formatters } from './formatters.js'\nimport { serializers } from './serializers.js'\n\nexport const chainConfig = {\n blockTime: 2_000,\n contracts,\n formatters,\n serializers,\n} as const\n","import { chainConfig } from '../../op-stack/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nconst sourceId = 1 // mainnet\n\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n})\n\nexport const basePreconf = /*#__PURE__*/ defineChain({\n ...base,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://mainnet-preconf.base.org'],\n },\n },\n})\n","import {\n createPublicClient,\n decodeFunctionData,\n encodeFunctionData,\n erc20Abi,\n http,\n type Address,\n type Hex,\n} from 'viem';\nimport { base } from 'viem/chains';\nimport { USDC_ADDRESS as USDC } from './usdc-balance';\nimport type { TenjinSigner } from './wallet/provider';\n\n/** Lives in `usdc-balance.ts`, which the viem-free hooks can load. */\nexport const USDC_ADDRESS: Address = USDC;\nexport const USDC_DECIMALS = 6;\n\nexport async function getUsdcBalance(address: Address, rpcUrl: string): Promise<bigint> {\n const client = createPublicClient({ chain: base, transport: http(rpcUrl) });\n return client.readContract({\n address: USDC_ADDRESS,\n abi: erc20Abi,\n functionName: 'balanceOf',\n args: [address],\n });\n}\n\n// The chain boundary for `tenjin wallet send`, two-phase around the human confirm:\n// prepareUsdcSend (read-only: encode, nonce, gas, fees, ETH-for-gas balance)\n// runs BEFORE the confirm so the prompt can show the fee, broadcastUsdcSend\n// (sign via the TenjinSigner seam, broadcast, wait for the receipt) runs after.\n// Command tests mock this whole module, so no test can ever reach a real chain.\n\n/**\n * Ceilings on the RPC-supplied gas and fee fields. The RPC endpoint is\n * config-controlled and its estimates go straight into the signed transaction; a\n * hostile or broken endpoint returning huge values would burn the wallet's ETH\n * as fees. An ERC-20 transfer is ~65k gas and Base fees run well under a gwei,\n * so estimates past these bounds mean something is wrong: refuse, never clamp\n * (a clamped maxFeePerGas below the real base fee would just strand the tx).\n * A genuine extreme fee spike on Base trips the same refusal; that is intended\n * — waiting it out beats signing an irreversible transfer at panic prices.\n */\nexport const SEND_GAS_CAP = 150_000n;\nexport const SEND_MAX_FEE_PER_GAS_CAP = 10_000_000_000n; // 10 gwei\nexport const SEND_MAX_PRIORITY_FEE_CAP = 2_000_000_000n; // 2 gwei\n\n/** An RPC gas/fee estimate exceeded the send ceilings; nothing was signed. */\nexport class FeeCapExceededError extends Error {\n constructor(field: string, value: bigint, cap: bigint) {\n super(`${field} estimate ${value} exceeds the send ceiling ${cap}`);\n this.name = 'FeeCapExceededError';\n }\n}\n\n/** The transfer was mined but reverted; the fee was spent, the USDC did not move. */\nexport class SendRevertedError extends Error {\n constructor(readonly txHash: Hex) {\n super(`Transaction ${txHash} reverted`);\n this.name = 'SendRevertedError';\n }\n}\n\n/** Broadcast succeeded but no receipt arrived in time; the tx may still mine. */\nexport class SendPendingError extends Error {\n constructor(readonly txHash: Hex) {\n super(`Transaction ${txHash} was broadcast but not confirmed in time`);\n this.name = 'SendPendingError';\n }\n}\n\nexport interface PrepareUsdcSendArgs {\n from: Address;\n to: Address;\n amountAtomic: bigint;\n rpcUrl: string;\n}\n\n/**\n * Everything signed later, fixed at prepare time, plus the gas-cost preview.\n * The nonce is pinned here, BEFORE the human confirm, so anything else spending\n * from this key during that window makes the later broadcast fail nonce-stale\n * (an RPC_ERROR from the node; nothing double-spends — re-run to re-prepare).\n * `to` and `amountAtomic` are the previewed intent; broadcastUsdcSend re-decodes\n * `data` against them before signing.\n */\nexport interface PreparedUsdcSend {\n to: Address;\n amountAtomic: bigint;\n data: Hex;\n nonce: number;\n gas: bigint;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n /** Worst-case fee (gas * maxFeePerGas), for the confirm prompt and gas check. */\n feeWei: bigint;\n /** The sender's native ETH balance, for the has-gas pre-check. */\n ethBalanceWei: bigint;\n}\n\nexport async function prepareUsdcSend({\n from,\n to,\n amountAtomic,\n rpcUrl,\n}: PrepareUsdcSendArgs): Promise<PreparedUsdcSend> {\n const client = createPublicClient({ chain: base, transport: http(rpcUrl) });\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: 'transfer',\n args: [to, amountAtomic],\n });\n const [nonce, gas, fees, ethBalanceWei] = await Promise.all([\n client.getTransactionCount({ address: from, blockTag: 'pending' }),\n client.estimateGas({ account: from, to: USDC_ADDRESS, data }),\n client.estimateFeesPerGas(),\n client.getBalance({ address: from }),\n ]);\n assertUnderCap('gas', gas, SEND_GAS_CAP);\n assertUnderCap('maxFeePerGas', fees.maxFeePerGas, SEND_MAX_FEE_PER_GAS_CAP);\n assertUnderCap('maxPriorityFeePerGas', fees.maxPriorityFeePerGas, SEND_MAX_PRIORITY_FEE_CAP);\n return {\n to,\n amountAtomic,\n data,\n nonce,\n gas,\n maxFeePerGas: fees.maxFeePerGas,\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas,\n feeWei: gas * fees.maxFeePerGas,\n ethBalanceWei,\n };\n}\n\nexport interface BroadcastUsdcSendArgs {\n signer: TenjinSigner;\n prepared: PreparedUsdcSend;\n rpcUrl: string;\n /** Receipt wait bound in ms; Base blocks are ~2s, so the default is generous. */\n receiptTimeoutMs?: number;\n}\n\n/**\n * Sign the prepared transfer through the TenjinSigner seam (never a raw key),\n * broadcast it, and wait for the receipt so \"sent\" means mined. Throws\n * SendRevertedError (mined but failed) or SendPendingError (no receipt in time);\n * both carry the hash so the caller can report it either way.\n */\nexport async function broadcastUsdcSend({\n signer,\n prepared,\n rpcUrl,\n receiptTimeoutMs = 120_000,\n}: BroadcastUsdcSendArgs): Promise<Hex> {\n const client = createPublicClient({ chain: base, transport: http(rpcUrl) });\n // Pre-sign cross-check, the calldata twin of send.ts's signer/preview match:\n // the bytes about to be signed must still decode to the previewed recipient\n // and amount. Unreachable unless prepare-time state was corrupted; refusing\n // here means nothing is signed against a preview it does not match.\n const decoded = decodeFunctionData({ abi: erc20Abi, data: prepared.data });\n if (\n decoded.functionName !== 'transfer' ||\n decoded.args[0].toLowerCase() !== prepared.to.toLowerCase() ||\n decoded.args[1] !== prepared.amountAtomic\n ) {\n throw new Error(\n 'Prepared calldata does not decode to the previewed recipient and amount; nothing was signed.',\n );\n }\n const serializedTransaction = await signer.signTransaction({\n type: 'eip1559',\n chainId: base.id,\n to: USDC_ADDRESS,\n // Explicitly zero: an ERC-20 transfer carries no native value (test-pinned).\n value: 0n,\n data: prepared.data,\n nonce: prepared.nonce,\n gas: prepared.gas,\n maxFeePerGas: prepared.maxFeePerGas,\n maxPriorityFeePerGas: prepared.maxPriorityFeePerGas,\n });\n const txHash = await client.sendRawTransaction({ serializedTransaction });\n let receipt;\n try {\n receipt = await client.waitForTransactionReceipt({ hash: txHash, timeout: receiptTimeoutMs });\n } catch {\n throw new SendPendingError(txHash);\n }\n if (receipt.status !== 'success') throw new SendRevertedError(txHash);\n return txHash;\n}\n\nfunction assertUnderCap(field: string, value: bigint, cap: bigint): void {\n if (value > cap) throw new FeeCapExceededError(field, value, cap);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMO,IAAM,YAAY;EACvB,gBAAgB,EAAE,SAAS,6CAA4C;EACvE,SAAS,EAAE,SAAS,6CAA4C;EAChE,wBAAwB;IACtB,SAAS;;EAEX,gBAAgB,EAAE,SAAS,6CAA4C;EACvE,kBAAkB,EAAE,SAAS,6CAA4C;EACzE,qBAAqB;IACnB,SAAS;;;;;ACEN,IAAM,aAAa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BAAsB,SAAS;AAAA,EACjC,CAAC;AACD,QAAM,SAAS,MAAM,OAAO,mBAAmB,EAAE,sBAAsB,CAAC;AACxE,MAAI;AACJ,MAAI;AACF,cAAU,MAAM,OAAO,0BAA0B,EAAE,MAAM,QAAQ,SAAS,iBAAiB,CAAC;AAAA,EAC9F,QAAQ;AACN,UAAM,IAAI,iBAAiB,MAAM;AAAA,EACnC;AACA,MAAI,QAAQ,WAAW,UAAW,OAAM,IAAI,kBAAkB,MAAM;AACpE,SAAO;AACT;AAEA,SAAS,eAAe,OAAe,OAAe,KAAmB;AACvE,MAAI,QAAQ,IAAK,OAAM,IAAI,oBAAoB,OAAO,OAAO,GAAG;AAClE;","names":["serializeTransaction","USDC_ADDRESS","USDC_ADDRESS"]}
1
+ {"version":3,"sources":["../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/contracts.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/formatters.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/serializers.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/chainConfig.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/chains/definitions/base.ts","../src/lib/usdc.ts"],"sourcesContent":["import type { Chain } from '../types/chain.js'\n\n/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n} as const satisfies Chain['contracts']\n","import type { ChainFormatters } from '../types/chain.js'\nimport type { RpcTransaction } from '../types/rpc.js'\nimport { hexToBigInt, hexToNumber } from '../utils/encoding/fromHex.js'\nimport { defineBlock } from '../utils/formatters/block.js'\nimport {\n defineTransaction,\n formatTransaction,\n} from '../utils/formatters/transaction.js'\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport type { OpStackBlock, OpStackRpcBlock } from './types/block.js'\nimport type {\n OpStackRpcTransaction,\n OpStackRpcTransactionReceipt,\n OpStackTransaction,\n OpStackTransactionReceipt,\n} from './types/transaction.js'\n\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args: OpStackRpcBlock): OpStackBlock {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string') return transaction\n const formatted = formatTransaction(\n transaction as RpcTransaction,\n ) as OpStackTransaction\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined\n formatted.sourceHash = transaction.sourceHash\n formatted.type = 'deposit'\n }\n return formatted\n })\n return {\n transactions,\n stateRoot: args.stateRoot,\n } as OpStackBlock\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args: OpStackRpcTransaction): OpStackTransaction {\n const transaction = {} as OpStackTransaction\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined\n transaction.sourceHash = args.sourceHash\n transaction.type = 'deposit'\n }\n return transaction\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args: OpStackRpcTransactionReceipt): OpStackTransactionReceipt {\n return {\n ...(args.depositNonce\n ? { depositNonce: hexToBigInt(args.depositNonce) }\n : {}),\n ...(args.depositReceiptVersion\n ? { depositReceiptVersion: hexToNumber(args.depositReceiptVersion) }\n : {}),\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n } as OpStackTransactionReceipt\n },\n }),\n} as const satisfies ChainFormatters\n","import { InvalidAddressError } from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ChainSerializers } from '../types/chain.js'\nimport type { Hex, Signature } from '../types/misc.js'\nimport type { TransactionSerializable } from '../types/transaction.js'\nimport type { RequiredBy } from '../types/utils.js'\nimport { isAddress } from '../utils/address/isAddress.js'\nimport { concatHex } from '../utils/data/concat.js'\nimport { toHex } from '../utils/encoding/toHex.js'\nimport { toRlp } from '../utils/encoding/toRlp.js'\nimport {\n type SerializeTransactionErrorType as SerializeTransactionErrorType_,\n serializeTransaction as serializeTransaction_,\n} from '../utils/transaction/serializeTransaction.js'\nimport type {\n OpStackTransactionSerializable,\n TransactionSerializableDeposit,\n TransactionSerializedDeposit,\n} from './types/transaction.js'\n\nexport type SerializeTransactionReturnType = ReturnType<\n typeof serializeTransaction\n>\n\nexport type SerializeTransactionErrorType =\n | SerializeTransactionErrorType_\n | ErrorType\n\nexport function serializeTransaction(\n transaction: OpStackTransactionSerializable,\n signature?: Signature,\n) {\n if (isDeposit(transaction)) return serializeTransactionDeposit(transaction)\n return serializeTransaction_(\n transaction as TransactionSerializable,\n signature,\n )\n}\n\nexport const serializers = {\n transaction: serializeTransaction,\n} as const satisfies ChainSerializers\n\n//////////////////////////////////////////////////////////////////////////////\n// Serializers\n\nexport type SerializeTransactionDepositReturnType = TransactionSerializedDeposit\n\nfunction serializeTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n): SerializeTransactionDepositReturnType {\n assertTransactionDeposit(transaction)\n\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } =\n transaction\n\n const serializedTransaction: Hex[] = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ]\n\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]) as SerializeTransactionDepositReturnType\n}\n\nfunction isDeposit(\n transaction: OpStackTransactionSerializable,\n): transaction is RequiredBy<TransactionSerializableDeposit, 'type'> {\n if (transaction.type === 'deposit') return true\n if (typeof transaction.sourceHash !== 'undefined') return true\n return false\n}\n\nexport function assertTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n) {\n const { from, to } = transaction\n if (from && !isAddress(from)) throw new InvalidAddressError({ address: from })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n}\n","import { contracts } from './contracts.js'\nimport { formatters } from './formatters.js'\nimport { serializers } from './serializers.js'\n\nexport const chainConfig = {\n blockTime: 2_000,\n contracts,\n formatters,\n serializers,\n} as const\n","import { chainConfig } from '../../op-stack/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nconst sourceId = 1 // mainnet\n\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n})\n\nexport const basePreconf = /*#__PURE__*/ defineChain({\n ...base,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://mainnet-preconf.base.org'],\n },\n },\n})\n","import {\n createPublicClient,\n decodeFunctionData,\n encodeFunctionData,\n erc20Abi,\n http,\n type Address,\n type Hex,\n} from 'viem';\nimport { base } from 'viem/chains';\nimport { USDC_ADDRESS as USDC } from './usdc-balance';\nimport type { TenjinSigner } from './wallet/provider';\n\n/** Lives in `usdc-balance.ts`, which the viem-free hooks can load. */\nexport const USDC_ADDRESS: Address = USDC;\nexport const USDC_DECIMALS = 6;\n\nexport async function getUsdcBalance(address: Address, rpcUrl: string): Promise<bigint> {\n const client = createPublicClient({ chain: base, transport: http(rpcUrl) });\n return client.readContract({\n address: USDC_ADDRESS,\n abi: erc20Abi,\n functionName: 'balanceOf',\n args: [address],\n });\n}\n\n// The chain boundary for `tenjin wallet send`, two-phase around the human confirm:\n// prepareUsdcSend (read-only: encode, nonce, gas, fees, ETH-for-gas balance)\n// runs BEFORE the confirm so the prompt can show the fee, broadcastUsdcSend\n// (sign via the TenjinSigner seam, broadcast, wait for the receipt) runs after.\n// Command tests mock this whole module, so no test can ever reach a real chain.\n\n/**\n * Ceilings on the RPC-supplied gas and fee fields. The RPC endpoint is\n * config-controlled and its estimates go straight into the signed transaction; a\n * hostile or broken endpoint returning huge values would burn the wallet's ETH\n * as fees. An ERC-20 transfer is ~65k gas and Base fees run well under a gwei,\n * so estimates past these bounds mean something is wrong: refuse, never clamp\n * (a clamped maxFeePerGas below the real base fee would just strand the tx).\n * A genuine extreme fee spike on Base trips the same refusal; that is intended\n * — waiting it out beats signing an irreversible transfer at panic prices.\n */\nexport const SEND_GAS_CAP = 150_000n;\nexport const SEND_MAX_FEE_PER_GAS_CAP = 10_000_000_000n; // 10 gwei\nexport const SEND_MAX_PRIORITY_FEE_CAP = 2_000_000_000n; // 2 gwei\n\n/** An RPC gas/fee estimate exceeded the send ceilings; nothing was signed. */\nexport class FeeCapExceededError extends Error {\n constructor(field: string, value: bigint, cap: bigint) {\n super(`${field} estimate ${value} exceeds the send ceiling ${cap}`);\n this.name = 'FeeCapExceededError';\n }\n}\n\n/** The transfer was mined but reverted; the fee was spent, the USDC did not move. */\nexport class SendRevertedError extends Error {\n constructor(readonly txHash: Hex) {\n super(`Transaction ${txHash} reverted`);\n this.name = 'SendRevertedError';\n }\n}\n\n/** Broadcast succeeded but no receipt arrived in time; the tx may still mine. */\nexport class SendPendingError extends Error {\n constructor(readonly txHash: Hex) {\n super(`Transaction ${txHash} was broadcast but not confirmed in time`);\n this.name = 'SendPendingError';\n }\n}\n\nexport interface PrepareUsdcSendArgs {\n from: Address;\n to: Address;\n amountAtomic: bigint;\n rpcUrl: string;\n}\n\n/**\n * Everything signed later, fixed at prepare time, plus the gas-cost preview.\n * The nonce is pinned here, BEFORE the human confirm, so anything else spending\n * from this key during that window makes the later broadcast fail nonce-stale\n * (an RPC_ERROR from the node; nothing double-spends — re-run to re-prepare).\n * `to` and `amountAtomic` are the previewed intent; broadcastUsdcSend re-decodes\n * `data` against them before signing.\n */\nexport interface PreparedUsdcSend {\n to: Address;\n amountAtomic: bigint;\n data: Hex;\n nonce: number;\n gas: bigint;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n /** Worst-case fee (gas * maxFeePerGas), for the confirm prompt and gas check. */\n feeWei: bigint;\n /** The sender's native ETH balance, for the has-gas pre-check. */\n ethBalanceWei: bigint;\n}\n\nexport async function prepareUsdcSend({\n from,\n to,\n amountAtomic,\n rpcUrl,\n}: PrepareUsdcSendArgs): Promise<PreparedUsdcSend> {\n const client = createPublicClient({ chain: base, transport: http(rpcUrl) });\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: 'transfer',\n args: [to, amountAtomic],\n });\n const [nonce, gas, fees, ethBalanceWei] = await Promise.all([\n client.getTransactionCount({ address: from, blockTag: 'pending' }),\n client.estimateGas({ account: from, to: USDC_ADDRESS, data }),\n client.estimateFeesPerGas(),\n client.getBalance({ address: from }),\n ]);\n assertUnderCap('gas', gas, SEND_GAS_CAP);\n assertUnderCap('maxFeePerGas', fees.maxFeePerGas, SEND_MAX_FEE_PER_GAS_CAP);\n assertUnderCap('maxPriorityFeePerGas', fees.maxPriorityFeePerGas, SEND_MAX_PRIORITY_FEE_CAP);\n return {\n to,\n amountAtomic,\n data,\n nonce,\n gas,\n maxFeePerGas: fees.maxFeePerGas,\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas,\n feeWei: gas * fees.maxFeePerGas,\n ethBalanceWei,\n };\n}\n\nexport interface BroadcastUsdcSendArgs {\n signer: TenjinSigner;\n prepared: PreparedUsdcSend;\n rpcUrl: string;\n /** Receipt wait bound in ms; Base blocks are ~2s, so the default is generous. */\n receiptTimeoutMs?: number;\n}\n\n/**\n * Sign the prepared transfer through the TenjinSigner seam (never a raw key),\n * broadcast it, and wait for the receipt so \"sent\" means mined. Throws\n * SendRevertedError (mined but failed) or SendPendingError (no receipt in time);\n * both carry the hash so the caller can report it either way.\n */\nexport async function broadcastUsdcSend({\n signer,\n prepared,\n rpcUrl,\n receiptTimeoutMs = 120_000,\n}: BroadcastUsdcSendArgs): Promise<Hex> {\n const client = createPublicClient({ chain: base, transport: http(rpcUrl) });\n // Pre-sign cross-check, the calldata twin of send.ts's signer/preview match:\n // the bytes about to be signed must still decode to the previewed recipient\n // and amount. Unreachable unless prepare-time state was corrupted; refusing\n // here means nothing is signed against a preview it does not match.\n const decoded = decodeFunctionData({ abi: erc20Abi, data: prepared.data });\n if (\n decoded.functionName !== 'transfer' ||\n decoded.args[0].toLowerCase() !== prepared.to.toLowerCase() ||\n decoded.args[1] !== prepared.amountAtomic\n ) {\n throw new Error(\n 'Prepared calldata does not decode to the previewed recipient and amount; nothing was signed.',\n );\n }\n const serializedTransaction = await signer.signTransaction({\n type: 'eip1559',\n chainId: base.id,\n to: USDC_ADDRESS,\n // Explicitly zero: an ERC-20 transfer carries no native value (test-pinned).\n value: 0n,\n data: prepared.data,\n nonce: prepared.nonce,\n gas: prepared.gas,\n maxFeePerGas: prepared.maxFeePerGas,\n maxPriorityFeePerGas: prepared.maxPriorityFeePerGas,\n });\n const txHash = await client.sendRawTransaction({ serializedTransaction });\n let receipt;\n try {\n receipt = await client.waitForTransactionReceipt({ hash: txHash, timeout: receiptTimeoutMs });\n } catch {\n throw new SendPendingError(txHash);\n }\n if (receipt.status !== 'success') throw new SendRevertedError(txHash);\n return txHash;\n}\n\nfunction assertUnderCap(field: string, value: bigint, cap: bigint): void {\n if (value > cap) throw new FeeCapExceededError(field, value, cap);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMO,IAAM,YAAY;EACvB,gBAAgB,EAAE,SAAS,6CAA4C;EACvE,SAAS,EAAE,SAAS,6CAA4C;EAChE,wBAAwB;IACtB,SAAS;;EAEX,gBAAgB,EAAE,SAAS,6CAA4C;EACvE,kBAAkB,EAAE,SAAS,6CAA4C;EACzE,qBAAqB;IACnB,SAAS;;;;;ACEN,IAAM,aAAa;EACxB,OAAqB,4BAAY;IAC/B,OAAO,MAAqB;AAC1B,YAAM,eAAe,KAAK,cAAc,IAAI,CAAC,gBAAe;AAC1D,YAAI,OAAO,gBAAgB;AAAU,iBAAO;AAC5C,cAAM,YAAY,kBAChB,WAA6B;AAE/B,YAAI,UAAU,YAAY,QAAQ;AAChC,oBAAU,aAAa,YAAY;AACnC,oBAAU,OAAO,YAAY,OACzB,YAAY,YAAY,IAAI,IAC5B;AACJ,oBAAU,aAAa,YAAY;AACnC,oBAAU,OAAO;QACnB;AACA,eAAO;MACT,CAAC;AACD,aAAO;QACL;QACA,WAAW,KAAK;;IAEpB;GACD;EACD,aAA2B,kCAAkB;IAC3C,OAAO,MAA2B;AAChC,YAAM,cAAc,CAAA;AACpB,UAAI,KAAK,S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 -2,7 +2,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  maybeUpdate,
4
4
  readUpdateSignal
5
- } from "./chunk-WM7TJEBP.js";
5
+ } from "./chunk-VZGAONSJ.js";
6
6
  import {
7
7
  PERMISSIONS_DOC_URL
8
8
  } from "./chunk-A36LQPHV.js";
@@ -10,23 +10,24 @@ import {
10
10
  defaultIo,
11
11
  emitFailure,
12
12
  emitSuccess
13
- } from "./chunk-TROZ6HL4.js";
13
+ } from "./chunk-KYFZTGMC.js";
14
14
  import {
15
15
  noteBaseUrlFlag
16
- } from "./chunk-USOLCBKC.js";
17
- import "./chunk-RJEPZMYY.js";
16
+ } from "./chunk-QUVVWYJW.js";
17
+ import "./chunk-IOODYAXL.js";
18
18
  import "./chunk-2I4QTOLB.js";
19
- import "./chunk-AMEUXNJT.js";
19
+ import "./chunk-AWFUPKTM.js";
20
20
  import {
21
21
  CliError,
22
22
  external_exports
23
- } from "./chunk-VVAHFCX2.js";
23
+ } from "./chunk-WO5BJNIB.js";
24
+ import "./chunk-O2FRQ2L2.js";
24
25
  import {
25
26
  dataDir
26
27
  } from "./chunk-SJLTEINJ.js";
27
28
  import {
28
29
  package_default
29
- } from "./chunk-LRCJ2IZ5.js";
30
+ } from "./chunk-VUFAK2LW.js";
30
31
  import {
31
32
  __commonJS,
32
33
  __require,
@@ -3493,12 +3494,17 @@ function registerCore(reg) {
3493
3494
  const { runCommand, leaf: leaf2, addGlobalFlags: addGlobalFlags2 } = reg;
3494
3495
  leaf2(SETUP, "install", "set up Tenjin for Claude Code and create a wallet").description(
3495
3496
  "Set up Claude Code to use Tenjin: a wallet if this machine has none, spend limits for each lookup, and the Claude Code plugin `tenjin` (its routing hooks and its `router` MCP server), registered through Claude Code's own `claude plugin` commands. A settings-based install from an earlier release is removed once the plugin has loaded."
3496
- ).option("--project", "register the plugin for this project only").option("--no-wallet", "create no wallet").option("--refresh", "bring the plugin this machine already has up to this version").option("--yes", "accept the default spend limits instead of asking").addHelpText(
3497
+ ).option("--project", "register the plugin for this project only").option("--no-wallet", "create no wallet").option("--refresh", "bring the plugin this machine already has up to this version").option("--yes", "accept the defaults ($5 a day, $0.25 a call) instead of asking").option("--session-budget <usd|none>", "your own daily limit, or none, instead of asking").option("--max-auto-spend <usd>", "your own per-call limit, at least 0.25 (the default)").addHelpText(
3497
3498
  "after",
3498
3499
  `
3499
3500
  Examples:
3500
3501
  $ tenjin install
3501
3502
  $ tenjin install --project
3503
+ $ tenjin install --max-auto-spend 0.50 --session-budget 10
3504
+
3505
+ The daily limit is the control, the per-call limit the runaway guard, and the
3506
+ wallet balance the hard stop. To turn the router off instead:
3507
+ $ tenjin config set router.enabled false
3502
3508
 
3503
3509
  Learn more:
3504
3510
  What the router may spend, and what leaves this machine:
@@ -3507,13 +3513,15 @@ Learn more:
3507
3513
  ).action(async function() {
3508
3514
  await runCommand("install", this, async (ctx) => {
3509
3515
  const o = this.opts();
3510
- const { runRouterInstall } = await import("./install-2GXXD4DK.js");
3516
+ const { runRouterInstall } = await import("./install-TUCRF32I.js");
3511
3517
  return runRouterInstall(
3512
3518
  {
3513
3519
  ...o.project === true ? { project: true } : {},
3514
3520
  ...o.refresh === true ? { refresh: true } : {},
3515
3521
  ...o.yes === true ? { yes: true } : {},
3516
- ...o.wallet === false ? { noWallet: true } : {}
3522
+ ...o.wallet === false ? { noWallet: true } : {},
3523
+ ...typeof o.maxAutoSpend === "string" ? { maxAutoSpend: o.maxAutoSpend } : {},
3524
+ ...typeof o.sessionBudget === "string" ? { sessionBudget: o.sessionBudget } : {}
3517
3525
  },
3518
3526
  ctx
3519
3527
  );
@@ -3524,7 +3532,7 @@ Learn more:
3524
3532
  ).option("--project", "remove the project-only install").action(async function() {
3525
3533
  await runCommand("uninstall", this, async (ctx) => {
3526
3534
  const o = this.opts();
3527
- const { runRouterUninstall } = await import("./uninstall-VOK2Z5M4.js");
3535
+ const { runRouterUninstall } = await import("./uninstall-HY6LKIIT.js");
3528
3536
  return runRouterUninstall({ ...o.project === true ? { project: true } : {} }, ctx);
3529
3537
  });
3530
3538
  });
@@ -3540,7 +3548,7 @@ Examples:
3540
3548
  `
3541
3549
  ).action(async function() {
3542
3550
  await runCommand("doctor", this, async (ctx) => {
3543
- const { runRouterDoctor } = await import("./doctor-SSTXGCHX.js");
3551
+ const { runRouterDoctor } = await import("./doctor-IQQJHGGM.js");
3544
3552
  return runRouterDoctor(ctx, this.opts().project === true ? { project: true } : {});
3545
3553
  });
3546
3554
  });
@@ -3548,7 +3556,7 @@ Examples:
3548
3556
  "Update tenjin-cli to the newest version npm publishes on the latest tag. It then runs `install --refresh` on the new binary, so the Claude Code plugin is registered at the build that just landed."
3549
3557
  ).option("--check", "report whether a newer version exists without installing it").action(async function() {
3550
3558
  await runCommand("update", this, async (ctx) => {
3551
- const { runUpdate } = await import("./update-FGP3HNLD.js");
3559
+ const { runUpdate } = await import("./update-OJV22LR3.js");
3552
3560
  return runUpdate({ check: this.opts().check === true }, ctx);
3553
3561
  });
3554
3562
  });
@@ -3567,7 +3575,7 @@ Examples:
3567
3575
  );
3568
3576
  config.action(async function() {
3569
3577
  await runCommand("config", this, async (ctx) => {
3570
- const { runConfigList } = await import("./config-YYKDH2TH.js");
3578
+ const { runConfigList } = await import("./config-OJQI27LT.js");
3571
3579
  return runConfigList(ctx);
3572
3580
  });
3573
3581
  });
@@ -3575,7 +3583,7 @@ Examples:
3575
3583
  "Print one effective config value by key. The effective value is what the command would use, defaults and environment overrides included."
3576
3584
  ).action(async function(key) {
3577
3585
  await runCommand("config.get", this, async (ctx) => {
3578
- const { runConfigGet } = await import("./config-YYKDH2TH.js");
3586
+ const { runConfigGet } = await import("./config-OJQI27LT.js");
3579
3587
  return runConfigGet({ key }, ctx);
3580
3588
  });
3581
3589
  });
@@ -3587,7 +3595,7 @@ Examples:
3587
3595
  ).option("--local", "with --project, write .tenjin/config.local.json instead, which is yours").action(async function(key, value) {
3588
3596
  const o = this.opts();
3589
3597
  await runCommand("config.set", this, async (ctx) => {
3590
- const { runConfigSet } = await import("./config-YYKDH2TH.js");
3598
+ const { runConfigSet } = await import("./config-OJQI27LT.js");
3591
3599
  return runConfigSet(
3592
3600
  { key, value, project: o.project === true, local: o.local === true },
3593
3601
  ctx
@@ -3609,7 +3617,7 @@ Examples:
3609
3617
  ).action(async function() {
3610
3618
  await runCommand("wallet.create", this, async (ctx) => {
3611
3619
  const o = this.opts();
3612
- const { runWalletCreate } = await import("./wallet-DA7OFNEW.js");
3620
+ const { runWalletCreate } = await import("./wallet-PD2IMZDU.js");
3613
3621
  return runWalletCreate(ctx, o.replace === true ? { replace: true } : {});
3614
3622
  });
3615
3623
  });
@@ -3618,7 +3626,7 @@ Examples:
3618
3626
  ).option("--no-qr", "print the address without the QR code").action(async function() {
3619
3627
  await runCommand("wallet.show", this, async (ctx) => {
3620
3628
  const o = this.opts();
3621
- const { runWalletShow } = await import("./wallet-DA7OFNEW.js");
3629
+ const { runWalletShow } = await import("./wallet-PD2IMZDU.js");
3622
3630
  return runWalletShow(ctx, o.qr === false ? { qr: false } : {});
3623
3631
  });
3624
3632
  });
@@ -3626,7 +3634,7 @@ Examples:
3626
3634
  "Read the wallet USDC balance on Base. It is a chain read: no key is unlocked and nothing is spent."
3627
3635
  ).action(async function() {
3628
3636
  await runCommand("wallet.balance", this, async (ctx) => {
3629
- const { runWalletBalance } = await import("./wallet-DA7OFNEW.js");
3637
+ const { runWalletBalance } = await import("./wallet-PD2IMZDU.js");
3630
3638
  return runWalletBalance(ctx);
3631
3639
  });
3632
3640
  });
@@ -3638,7 +3646,7 @@ Examples:
3638
3646
  ).action(async function(amountUsd) {
3639
3647
  await runCommand("wallet.fund", this, async (ctx) => {
3640
3648
  const o = this.opts();
3641
- const { runFund } = await import("./fund-QWVWRVDK.js");
3649
+ const { runFund } = await import("./fund-WEV6DMTD.js");
3642
3650
  return runFund(ctx, {
3643
3651
  ...amountUsd !== void 0 ? { amountUsd } : {},
3644
3652
  ...o.open === false ? { open: false } : {},
@@ -3658,7 +3666,7 @@ Examples:
3658
3666
  ).action(async function(amount, token, to) {
3659
3667
  await runCommand("wallet.send", this, async (ctx) => {
3660
3668
  const o = this.opts();
3661
- const { runSend } = await import("./send-MHAOLPK3.js");
3669
+ const { runSend } = await import("./send-KVJX4XIR.js");
3662
3670
  return runSend({ amount, token, to, ...o.yes === true ? { yes: true } : {} }, ctx);
3663
3671
  });
3664
3672
  });
@@ -3678,7 +3686,7 @@ Examples:
3678
3686
  ).action(async function(url) {
3679
3687
  await runCommand("pay", this, async (ctx) => {
3680
3688
  const o = this.opts();
3681
- const { runPay } = await import("./pay-LSDJBIAZ.js");
3689
+ const { runPay } = await import("./pay-2C2UBBXJ.js");
3682
3690
  return runPay(
3683
3691
  {
3684
3692
  url,
@@ -3705,7 +3713,7 @@ function registerRouter(reg) {
3705
3713
  const ctx = buildContext2(this);
3706
3714
  const [{ aliveMain }, { default: pkg }] = await Promise.all([
3707
3715
  import("./alive-3J3CHOQP.js"),
3708
- import("./package-6DJA3Y2O.js")
3716
+ import("./package-LGKYOEPV.js")
3709
3717
  ]);
3710
3718
  await aliveMain({ dataDir: ctx.dataDir, version: pkg.version });
3711
3719
  });
@@ -3722,7 +3730,7 @@ function registerRouter(reg) {
3722
3730
  ]) {
3723
3731
  addGlobalFlags2(hook.command(name)).summary(summary).action(async function() {
3724
3732
  const ctx = buildContext2(this);
3725
- const { runHookCommand } = await import("./hook-command-VWJXRT7H.js");
3733
+ const { runHookCommand } = await import("./hook-command-D2P3ILRV.js");
3726
3734
  await runHookCommand(name, io, {
3727
3735
  dataDir: ctx.dataDir,
3728
3736
  ...ctx.flags.baseUrl !== void 0 ? { baseUrl: ctx.flags.baseUrl } : {}
@@ -3735,21 +3743,21 @@ function registerRouter(reg) {
3735
3743
  "Run the local stdio MCP server that carries the `request` tool: one free routing decision per lookup, then the provider call, built here from the offer's spec and your assistant's input where it has one, under your local spend policy. It speaks on stdin and stdout and runs until the client disconnects, so it prints no envelope of its own."
3736
3744
  ).action(async function() {
3737
3745
  const ctx = buildContext2(this);
3738
- const { runRouterMcpServer } = await import("./mcp-42H2F4NY.js");
3746
+ const { runRouterMcpServer } = await import("./mcp-QML7ZMPH.js");
3739
3747
  await runRouterMcpServer({ dataDir: ctx.dataDir, flags: ctx.flags });
3740
3748
  });
3741
3749
  leaf2(INTEGRATION, "status-line", "the live footer, for Claude Code's status line").description(
3742
3750
  "Print one line naming what this session is looking up right now: the provider actually being called, its bounded parameters, and what it cost. It reads Claude Code's status event on stdin for the session identity, reads that session's own progress records, writes nothing, and prints `x402 \xB7 ready` when this session has no activity. Opt-in: set it as your Claude Code status line command yourself."
3743
3751
  ).action(async function() {
3744
3752
  const ctx = buildContext2(this);
3745
- const { runStatusLine } = await import("./status-line-45TVCRM3.js");
3753
+ const { runStatusLine } = await import("./status-line-YR2T5HC4.js");
3746
3754
  await runStatusLine(io, { dataDir: ctx.dataDir });
3747
3755
  });
3748
3756
  leaf2(SETUP, "status", "what this machine has spent, and what is still open").description(
3749
3757
  "Report the rolling 24h spend window from spend.json: what has settled, what is reserved by a request still in flight, and the per-call and per-day caps in force."
3750
3758
  ).action(async function() {
3751
3759
  await runCommand("status", this, async (ctx) => {
3752
- const { runRouterStatus } = await import("./status-O2RWLPS5.js");
3760
+ const { runRouterStatus } = await import("./status-S7C3WMSH.js");
3753
3761
  return runRouterStatus(ctx);
3754
3762
  });
3755
3763
  });
@@ -3758,7 +3766,7 @@ function registerRouter(reg) {
3758
3766
  );
3759
3767
  payments.action(async function() {
3760
3768
  await runCommand("payments", this, async (ctx) => {
3761
- const { runPaymentsList } = await import("./payments-SPECLBRQ.js");
3769
+ const { runPaymentsList } = await import("./payments-C44QUFXU.js");
3762
3770
  return runPaymentsList(ctx);
3763
3771
  });
3764
3772
  });
@@ -3766,7 +3774,7 @@ function registerRouter(reg) {
3766
3774
  "For each paid lookup whose seller never confirmed settlement and whose authorization has expired, ask USDC on Base (through the configured rpcUrl) whether it was used: used means it was charged, unused means it never can be. Nothing is signed or sent but that one read."
3767
3775
  ).action(async function() {
3768
3776
  await runCommand("payments.reconcile", this, async (ctx) => {
3769
- const { runPaymentsReconcile } = await import("./payments-SPECLBRQ.js");
3777
+ const { runPaymentsReconcile } = await import("./payments-C44QUFXU.js");
3770
3778
  return runPaymentsReconcile(ctx);
3771
3779
  });
3772
3780
  });
@@ -3916,4 +3924,4 @@ export {
3916
3924
  buildProgram,
3917
3925
  main
3918
3926
  };
3919
- //# sourceMappingURL=cli-JPTDHGRX.js.map
3927
+ //# sourceMappingURL=cli-O5SN7ZJ4.js.map