@blockrun/franklin 3.41.0 → 3.42.0
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.
- package/README.md +54 -4
- package/dist/agent/context.js +7 -10
- package/dist/agent/error-classifier.d.ts +7 -0
- package/dist/agent/error-classifier.js +11 -2
- package/dist/agent/intent-prefetch.d.ts +3 -1
- package/dist/agent/intent-prefetch.js +25 -21
- package/dist/agent/loop.js +31 -3
- package/dist/agent/permissions.d.ts +3 -1
- package/dist/agent/permissions.js +21 -1
- package/dist/agent/streaming-executor.js +54 -53
- package/dist/agent/tokens.js +5 -1
- package/dist/agent/types.d.ts +13 -0
- package/dist/commands/serve.js +4 -1
- package/dist/pricing.js +33 -20
- package/dist/router/index.d.ts +17 -0
- package/dist/router/index.js +80 -1
- package/dist/router/vision.js +10 -3
- package/dist/serve/agent-host.d.ts +5 -0
- package/dist/serve/agent-host.js +13 -3
- package/dist/serve/server.d.ts +11 -0
- package/dist/serve/server.js +285 -69
- package/dist/tools/jupiter.js +16 -2
- package/dist/tools/zerox-base.js +15 -2
- package/dist/tools/zerox-gasless.js +14 -4
- package/dist/ui/model-picker.js +13 -3
- package/package.json +10 -3
package/README.md
CHANGED
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
|
|
29
29
|
<p>
|
|
30
30
|
<a href="#quick-start">Quick start</a> ·
|
|
31
|
+
<a href="#franklin-desktop-beta">Desktop</a> ·
|
|
31
32
|
<a href="#yopo">YOPO</a> ·
|
|
32
33
|
<a href="#a-new-category">Category</a> ·
|
|
33
34
|
<a href="#what-franklin-can-execute">What it does</a> ·
|
|
@@ -113,6 +114,34 @@ VS Code → Extensions (Cmd+Shift+X / Ctrl+Shift+X)
|
|
|
113
114
|
|
|
114
115
|
Free models work immediately. Paid models, image gen, and video gen activate the moment your wallet has USDC. The CLI and the extension share the same `~/.blockrun/` config and session history, so jumping between terminal and VS Code is seamless.
|
|
115
116
|
|
|
117
|
+
### Franklin Desktop (Beta)
|
|
118
|
+
|
|
119
|
+
Franklin Desktop brings the real Franklin agent into a native workspace for macOS
|
|
120
|
+
and Windows. It uses the same local wallet, models, tools, and session runtime as
|
|
121
|
+
the CLI, with a visual chat, conversation history, gallery, wallet, tools, skills,
|
|
122
|
+
and CLI panels.
|
|
123
|
+
|
|
124
|
+
| Platform | Current beta package |
|
|
125
|
+
| -------- | -------------------- |
|
|
126
|
+
| macOS (Apple silicon) | Unsigned `.dmg` test build |
|
|
127
|
+
| Windows (x64) | Unsigned `.exe` test build |
|
|
128
|
+
|
|
129
|
+
> **Beta distribution:** signed public downloads and automatic updates are not
|
|
130
|
+
> live yet. Maintainers can download the short-lived unsigned installers from
|
|
131
|
+
> [Desktop CI](https://github.com/BlockRunAI/Franklin/actions/workflows/desktop-ci.yml).
|
|
132
|
+
> Public signed builds will appear on the
|
|
133
|
+
> [Franklin releases page](https://github.com/BlockRunAI/Franklin/releases).
|
|
134
|
+
|
|
135
|
+
Desktop is local-first: it opens in `Documents/Franklin`, keeps session history
|
|
136
|
+
local by default, and asks before an agent accesses files outside the active
|
|
137
|
+
workspace. External files are not blocked; each access requires explicit approval.
|
|
138
|
+
Shell commands also require approval in the current beta.
|
|
139
|
+
|
|
140
|
+
The stable beta currently runs the Franklin agent. Team Mode and Studio adapters
|
|
141
|
+
for additional agent CLIs are being developed separately and are not included in
|
|
142
|
+
this release. See the [Desktop guide](apps/desktop/README.md) for development and
|
|
143
|
+
packaging instructions.
|
|
144
|
+
|
|
116
145
|
---
|
|
117
146
|
|
|
118
147
|
## YOPO
|
|
@@ -257,7 +286,7 @@ Every tool call is itemized. Every token is priced. When the wallet hits zero, F
|
|
|
257
286
|
|
|
258
287
|
## Smart Router
|
|
259
288
|
|
|
260
|
-
**<!-- br:models.chatVisible -->
|
|
289
|
+
**<!-- br:models.chatVisible -->72<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
|
|
261
290
|
|
|
262
291
|
You don't pick models. Franklin picks for you.
|
|
263
292
|
|
|
@@ -338,7 +367,7 @@ No email. No phone. No KYC. Your Base or Solana address is your account — port
|
|
|
338
367
|
| Writes code | ✅ | ✅ | ⚠️ | ✅ |
|
|
339
368
|
| **Spends money for you** | ❌ | ❌ | ❌ | ✅ **USDC wallet, x402** |
|
|
340
369
|
| **Buys data + APIs + images + search** | ❌ | ❌ | ❌ | ✅ **55+ APIs, one wallet** |
|
|
341
|
-
| Picks best model per task | ❌ single-vendor | ❌ plan-tied | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->
|
|
370
|
+
| Picks best model per task | ❌ single-vendor | ❌ plan-tied | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->72<!-- /br:models.chatVisible --> models** |
|
|
342
371
|
| Pricing model | Subscription | Subscription | Subscription | **YOPO** — per outcome, USDC |
|
|
343
372
|
| Monthly fee | $20–$200 | $20–$40 | $20+ | **$0** |
|
|
344
373
|
| Rate-limited | Yes | Yes | Yes | No — limited only by wallet |
|
|
@@ -366,14 +395,14 @@ Ask "what's BTC looking like?" — Franklin fetches live price data, computes RS
|
|
|
366
395
|
**🎨 AI image generation**
|
|
367
396
|
Ask "generate a logo" — Franklin calls DALL-E / GPT Image, saves the result locally, paid from your wallet.
|
|
368
397
|
|
|
369
|
-
**🧠 <!-- br:models.chatVisible -->
|
|
398
|
+
**🧠 <!-- br:models.chatVisible -->72<!-- /br:models.chatVisible --> models via one wallet**
|
|
370
399
|
Anthropic, OpenAI, Google, xAI, DeepSeek, GLM, Kimi, Minimax, NVIDIA free tier. One wallet, one interface, automatic fallback.
|
|
371
400
|
|
|
372
401
|
**💳 x402 micropayments (YOPO)**
|
|
373
402
|
HTTP 402 native. Every paid action is a signed USDC micropayment via EIP-712 — non-custodial, your keys never leave your machine. YOPO: you pay only for outcomes.
|
|
374
403
|
|
|
375
404
|
**🧠 Learned model router**
|
|
376
|
-
Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->
|
|
405
|
+
Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->72<!-- /br:models.chatVisible --> LLMs. Four profiles (auto/eco/premium/free). Adapts to your usage over time.
|
|
377
406
|
|
|
378
407
|
</td>
|
|
379
408
|
<td width="50%" valign="top">
|
|
@@ -565,6 +594,27 @@ npm run test:free-models # live matrix across current free NVIDIA models
|
|
|
565
594
|
node dist/index.js --help
|
|
566
595
|
```
|
|
567
596
|
|
|
597
|
+
### Desktop app
|
|
598
|
+
|
|
599
|
+
The stable Franklin Desktop shell lives in [`apps/desktop`](apps/desktop). It uses
|
|
600
|
+
the Franklin runtime built by this monorepo, so CLI and Desktop changes are
|
|
601
|
+
versioned and tested together. See the [Desktop guide](apps/desktop/README.md) for
|
|
602
|
+
the product status, security model, and complete development workflow.
|
|
603
|
+
|
|
604
|
+
```bash
|
|
605
|
+
npm run desktop:dev # Desktop UI with the local mock agent
|
|
606
|
+
npm run desktop:real --workspace @blockrun/franklin-desktop # real Franklin agent
|
|
607
|
+
npm run desktop:build # type-check and build the renderer
|
|
608
|
+
npm run desktop:package:mac
|
|
609
|
+
npm run desktop:package:win
|
|
610
|
+
```
|
|
611
|
+
|
|
612
|
+
Packaged builds create a private, per-launch credential for the local Franklin
|
|
613
|
+
service, keep cloud session sync off unless the user explicitly enables it, and
|
|
614
|
+
use `Documents/Franklin` as the default workspace. Files outside that workspace
|
|
615
|
+
remain available after an explicit approval, similar to other coding agents.
|
|
616
|
+
Team Mode is being developed separately and is not part of this stable integration.
|
|
617
|
+
|
|
568
618
|
For the recommended live validation order and failure triage, see [docs/live-e2e-checklist.md](docs/live-e2e-checklist.md).
|
|
569
619
|
|
|
570
620
|
**Contributing:** open an issue first to discuss meaningful changes. PRs welcome on bugs, docs, new models in pricing, and new tools.
|
package/dist/agent/context.js
CHANGED
|
@@ -242,7 +242,7 @@ You run on the BlockRun AI Gateway. When the user asks you to "test the BlockRun
|
|
|
242
242
|
- \`GET /.well-known/x402\` — x402 resource list with prices
|
|
243
243
|
|
|
244
244
|
**LLM (POST, x402-paid)**
|
|
245
|
-
- \`POST /v1/chat/completions\` — OpenAI-compatible. Body: \`{ model, messages, stream?, tools?, max_tokens?, temperature? }\`. \`model\` MUST come from \`GET /v1/models\` (real frontier examples on the gateway, verified live 2026-08-
|
|
245
|
+
- \`POST /v1/chat/completions\` — OpenAI-compatible. Body: \`{ model, messages, stream?, tools?, max_tokens?, temperature? }\`. \`model\` MUST come from \`GET /v1/models\` (real frontier examples on the gateway, verified live 2026-08-29: \`anthropic/claude-sonnet-5\`, \`anthropic/claude-opus-5\`, \`openai/gpt-5.6-sol\`, \`deepseek/deepseek-v4-pro\`, \`zai/glm-5.3\`, \`zai/glm-5.3-flash\`, \`xai/grok-4.5\`, \`qwen/qwen3.7-flash\`, \`nvidia/nemotron-nano-9b-v2\` (free)). Do NOT invent versions like \`openai/gpt-5.1\` or \`xai/grok-5\` — those don't exist; the gateway 400s with the valid list in the error body, so when in doubt fetch \`GET /v1/models\` first.
|
|
246
246
|
- \`POST /v1/messages\` — Anthropic-compatible. Body: \`{ model, messages, max_tokens, system?, tools? }\`.
|
|
247
247
|
|
|
248
248
|
**Media (POST, x402-paid; GET to poll async jobs)**
|
|
@@ -274,23 +274,20 @@ You run on the BlockRun AI Gateway. When the user asks you to "test the BlockRun
|
|
|
274
274
|
- \`POST /v1/solana/rpc\` — JSON-RPC passthrough to public mainnet-beta (getAccountInfo, getTokenSupply, sendTransaction, etc.). \$0.0005 per call (per element of a batch). Use this instead of running your own RPC infra.
|
|
275
275
|
|
|
276
276
|
**Solana DEX swap (Jupiter Ultra)**
|
|
277
|
-
- Use
|
|
277
|
+
- Use **\`JupiterQuote\`** for read-only routes and prices. **\`JupiterSwap\`** is temporarily disabled until Franklin can locally validate every instruction, resolved account, and asset movement before signing.
|
|
278
278
|
- Do NOT try to call \`/v1/jupiter/...\` on the BlockRun gateway — there is no such endpoint (Jupiter ToU forbids the gateway-proxy model).
|
|
279
279
|
|
|
280
|
-
**Base DEX swap (0x V2 via BlockRun gateway)**
|
|
280
|
+
**Base DEX swap (0x V2 via BlockRun gateway)**
|
|
281
281
|
|
|
282
282
|
- **\`Base0xQuote\`** (read-only): inspect price + impact + route. Free.
|
|
283
|
-
- **\`Base0xSwap\`**
|
|
284
|
-
- **\`Base0xGaslessSwap\`**
|
|
283
|
+
- **\`Base0xSwap\`** is temporarily disabled until Franklin can locally validate every transaction field and asset movement.
|
|
284
|
+
- **\`Base0xGaslessSwap\`** is temporarily disabled until Franklin can locally validate every EIP-712 domain, approval, token, amount, recipient, nonce, and deadline.
|
|
285
285
|
|
|
286
|
-
|
|
287
|
-
- User holds ETH on Base → use \`Base0xSwap\` (more flexibility, supports any input token).
|
|
288
|
-
- User holds USDC/DAI but no ETH → use \`Base0xGaslessSwap\` (zero gas needed).
|
|
289
|
-
- User asks for a quote without committing → use \`Base0xQuote\`.
|
|
286
|
+
Use \`Base0xQuote\` to inspect the route and explain that live execution is temporarily unavailable for safety.
|
|
290
287
|
|
|
291
288
|
Symbol shortcuts pre-mapped on all three: ETH (native, Base0xSwap only), WETH, USDC, USDT, CBBTC, CBETH, AERO, DAI. Raw \`0x...\` addresses pass through.
|
|
292
289
|
|
|
293
|
-
|
|
290
|
+
When live execution is restored, its on-chain affiliate fee and local-signing behavior must remain clearly disclosed.
|
|
294
291
|
|
|
295
292
|
**Sandbox (POST, x402-paid)**
|
|
296
293
|
- \`/v1/modal/{...path}\` — Modal GPU sandbox passthrough (create/exec/etc.).
|
|
@@ -24,5 +24,12 @@ export interface AgentErrorInfo {
|
|
|
24
24
|
* malicious or buggy server can't pin the agent indefinitely.
|
|
25
25
|
*/
|
|
26
26
|
retryAfterMs?: number;
|
|
27
|
+
/**
|
|
28
|
+
* The gateway rejected the model id itself (400 "Unknown model", 404, 410
|
|
29
|
+
* provider EOL) — not the request shape. Retrying the same id can never
|
|
30
|
+
* succeed; when the id came from Auto routing the loop feeds it to the
|
|
31
|
+
* router's dead-rung kill-switch (markModelUnavailable) and re-routes.
|
|
32
|
+
*/
|
|
33
|
+
modelUnavailable?: boolean;
|
|
27
34
|
}
|
|
28
35
|
export declare function classifyAgentError(message: string): AgentErrorInfo;
|
|
@@ -202,15 +202,24 @@ export function classifyAgentError(message) {
|
|
|
202
202
|
// "Unknown model: moonshot/kimi-k2". Without this branch the error falls
|
|
203
203
|
// through to the catch-all 'unknown' category and shows the user a bare
|
|
204
204
|
// "Type: Unknown" with no actionable next step.
|
|
205
|
+
// A retired id looks the same to the loop: NVIDIA EOLs surface as HTTP
|
|
206
|
+
// 410 through the gateway (qwen3-next 2026-07-27, deepseek-v4-flash
|
|
207
|
+
// 2026-08-12), and a model the gateway dropped from its catalog 400s as
|
|
208
|
+
// unknown. Either way the id is dead for the rest of the session.
|
|
205
209
|
if (includesAny(err, [
|
|
206
210
|
'unknown model',
|
|
207
211
|
'model not found',
|
|
208
212
|
'model does not exist',
|
|
209
213
|
'no such model',
|
|
210
|
-
|
|
214
|
+
'model has been retired',
|
|
215
|
+
'model is retired',
|
|
216
|
+
'model is no longer available',
|
|
217
|
+
'model no longer available',
|
|
218
|
+
]) || (/\b410\b/.test(err) && err.includes('model'))) {
|
|
211
219
|
return {
|
|
212
220
|
category: 'schema', label: 'Schema', isTransient: false, maxRetries: 0,
|
|
213
|
-
|
|
221
|
+
modelUnavailable: true,
|
|
222
|
+
suggestion: 'The gateway rejected the model id (unknown / retired). Use /model to pick a valid one, or upgrade Franklin if a fallback chain references a stale id.',
|
|
214
223
|
};
|
|
215
224
|
}
|
|
216
225
|
if (includesAny(err, [
|
|
@@ -52,7 +52,9 @@ export interface PrefetchResult {
|
|
|
52
52
|
anyOk: boolean;
|
|
53
53
|
}
|
|
54
54
|
/** Run the prefetch for an intent. Concurrent fan-out for price + news. */
|
|
55
|
-
export declare function prefetchForIntent(intent: Intent, client: ModelClient
|
|
55
|
+
export declare function prefetchForIntent(intent: Intent, client: ModelClient, options?: {
|
|
56
|
+
allowPaid?: boolean;
|
|
57
|
+
}): Promise<PrefetchResult | null>;
|
|
56
58
|
/**
|
|
57
59
|
* Read an ExaAnswer response through BOTH wire shapes — the live BlockRun
|
|
58
60
|
* gateway returns `{ answer, costDollars }` at the TOP level, while older or
|
|
@@ -46,7 +46,7 @@ function formatUsd(n) {
|
|
|
46
46
|
return `$${n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')}`;
|
|
47
47
|
}
|
|
48
48
|
/** Run the prefetch for an intent. Concurrent fan-out for price + news. */
|
|
49
|
-
export async function prefetchForIntent(intent, client) {
|
|
49
|
+
export async function prefetchForIntent(intent, client, options = {}) {
|
|
50
50
|
if (!intent)
|
|
51
51
|
return null;
|
|
52
52
|
const tasks = [];
|
|
@@ -54,25 +54,27 @@ export async function prefetchForIntent(intent, client) {
|
|
|
54
54
|
// 1. Price
|
|
55
55
|
if (intent.kind === 'ticker') {
|
|
56
56
|
if (intent.assetClass === 'stock') {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
57
|
+
if (options.allowPaid !== false) {
|
|
58
|
+
const market = intent.market || 'us';
|
|
59
|
+
tasks.push((async () => {
|
|
60
|
+
// The stock price is a paid x402 call ($0.001) BUT cached for 5 min,
|
|
61
|
+
// so a repeat ticker within the window pays nothing. Book the REAL
|
|
62
|
+
// spend by diffing telemetry around the call (recordFetch fires only
|
|
63
|
+
// on a fresh paid fetch, never a cache hit) instead of hardcoding
|
|
64
|
+
// $0.001 — otherwise a cached hit over-reports the prefetch cost.
|
|
65
|
+
const before = blockrunSpendUsdToday();
|
|
66
|
+
const r = await getStockPrice(intent.symbol, market);
|
|
67
|
+
const paidUsd = Math.max(0, blockrunSpendUsdToday() - before);
|
|
68
|
+
if (typeof r === 'string') {
|
|
69
|
+
return { ok: false, line: `- ${intent.symbol} (${market}): lookup failed — ${r.slice(0, 80)}`, cost: paidUsd };
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
ok: true,
|
|
73
|
+
line: `- ${intent.symbol} (${market}) live price: ${formatUsd(r.price)} (BlockRun Gateway / Pyth)`,
|
|
74
|
+
cost: paidUsd,
|
|
75
|
+
};
|
|
76
|
+
})());
|
|
77
|
+
}
|
|
76
78
|
}
|
|
77
79
|
else {
|
|
78
80
|
// crypto
|
|
@@ -90,7 +92,7 @@ export async function prefetchForIntent(intent, client) {
|
|
|
90
92
|
}
|
|
91
93
|
}
|
|
92
94
|
// 2. News, if asked
|
|
93
|
-
if (intent.kind === 'ticker' && intent.wantNews) {
|
|
95
|
+
if (intent.kind === 'ticker' && intent.wantNews && options.allowPaid !== false) {
|
|
94
96
|
const query = intent.assetClass === 'stock'
|
|
95
97
|
? `Why did ${intent.symbol} stock move over the past week? Recent news and catalysts for ${intent.symbol} as of today.`
|
|
96
98
|
: `What are the most important recent news events affecting ${intent.symbol} cryptocurrency in the past week?`;
|
|
@@ -107,6 +109,8 @@ export async function prefetchForIntent(intent, client) {
|
|
|
107
109
|
};
|
|
108
110
|
}));
|
|
109
111
|
}
|
|
112
|
+
if (tasks.length === 0)
|
|
113
|
+
return null;
|
|
110
114
|
const results = await Promise.all(tasks);
|
|
111
115
|
const anyOk = results.some(r => r.ok);
|
|
112
116
|
cost = results.reduce((s, r) => s + r.cost, 0);
|
package/dist/agent/loop.js
CHANGED
|
@@ -43,7 +43,7 @@ import { writeLiveAgent } from '../session/live-registry.js';
|
|
|
43
43
|
import { estimateCost, OPUS_PRICING } from '../pricing.js';
|
|
44
44
|
import { maybeMidSessionExtract } from '../learnings/extractor.js';
|
|
45
45
|
import { extractMentions, buildEntityContext, loadEntities } from '../brain/store.js';
|
|
46
|
-
import { routeRequest, parseRoutingProfile, getFallbackChain, pickFreeFallback, isVisionModel, messageNeedsVision, pickVisionSibling } from '../router/index.js';
|
|
46
|
+
import { routeRequest, parseRoutingProfile, getFallbackChain, pickFreeFallback, isVisionModel, messageNeedsVision, pickVisionSibling, markModelUnavailable } from '../router/index.js';
|
|
47
47
|
import { recordOutcome } from '../router/local-elo.js';
|
|
48
48
|
import { shouldPlan, getPlanningPrompt, getExecutorModel, isExecutorStuck, toolCallSignature } from './planner.js';
|
|
49
49
|
import { shouldVerify, runVerification } from './verification.js';
|
|
@@ -552,7 +552,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
|
|
|
552
552
|
: capabilityMap;
|
|
553
553
|
const maxTurns = config.maxTurns ?? 15;
|
|
554
554
|
const workDir = config.workingDir ?? process.cwd();
|
|
555
|
-
const permissions = new PermissionManager(config.permissionMode ?? 'default', config.permissionPromptFn);
|
|
555
|
+
const permissions = new PermissionManager(config.permissionMode ?? 'default', config.permissionPromptFn, config.permissionPolicyFn);
|
|
556
556
|
// ── Lifecycle hooks ──
|
|
557
557
|
// User-authored guardrails (spend caps, blacklists, audit) loaded once per
|
|
558
558
|
// session. Built here so every driver (TUI, headless, serve, bots) gets
|
|
@@ -957,6 +957,12 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
|
|
|
957
957
|
// reuse the decision unless a real provider/payment failure deliberately
|
|
958
958
|
// switches config.model to a fallback.
|
|
959
959
|
let pinnedRouting;
|
|
960
|
+
// Re-routes taken this turn because the gateway rejected the routed model
|
|
961
|
+
// id outright. Bounded so a chain that is dead end-to-end surfaces the
|
|
962
|
+
// error instead of cycling; each re-route is a $0 request anyway (the
|
|
963
|
+
// gateway rejects the id before any payment settles).
|
|
964
|
+
let deadModelReroutes = 0;
|
|
965
|
+
const MAX_DEAD_MODEL_REROUTES = 3;
|
|
960
966
|
let routingCandidates = [];
|
|
961
967
|
const turnIdleReference = lastSessionActivity;
|
|
962
968
|
lastSessionActivity = Date.now();
|
|
@@ -1104,7 +1110,9 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
|
|
|
1104
1110
|
// prefetch-classifier call that previously ran here.
|
|
1105
1111
|
try {
|
|
1106
1112
|
if (turnAnalysis?.intent) {
|
|
1107
|
-
const prefetch = await prefetchForIntent(turnAnalysis.intent, client
|
|
1113
|
+
const prefetch = await prefetchForIntent(turnAnalysis.intent, client, {
|
|
1114
|
+
allowPaid: config.allowPaidPrefetch !== false,
|
|
1115
|
+
});
|
|
1108
1116
|
if (prefetch && prefetch.anyOk) {
|
|
1109
1117
|
if (config.showPrefetchStatus !== false) {
|
|
1110
1118
|
onEvent({ kind: 'text_delta', text: `\n${prefetch.statusLine}\n\n` });
|
|
@@ -1707,6 +1715,26 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
|
|
|
1707
1715
|
}
|
|
1708
1716
|
const errMsg = err.message || '';
|
|
1709
1717
|
const classified = classifyAgentError(errMsg);
|
|
1718
|
+
// ── Dead model id (400 "Unknown model" / 404 / 410) ──
|
|
1719
|
+
// Retrying can't help and a fallback chain that still names the id
|
|
1720
|
+
// would just hand it back. When Auto routing picked it, feed the
|
|
1721
|
+
// router's dead-rung kill-switch and re-route this same turn: the
|
|
1722
|
+
// shared Router removes the id from every chain before its next
|
|
1723
|
+
// selection. A concrete user-pinned model is left alone — the user
|
|
1724
|
+
// chose it, and the classified suggestion already says /model.
|
|
1725
|
+
if (classified.modelUnavailable && parseRoutingProfile(config.model)) {
|
|
1726
|
+
const dead = resolvedModel;
|
|
1727
|
+
if (markModelUnavailable(dead) && deadModelReroutes < MAX_DEAD_MODEL_REROUTES) {
|
|
1728
|
+
deadModelReroutes++;
|
|
1729
|
+
pinnedRouting = undefined;
|
|
1730
|
+
logger.warn(`[franklin] ${dead} rejected by the gateway as unavailable — re-routing (${deadModelReroutes}/${MAX_DEAD_MODEL_REROUTES})`);
|
|
1731
|
+
onEvent({
|
|
1732
|
+
kind: 'text_delta',
|
|
1733
|
+
text: `\n*${dead} is no longer served by the gateway — re-routing*\n`,
|
|
1734
|
+
});
|
|
1735
|
+
continue;
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1710
1738
|
// ── Media size error recovery (strip images/PDFs + retry) ──
|
|
1711
1739
|
if (isMediaSizeError(errMsg) && recoveryAttempts < MAX_RECOVERY_ATTEMPTS) {
|
|
1712
1740
|
recoveryAttempts++;
|
|
@@ -13,12 +13,14 @@ export interface PermissionDecision {
|
|
|
13
13
|
behavior: PermissionBehavior;
|
|
14
14
|
reason?: string;
|
|
15
15
|
}
|
|
16
|
+
export type PermissionPolicyFn = (toolName: string, input: Record<string, unknown>) => PermissionDecision | undefined | Promise<PermissionDecision | undefined>;
|
|
16
17
|
export declare class PermissionManager {
|
|
17
18
|
private rules;
|
|
18
19
|
private mode;
|
|
19
20
|
private sessionAllowed;
|
|
20
21
|
private promptFn?;
|
|
21
|
-
|
|
22
|
+
private policyFn?;
|
|
23
|
+
constructor(mode?: PermissionMode, promptFn?: (toolName: string, description: string) => Promise<'yes' | 'no' | 'always'>, policyFn?: PermissionPolicyFn);
|
|
22
24
|
/**
|
|
23
25
|
* Check if a tool can be used. Returns the decision.
|
|
24
26
|
*/
|
|
@@ -78,15 +78,22 @@ export class PermissionManager {
|
|
|
78
78
|
mode;
|
|
79
79
|
sessionAllowed = new Set(); // "always allow" for this session
|
|
80
80
|
promptFn;
|
|
81
|
-
|
|
81
|
+
policyFn;
|
|
82
|
+
constructor(mode = 'default', promptFn, policyFn) {
|
|
82
83
|
this.mode = mode;
|
|
83
84
|
this.rules = this.loadRules();
|
|
84
85
|
this.promptFn = promptFn;
|
|
86
|
+
this.policyFn = policyFn;
|
|
85
87
|
}
|
|
86
88
|
/**
|
|
87
89
|
* Check if a tool can be used. Returns the decision.
|
|
88
90
|
*/
|
|
89
91
|
async check(toolName, input) {
|
|
92
|
+
// Driver policy is authoritative and runs before trust/session/default
|
|
93
|
+
// shortcuts, so a persisted "always allow" cannot bypass a boundary.
|
|
94
|
+
const policyDecision = await this.policyFn?.(toolName, input);
|
|
95
|
+
if (policyDecision)
|
|
96
|
+
return policyDecision;
|
|
90
97
|
// Trust mode: allow everything
|
|
91
98
|
if (this.mode === 'trust') {
|
|
92
99
|
return { behavior: 'allow', reason: 'trust mode' };
|
|
@@ -324,6 +331,19 @@ export class PermissionManager {
|
|
|
324
331
|
}
|
|
325
332
|
return `Execute: ${preview}`;
|
|
326
333
|
}
|
|
334
|
+
case 'Detach': {
|
|
335
|
+
const cmd = String(input.command ?? '');
|
|
336
|
+
const preview = cmd.length > 160 ? cmd.slice(0, 160) + '...' : cmd;
|
|
337
|
+
return `Run in background: ${preview}`;
|
|
338
|
+
}
|
|
339
|
+
case 'PolymarketBet': {
|
|
340
|
+
const action = String(input.action ?? 'unknown').toLowerCase();
|
|
341
|
+
const amount = input.amount != null ? String(input.amount)
|
|
342
|
+
: input.amount_usd != null ? `$${String(input.amount_usd)}`
|
|
343
|
+
: action === 'withdraw' ? 'full available balance' : 'not specified';
|
|
344
|
+
const destination = String(input.to_address ?? input.market_id ?? input.condition_id ?? 'default wallet/market');
|
|
345
|
+
return `Polymarket ${action} — amount: ${amount}; destination/market: ${destination}`;
|
|
346
|
+
}
|
|
327
347
|
case 'Write': {
|
|
328
348
|
const fp = input.file_path || '';
|
|
329
349
|
return `Write file: ${fp}`;
|
|
@@ -134,6 +134,60 @@ export class StreamingExecutor {
|
|
|
134
134
|
}
|
|
135
135
|
async executeWithPermissions(invocation, pendingCount = 1, callStart = true // false for concurrent tools (already called in onToolReceived)
|
|
136
136
|
) {
|
|
137
|
+
// Canonicalize the tool name and normalize schema-typed values before any
|
|
138
|
+
// hook, guard, or permission boundary. Otherwise an alias such as
|
|
139
|
+
// `detach` or a boolean-like value such as `confirm: "true"` could be
|
|
140
|
+
// authorized under a different shape than the handler later executes.
|
|
141
|
+
let handler = this.handlers.get(invocation.name);
|
|
142
|
+
if (!handler) {
|
|
143
|
+
const attempted = invocation.name;
|
|
144
|
+
const lower = attempted.toLowerCase();
|
|
145
|
+
for (const [name, candidate] of this.handlers) {
|
|
146
|
+
if (name.toLowerCase() === lower || name.toLowerCase().replace(/[-_ ]/g, '') === lower.replace(/[-_ ]/g, '')) {
|
|
147
|
+
handler = candidate;
|
|
148
|
+
invocation = { ...invocation, name };
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (!handler) {
|
|
153
|
+
this.guard?.cancelInvocation(invocation.id);
|
|
154
|
+
const available = [...this.handlers.keys()].join(', ');
|
|
155
|
+
return {
|
|
156
|
+
output: `Unknown tool "${attempted}". Available tools: ${available}. Check spelling and try again.`,
|
|
157
|
+
isError: true,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const schema = handler.spec.input_schema;
|
|
162
|
+
if (schema?.properties) {
|
|
163
|
+
for (const [key, value] of Object.entries(invocation.input)) {
|
|
164
|
+
if (value == null)
|
|
165
|
+
continue;
|
|
166
|
+
const prop = schema.properties[key];
|
|
167
|
+
if (!prop?.type)
|
|
168
|
+
continue;
|
|
169
|
+
if (prop.type === 'number' && typeof value === 'string' && !isNaN(Number(value))) {
|
|
170
|
+
invocation.input[key] = Number(value);
|
|
171
|
+
}
|
|
172
|
+
else if (prop.type === 'boolean' && typeof value === 'string') {
|
|
173
|
+
if (value === 'true')
|
|
174
|
+
invocation.input[key] = true;
|
|
175
|
+
else if (value === 'false')
|
|
176
|
+
invocation.input[key] = false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (schema?.required) {
|
|
181
|
+
for (const field of schema.required) {
|
|
182
|
+
if (invocation.input[field] === undefined || invocation.input[field] === null) {
|
|
183
|
+
const desc = schema.properties?.[field]?.description || '';
|
|
184
|
+
return {
|
|
185
|
+
output: `Error: missing required parameter "${field}" for ${handler.spec.name}. ${desc}`,
|
|
186
|
+
isError: true,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
137
191
|
// User hooks fire first — before built-in policy — so an explicit deny
|
|
138
192
|
// is reported with the hook's own reason rather than a generic one.
|
|
139
193
|
if (this.hooks?.hasHooks('PreToolUse')) {
|
|
@@ -178,27 +232,6 @@ export class StreamingExecutor {
|
|
|
178
232
|
const preview = this.inputPreview(invocation);
|
|
179
233
|
this.onStart(invocation.id, invocation.name, preview);
|
|
180
234
|
}
|
|
181
|
-
let handler = this.handlers.get(invocation.name);
|
|
182
|
-
if (!handler) {
|
|
183
|
-
// Attempt repair: lowercase, normalize hyphens/spaces → match
|
|
184
|
-
const attempted = invocation.name;
|
|
185
|
-
const lower = attempted.toLowerCase();
|
|
186
|
-
for (const [name, h] of this.handlers) {
|
|
187
|
-
if (name.toLowerCase() === lower || name.toLowerCase().replace(/[-_ ]/g, '') === lower.replace(/[-_ ]/g, '')) {
|
|
188
|
-
handler = h;
|
|
189
|
-
invocation = { ...invocation, name };
|
|
190
|
-
break;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
if (!handler) {
|
|
194
|
-
this.guard?.cancelInvocation(invocation.id);
|
|
195
|
-
const available = [...this.handlers.keys()].join(', ');
|
|
196
|
-
return {
|
|
197
|
-
output: `Unknown tool "${attempted}". Available tools: ${available}. Check spelling and try again.`,
|
|
198
|
-
isError: true,
|
|
199
|
-
};
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
235
|
// Wire per-invocation progress to onProgress callback
|
|
203
236
|
const progressScope = this.onProgress
|
|
204
237
|
? {
|
|
@@ -207,38 +240,6 @@ export class StreamingExecutor {
|
|
|
207
240
|
}
|
|
208
241
|
: this.scope;
|
|
209
242
|
try {
|
|
210
|
-
// Runtime input validation: check required fields and types
|
|
211
|
-
const schema = handler.spec.input_schema;
|
|
212
|
-
if (schema?.required) {
|
|
213
|
-
for (const field of schema.required) {
|
|
214
|
-
if (invocation.input[field] === undefined || invocation.input[field] === null) {
|
|
215
|
-
const desc = schema.properties?.[field]?.description || '';
|
|
216
|
-
return {
|
|
217
|
-
output: `Error: missing required parameter "${field}" for ${handler.spec.name}. ${desc}`,
|
|
218
|
-
isError: true,
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
// Type coercion for common model mistakes (string↔number, string↔boolean)
|
|
224
|
-
if (schema?.properties) {
|
|
225
|
-
for (const [key, value] of Object.entries(invocation.input)) {
|
|
226
|
-
if (value == null)
|
|
227
|
-
continue;
|
|
228
|
-
const prop = schema.properties[key];
|
|
229
|
-
if (!prop?.type)
|
|
230
|
-
continue;
|
|
231
|
-
if (prop.type === 'number' && typeof value === 'string' && !isNaN(Number(value))) {
|
|
232
|
-
invocation.input[key] = Number(value);
|
|
233
|
-
}
|
|
234
|
-
else if (prop.type === 'boolean' && typeof value === 'string') {
|
|
235
|
-
if (value === 'true')
|
|
236
|
-
invocation.input[key] = true;
|
|
237
|
-
else if (value === 'false')
|
|
238
|
-
invocation.input[key] = false;
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
243
|
// Track elapsed for slow-tool forensics. Verified 2026-05-04
|
|
243
244
|
// from a real session: a 337.6s Bash error left no trace in
|
|
244
245
|
// franklin-debug.log — the user could see the ✗ in the UI but
|
package/dist/agent/tokens.js
CHANGED
|
@@ -202,7 +202,7 @@ const MODEL_CONTEXT_WINDOWS = {
|
|
|
202
202
|
'anthropic/claude-opus-5': 200_000,
|
|
203
203
|
'anthropic/claude-opus-4.8': 200_000,
|
|
204
204
|
'anthropic/claude-opus-4.7': 200_000,
|
|
205
|
-
'anthropic/claude-opus-4.6': 200_000,
|
|
205
|
+
'anthropic/claude-opus-4.6': 200_000, // hidden from /v1/models, still served (probed 2026-08-29)
|
|
206
206
|
'anthropic/claude-opus-4.5': 200_000,
|
|
207
207
|
'anthropic/claude-sonnet-5': 200_000,
|
|
208
208
|
'anthropic/claude-sonnet-4.6': 200_000,
|
|
@@ -258,16 +258,20 @@ const MODEL_CONTEXT_WINDOWS = {
|
|
|
258
258
|
'xai/grok-4.5': 500_000,
|
|
259
259
|
'xai/grok-4.3': 1_000_000,
|
|
260
260
|
'xai/grok-build-0.1': 256_000,
|
|
261
|
+
// xAI 3.x / 4-0709 / 4-1-fast: hidden from /v1/models since 2026-08 but
|
|
262
|
+
// still served and charged (probed 2026-08-29) — keep their windows.
|
|
261
263
|
'xai/grok-3': 131_072,
|
|
262
264
|
'xai/grok-4-0709': 131_072,
|
|
263
265
|
'xai/grok-4-1-fast-reasoning': 131_072,
|
|
264
266
|
// Others
|
|
265
267
|
'zai/glm-5.3': 1_000_000, // flagship 2026-08 — 1M context, always-on reasoning
|
|
268
|
+
'zai/glm-5.3-flash': 1_000_000, // 2026-08-29 catalog sync — 1M context, vision, $0.15/$0.5
|
|
266
269
|
'zai/glm-5.2': 1_000_000, // flagship bump 2026-06 — context jumped 200K → 1M
|
|
267
270
|
'zai/glm-5.1': 200_000,
|
|
268
271
|
'zai/glm-5': 200_000,
|
|
269
272
|
'zai/glm-5-turbo': 200_000,
|
|
270
273
|
'moonshot/kimi-k3': 1_048_576,
|
|
274
|
+
// K2.x: hidden from /v1/models, still served (probed 2026-08-29).
|
|
271
275
|
'moonshot/kimi-k2.7': 256_000,
|
|
272
276
|
'moonshot/kimi-k2.6': 256_000,
|
|
273
277
|
'moonshot/kimi-k2.5': 128_000,
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -173,6 +173,17 @@ export interface AgentConfig {
|
|
|
173
173
|
* Returns 'yes' | 'no' | 'always' (always = allow for rest of session).
|
|
174
174
|
*/
|
|
175
175
|
permissionPromptFn?: (toolName: string, description: string) => Promise<'yes' | 'no' | 'always'>;
|
|
176
|
+
/**
|
|
177
|
+
* Optional driver-level policy evaluated before Franklin's normal permission
|
|
178
|
+
* rules. Returning undefined delegates to the normal policy.
|
|
179
|
+
*/
|
|
180
|
+
permissionPolicyFn?: (toolName: string, input: Record<string, unknown>) => {
|
|
181
|
+
behavior: 'allow' | 'deny' | 'ask';
|
|
182
|
+
reason?: string;
|
|
183
|
+
} | undefined | Promise<{
|
|
184
|
+
behavior: 'allow' | 'deny' | 'ask';
|
|
185
|
+
reason?: string;
|
|
186
|
+
} | undefined>;
|
|
176
187
|
/** Routes AskUser questions through ink UI input to avoid raw-mode stdin conflict */
|
|
177
188
|
onAskUser?: (question: string, options?: string[]) => Promise<string>;
|
|
178
189
|
/** Notify UI when agent switches model. `reason` is 'user' for explicit /model
|
|
@@ -199,6 +210,8 @@ export interface AgentConfig {
|
|
|
199
210
|
* bound a single run to keep autonomous execution inside a known envelope.
|
|
200
211
|
*/
|
|
201
212
|
maxSpendUsd?: number;
|
|
213
|
+
/** Disable proactive data sources that may sign an x402 payment. */
|
|
214
|
+
allowPaidPrefetch?: boolean;
|
|
202
215
|
/** Show user-visible harness prefetch status lines (interactive UX only). */
|
|
203
216
|
showPrefetchStatus?: boolean;
|
|
204
217
|
/**
|
package/dist/commands/serve.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { startServer } from '../serve/server.js';
|
|
3
3
|
export async function serveCommand(options) {
|
|
4
|
-
const
|
|
4
|
+
const parsedPort = options.port == null ? 3737 : Number(options.port);
|
|
5
|
+
const port = Number.isInteger(parsedPort) && parsedPort >= 0 && parsedPort <= 65535
|
|
6
|
+
? parsedPort
|
|
7
|
+
: 3737;
|
|
5
8
|
const workDir = options.workDir ? path.resolve(options.workDir) : process.cwd();
|
|
6
9
|
await startServer({ port, workDir, debug: !!options.debug });
|
|
7
10
|
}
|