@blockrun/franklin 3.49.5 → 3.49.7

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 (39) hide show
  1. package/README.md +8 -8
  2. package/dist/agent/approvals.d.ts +1 -1
  3. package/dist/agent/commands.js +2 -0
  4. package/dist/agent/context.js +15 -2
  5. package/dist/agent/payment-hold.d.ts +116 -0
  6. package/dist/agent/payment-hold.js +821 -0
  7. package/dist/agent/streaming-executor.js +10 -3
  8. package/dist/agent/tool-guard.d.ts +25 -1
  9. package/dist/agent/tool-guard.js +305 -1
  10. package/dist/agent/types.d.ts +7 -0
  11. package/dist/audit/approvals.d.ts +2 -2
  12. package/dist/audit/approvals.js +1 -1
  13. package/dist/hooks/runner.js +8 -2
  14. package/dist/mcp/client.js +4 -1
  15. package/dist/mcp/codegraph.js +2 -0
  16. package/dist/memory/store.js +2 -0
  17. package/dist/tasks/runner.js +2 -1
  18. package/dist/tasks/spawn.js +2 -1
  19. package/dist/tools/bash.js +11 -10
  20. package/dist/tools/grep.js +3 -0
  21. package/dist/tools/jupiter.d.ts +1 -0
  22. package/dist/tools/jupiter.js +1 -1
  23. package/dist/tools/polymarket/creds.d.ts +8 -2
  24. package/dist/tools/polymarket/creds.js +1 -0
  25. package/dist/tools/polymarket/orders.d.ts +7 -0
  26. package/dist/tools/polymarket/orders.js +36 -0
  27. package/dist/tools/polymarket/relayer.js +38 -4
  28. package/dist/tools/polymarket/withdraw.js +122 -10
  29. package/dist/tools/polymarket-bet.js +6 -6
  30. package/dist/tools/subprocess-env.d.ts +2 -0
  31. package/dist/tools/subprocess-env.js +15 -0
  32. package/dist/tools/trade-plan.js +6 -3
  33. package/dist/tools/zerox-base.d.ts +2 -0
  34. package/dist/tools/zerox-base.js +1 -1
  35. package/dist/tools/zerox-gasless.d.ts +2 -0
  36. package/dist/tools/zerox-gasless.js +1 -1
  37. package/dist/trading/trade-plan.d.ts +9 -1
  38. package/dist/trading/trade-plan.js +153 -36
  39. package/package.json +2 -2
package/README.md CHANGED
@@ -45,7 +45,7 @@
45
45
 
46
46
  ## The pitch in one paragraph
47
47
 
48
- Franklin Agent is an **autonomous economic agent** — an AI that holds a USDC wallet and spends it to get real work done, with **trading as its flagship arena**. It buys live market data, proposes trade plans you approve before a cent moves, pursues long-running goals across sessions, keeps a wallet-bound trading journal, and picks the best model per task from <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models. You state an outcome and set a budget. Franklin Agent decides what to call, what to pay for, and when to stop. No subscriptions, no seats, no rate limits.
48
+ Franklin Agent is an **autonomous economic agent** — an AI that holds a USDC wallet and spends it to get real work done, with **trading as its flagship arena**. It buys live market data, proposes trade plans you approve before a cent moves, pursues long-running goals across sessions, keeps a wallet-bound trading journal, and picks the best model per task from <!-- br:models.chatVisible -->88<!-- /br:models.chatVisible --> models. You state an outcome and set a budget. Franklin Agent decides what to call, what to pay for, and when to stop. No subscriptions, no seats, no rate limits.
49
49
 
