@blockrun/franklin 3.49.5 → 3.49.6

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.
@@ -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,15 @@ 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
+ - In the final report, account for every attempt and every settlement. Never report one payment when two may have landed.`;
107
116
  }
108
117
  function getOutputEfficiencySection() {
109
118
  return `# Output Efficiency
@@ -725,7 +734,7 @@ function buildEnvironmentSection(workingDir) {
725
734
  catch { /* ignore */ }
726
735
  // Git repo detection
727
736
  try {
728
- execSync('git rev-parse --is-inside-work-tree', { cwd: workingDir, timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'] });
737
+ execSync('git rev-parse --is-inside-work-tree', { env: sanitizeSubprocessEnv(), cwd: workingDir, timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'] });
729
738
  lines.push('- Is a git repository: true');
730
739
  }
731
740
  catch {
@@ -833,6 +842,7 @@ const GIT_TIMEOUT_MS = 5_000;
833
842
  const MAX_GIT_LOG_CHARS = 800;
834
843
  function getGitContext(workingDir) {
835
844
  const gitCmd = (cmd) => execSync(cmd, {
845
+ env: sanitizeSubprocessEnv(),
836
846
  cwd: workingDir,
837
847
  encoding: 'utf-8',
838
848
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { checkTradePlanGate, recordTradeExecution } from '../trading/trade-plan.js';
3
+ import { checkTradePlanGate, recordTradeExecution, releaseTradeReservation } from '../trading/trade-plan.js';
4
4
  const MAX_WEBSEARCHES_PER_TURN = 8;
5
5
  const MAX_SIMILAR_SEARCHES_PER_TURN = 4;
6
6
  const MAX_NO_SIGNAL_SEARCHES_PER_FAMILY = 2;
@@ -423,6 +423,12 @@ export class SessionToolGuard {
423
423
  this.recentGlobs.set(key, { preview, turn: this.turn });
424
424
  }
425
425
  cancelInvocation(invocationId) {
426
+ // Denied before execution (permission refused, PreSpend veto): nothing
427
+ // was submitted, so a trade-plan reservation made by the gate goes back.
428
+ try {
429
+ releaseTradeReservation(invocationId);
430
+ }
431
+ catch { /* budget accounting must never break tool flow */ }
426
432
  this.pendingSearches.delete(invocationId);
427
433
  this.pendingReads.delete(invocationId);
428
434
  this.pendingFetches.delete(invocationId);
@@ -82,6 +82,13 @@ export interface CapabilityResult {
82
82
  mediaType: string;
83
83
  base64: string;
84
84
  }>;
85
+ /**
86
+ * Set by a money-moving tool only when the call provably never submitted
87
+ * anything (validation failure, user cancel, definite venue rejection). The
88
+ * trade-plan gate reserves budget before execution and releases it only on
89
+ * this signal — an error alone may hide an accepted, unacknowledged order.
90
+ */
91
+ notSubmitted?: boolean;
85
92
  }
86
93
  export interface ExecutionScope {
87
94
  workingDir: string;
@@ -17,6 +17,7 @@ import { logger } from '../logger.js';
17
17
  import { appendApprovalRecord } from '../audit/approvals.js';
18
18
  import { loadHooks } from './loader.js';
19
19
  import { BLOCKING_EVENTS, } from './types.js';
20
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
20
21
  const DEFAULT_TIMEOUT_SECS = 5;
21
22
  const MAX_STDOUT_BYTES = 64 * 1024;
22
23
  export class HookEngine {
@@ -78,13 +79,18 @@ export class HookEngine {
78
79
  if (fs.existsSync(resolved))
79
80
  command = resolved;
80
81
  }
82
+ // Lifecycle hooks are user-authored and keep the full env. Tool and spend
83
+ // hooks receive model-controlled input on stdin and may execute it, so the
84
+ // inherited env drops wallet/account keys; the hook's own configured `env`
85
+ // is an explicit user grant and still applies.
86
+ const inherited = input.toolInput || input.spend ? sanitizeSubprocessEnv() : process.env;
87
+ const env = { ...inherited, ...hook.handler.env };
81
88
  return new Promise(resolve => {
82
89
  const child = execFile('/bin/sh', ['-c', command], {
83
90
  timeout: timeoutMs,
84
91
  maxBuffer: MAX_STDOUT_BYTES,
85
92
  env: {
86
- ...process.env,
87
- ...hook.handler.env,
93
+ ...env,
88
94
  // Reserved vars always win over handler env.
89
95
  FRANKLIN_HOOK_EVENT: input.hookEventName,
90
96
  FRANKLIN_SESSION_ID: input.sessionId,
@@ -21,6 +21,7 @@ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/
21
21
  import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
22
22
  import { logger } from '../logger.js';
23
23
  import { createOAuthProvider } from './oauth.js';
24
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
24
25
  // ─── State ────────────────────────────────────────────────────────────────
25
26
  const connections = new Map();
26
27
  const lastFailures = new Map();
@@ -156,7 +157,9 @@ async function connectStdio(name, config) {
156
157
  const transport = new StdioClientTransport({
157
158
  command: config.command,
158
159
  args: config.args || [],
159
- env: { ...process.env, ...(config.env || {}) },
160
+ // Inherited env drops wallet/account keys; values the user wrote into this
161
+ // server's own `env` config are an explicit grant and pass through.
162
+ env: { ...sanitizeSubprocessEnv(), ...(config.env || {}) },
160
163
  // Capture stderr so we can show it in `/mcp` rather than dumping to the
161
164
  // user's terminal. The previous `'ignore'` mode meant a misconfigured
162
165
  // server (missing env, OAuth failure, missing binary) showed up as a
@@ -20,6 +20,7 @@ import { spawn } from 'node:child_process';
20
20
  import fs from 'node:fs';
21
21
  import path from 'node:path';
22
22
  import { logger } from '../logger.js';
23
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
23
24
  const require = createRequire(import.meta.url);
24
25
  /** True unless the user explicitly disabled CodeGraph via env. */
25
26
  function userEnabled() {
@@ -99,6 +100,7 @@ export function ensureCodegraphIndex(workDir) {
99
100
  try {
100
101
  const child = spawn(process.execPath, [shim, 'init', workDir, '-i'], {
101
102
  cwd: workDir,
103
+ env: sanitizeSubprocessEnv(),
102
104
  // Discard output: this is best-effort background indexing. Failures are
103
105
  // non-fatal — the agent simply keeps using grep/read until (and if) the
104
106
  // index appears. Surfacing a stack trace here would just be noise.
@@ -23,6 +23,7 @@ import path from 'node:path';
23
23
  import crypto from 'node:crypto';
24
24
  import { execFileSync } from 'node:child_process';
25
25
  import { BLOCKRUN_DIR } from '../config.js';
26
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
26
27
  export function memoryEnabled() {
27
28
  return process.env.FRANKLIN_MEMORY !== '0';
28
29
  }
@@ -49,6 +50,7 @@ export function repoIdentity(workDir) {
49
50
  let identity = null;
50
51
  try {
51
52
  const url = execFileSync('git', ['-C', workDir, 'remote', 'get-url', 'origin'], {
53
+ env: sanitizeSubprocessEnv(),
52
54
  encoding: 'utf-8',
53
55
  timeout: 2000,
54
56
  stdio: ['ignore', 'pipe', 'ignore'],
@@ -22,6 +22,7 @@ import { spawn } from 'node:child_process';
22
22
  import fs from 'node:fs';
23
23
  import { readTaskMeta, applyEvent, writeTaskMeta } from './store.js';
24
24
  import { taskLogPath, ensureTaskDir } from './paths.js';
25
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
25
26
  const HEARTBEAT_MS = 5_000;
26
27
  const TAIL_BYTES = 500;
27
28
  function safeCloseFd(fd) {
@@ -129,7 +130,7 @@ export async function runDetachedTask(runId) {
129
130
  const child = spawn('bash', ['-lc', meta.command], {
130
131
  cwd: meta.workingDir,
131
132
  stdio: ['ignore', logFd, logFd],
132
- env: { ...process.env, FRANKLIN_TASK_RUN_ID: runId },
133
+ env: { ...sanitizeSubprocessEnv(), FRANKLIN_TASK_RUN_ID: runId },
133
134
  });
134
135
  // Cancel path: parent CLI sends SIGTERM (or user hits Ctrl-C). We must
135
136
  // (a) flip `finalized` BEFORE the soon-to-fire child.exit handler runs so
@@ -30,6 +30,7 @@ import path from 'node:path';
30
30
  import { randomUUID } from 'node:crypto';
31
31
  import { writeTaskMeta } from './store.js';
32
32
  import { taskLogPath, ensureTaskDir } from './paths.js';
33
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
33
34
  // Captured at module load so it survives later chdir / argv mutation.
34
35
  // `process.argv[1]` may be relative (`dist/index.js` in dev mode); we
35
36
  // resolve against process.cwd() at startup which is when the user's
@@ -83,7 +84,7 @@ export function startDetachedTask(input) {
83
84
  cwd: input.workingDir,
84
85
  detached: true,
85
86
  stdio: ['ignore', logFd, logFd],
86
- env: { ...process.env, FRANKLIN_TASK_RUN_ID: runId },
87
+ env: { ...sanitizeSubprocessEnv(), FRANKLIN_TASK_RUN_ID: runId },
87
88
  });
88
89
  child.unref();
89
90
  // The child has duped the fd; closing ours frees the parent's slot.
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import { spawn } from 'node:child_process';
5
5
  import fs from 'node:fs';
6
+ import { sanitizeSubprocessEnv } from './subprocess-env.js';
6
7
  // ─── Smart Output Compression ─────────────────────────────────────────────
7
8
  // Learned from RTK (Rust Token Killer): strip noise before sending to LLM.
8
9
  // Applied after capture, before the 32KB cap — reduces tokens on verbose commands.
@@ -289,22 +290,22 @@ function executeCommand(command, timeoutMs, ctx) {
289
290
  const shell = fs.existsSync('/bin/bash') ? '/bin/bash' : (process.env.SHELL || '/bin/sh');
290
291
  let child;
291
292
  try {
292
- // The account bearer key is deliberately withheld from the subprocess.
293
- // bash-guard auto-approves `printenv` and `echo` as safe, so
294
- // `printenv BLOCKRUN_API_KEY` ran with no confirmation and returned the
295
- // key as tool output — into the model prompt and the saved transcript.
296
- // Wallet private keys are never in the environment at all; this gives
297
- // the key the same treatment. Franklin's own gateway calls read
298
- // process.env in-process and are unaffected, and a user who genuinely
299
- // needs the key in a shell can export it there themselves.
293
+ // Credentials are withheld from the subprocess. bash-guard auto-approves
294
+ // `printenv` and `echo` as safe, so `printenv BLOCKRUN_API_KEY` once ran
295
+ // with no confirmation and returned the key as tool output. The same
296
+ // holds for the wallet keys the SDK reads from BLOCKRUN_WALLET_KEY /
297
+ // BASE_CHAIN_WALLET_KEY / SOLANA_WALLET_KEY: inherited, they let a
298
+ // model-written script sign transfers that no Franklin gate ever sees.
299
+ // Franklin's own gateway calls read process.env in-process and are
300
+ // unaffected, and a user who genuinely needs a key in a shell can
301
+ // export it there themselves.
300
302
  const childEnv = {
301
- ...process.env,
303
+ ...sanitizeSubprocessEnv(),
302
304
  FRANKLIN: '1', // Let scripts detect they're running inside Franklin
303
305
  FRANKLIN_WORKDIR: ctx.workingDir,
304
306
  RUNCODE: '1', // Backwards compat
305
307
  RUNCODE_WORKDIR: ctx.workingDir,
306
308
  };
307
- delete childEnv.BLOCKRUN_API_KEY;
308
309
  child = spawn(shell, ['-c', command], {
309
310
  cwd: ctx.workingDir,
310
311
  env: childEnv,
@@ -6,6 +6,7 @@ import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { BLOCKRUN_DIR } from '../config.js';
8
8
  import { WALLET_KEY_PATHS, hostCredentialDirPaths, isHostCredentialPath, isWalletKeyPath, secretPathRefusal, } from './sensitive-paths.js';
9
+ import { sanitizeSubprocessEnv } from './subprocess-env.js';
9
10
  const MAX_GREP_OUTPUT_CHARS = 16_000; // ~4,000 tokens — prevents huge grep results
10
11
  let _hasRipgrep = null;
11
12
  function hasRipgrep() {
@@ -123,6 +124,7 @@ function runRipgrep(opts, searchPath, mode, limit, cwd) {
123
124
  args.push(searchPath);
124
125
  try {
125
126
  const result = execFileSync('rg', args, {
127
+ env: sanitizeSubprocessEnv(),
126
128
  encoding: 'utf-8',
127
129
  maxBuffer: 2 * 1024 * 1024,
128
130
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -193,6 +195,7 @@ function runNativeGrep(opts, searchPath, mode, limit, cwd) {
193
195
  args.push('-e', opts.pattern, searchPath);
194
196
  try {
195
197
  const result = execFileSync('grep', args, {
198
+ env: sanitizeSubprocessEnv(),
196
199
  encoding: 'utf-8',
197
200
  maxBuffer: 2 * 1024 * 1024,
198
201
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -16,6 +16,7 @@
16
16
  * https://github.com/Jupiter-DevRel/typescript-examples/tree/main/ultra/order-execute-with-referral-accounts
17
17
  */
18
18
  import type { CapabilityHandler } from '../agent/types.js';
19
+ export declare function resolveMint(input: string): string;
19
20
  export declare function toAtomicUnits(amount: number, decimals: number): string;
20
21
  export declare const jupiterQuoteCapability: CapabilityHandler;
21
22
  export declare const jupiterSwapCapability: CapabilityHandler;
@@ -68,7 +68,7 @@ const TOKEN_DECIMALS = {
68
68
  // WIF — 6
69
69
  EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm: 6,
70
70
  };
71
- function resolveMint(input) {
71
+ export function resolveMint(input) {
72
72
  const upper = input.trim().toUpperCase();
73
73
  if (SYMBOL_TO_MINT[upper])
74
74
  return SYMBOL_TO_MINT[upper];
@@ -22,8 +22,14 @@ export interface PolymarketState {
22
22
  * while this is set and unresolved. Cleared on confirm/failure.
23
23
  */
24
24
  pendingWithdraw?: {
25
- transactionID: string;
26
- deadline: number;
25
+ transactionID?: string;
26
+ deadline?: number;
27
+ payloadHash?: string;
28
+ txHash?: string;
29
+ nonce?: string | number;
30
+ from?: string;
31
+ /** EOA path: the signed bytes, so a retry re-broadcasts them instead of signing anew. */
32
+ serializedTransaction?: string;
27
33
  };
28
34
  }
29
35
  export declare function loadL2Creds(address: string, sigType: number): L2Creds | null;
@@ -96,6 +96,7 @@ export function loadDepositWalletForSigner(signer) {
96
96
  return undefined;
97
97
  }
98
98
  export function saveState(patch) {
99
+ // franklin-local: TODO: serialize read/modify/write across processes with a lock.
99
100
  const next = { ...loadState(), ...patch };
100
101
  writeJsonFile(STATE_FILE, next);
101
102
  return next;
@@ -33,6 +33,13 @@ export interface ToolResult {
33
33
  text: string;
34
34
  structured?: Record<string, unknown>;
35
35
  isError?: boolean;
36
+ /**
37
+ * franklin-local: true only when this call provably never handed an order or
38
+ * transaction to the venue (validation, preview, or a definite rejection).
39
+ * Callers holding a spend reservation may release it ONLY on this signal;
40
+ * any other error may have been accepted upstream.
41
+ */
42
+ notSubmitted?: boolean;
36
43
  }
37
44
  export declare function executeTrade(input: TradeInput): Promise<ToolResult>;
38
45
  export declare function listOpenOrders(input: {
@@ -205,7 +205,24 @@ async function withCredsRetry(fn) {
205
205
  return fn(fresh);
206
206
  }
207
207
  }
208
+ /**
209
+ * franklin-local: a submit error is a definite rejection only when the CLOB
210
+ * answered with a 4xx. A missing status (no response: timeout, reset) or a 5xx
211
+ * means the order may have been accepted and its acknowledgement lost.
212
+ */
213
+ function isDefiniteSubmitRejection(err) {
214
+ const status = err?.status;
215
+ return typeof status === "number" && status >= 400 && status < 500 && status !== 408;
216
+ }
208
217
  export async function executeTrade(input) {
218
+ // franklin-local: report whether the order could have reached the CLOB.
219
+ const progress = { submitStarted: false, rejected: false };
220
+ const result = await executeTradeUnchecked(input, progress);
221
+ if (result.isError && (!progress.submitStarted || progress.rejected))
222
+ return { ...result, notSubmitted: true };
223
+ return result;
224
+ }
225
+ async function executeTradeUnchecked(input, progress) {
209
226
  const side = input.action === "buy" ? Side.BUY : Side.SELL;
210
227
  const isLimit = input.price !== undefined;
211
228
  // Cross-field validation (zod schema is per-field; rules live here).
@@ -340,6 +357,10 @@ export async function executeTrade(input) {
340
357
  // Reserve now (before the await) so a concurrent order sees this spend;
341
358
  // roll back if the submit throws so a failed order doesn't consume budget.
342
359
  reserveBet(notional, input.agent_id);
360
+ // withCredsRetry may re-run this body after a definite 401; each attempt
361
+ // starts unrejected so a later ambiguous failure is never mislabelled.
362
+ progress.submitStarted = true;
363
+ progress.rejected = false;
343
364
  let response;
344
365
  try {
345
366
  try {
@@ -361,7 +382,21 @@ export async function executeTrade(input) {
361
382
  }
362
383
  }
363
384
  catch (submitErr) {
385
+ // franklin-local: only a definite rejection frees the reservation. A
386
+ // lost acknowledgement may still be a live order; releasing here let
387
+ // the retry place a second one under a cap that no longer counted it.
388
+ if (!isDefiniteSubmitRejection(submitErr)) {
389
+ commitBet();
390
+ const raw = submitErr instanceof Error ? submitErr.message : String(submitErr);
391
+ return {
392
+ text: `Order outcome UNKNOWN — the submit failed without a definite rejection (${raw}), so the CLOB ` +
393
+ `may have accepted it. Do NOT place it again. Check action:"orders" and action:"positions" first; ` +
394
+ `the session cap still counts this order.\n${summary}`,
395
+ isError: true,
396
+ };
397
+ }
364
398
  releaseBet(notional, input.agent_id);
399
+ progress.rejected = true;
365
400
  throw submitErr;
366
401
  }
367
402
  const r = response;
@@ -373,6 +408,7 @@ export async function executeTrade(input) {
373
408
  const placed = r?.success !== false && (r?.orderID || r?.status === "matched");
374
409
  if (!placed) {
375
410
  releaseBet(notional, input.agent_id);
411
+ progress.rejected = true;
376
412
  throw new Error(r?.errorMsg || "order rejected");
377
413
  }
378
414
  commitBet();
@@ -19,6 +19,13 @@ import { getPolymarketAccount } from "./client.js";
19
19
  import { CLOB_HOST, POLYGON_CHAIN_ID, POLYGON_WRITE_RPC_URL, RELAYER_URL } from "./constants.js";
20
20
  import { loadBuilderCreds, loadL2Creds, saveBuilderCreds, saveL2Creds, saveState } from "./creds.js";
21
21
  import { deriveApiCreds } from "./l1-auth-1271.js";
22
+ // franklin-local: use the SDK builder to persist the signed batch before submission.
23
+ import { AxiosHeaders } from "axios";
24
+ import { keccak256, toHex } from "viem";
25
+ import { buildDepositWalletBatchRequest } from "@polymarket/builder-relayer-client/dist/builder/deposit-wallet.js";
26
+ import { isDepositWalletContractConfigValid } from "@polymarket/builder-relayer-client/dist/config/index.js";
27
+ import { ClientRelayerTransactionResponse } from "@polymarket/builder-relayer-client/dist/response/index.js";
28
+ import { SUBMIT_TRANSACTION } from "@polymarket/builder-relayer-client/dist/endpoints.js";
22
29
  let _relayClient = null;
23
30
  /**
24
31
  * Programmatically obtain Builder API credentials (key/secret/passphrase) for
@@ -112,6 +119,32 @@ export async function getRelayerTransactionState(transactionID) {
112
119
  return undefined;
113
120
  }
114
121
  }
122
+ // franklin-local: signing/auth failures leave no marker; once send starts, a lost
123
+ // response must retain the guard because the relayer may already have the batch.
124
+ async function submitTrackedWithdraw(client, calls, depositWallet, deadline) {
125
+ if (!client.signer)
126
+ throw new Error("Relayer signer unavailable");
127
+ const config = client.contractConfig.DepositWalletContracts;
128
+ if (!isDepositWalletContractConfigValid(config))
129
+ throw new Error("Deposit wallet config unavailable");
130
+ const from = await client.signer.getAddress();
131
+ const { nonce } = await client.getNonce(from, "WALLET");
132
+ const request = await buildDepositWalletBatchRequest(client.signer, {
133
+ from, chainId: client.chainId, walletAddress: depositWallet, nonce, deadline: String(deadline), calls,
134
+ }, config);
135
+ const body = JSON.stringify(request);
136
+ // Mirrors the SDK's private sendAuthedRequest: builder headers only when the
137
+ // builder config is valid, otherwise an unauthenticated submit.
138
+ const headers = client.builderConfig?.isValid()
139
+ ? await client.builderConfig.generateBuilderHeaders("POST", SUBMIT_TRANSACTION, body)
140
+ : undefined;
141
+ const pending = { deadline, from, nonce, payloadHash: keccak256(toHex(body)) };
142
+ const options = { headers: new AxiosHeaders(headers ? { ...headers } : {}), data: body };
143
+ saveState({ pendingWithdraw: pending });
144
+ const { data } = await client.httpClient.send(`${client.relayerUrl}${SUBMIT_TRANSACTION}`, "POST", options);
145
+ saveState({ pendingWithdraw: { ...pending, transactionID: data.transactionID } });
146
+ return new ClientRelayerTransactionResponse(data.transactionID, data.state, data.transactionHash, client);
147
+ }
115
148
  /**
116
149
  * Execute a signed WALLET batch from the deposit wallet (approvals, redeem…).
117
150
  * The SDK fetches the nonce, EIP-712-signs the Batch with the local key, and
@@ -131,10 +164,11 @@ export async function getRelayerTransactionState(transactionID) {
131
164
  */
132
165
  export async function sendWalletBatch(calls, depositWallet, description, opts) {
133
166
  const deadlineSec = Math.floor(Date.now() / 1000) + BATCH_DEADLINE_SECS;
134
- const response = await (await getRelayClient()).executeDepositWalletBatch(calls, depositWallet, String(deadlineSec));
135
- if (opts?.trackPendingWithdraw) {
136
- saveState({ pendingWithdraw: { transactionID: response.transactionID, deadline: deadlineSec } });
137
- }
167
+ // franklin-local: only withdrawals need the pre-submission persistence boundary.
168
+ const client = await getRelayClient();
169
+ const response = opts?.trackPendingWithdraw
170
+ ? await submitTrackedWithdraw(client, calls, depositWallet, deadlineSec)
171
+ : await client.executeDepositWalletBatch(calls, depositWallet, String(deadlineSec));
138
172
  const confirmed = await response.wait();
139
173
  if (!confirmed) {
140
174
  const state = await getRelayerTransactionState(response.transactionID);
@@ -29,6 +29,8 @@ import { getFundsAddress } from "./positions.js";
29
29
  import { loadState, saveState } from "./creds.js";
30
30
  import { getRelayerTransactionState, sendWalletBatch } from "./relayer.js";
31
31
  import { getPublicClient } from "./setup.js";
32
+ // franklin-local: identify an EOA transfer before handing it to the RPC.
33
+ import { keccak256 } from "viem";
32
34
  async function rawTokenBalance(token, owner) {
33
35
  return getPublicClient().readContract({
34
36
  address: token,
@@ -101,17 +103,67 @@ async function readPusdUntil(owner, minimum) {
101
103
  }
102
104
  return observed;
103
105
  }
106
+ // franklin-local: RPC rejections that prove a node refused (and so never
107
+ // relayed) a raw transaction. "already known" is deliberately absent: it means
108
+ // the node HAS the transaction. So is "nonce too low": nonce movement is not
109
+ // evidence about which transaction used the nonce.
110
+ const DEFINITE_REJECTION_RE = /insufficient funds|intrinsic gas too low|max fee per gas less than block base fee|transaction underpriced|invalid sender/i;
111
+ function isDefiniteBroadcastRejection(err) {
112
+ for (let e = err, depth = 0; e && depth < 5; e = e.cause, depth++) {
113
+ const msg = e instanceof Error ? `${e.message} ${e.details ?? ""}` : String(e);
114
+ if (DEFINITE_REJECTION_RE.test(msg))
115
+ return true;
116
+ }
117
+ return false;
118
+ }
119
+ /** True unless the RPC positively reports the hash as unknown. Read errors count as known (fail closed). */
120
+ async function transactionKnown(hash) {
121
+ try {
122
+ await getPublicClient().getTransaction({ hash });
123
+ return true;
124
+ }
125
+ catch (err) {
126
+ return !(err instanceof Error && err.name === "TransactionNotFoundError");
127
+ }
128
+ }
129
+ /**
130
+ * franklin-local: the EOA withdrawal's on-chain outcome, or null while unknown.
131
+ * Only a receipt resolves it. An advanced account nonce plus an RPC that does
132
+ * not know our hash proves nothing — the RPC may lag, or our transaction may
133
+ * be the one that used the nonce — so it is never read as "dropped". While
134
+ * unknown, the same signed bytes are re-broadcast (same nonce, so at most one
135
+ * transfer can ever execute) — never a fresh signature.
136
+ */
137
+ async function eoaPendingStatus(pending) {
138
+ const receipt = await getPublicClient().getTransactionReceipt({ hash: pending.txHash }).catch(() => null);
139
+ if (receipt)
140
+ return receipt.status === "success" ? "success" : "reverted";
141
+ if (pending.serializedTransaction) {
142
+ const account = getPolymarketAccount();
143
+ const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_WRITE_RPC_URL) });
144
+ await wallet.sendRawTransaction({ serializedTransaction: pending.serializedTransaction }).catch(() => undefined);
145
+ }
146
+ return null;
147
+ }
104
148
  const WITHDRAW_GUIDANCE = 'check the pUSD balance with action:"setup" and the bridge status endpoint before ANY retry — ' +
105
149
  "a resubmitted withdrawal signs a SECOND transfer and can double-send";
106
150
  export async function withdrawFunds(input) {
107
151
  let owner;
152
+ let recipient;
108
153
  try {
154
+ // franklin-local: this is the agent's x402 signer, not the deposit wallet.
155
+ recipient = getPolymarketAccount().address;
156
+ if (input.to_address !== undefined && (typeof input.to_address !== "string" || input.to_address.toLowerCase() !== recipient.toLowerCase())) {
157
+ return {
158
+ text: "Withdraw to your agent wallet first; moving funds to an external address is not something the agent does on its own.",
159
+ isError: true,
160
+ };
161
+ }
109
162
  owner = getFundsAddress();
110
163
  }
111
164
  catch (err) {
112
165
  return { text: err instanceof Error ? err.message : String(err), isError: true };
113
166
  }
114
- const recipient = input.to_address || getPolymarketAccount().address;
115
167
  try {
116
168
  // Refuse to sign while an earlier withdrawal batch may still land: its
117
169
  // signature stays executable until its deadline, and a second signed
@@ -120,15 +172,39 @@ export async function withdrawFunds(input) {
120
172
  const pending = loadState().pendingWithdraw;
121
173
  if (pending && input.confirm === true) {
122
174
  const graceSec = 60; // relayer can mine right at the deadline; don't race it
123
- if (Math.floor(Date.now() / 1000) < pending.deadline + graceSec) {
124
- const state = await getRelayerTransactionState(pending.transactionID);
125
- if (state === "STATE_MINED" || state === "STATE_CONFIRMED" || state === "STATE_FAILED" || state === "STATE_INVALID") {
126
- saveState({ pendingWithdraw: undefined });
175
+ // franklin-local: resolving an earlier withdrawal ENDS this call. The
176
+ // retry that finds the first transfer settled is the same call that
177
+ // would otherwise sign a second one on top of it — the double-send this
178
+ // guard exists to stop. The outcome is reported; another withdrawal
179
+ // needs a fresh, deliberate call.
180
+ let resolution = null;
181
+ if (pending.txHash) {
182
+ // franklin-local: EOA transfers have no deadline; only a receipt proves resolution.
183
+ const status = await eoaPendingStatus(pending);
184
+ if (status === null) {
185
+ return {
186
+ text: `A previous withdrawal (${pending.txHash}) has no receipt and may still land — it was re-broadcast ` +
187
+ `as the same signed transaction. Do not retry; check the balance again in a few minutes.`,
188
+ isError: true,
189
+ };
190
+ }
191
+ resolution = status === "success"
192
+ ? `The previous withdrawal SETTLED on-chain (tx ${pending.txHash}).`
193
+ : `The previous withdrawal REVERTED on-chain (tx ${pending.txHash}); no pUSD moved.`;
194
+ // franklin-local: an unacknowledged batch cannot be queried, but can still execute.
195
+ }
196
+ else if (pending.deadline === undefined || Math.floor(Date.now() / 1000) < pending.deadline + graceSec) {
197
+ const state = pending.transactionID ? await getRelayerTransactionState(pending.transactionID) : undefined;
198
+ if (state === "STATE_MINED" || state === "STATE_CONFIRMED") {
199
+ resolution = `The previous withdrawal SETTLED (relayer tx ${pending.transactionID}, ${state}).`;
200
+ }
201
+ else if (state === "STATE_FAILED" || state === "STATE_INVALID") {
202
+ resolution = `The previous withdrawal FAILED (relayer tx ${pending.transactionID}, ${state}); no pUSD moved.`;
127
203
  }
128
204
  else {
129
- const waitSecs = pending.deadline + graceSec - Math.floor(Date.now() / 1000);
205
+ const waitSecs = pending.deadline === undefined ? "unknown" : pending.deadline + graceSec - Math.floor(Date.now() / 1000);
130
206
  return {
131
- text: `A previous withdrawal (relayer tx ${pending.transactionID}, state: ${state ?? "unreachable"}) ` +
207
+ text: `A previous withdrawal (relayer tx ${pending.transactionID ?? "unacknowledged"}, state: ${state ?? "unreachable"}) ` +
132
208
  `may still execute — its signed transfer stays valid for up to ~${waitSecs}s more. Signing another ` +
133
209
  `one now could double-send. Re-run after that window, when the balance reads will show what happened.`,
134
210
  isError: true,
@@ -136,8 +212,18 @@ export async function withdrawFunds(input) {
136
212
  }
137
213
  }
138
214
  else {
139
- saveState({ pendingWithdraw: undefined }); // deadline long past — expired, safe
215
+ // Deadline long past: the batch can no longer execute, but it may
216
+ // already have, so this is not proof that nothing moved.
217
+ resolution = `The previous withdrawal's signature expired (relayer tx ${pending.transactionID ?? "unacknowledged"}). ` +
218
+ `It may or may not have executed before its deadline.`;
140
219
  }
220
+ saveState({ pendingWithdraw: undefined });
221
+ return {
222
+ text: `${resolution} Nothing new was signed. Check the balances (action:"setup") and the bridge status ` +
223
+ `before deciding whether ANOTHER withdrawal is wanted; only then call withdraw again.`,
224
+ isError: true,
225
+ structured: { previousWithdrawal: resolution },
226
+ };
141
227
  }
142
228
  // Withdrawable = pUSD + legacy USDC.e (wrapped on demand below).
143
229
  const [pusdRaw, usdceRaw] = await Promise.all([
@@ -227,14 +313,34 @@ export async function withdrawFunds(input) {
227
313
  else {
228
314
  const account = getPolymarketAccount();
229
315
  const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_WRITE_RPC_URL) });
230
- txHash = await wallet.sendTransaction({ to: PUSD_COLLATERAL, data, chain: polygon, account });
316
+ // franklin-local: hash the locally signed bytes and persist before any broadcast.
317
+ const nonce = await getPublicClient().getTransactionCount({ address: account.address, blockTag: "pending" });
318
+ const request = await wallet.prepareTransactionRequest({ to: PUSD_COLLATERAL, data, chain: polygon, account, nonce });
319
+ const serializedTransaction = await wallet.signTransaction(request);
320
+ txHash = keccak256(serializedTransaction);
321
+ saveState({ pendingWithdraw: { txHash, nonce, from: account.address, serializedTransaction } });
322
+ try {
323
+ await wallet.sendRawTransaction({ serializedTransaction });
324
+ }
325
+ catch (err) {
326
+ // franklin-local: a node that rejected these bytes outright never
327
+ // relayed them, so only that case may release the guard. Anything
328
+ // ambiguous (timeout, 5xx) keeps it until a receipt says otherwise.
329
+ if (isDefiniteBroadcastRejection(err) && !(await transactionKnown(txHash))) {
330
+ saveState({ pendingWithdraw: undefined });
331
+ }
332
+ throw err;
333
+ }
231
334
  // viem does NOT throw on a reverted tx — it resolves with status:"reverted".
232
335
  // Discarding the receipt meant a REVERTED pUSD transfer still printed
233
336
  // "✅ Withdrawal submitted … the bridge delivers USDC to Base" with a link
234
337
  // to the failed tx and no isError, so the user waited for money that was
235
338
  // never sent and blamed the bridge. redeem.ts and setup.ts both assert
236
339
  // status; this path was the one that did not.
237
- assertTransactionSucceeded(await getPublicClient().waitForTransactionReceipt({ hash: txHash }), "pUSD transfer", txHash);
340
+ // franklin-local: either receipt status resolves the guard; timeouts retain it.
341
+ const receipt = await getPublicClient().waitForTransactionReceipt({ hash: txHash });
342
+ saveState({ pendingWithdraw: undefined });
343
+ assertTransactionSucceeded(receipt, "pUSD transfer", txHash);
238
344
  }
239
345
  return {
240
346
  text: [
@@ -62,7 +62,7 @@ async function execute(raw, ctx) {
62
62
  await ensurePolymarketWallet();
63
63
  }
64
64
  catch (err) {
65
- return { output: `Wallet unavailable: ${err instanceof Error ? err.message : String(err)}`, isError: true };
65
+ return { output: `Wallet unavailable: ${err instanceof Error ? err.message : String(err)}`, isError: true, notSubmitted: true };
66
66
  }
67
67
  const wantsConfirm = input.confirm === true;
68
68
  const autoApprove = input.auto_approve === true || process.env.FRANKLIN_POLYMARKET_AUTO_APPROVE === '1';
@@ -77,11 +77,11 @@ async function execute(raw, ctx) {
77
77
  if (preview.isError) {
78
78
  // The dry-run itself failed (bad params, insufficient balance, not set
79
79
  // up) — surface that instead of prompting to sign a doomed action.
80
- return { output: preview.text, isError: true, fullOutput: preview.text };
80
+ return { output: preview.text, isError: true, fullOutput: preview.text, notSubmitted: true };
81
81
  }
82
82
  }
83
83
  catch (err) {
84
- return { output: `Preview failed: ${err instanceof Error ? err.message : String(err)}`, isError: true };
84
+ return { output: `Preview failed: ${err instanceof Error ? err.message : String(err)}`, isError: true, notSubmitted: true };
85
85
  }
86
86
  const answer = await ctx.onAskUser([
87
87
  previewText,
@@ -89,7 +89,7 @@ async function execute(raw, ctx) {
89
89
  '⚠ REAL MONEY — confirming signs and submits this on-chain (Polygon). Proceed?',
90
90
  ].join('\n'), ['Confirm', 'Cancel']);
91
91
  if (answer.toLowerCase() !== 'confirm') {
92
- return { output: 'Polymarket action cancelled by user.' };
92
+ return { output: 'Polymarket action cancelled by user.', notSubmitted: true };
93
93
  }
94
94
  }
95
95
  // Execute for real (or return the dry-run when confirm was never requested).
@@ -113,7 +113,7 @@ async function execute(raw, ctx) {
113
113
  }
114
114
  }
115
115
  if (result.isError) {
116
- return { output: result.text, isError: true, fullOutput: result.text };
116
+ return { output: result.text, isError: true, fullOutput: result.text, ...(result.notSubmitted ? { notSubmitted: true } : {}) };
117
117
  }
118
118
  return { output: result.text, fullOutput: result.text };
119
119
  }
@@ -149,7 +149,7 @@ export const polymarketBetCapability = {
149
149
  post_only: { type: 'boolean', description: 'Maker-only limit order (rejected if it would cross the book).' },
150
150
  order_id: { type: 'string', description: 'Order ID to cancel.' },
151
151
  all: { type: 'boolean', description: 'cancel: cancel ALL open orders.' },
152
- to_address: { type: 'string', description: 'withdraw: destination address on Base (default: your agent wallet).' },
152
+ to_address: { type: 'string', description: 'withdraw: your agent wallet on Base only (default). Other recipients are refused; withdraw to your agent wallet first.' },
153
153
  confirm: { type: 'boolean', description: 'Must be true to place orders / sign approvals / redeem. Omit for a dry-run preview.' },
154
154
  auto_approve: { type: 'boolean', description: 'Skip the interactive user confirmation prompt (headless use). Caps still apply.' },
155
155
  agent_id: { type: 'string', description: 'Tag for the session betting ledger (bets do NOT draw from the x402 API budget).' },
@@ -0,0 +1,2 @@
1
+ export declare const SENSITIVE_ENV_NAMES: readonly ['BLOCKRUN_API_KEY', 'BLOCKRUN_WALLET_KEY', 'BASE_CHAIN_WALLET_KEY', 'SOLANA_WALLET_KEY'];
2
+ export declare function sanitizeSubprocessEnv(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
@@ -0,0 +1,15 @@
1
+ // SDK credential env names must not reach model-driven commands or their output.
2
+ export const SENSITIVE_ENV_NAMES = [
3
+ 'BLOCKRUN_API_KEY',
4
+ 'BLOCKRUN_WALLET_KEY',
5
+ 'BASE_CHAIN_WALLET_KEY',
6
+ 'SOLANA_WALLET_KEY',
7
+ ];
8
+ export function sanitizeSubprocessEnv(env = process.env) {
9
+ const sanitized = { ...env };
10
+ for (const name of SENSITIVE_ENV_NAMES)
11
+ delete sanitized[name];
12
+ // The same OS user can still read key files under ~/.blockrun. This closes
13
+ // the environment path, not file access; in-process gateway calls keep theirs.
14
+ return sanitized;
15
+ }
@@ -33,7 +33,7 @@ export function createTradePlanCapability() {
33
33
  properties: {
34
34
  venue: { type: 'string', enum: ['jupiter', 'zerox', 'polymarket'] },
35
35
  action: { type: 'string', enum: ['buy', 'sell', 'swap', 'bet'] },
36
- asset: { type: 'string', description: 'Symbol, mint/token address, or market outcome.' },
36
+ asset: { type: 'string', description: 'Exactly what the execution call will name: the token symbol/mint/address being bought (or sold, for sells); for polymarket, the token_id, or the condition_id with direction set to the outcome. Matched against that field only.' },
37
37
  direction: { type: 'string', enum: ['long', 'short', 'yes', 'no'] },
38
38
  amountUsd: { type: 'number', description: 'USD to commit to this trade.' },
39
39
  maxSlippageBps: { type: 'number' },
@@ -21,6 +21,8 @@
21
21
  * ZERO_EX_API_KEY — get one free at https://dashboard.0x.org
22
22
  * BASE_RPC_URL — optional override; defaults to public Base RPC
23
23
  */
24
+ import { type Address } from 'viem';
24
25
  import type { CapabilityHandler } from '../agent/types.js';
26
+ export declare function resolveTokenAddress(input: string): Address;
25
27
  export declare const base0xQuoteCapability: CapabilityHandler;
26
28
  export declare const base0xSwapCapability: CapabilityHandler;
@@ -83,7 +83,7 @@ const STABLECOIN_ADDRESSES = new Set([
83
83
  '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2', // USDT
84
84
  '0x50c5725949a6f0c72e6c4a641f24049a917db0cb', // DAI
85
85
  ]);
86
- function resolveTokenAddress(input) {
86
+ export function resolveTokenAddress(input) {
87
87
  const upper = input.trim().toUpperCase();
88
88
  if (SYMBOL_TO_ADDRESS[upper])
89
89
  return SYMBOL_TO_ADDRESS[upper];
@@ -17,5 +17,7 @@
17
17
  *
18
18
  * Reference: https://github.com/0xProject/0x-examples/tree/main/gasless-v2-headless-example
19
19
  */
20
+ import { type Address } from 'viem';
20
21
  import type { CapabilityHandler } from '../agent/types.js';
22
+ export declare function resolveTokenAddress(input: string): Address;
21
23
  export declare const base0xGaslessSwapCapability: CapabilityHandler;
@@ -63,7 +63,7 @@ const STABLECOIN_ADDRESSES = new Set([
63
63
  '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2',
64
64
  '0x50c5725949a6f0c72e6c4a641f24049a917db0cb',
65
65
  ]);
66
- function resolveTokenAddress(input) {
66
+ export function resolveTokenAddress(input) {
67
67
  const upper = input.trim().toUpperCase();
68
68
  if (SYMBOL_TO_ADDRESS[upper])
69
69
  return SYMBOL_TO_ADDRESS[upper];
@@ -39,6 +39,7 @@ export interface TradePlan {
39
39
  decidedBy?: string;
40
40
  changeRequest?: string;
41
41
  consumedUsd: number;
42
+ consumedLineUsd?: number[];
42
43
  }
43
44
  export declare const TRADE_PLAN_TTL_MS: number;
44
45
  export declare function tradePlansDir(): string;
@@ -61,6 +62,11 @@ export declare function formatTradePlanText(plan: TradePlan, walletBalanceUsd?:
61
62
  export declare function setTradePlanSessionId(id: string): void;
62
63
  /** The session's live (approved, unexpired, unconsumed) plan, if any. */
63
64
  export declare function activeTradePlan(sessionId?: string): TradePlan | null;
65
+ /**
66
+ * Release a reservation for a call that was denied before it executed.
67
+ * Safe to call for any invocation id; a no-op when nothing was reserved.
68
+ */
69
+ export declare function releaseTradeReservation(invocationId: string): void;
64
70
  /**
65
71
  * Trade-plan gate — called from SessionToolGuard.beforeExecute for every
66
72
  * invocation. Returns a deny result when a trade-execution call lacks plan
@@ -69,7 +75,9 @@ export declare function activeTradePlan(sessionId?: string): TradePlan | null;
69
75
  */
70
76
  export declare function checkTradePlanGate(invocation: CapabilityInvocation, sessionId?: string): CapabilityResult | null;
71
77
  /**
72
- * Draw down the plan budget after a successful gated execution. Called from
78
+ * Settle the reservation made at the gate. Called from
73
79
  * SessionToolGuard.afterExecute for every invocation (no-op for non-trades).
80
+ * The budget stays spent unless the tool reports `notSubmitted`; an error
81
+ * without that signal may be an accepted order whose response was lost.
74
82
  */
75
83
  export declare function recordTradeExecution(invocation: CapabilityInvocation, result: CapabilityResult, sessionId?: string): void;
@@ -19,6 +19,9 @@ import crypto from 'node:crypto';
19
19
  import { BLOCKRUN_DIR } from '../config.js';
20
20
  import { appendApprovalRecord } from '../audit/approvals.js';
21
21
  import { estimateSpendUsd, TRADE_EXECUTION_TOOLS } from '../tools/spend-tools.js';
22
+ import { resolveMint } from '../tools/jupiter.js';
23
+ import { resolveTokenAddress as resolveBaseToken } from '../tools/zerox-base.js';
24
+ import { resolveTokenAddress as resolveGaslessToken } from '../tools/zerox-gasless.js';
22
25
  import { captureTradeEvent } from '../memory/capture.js';
23
26
  import { getAddress } from '../wallet/manager.js';
24
27
  export const TRADE_PLAN_TTL_MS = 15 * 60 * 1000;
@@ -36,6 +39,7 @@ function planPath(id) {
36
39
  return path.join(tradePlansDir(), `${id}.json`);
37
40
  }
38
41
  export function saveTradePlan(plan) {
42
+ // TODO: protect read/modify/write with a cross-process lock.
39
43
  fs.mkdirSync(tradePlansDir(), { recursive: true });
40
44
  const tmp = path.join(tradePlansDir(), `.${plan.id}.tmp`);
41
45
  fs.writeFileSync(tmp, JSON.stringify(plan, null, 2));
@@ -111,7 +115,7 @@ export function createTradePlan(opts) {
111
115
  expiresAt: Date.now() + (opts.ttlMs ?? TRADE_PLAN_TTL_MS),
112
116
  status: 'pending',
113
117
  trades: opts.trades,
114
- totalSpendUsd: opts.trades.reduce((sum, t) => sum + t.amountUsd, 0),
118
+ totalSpendUsd: opts.trades.reduce((sum, t) => sum + usdUnits(t.amountUsd), 0) / 1e6,
115
119
  rationale: opts.rationale,
116
120
  consumedUsd: 0,
117
121
  };
@@ -119,11 +123,15 @@ export function createTradePlan(opts) {
119
123
  return plan;
120
124
  }
121
125
  export function decideTradePlan(plan, decision, by, reason) {
126
+ // Start from the stored plan, not the caller's copy: a plan object held
127
+ // across an execution would otherwise write back stale consumption and
128
+ // hand an already reserved or spent line its budget again.
129
+ const current = loadTradePlan(plan.id) ?? plan;
122
130
  const updated = {
123
- ...plan,
131
+ ...current,
124
132
  status: decision,
125
133
  decidedBy: by,
126
- changeRequest: decision === 'rejected' ? reason : plan.changeRequest,
134
+ changeRequest: decision === 'rejected' ? reason : current.changeRequest,
127
135
  };
128
136
  saveTradePlan(updated);
129
137
  appendApprovalRecord({
@@ -162,23 +170,91 @@ export function setTradePlanSessionId(id) {
162
170
  gateSessionId = id;
163
171
  }
164
172
  function planIsLive(plan) {
165
- return plan.status === 'approved' && plan.expiresAt > Date.now() && plan.consumedUsd < plan.totalSpendUsd;
173
+ return plan.status === 'approved' && plan.expiresAt > Date.now() && usdUnits(plan.consumedUsd) < usdUnits(plan.totalSpendUsd);
166
174
  }
167
175
  /** The session's live (approved, unexpired, unconsumed) plan, if any. */
168
176
  export function activeTradePlan(sessionId = gateSessionId) {
169
177
  return listTradePlans().find(p => p.sessionId === sessionId && planIsLive(p)) ?? null;
170
178
  }
171
- /** Does the tool input plausibly reference the planned asset? Lenient by design:
172
- * symbols vs mint addresses vs market ids all count as a mention anywhere in
173
- * the input values. A mismatch denies, so false negatives (blocking a covered
174
- * trade) are worse than false positives here — the budget cap still binds. */
175
- function assetMentioned(asset, input) {
176
- const needle = asset.toLowerCase();
177
- for (const value of Object.values(input)) {
178
- if (typeof value === 'string' && value.toLowerCase().includes(needle))
179
- return true;
179
+ // Integer micro-dollars avoid granting an extra cent on each execution.
180
+ function usdUnits(usd) {
181
+ return Math.round(usd * 1e6);
182
+ }
183
+ const authorizations = new WeakMap();
184
+ // Same reservations by invocation id, for denials that only know the id
185
+ // (permission prompt refused, PreSpend hook veto) before the tool ever ran.
186
+ const authorizationsById = new Map();
187
+ /**
188
+ * Move a plan's consumption by `deltaUnits` on one line, re-reading the plan
189
+ * from disk so the write starts from the latest state. Reservation (+) can
190
+ * mark the plan consumed; a release (-) can only reopen a plan that a
191
+ * reservation closed, never a cancelled/expired/rejected one.
192
+ */
193
+ function adjustPlanConsumption(planId, line, deltaUnits) {
194
+ const plan = loadTradePlan(planId);
195
+ if (!plan)
196
+ return null;
197
+ const consumedUnits = Math.max(0, usdUnits(plan.consumedUsd) + deltaUnits);
198
+ const consumedLineUsd = plan.trades.map((_, i) => Math.max(0, usdUnits(plan.consumedLineUsd?.[i] ?? 0) + (i === line ? deltaUnits : 0)) / 1e6);
199
+ const full = consumedUnits >= usdUnits(plan.totalSpendUsd);
200
+ const status = full && plan.status === 'approved' ? 'consumed'
201
+ : !full && plan.status === 'consumed' ? 'approved'
202
+ : plan.status;
203
+ const updated = { ...plan, consumedUsd: consumedUnits / 1e6, consumedLineUsd, status };
204
+ saveTradePlan(updated);
205
+ return updated;
206
+ }
207
+ /**
208
+ * Release a reservation for a call that was denied before it executed.
209
+ * Safe to call for any invocation id; a no-op when nothing was reserved.
210
+ */
211
+ export function releaseTradeReservation(invocationId) {
212
+ const invocation = authorizationsById.get(invocationId);
213
+ if (!invocation)
214
+ return;
215
+ authorizationsById.delete(invocationId);
216
+ const authorization = authorizations.get(invocation);
217
+ authorizations.delete(invocation);
218
+ if (authorization)
219
+ adjustPlanConsumption(authorization.planId, authorization.line, -authorization.units);
220
+ }
221
+ function matchesTrade(trade, invocation) {
222
+ const { name, input } = invocation;
223
+ const equal = (value, resolve = s => s.trim()) => typeof value === 'string' && resolve(value).toLowerCase() === resolve(trade.asset).toLowerCase();
224
+ if (name === 'PolymarketBet') {
225
+ if ((trade.action === 'bet' ? 'buy' : trade.action) !== input.action)
226
+ return false;
227
+ // token_id takes precedence in the tool; unused condition/outcome fields
228
+ // cannot authorize a different token or claim an unverified direction.
229
+ if (input.token_id)
230
+ return !trade.direction && equal(input.token_id);
231
+ if (!input.condition_id || !input.outcome)
232
+ return false;
233
+ if (trade.direction && String(input.outcome).toLowerCase() !== trade.direction)
234
+ return false;
235
+ // The market is identified by condition_id alone. An outcome label such as
236
+ // "Yes" exists in every market, so it can never stand in for the asset.
237
+ return equal(input.condition_id);
238
+ }
239
+ if (trade.action === 'bet')
240
+ return false;
241
+ if (name === 'JupiterSwap') {
242
+ return equal(input[trade.action === 'sell' ? 'input_mint' : 'output_mint'], resolveMint);
243
+ }
244
+ return equal(input[trade.action === 'sell' ? 'sell_token' : 'buy_token'], name === 'Base0xGaslessSwap' ? resolveGaslessToken : resolveBaseToken);
245
+ }
246
+ function tradeAmount(invocation) {
247
+ // Sells do not count as spend in hooks, but still consume their approved line.
248
+ if (invocation.name === 'PolymarketBet') {
249
+ const { price, size, action } = invocation.input;
250
+ if (typeof size === 'number' && Number.isFinite(size) && size > 0) {
251
+ if (action === 'sell')
252
+ return size; // a share can fill above its limit, up to $1
253
+ if (typeof price === 'number' && Number.isFinite(price) && price > 0 && price <= 1)
254
+ return price * size;
255
+ }
180
256
  }
181
- return false;
257
+ return estimateSpendUsd(invocation.name, invocation.input);
182
258
  }
183
259
  function isGatedInvocation(invocation) {
184
260
  if (!TRADE_EXECUTION_TOOLS.has(invocation.name))
@@ -202,11 +278,15 @@ function isGatedInvocation(invocation) {
202
278
  * skips its redundant per-swap confirm (the plan approval IS the confirm).
203
279
  */
204
280
  export function checkTradePlanGate(invocation, sessionId = gateSessionId) {
281
+ // A re-check of the same invocation must not stack a second reservation.
282
+ if (authorizations.has(invocation))
283
+ releaseTradeReservation(invocation.id);
284
+ authorizations.delete(invocation);
205
285
  if (!isGatedInvocation(invocation))
206
286
  return null;
207
287
  const plan = activeTradePlan(sessionId);
208
288
  const venue = VENUE_BY_TOOL[invocation.name];
209
- const estimate = estimateSpendUsd(invocation.name, invocation.input);
289
+ const estimate = tradeAmount(invocation);
210
290
  if (!plan) {
211
291
  appendApprovalRecord({
212
292
  ts: Date.now(),
@@ -225,24 +305,56 @@ export function checkTradePlanGate(invocation, sessionId = gateSessionId) {
225
305
  isError: true,
226
306
  };
227
307
  }
228
- const remaining = plan.totalSpendUsd - plan.consumedUsd;
229
- const matched = plan.trades.find(t => t.venue === venue && assetMentioned(t.asset, invocation.input));
230
- if (!matched) {
308
+ // Plans saved before per-line accounting carry spend that cannot be
309
+ // attributed to a line; treating their lines as unused would let an already
310
+ // consumed line run again. Require a fresh plan instead.
311
+ if (usdUnits(plan.consumedUsd) > 0 && !Array.isArray(plan.consumedLineUsd)) {
312
+ return {
313
+ output: `Trade blocked: plan ${plan.id} predates per-line budget tracking and has already been drawn on, ` +
314
+ 'so its remaining lines cannot be verified. Propose a new plan via the TradePlan tool.',
315
+ isError: true,
316
+ };
317
+ }
318
+ const remaining = usdUnits(plan.totalSpendUsd) - usdUnits(plan.consumedUsd);
319
+ const matching = plan.trades.map((trade, line) => ({ trade, line }))
320
+ .filter(({ trade }) => trade.venue === venue && matchesTrade(trade, invocation));
321
+ if (matching.length === 0) {
231
322
  return {
232
- output: `Trade blocked: approved plan ${plan.id} does not include a ${venue} trade matching this call's asset. ` +
323
+ output: `Trade blocked: approved plan ${plan.id} does not include a ${venue} trade matching this call's asset, action and direction. ` +
233
324
  'Either execute only the planned trades, or propose a new plan via the TradePlan tool.',
234
325
  isError: true,
235
326
  };
236
327
  }
237
- const spendNeeded = estimate ?? matched.amountUsd;
238
- if (spendNeeded > remaining + 0.01) {
328
+ if (estimate === null || !Number.isSafeInteger(usdUnits(estimate)) || usdUnits(estimate) <= 0) {
329
+ return { output: 'Trade blocked: cannot determine a USD amount for this call to enforce the approved line budget.', isError: true };
330
+ }
331
+ const units = usdUnits(estimate);
332
+ const matched = matching.find(({ trade, line }) => units <= usdUnits(trade.amountUsd) - usdUnits(plan.consumedLineUsd?.[line] ?? 0));
333
+ if (!matched || units > remaining) {
239
334
  return {
240
- output: `Trade blocked: this call needs ~$${spendNeeded.toFixed(2)} but plan ${plan.id} has only ` +
241
- `$${remaining.toFixed(2)} of its approved $${plan.totalSpendUsd.toFixed(2)} budget left. ` +
335
+ output: `Trade blocked: this call needs ~$${estimate.toFixed(2)} but plan ${plan.id} has insufficient per-line or total budget left. ` +
242
336
  'Propose a new plan for the additional spend.',
243
337
  isError: true,
244
338
  };
245
339
  }
340
+ // Reserve BEFORE execution. Debiting only after a clean result let an order
341
+ // that was accepted upstream but answered with an error (lost
342
+ // acknowledgement) leave its line unspent, so a retry placed it twice. The
343
+ // reservation is released only when the tool proves nothing was submitted.
344
+ try {
345
+ if (!adjustPlanConsumption(plan.id, matched.line, units))
346
+ throw new Error('plan vanished');
347
+ }
348
+ catch (err) {
349
+ return {
350
+ output: `Trade blocked: could not reserve budget on plan ${plan.id} (${err instanceof Error ? err.message : String(err)}).`,
351
+ isError: true,
352
+ };
353
+ }
354
+ // Keep authorization out of tool inputs and transcripts, and retain the
355
+ // exact plan even if another approval/cancellation occurs while executing.
356
+ authorizations.set(invocation, { planId: plan.id, line: matched.line, units });
357
+ authorizationsById.set(invocation.id, invocation);
246
358
  // Covered: the plan approval already carried the human decision — skip the
247
359
  // tool's own per-swap AskUser confirm (all swap tools honor auto_approve).
248
360
  if (invocation.name !== 'PolymarketBet') {
@@ -251,25 +363,30 @@ export function checkTradePlanGate(invocation, sessionId = gateSessionId) {
251
363
  return null;
252
364
  }
253
365
  /**
254
- * Draw down the plan budget after a successful gated execution. Called from
366
+ * Settle the reservation made at the gate. Called from
255
367
  * SessionToolGuard.afterExecute for every invocation (no-op for non-trades).
368
+ * The budget stays spent unless the tool reports `notSubmitted`; an error
369
+ * without that signal may be an accepted order whose response was lost.
256
370
  */
257
371
  export function recordTradeExecution(invocation, result, sessionId = gateSessionId) {
258
- if (result.isError || !isGatedInvocation(invocation))
372
+ void sessionId;
373
+ const authorization = authorizations.get(invocation);
374
+ authorizations.delete(invocation);
375
+ authorizationsById.delete(invocation.id);
376
+ if (!authorization)
259
377
  return;
260
- const plan = activeTradePlan(sessionId);
378
+ if (result.notSubmitted) {
379
+ adjustPlanConsumption(authorization.planId, authorization.line, -authorization.units);
380
+ return;
381
+ }
382
+ if (result.isError)
383
+ return;
384
+ const plan = loadTradePlan(authorization.planId);
261
385
  if (!plan)
262
386
  return;
263
- const venue = VENUE_BY_TOOL[invocation.name];
264
- const matched = plan.trades.find(t => t.venue === venue && assetMentioned(t.asset, invocation.input));
265
- const spent = estimateSpendUsd(invocation.name, invocation.input) ?? matched?.amountUsd ?? 0;
266
- const consumedUsd = plan.consumedUsd + spent;
267
- const updated = {
268
- ...plan,
269
- consumedUsd,
270
- status: consumedUsd >= plan.totalSpendUsd - 0.01 ? 'consumed' : plan.status,
271
- };
272
- saveTradePlan(updated);
387
+ const matched = plan.trades[authorization.line];
388
+ const venue = matched.venue;
389
+ const spent = authorization.units / 1e6;
273
390
  // Journal the real-money execution into wallet-keyed document memory —
274
391
  // the trade journal follows the wallet, not the working directory.
275
392
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.49.5",
3
+ "version": "3.49.6",
4
4
  "description": "Franklin Agent — The AI agent with a wallet. Spends USDC autonomously to get real work done. Pay per action, no subscriptions.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -38,7 +38,7 @@
38
38
  "desktop:package:win": "npm run dist:win --workspace @blockrun/franklin-desktop",
39
39
  "dev": "tsc --watch",
40
40
  "start": "node dist/index.js",
41
- "test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/api-key.local.mjs test/solana-migration.local.mjs test/serve-security.local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs test/reservation.local.mjs test/model-catalog.local.mjs test/arc.local.mjs",
41
+ "test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/api-key.local.mjs test/solana-migration.local.mjs test/serve-security.local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs test/reservation.local.mjs test/model-catalog.local.mjs test/arc.local.mjs test/subprocess-env.local.mjs test/withdraw.local.mjs test/orders.local.mjs",
42
42
  "test:e2e": "npm run build && node --test --test-reporter=spec test/e2e.mjs",
43
43
  "e2e:polymarket:readonly": "npm run build && node scripts/polymarket-e2e-readonly.mjs",
44
44
  "test:free-models": "npm run build && node --test --test-reporter=spec test/free-model-matrix.mjs",