50
50
  Funding it is your choice. Fund a **USDC wallet** and every paid action routes through the [x402](https://x402.org) micropayment protocol, settling on-chain against a wallet only you control — no signup, no account, the wallet is the identity. Or top up a **prepaid balance** at [user.blockrun.ai](https://user.blockrun.ai) and hand Franklin an API key. Same models, same tools, same agent. See [Two ways to pay](#two-ways-to-pay).
51
51
 
@@ -387,7 +387,7 @@ Every tool call is itemized. Every token is priced. When the wallet hits zero, F
387
387
 
388
388
  ## Smart Router
389
389
 
390
- **<!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
390
+ **<!-- br:models.chatVisible -->88<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
391
391
 
392
392
  You don't pick models. Franklin picks for you.
393
393
 
@@ -467,7 +467,7 @@ No email. No phone. No KYC. Your Solana, Base or Arc address is your account —
467
467
  | -------------------------------------- | ---------------- | ----------------------- | -------------------- | ------------------------------- |
468
468
  | **Spends money for you** | ❌ | ⚠️ you wire payments | ⚠️ trades only | ✅ **USDC wallet or prepaid key** |
469
469
  | **Buys data + APIs + images + search** | ❌ | ⚠️ one key per service | ❌ | ✅ **one wallet pays for all** |
470
- | Picks best model per task | ❌ single-vendor | ⚠️ you pick | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models** |
470
+ | Picks best model per task | ❌ single-vendor | ⚠️ you pick | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->88<!-- /br:models.chatVisible --> models** |
471
471
  | **Money moves only on your approval** | — | ⚠️ build it yourself | ❌ runs on rules | ✅ **trade plan, every mode** |
472
472
  | Spend guardrails | — | ⚠️ build it yourself | ⚠️ per-bot limits | ✅ **budget caps + hooks** |
473
473
  | Works when a provider goes down | ❌ | ⚠️ if you code it | ❌ | ✅ **routes to another** |
@@ -494,14 +494,14 @@ Ask "what's BTC looking like?" — Franklin fetches live price data, computes RS
494
494
  **🎨 AI image generation**
495
495
  Ask "generate a logo" — Franklin calls DALL-E / GPT Image, saves the result locally, paid from your wallet.
496
496
 
497
- **🧠 <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models via one wallet**
497
+ **🧠 <!-- br:models.chatVisible -->88<!-- /br:models.chatVisible --> models via one wallet**
498
498
  Anthropic, OpenAI, Google, xAI, DeepSeek, GLM, Kimi, Minimax, plus a free tier. One wallet, one interface, automatic fallback.
499
499
 
500
500
  **💳 x402 micropayments (YOPO)**
501
501
  HTTP 402 native. Every paid action is a signed USDC micropayment — an EIP-712 authorization on Base and Arc, a signed SPL transfer on Solana. Non-custodial: your keys never leave your machine. YOPO: you pay only for outcomes.
502
502
 
503
503
  **🧠 Learned model router**
504
- Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> LLMs. Four profiles (auto/eco/premium/free). Adapts to your usage over time.
504
+ Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->88<!-- /br:models.chatVisible --> LLMs. Four profiles (auto/eco/premium/free). Adapts to your usage over time.
505
505
 
506
506
  </td>
507
507
  <td width="50%" valign="top">
@@ -581,13 +581,13 @@ Found a vulnerability? Please report it privately — see [SECURITY.md](SECURITY
581
581
  │ Intent → Smart Router → Tool Use → Spend Control → Result │
582
582
  ├──────────────────────────────────────────────────────────────┤
583
583
  │ Learned Router │
584
- │ 2M+ requests · <!-- br:models.chatVisible@live -->86<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
584
+ │ 2M+ requests · <!-- br:models.chatVisible@live -->88<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
585
585
  ├──────────────────────────────────────────────────────────────┤
586
586
  │ Agent Loop │
587
587
  │ 60+ tools · Sessions · Compaction · Pricing · Plugin SDK │
588
588
  ├──────────────────────────────────────────────────────────────┤
589
589
  │ BlockRun Gateway │
590
- │ <!-- br:models.chatVisible@live -->86<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
590
+ │ <!-- br:models.chatVisible@live -->88<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
591
591
  ├──────────────────────────────────────────────────────────────┤
592
592
  │ x402 Micropayment Protocol │
593
593
  │ HTTP 402 · USDC on Solana, Base & Arc · signed payloads │
@@ -636,7 +636,7 @@ src/
636
636
  ├── stats/ Usage tracking + insights engine
637
637
  ├── ui/ Ink-based terminal UI
638
638
  ├── proxy/ Payment proxy for external tools
639
- ├── router/ Learned model router (<!-- br:models.chatVisible@live -->86<!-- /br:models.chatVisible@live --> models, Elo scoring)
639
+ ├── router/ Learned model router (<!-- br:models.chatVisible@live -->88<!-- /br:models.chatVisible@live --> models, Elo scoring)
640
640
  ├── wallet/ Wallet management (Base/Arc + Solana)
641
641
  ├── mcp/ MCP server auto-discovery
642
642
  └── commands/ CLI subcommands
@@ -10,7 +10,7 @@
10
10
  export interface ApprovalRequest {
11
11
  requestId: string;
12
12
  sessionId: string;
13
- kind: 'trade-plan' | 'tool-permission' | 'ask-user';
13
+ kind: 'trade-plan' | 'tool-permission' | 'ask-user' | 'payment-hold';
14
14
  /** Short human-readable headline. */
15
15
  title: string;
16
16
  /** Full body — markdown-ish text rendered by the answering surface. */
@@ -17,9 +17,11 @@ import { resolveModel } from '../ui/model-picker.js';
17
17
  import { isFreeModelId } from '../free-models.js';
18
18
  import { listSessions, loadSessionHistory, } from '../session/storage.js';
19
19
  import { matchSkill } from '../skills/invoke.js';
20
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
20
21
  // ─── Git helpers ──────────────────────────────────────────────────────────
21
22
  function gitExec(cmd, cwd, timeout = 5000, maxBuffer) {
22
23
  return execSync(cmd, {
24
+ env: sanitizeSubprocessEnv(),
23
25
  cwd,
24
26
  encoding: 'utf-8',
25
27
  timeout,
@@ -11,6 +11,7 @@ import { Keypair } from '@solana/web3.js';
11
11
  import bs58 from 'bs58';
12
12
  import { loadLearnings, decayLearnings, saveLearnings, formatForPrompt } from '../learnings/store.js';
13
13
  import { isKeyMode, resolvePayMode } from '../payments/auth-mode.js';
14
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
14
15
  // ─── System Instructions Assembly ──────────────────────────────────────────
15
16
  // Composable prompt sections — each independently maintainable and conditionally includable.
16
17
  function getCoreInstructions() {
@@ -103,7 +104,18 @@ Examples of risky actions that warrant user confirmation:
103
104
 
104
105
  When you encounter an obstacle, do not use destructive actions as a shortcut. Identify root causes and fix underlying issues rather than bypassing safety checks (e.g. --no-verify). If you discover unexpected state like unfamiliar files, branches, or configuration, investigate before deleting or overwriting — it may represent the user's in-progress work.
105
106
 
106
- A user approving an action once does NOT mean they approve it in all contexts. Match the scope of your actions to what was actually requested. When in doubt, ask before acting.`;
107
+ A user approving an action once does NOT mean they approve it in all contexts. Match the scope of your actions to what was actually requested. When in doubt, ask before acting.
108
+
109
+ ## Ambiguous payment outcomes
110
+ A payment, transfer, bet, or swap that was signed and sent may have settled even when the response says otherwise. A timeout, a 5xx (502 "upstream response lost" included), a dropped connection, or a missing receipt after a send means the outcome is UNKNOWN, not failed. This holds whichever path sent it: a built-in tool, a Bash script, or an MCP tool.
111
+ - Never send a new payment for the same obligation while an earlier attempt's outcome is unknown. A new nonce or a new signature turns one obligation into two settlements.
112
+ - Reconcile first: look up the earlier attempt by its transaction hash (receipt), the sender's nonce, and the sender/recipient balances or the venue's own status endpoint. If it settled, the obligation is paid. Do not pay again.
113
+ - If it is still pending, wait and check again. If a retry is truly needed, re-broadcast the SAME signed transaction (same nonce), so at most one can ever land. Never sign a fresh one.
114
+ - Only when the attempt has provably not settled (a reverted receipt, or a definite rejection of bytes the network never accepted) may a new payment be sent. If you cannot establish that, stop and tell the user exactly what is unknown.
115
+ - Never record an attempt as failed or unpaid until a check has established that; until then its status is UNKNOWN.
116
+ - In the final report, account for every attempt and every settlement. Never report one payment when two may have landed.
117
+ - Franklin enforces this in code for Bash payments: an ambiguous send is marked OUTCOME UNKNOWN, a new send to the same recipient is held for the user's decision, and a failed/unpaid record is refused until a read-only check has run. A hold is not an error to work around — reconcile and report.
118
+ - An approved trade plan executes nothing. Money has moved only when an execution tool call returns success.`;
107
119
  }
108
120
  function getOutputEfficiencySection() {
109
121
  return `# Output Efficiency
@@ -725,7 +737,7 @@ function buildEnvironmentSection(workingDir) {
725
737
  catch { /* ignore */ }
726
738
  // Git repo detection
727
739
  try {
728
- execSync('git rev-parse --is-inside-work-tree', { cwd: workingDir, timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'] });
740
+ execSync('git rev-parse --is-inside-work-tree', { env: sanitizeSubprocessEnv(), cwd: workingDir, timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'] });
729
741
  lines.push('- Is a git repository: true');
730
742
  }
731
743
  catch {
@@ -833,6 +845,7 @@ const GIT_TIMEOUT_MS = 5_000;
833
845
  const MAX_GIT_LOG_CHARS = 800;
834
846
  function getGitContext(workingDir) {
835
847
  const gitCmd = (cmd) => execSync(cmd, {
848
+ env: sanitizeSubprocessEnv(),
836
849
  cwd: workingDir,
837
850
  encoding: 'utf-8',
838
851
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Payment hold — the code half of the "Ambiguous payment outcomes" rule.
3
+ *
4
+ * The system prompt tells the model that a timeout or 5xx after a send means
5
+ * UNKNOWN, not failed. An external audit (EmberTail, Franklin 3.49.6, 37
6
+ * sessions) showed the model does not reliably apply it: after a timeout or
7
+ * a 502 it rewrote the payment script and sent again (three double payments),
8
+ * or recorded the invoice as unpaid without checking. The exact-command dedup
9
+ * caught one resend out of four because it compares command text, and a
10
+ * rewritten script is different text.
11
+ *
12
+ * This module keys on what a Bash run DOES, not what it says:
13
+ * 1. A Bash run whose command — or the script file it runs — sends a
14
+ * transaction or payment is a payment attempt.
15
+ * 2. If that attempt ends in a timeout, a 5xx, a dropped connection, a
16
+ * missing receipt, an error after a tx hash was printed, or detaches to
17
+ * the background, its outcome is UNKNOWN. The tool result is annotated
18
+ * so the model sees that before it decides anything.
19
+ * 3. While an attempt is unknown, any new send that could pay the same
20
+ * recipient is held and goes to the user for an explicit decision; no
21
+ * approval surface (headless) = held. Rewording the script cannot get
22
+ * around this.
23
+ * 4. While an attempt is unknown and no read-only reconciliation (receipt,
24
+ * nonce, balance, status lookup) has run since, recording it as
25
+ * failed/unpaid is refused: the outcome has not been established.
26
+ *
27
+ * Pure detection helpers are exported for tests; SessionToolGuard owns the
28
+ * per-session state.
29
+ */
30
+ interface SimpleCommand {
31
+ /** Words in order, quotes removed, redirect targets excluded. */
32
+ words: string[];
33
+ /** Files redirected into stdin: `node < pay.mjs`. */
34
+ stdinFiles: string[];
35
+ /** Here-strings fed to stdin: `node <<< "code"`. */
36
+ hereStrings: string[];
37
+ /** The command whose output is piped into this one: `cat pay.mjs | node`. */
38
+ pipedFrom: SimpleCommand | null;
39
+ /** Ended by a lone `&`: the shell returns before it finishes. */
40
+ background: boolean;
41
+ /** Has an output redirect to a file (`> f`, `>> f`, `&> f`). */
42
+ writesFile: boolean;
43
+ /** The files those output redirects write. */
44
+ outFiles: string[];
45
+ }
46
+ /**
47
+ * Split shell text into simple commands, honoring single/double quotes and
48
+ * backslash escapes. Separators: newline ; & && | || ( ) $( ` . Output
49
+ * redirects drop their target word (`> pay.mjs` writes the file, it does not
50
+ * run it); input redirects and pipes are kept, because an interpreter reading
51
+ * stdin runs whatever arrives there.
52
+ */
53
+ export declare function splitShellCommands(text: string): SimpleCommand[];
54
+ export interface BashExecution {
55
+ /** Only code that executes. Payment-send and reconciliation detection. */
56
+ code: string;
57
+ /** What it writes or prints rather than runs. Outcome-record detection. */
58
+ data: string;
59
+ /** Part of it keeps running after the Bash call returns. */
60
+ detached: boolean;
61
+ }
62
+ /**
63
+ * What a Bash run will actually execute: the shell text, heredocs an
64
+ * interpreter reads, inline programs (`node -e`, `bash -c`, `eval`), chain
65
+ * CLI calls, and the contents of every local script file it runs — resolved
66
+ * through `cd`, quoting and wrappers like `timeout` or `npx`. A model that
67
+ * writes `pay.mjs` and then runs `bash -c 'node "pay scripts/pay.mjs"'` must
68
+ * not slip past a check that only reads the command line; a command that
69
+ * merely reads or writes a script (`cat pay.mjs`, `printf … > check.mjs`)
70
+ * must not count as running it.
71
+ */
72
+ export declare function analyzeBash(command: string, workingDir: string): BashExecution;
73
+ export declare function bashExecutedText(command: string, workingDir: string): string;
74
+ export declare function isPaymentSend(text: string): boolean;
75
+ export declare function isReconciliation(text: string): boolean;
76
+ /** Addresses that may identify who is being paid, lower-cased. */
77
+ export declare function extractRecipients(text: string, ownAddresses?: string[]): string[];
78
+ /**
79
+ * Why a payment attempt's outcome is unknown, or null when the result is
80
+ * conclusive (clean success, or an error with no sign anything was sent).
81
+ */
82
+ export declare function ambiguousOutcomeReason(output: string, isError: boolean | undefined, ranInBackground: boolean): string | null;
83
+ export declare function extractTxHashes(output: string): string[];
84
+ export declare function recordsNegativeOutcome(text: string): boolean;
85
+ /**
86
+ * Whether code a Bash run executes records a failed/unpaid outcome: it
87
+ * persists something AND carries a negative outcome. A lookup that merely
88
+ * prints `paid` / `unpaid` writes nothing and passes; a ledger script that
89
+ * writes `{"status":"unpaid"}` does not.
90
+ */
91
+ export declare function codeRecordsNegativeOutcome(code: string): boolean;
92
+ export interface PaymentAttempt {
93
+ id: number;
94
+ turn: number;
95
+ at: number;
96
+ /** One-line preview of the command that sent it. */
97
+ command: string;
98
+ /** Candidate recipients; empty = could not tell, so it matches any send. */
99
+ recipients: string[];
100
+ /** The paying wallet(s), so a sender nonce/balance lookup counts as a check. */
101
+ senders: string[];
102
+ reason: string;
103
+ txHashes: string[];
104
+ /** Set once a read-only receipt/nonce/balance lookup ran after it. */
105
+ reconciled: boolean;
106
+ /** Set when the user explicitly allowed a new payment despite it. */
107
+ overriddenByUser: boolean;
108
+ }
109
+ export declare function attemptsOverlap(a: string[], b: string[]): boolean;
110
+ export declare function commandPreview(command: string): string;
111
+ export declare function describeAttempt(a: PaymentAttempt): string;
112
+ export declare function unknownOutcomeNotice(a: PaymentAttempt): string;
113
+ export declare function paymentHoldsDir(): string;
114
+ export declare function loadPaymentAttempts(sessionId: string): PaymentAttempt[];
115
+ export declare function savePaymentAttempts(sessionId: string, attempts: PaymentAttempt[]): void;
116
+ export {};