@blockrun/franklin 3.21.9 → 3.23.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 +12 -0
- package/dist/agent/context.js +6 -4
- package/dist/agent/llm.js +20 -7
- package/dist/agent/loop.js +29 -0
- package/dist/agent/optimize.js +3 -2
- package/dist/agent/repair/flatten.d.ts +32 -0
- package/dist/agent/repair/flatten.js +77 -0
- package/dist/agent/repair/index.d.ts +66 -0
- package/dist/agent/repair/index.js +77 -0
- package/dist/agent/repair/scavenge.d.ts +12 -0
- package/dist/agent/repair/scavenge.js +193 -0
- package/dist/agent/repair/truncation.d.ts +17 -0
- package/dist/agent/repair/truncation.js +94 -0
- package/dist/agent/tokens.js +2 -1
- package/dist/commands/init.js +1 -1
- package/dist/content/image-pricing.d.ts +7 -1
- package/dist/content/image-pricing.js +40 -17
- package/dist/content/record-image.d.ts +1 -1
- package/dist/content/record-image.js +2 -2
- package/dist/pricing.js +2 -1
- package/dist/proxy/server.js +2 -1
- package/dist/router/index.js +6 -5
- package/dist/router/vision.js +1 -0
- package/dist/tools/blockrun.js +13 -4
- package/dist/tools/imagegen.d.ts +22 -3
- package/dist/tools/imagegen.js +252 -88
- package/dist/tools/index.js +5 -1
- package/dist/tools/realface.d.ts +29 -0
- package/dist/tools/realface.js +263 -0
- package/dist/tools/surf.d.ts +22 -0
- package/dist/tools/surf.js +281 -0
- package/dist/tools/tool-categories.js +7 -0
- package/dist/tools/videogen.js +44 -1
- package/dist/ui/model-picker.js +3 -2
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -487,6 +487,18 @@ Same wallet. Same tools. From your phone.
|
|
|
487
487
|
|
|
488
488
|
---
|
|
489
489
|
|
|
490
|
+
## Contributors
|
|
491
|
+
|
|
492
|
+
External contributors whose work has shipped into Franklin:
|
|
493
|
+
|
|
494
|
+
- [**@KillerQueen-Z**](https://github.com/KillerQueen-Z) — typed Phone & Voice tools (#58), permissions classifier + internal VoiceStatus polling (#59), inline-paste threshold (#60), voicemail controls (#61), PredictionMarket / Predexon v2 schema realignment + agent-loop retry guard (#62)
|
|
495
|
+
- [**@BeneficialVast1048**](https://github.com/BeneficialVast1048) — VoiceCall `interruption_threshold` + `model` controls (#66)
|
|
496
|
+
- [**@TateLyman**](https://github.com/TateLyman) — test path-with-spaces fix (#57)
|
|
497
|
+
|
|
498
|
+
PRs welcome — see the Development section below for the local loop.
|
|
499
|
+
|
|
500
|
+
---
|
|
501
|
+
|
|
490
502
|
## Development
|
|
491
503
|
|
|
492
504
|
```bash
|
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 as of 2026-05: \`anthropic/claude-sonnet-4.6\`, \`anthropic/claude-opus-4.
|
|
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 as of 2026-05: \`anthropic/claude-sonnet-4.6\`, \`anthropic/claude-opus-4.8\`, \`deepseek/deepseek-v4-pro\`, \`zai/glm-5.1\`, \`nvidia/qwen3-coder-480b\`, \`openai/gpt-5-nano\`). 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)**
|
|
@@ -305,8 +305,10 @@ On-chain affiliate (20 bps in sell-token, force-set server-side) flows to BlockR
|
|
|
305
305
|
- US/CA destinations only. Marketing/sales calls require prior express consent (TCPA).
|
|
306
306
|
|
|
307
307
|
**Surf — crypto data + chat (x402-paid)** via the generic \`BlockRun\` capability. ~55 curated endpoints. Tier-1 $0.001, Tier-2 $0.005, Tier-3 / chat $0.02.
|
|
308
|
-
- \`/v1/surf/
|
|
309
|
-
- \`/v1/surf/market
|
|
308
|
+
- \`/v1/surf/market/ranking\` — token rankings (market cap, volume, change). **This is the token-ranking endpoint — there is no \`market/token-ranking\` or \`market/concept-ranking\`.**
|
|
309
|
+
- \`/v1/surf/market/fear-greed\` — Fear & Greed index. \`market/futures\` — futures overview. \`market/price\` (needs \`symbol\`) — price history. \`market/etf\` (needs \`symbol\`) — spot ETF flows. \`market/options\` (needs \`symbol\`) — options skew/IV.
|
|
310
|
+
- \`/v1/surf/market/{liquidation/chart,liquidation/order,onchain-indicator,price-indicator}\` — liquidations, on-chain indicators (NUPL/SOPR/MVRV), technical indicators (RSI/MACD/BBANDS). Tier-2 $0.005.
|
|
311
|
+
- \`/v1/surf/exchange/{price,perp,markets,depth,klines,funding-history}\` — CEX ticker, perps, pairs catalog, depth, klines, funding.
|
|
310
312
|
- \`/v1/surf/news/{feed,detail}\` — AI-curated crypto news.
|
|
311
313
|
- \`/v1/surf/onchain/{bridge,yield,gas-price,tx,schema,query,sql}\` — bridge/yield rankings, gas, tx detail, **raw SQL against 80+ indexed chain tables (Tier-3, $0.02)**, structured chain query, schema introspection.
|
|
312
314
|
- \`/v1/surf/token/{tokenomics,dex-trades,holders,transfers}\` — token analytics.
|
|
@@ -315,7 +317,7 @@ On-chain affiliate (20 bps in sell-token, force-set server-side) flows to BlockR
|
|
|
315
317
|
- \`/v1/surf/fund/{detail,portfolio,ranking}\` — VC fund profiles, portfolios, ranking.
|
|
316
318
|
- \`/v1/surf/project/{detail,defi/metrics,defi/ranking}\` — project profiles + DeFi protocol metrics.
|
|
317
319
|
|
|
318
|
-
|
|
320
|
+
**Endpoint discovery**: if you are unsure of the exact Surf path, do NOT guess blindly — any wrong \`/v1/surf/...\` path returns a 404 whose body lists every valid endpoint under \`available\`. Read that list and retry with a real path. The bundled skills (\`/surf-market\`, \`/surf-chain\`, \`/surf-social\`) also document which endpoint to pick for which question and the cost trade-off. Skipped (use the dedicated tools instead): \`/v1/surf/prediction-market/*\` (use \`PredictionMarket\`), \`/v1/surf/search/*\` (use \`ExaSearch\`), \`/v1/surf/web/*\` (use \`BrowserX\`). The Surf chat surface (\`/v1/surf/chat/completions\`, surf-1.5) is **not currently exposed** by the BlockRun gateway — removed from the registry pending an upstream redesign around per-token billing. Do not attempt to call it; use the data endpoints above for crypto context, or any of the standard LLMs on \`/v1/chat/completions\` for general chat.
|
|
319
321
|
|
|
320
322
|
**Generic gateway primitive**: \`BlockRun({ path, method, params, body })\` is a single capability that signs x402 and forwards to ANY path under \`/api\`. Use it for Surf endpoints (above) and any future BlockRun partner that doesn't have a dedicated capability yet. Always specify the exact path; the primitive will not guess.
|
|
321
323
|
|
package/dist/agent/llm.js
CHANGED
|
@@ -9,6 +9,7 @@ import { appendSettlementRow } from '../stats/cost-log.js';
|
|
|
9
9
|
import { routeRequest, parseRoutingProfile } from '../router/index.js';
|
|
10
10
|
import { ThinkTagStripper } from './think-tag-stripper.js';
|
|
11
11
|
import { isNemotronProseModel, stripNemotronProse } from './nemotron-prose-stripper.js';
|
|
12
|
+
import { repairAndParseArgs } from './repair/index.js';
|
|
12
13
|
// Reasoning-tier models the gateway routes to that reject `tool_choice`
|
|
13
14
|
// outright. Pattern: OpenAI o1/o3 family + DeepSeek's reasoner variant.
|
|
14
15
|
// Add new entries as their 400 errors appear in real sessions; this is
|
|
@@ -195,6 +196,8 @@ export function modelHasExtendedThinking(model) {
|
|
|
195
196
|
const m = model.toLowerCase();
|
|
196
197
|
// Excluded: Opus 4.7+ uses adaptive thinking; sending `thinking: enabled`
|
|
197
198
|
// causes the API to 400.
|
|
199
|
+
if (m.includes('opus-4.8') || m.includes('opus-4-8'))
|
|
200
|
+
return false;
|
|
198
201
|
if (m.includes('opus-4.7') || m.includes('opus-4-7'))
|
|
199
202
|
return false;
|
|
200
203
|
return (m.includes('opus-4.6') || m.includes('opus-4-6') ||
|
|
@@ -774,17 +777,27 @@ export class ModelClient {
|
|
|
774
777
|
if (currentToolId) {
|
|
775
778
|
let parsedInput = {};
|
|
776
779
|
let inputParseError = false;
|
|
780
|
+
// First try strict parse; on failure, fall back to the
|
|
781
|
+
// truncation-repair pipeline (closes unbalanced braces,
|
|
782
|
+
// trims trailing commas, fills dangling keys with null).
|
|
783
|
+
// Saves a turn whenever max_tokens cut a tool_use mid-emit.
|
|
777
784
|
try {
|
|
778
785
|
parsedInput = JSON.parse(currentToolInput || '{}');
|
|
779
786
|
}
|
|
780
787
|
catch (parseErr) {
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
+
const repaired = repairAndParseArgs(currentToolInput || '{}');
|
|
789
|
+
if (repaired) {
|
|
790
|
+
parsedInput = repaired.input;
|
|
791
|
+
if (this.debug && repaired.repaired) {
|
|
792
|
+
console.error(`[franklin] repaired truncated tool_use JSON for ${currentToolName}: ${repaired.notes.join('; ')}`);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
else {
|
|
796
|
+
inputParseError = true;
|
|
797
|
+
if (this.debug) {
|
|
798
|
+
console.error(`[franklin] Malformed tool input JSON for ${currentToolName}: ${parseErr.message}`);
|
|
799
|
+
console.error(`[franklin] Raw input was: ${currentToolInput.slice(0, 200)}`);
|
|
800
|
+
}
|
|
788
801
|
}
|
|
789
802
|
}
|
|
790
803
|
if (inputParseError) {
|
package/dist/agent/loop.js
CHANGED
|
@@ -14,6 +14,7 @@ import { StreamingExecutor } from './streaming-executor.js';
|
|
|
14
14
|
import { optimizeHistory, CAPPED_MAX_TOKENS, ESCALATED_MAX_TOKENS, getMaxOutputTokens } from './optimize.js';
|
|
15
15
|
import { classifyAgentError } from './error-classifier.js';
|
|
16
16
|
import { SessionToolGuard } from './tool-guard.js';
|
|
17
|
+
import { ToolCallRepair } from './repair/index.js';
|
|
17
18
|
import { resetToolSessionState } from '../tools/index.js';
|
|
18
19
|
import { CORE_TOOL_NAMES, dynamicToolsEnabled } from '../tools/tool-categories.js';
|
|
19
20
|
import { createActivateToolCapability } from '../tools/activate.js';
|
|
@@ -608,6 +609,11 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
|
|
|
608
609
|
// outputs, or paths. Fed into opt-in telemetry at session end.
|
|
609
610
|
const sessionToolCounts = new Map();
|
|
610
611
|
const toolGuard = new SessionToolGuard();
|
|
612
|
+
// Recovers tool calls that the model leaked into the text or thinking
|
|
613
|
+
// channels instead of the structured tool_use channel. See
|
|
614
|
+
// src/agent/repair/scavenge.ts for the failure modes — most common on
|
|
615
|
+
// DeepSeek R1 and small Qwen/Llama variants behind the BlockRun gateway.
|
|
616
|
+
const callRepair = new ToolCallRepair({ allowedToolNames: activeTools });
|
|
611
617
|
const persistSessionMeta = () => {
|
|
612
618
|
updateSessionMeta(sessionId, {
|
|
613
619
|
model: config.model,
|
|
@@ -1302,6 +1308,29 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
|
|
|
1302
1308
|
responseParts = result.content;
|
|
1303
1309
|
usage = result.usage;
|
|
1304
1310
|
stopReason = result.stopReason;
|
|
1311
|
+
// ── Tool-call scavenge ──
|
|
1312
|
+
// Recover tool calls the model emitted as text/thinking instead of
|
|
1313
|
+
// structured tool_use blocks. Common on DeepSeek R1 (leaks JSON
|
|
1314
|
+
// into reasoning_content) and small Qwen/Llama variants. If the
|
|
1315
|
+
// scavenger finds anything, splice it into responseParts so the
|
|
1316
|
+
// empty-response and stalled-intent checks below see tools.
|
|
1317
|
+
{
|
|
1318
|
+
const declaredCalls = responseParts.filter((p) => p.type === 'tool_use');
|
|
1319
|
+
const reasoningText = responseParts
|
|
1320
|
+
.filter((p) => p.type === 'thinking')
|
|
1321
|
+
.map(p => p.thinking)
|
|
1322
|
+
.join('\n');
|
|
1323
|
+
const contentText = responseParts
|
|
1324
|
+
.filter((p) => p.type === 'text')
|
|
1325
|
+
.map(p => p.text)
|
|
1326
|
+
.join('\n');
|
|
1327
|
+
const repaired = callRepair.process(declaredCalls, reasoningText || null, contentText || null);
|
|
1328
|
+
if (repaired.report.scavenged > 0) {
|
|
1329
|
+
const novelCalls = repaired.calls.slice(declaredCalls.length);
|
|
1330
|
+
responseParts = [...responseParts, ...novelCalls];
|
|
1331
|
+
logger.warn(`[franklin] scavenged ${repaired.report.scavenged} leaked tool call(s) from ${config.model}: ${repaired.report.notes.join('; ')}`);
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1305
1334
|
// ── Empty response recovery ──
|
|
1306
1335
|
// If the model returns nothing, DON'T just retry the same model with the same input.
|
|
1307
1336
|
// That's deterministic waste. Instead: switch to a different model — then give up and tell the user.
|
package/dist/agent/optimize.js
CHANGED
|
@@ -21,10 +21,11 @@ export const CAPPED_MAX_TOKENS = 16_384;
|
|
|
21
21
|
export const ESCALATED_MAX_TOKENS = 65_536;
|
|
22
22
|
/** Per-model max output tokens — prevents requesting more than the model supports */
|
|
23
23
|
const MODEL_MAX_OUTPUT = {
|
|
24
|
-
// Opus 4.7
|
|
25
|
-
// (anthropic/claude-opus-4.
|
|
24
|
+
// Opus 4.8 / 4.7 support 128k output per the BlockRun gateway model entry
|
|
25
|
+
// (anthropic/claude-opus-4.8 maxOutput: 128000). Bumping from 32k to
|
|
26
26
|
// 128k unlocks the full headroom — runaway generations are gated
|
|
27
27
|
// separately by CAPPED_MAX_TOKENS / ESCALATED_MAX_TOKENS budgets.
|
|
28
|
+
'anthropic/claude-opus-4.8': 128_000,
|
|
28
29
|
'anthropic/claude-opus-4.7': 128_000,
|
|
29
30
|
'anthropic/claude-opus-4.6': 32_000,
|
|
30
31
|
'anthropic/claude-sonnet-4.6': 64_000,
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema flatten — ported from reasonix (MIT) and adapted to Franklin's
|
|
3
|
+
* CapabilitySchema shape. Deep / wide schemas get dropped or hallucinated
|
|
4
|
+
* by some models (DeepSeek R1, smaller Llamas, some Qwen variants); present
|
|
5
|
+
* them as dot-paths and re-nest before dispatch.
|
|
6
|
+
*
|
|
7
|
+
* Pure functions; no side effects. Wire into a tool registry via
|
|
8
|
+
* analyzeSchema(spec.input_schema) at registration time, then call
|
|
9
|
+
* flattenSchema() on the spec sent to the model and nestArguments() on
|
|
10
|
+
* the parsed call arguments before invoking the handler.
|
|
11
|
+
*/
|
|
12
|
+
import type { CapabilitySchema } from '../types.js';
|
|
13
|
+
/** Loose recursive schema — properties of a CapabilitySchema are typed
|
|
14
|
+
* `unknown`, but in practice they are JSON-Schema-like objects. */
|
|
15
|
+
export interface SchemaNode {
|
|
16
|
+
type?: string | string[];
|
|
17
|
+
properties?: Record<string, SchemaNode>;
|
|
18
|
+
required?: string[];
|
|
19
|
+
items?: SchemaNode;
|
|
20
|
+
[k: string]: unknown;
|
|
21
|
+
}
|
|
22
|
+
export interface FlattenDecision {
|
|
23
|
+
shouldFlatten: boolean;
|
|
24
|
+
leafCount: number;
|
|
25
|
+
maxDepth: number;
|
|
26
|
+
}
|
|
27
|
+
export declare function analyzeSchema(schema: SchemaNode | CapabilitySchema | undefined, opts?: {
|
|
28
|
+
leafLimit?: number;
|
|
29
|
+
depthLimit?: number;
|
|
30
|
+
}): FlattenDecision;
|
|
31
|
+
export declare function flattenSchema(schema: SchemaNode | CapabilitySchema): CapabilitySchema;
|
|
32
|
+
export declare function nestArguments(flatArgs: Record<string, unknown>): Record<string, unknown>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** Caller defines the trigger thresholds; reasonix's defaults are 10/2. */
|
|
2
|
+
const DEFAULT_LEAF_LIMIT = 10;
|
|
3
|
+
const DEFAULT_DEPTH_LIMIT = 2;
|
|
4
|
+
export function analyzeSchema(schema, opts = {}) {
|
|
5
|
+
if (!schema)
|
|
6
|
+
return { shouldFlatten: false, leafCount: 0, maxDepth: 0 };
|
|
7
|
+
const leafLimit = opts.leafLimit ?? DEFAULT_LEAF_LIMIT;
|
|
8
|
+
const depthLimit = opts.depthLimit ?? DEFAULT_DEPTH_LIMIT;
|
|
9
|
+
let leafCount = 0;
|
|
10
|
+
let maxDepth = 0;
|
|
11
|
+
walk(schema, 0, (depth, isLeaf) => {
|
|
12
|
+
if (isLeaf)
|
|
13
|
+
leafCount++;
|
|
14
|
+
if (depth > maxDepth)
|
|
15
|
+
maxDepth = depth;
|
|
16
|
+
});
|
|
17
|
+
return {
|
|
18
|
+
shouldFlatten: leafCount > leafLimit || maxDepth > depthLimit,
|
|
19
|
+
leafCount,
|
|
20
|
+
maxDepth,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export function flattenSchema(schema) {
|
|
24
|
+
const flatProps = {};
|
|
25
|
+
const required = [];
|
|
26
|
+
collect('', schema, flatProps, required, true);
|
|
27
|
+
return {
|
|
28
|
+
type: 'object',
|
|
29
|
+
properties: flatProps,
|
|
30
|
+
required,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export function nestArguments(flatArgs) {
|
|
34
|
+
const out = {};
|
|
35
|
+
for (const [key, value] of Object.entries(flatArgs)) {
|
|
36
|
+
setByPath(out, key.split('.'), value);
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
function walk(schema, depth, visit) {
|
|
41
|
+
if (schema.type === 'object' && schema.properties) {
|
|
42
|
+
for (const child of Object.values(schema.properties)) {
|
|
43
|
+
walk(child, depth + 1, visit);
|
|
44
|
+
}
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (schema.type === 'array' && schema.items) {
|
|
48
|
+
walk(schema.items, depth + 1, visit);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
visit(depth, true);
|
|
52
|
+
}
|
|
53
|
+
function collect(prefix, schema, out, required, isRootRequired) {
|
|
54
|
+
if (schema.type === 'object' && schema.properties) {
|
|
55
|
+
const requiredSet = new Set(schema.required ?? []);
|
|
56
|
+
for (const [key, child] of Object.entries(schema.properties)) {
|
|
57
|
+
const nextPrefix = prefix ? `${prefix}.${key}` : key;
|
|
58
|
+
const childRequired = isRootRequired && requiredSet.has(key);
|
|
59
|
+
collect(nextPrefix, child, out, required, childRequired);
|
|
60
|
+
}
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
out[prefix] = schema;
|
|
64
|
+
if (isRootRequired)
|
|
65
|
+
required.push(prefix);
|
|
66
|
+
}
|
|
67
|
+
function setByPath(target, path, value) {
|
|
68
|
+
let cur = target;
|
|
69
|
+
for (let i = 0; i < path.length - 1; i++) {
|
|
70
|
+
const key = path[i];
|
|
71
|
+
const next = cur[key];
|
|
72
|
+
if (typeof next !== 'object' || next === null)
|
|
73
|
+
cur[key] = {};
|
|
74
|
+
cur = cur[key];
|
|
75
|
+
}
|
|
76
|
+
cur[path[path.length - 1]] = value;
|
|
77
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool-call repair pipeline — ported and adapted from reasonix (MIT).
|
|
3
|
+
*
|
|
4
|
+
* The pipeline has three layers, each used at a different boundary:
|
|
5
|
+
*
|
|
6
|
+
* 1. `repairTruncatedJson(rawArgs)` — call at the LLM-client boundary,
|
|
7
|
+
* right before JSON.parse on the streamed tool_use input. Catches
|
|
8
|
+
* max_tokens-cut-mid-structure and rebalances the braces.
|
|
9
|
+
* 2. `ToolCallRepair.process(calls, reasoning, content)` — call once
|
|
10
|
+
* the assistant turn has finished but before dispatch. Scavenges
|
|
11
|
+
* tool calls the model leaked into text/reasoning channels and
|
|
12
|
+
* merges them in (deduped).
|
|
13
|
+
* 3. `analyzeSchema` + `flattenSchema` + `nestArguments` — apply at
|
|
14
|
+
* tool-registration time for tools whose schemas are deep or wide
|
|
15
|
+
* enough that smaller models drop required params.
|
|
16
|
+
*
|
|
17
|
+
* Storm suppression is intentionally not part of this pipeline.
|
|
18
|
+
* Franklin's `SessionToolGuard` (src/agent/tool-guard.ts) already does
|
|
19
|
+
* per-tool repeat suppression with richer logic — Jaccard search
|
|
20
|
+
* families, mtime-aware Read cache, per-tool circuit breakers.
|
|
21
|
+
*/
|
|
22
|
+
import type { CapabilityInvocation } from '../types.js';
|
|
23
|
+
export { analyzeSchema, flattenSchema, nestArguments } from './flatten.js';
|
|
24
|
+
export type { FlattenDecision, SchemaNode } from './flatten.js';
|
|
25
|
+
export { repairTruncatedJson } from './truncation.js';
|
|
26
|
+
export type { TruncationRepairResult } from './truncation.js';
|
|
27
|
+
export { scavengeToolCalls } from './scavenge.js';
|
|
28
|
+
export type { ScavengeOptions, ScavengeResult } from './scavenge.js';
|
|
29
|
+
export interface RepairReport {
|
|
30
|
+
scavenged: number;
|
|
31
|
+
duplicatesDropped: number;
|
|
32
|
+
notes: string[];
|
|
33
|
+
}
|
|
34
|
+
export interface ToolCallRepairOptions {
|
|
35
|
+
allowedToolNames: ReadonlySet<string>;
|
|
36
|
+
maxScavenge?: number;
|
|
37
|
+
}
|
|
38
|
+
/** Boundary-level helper: parse tool-use argument JSON with truncation
|
|
39
|
+
* recovery. Returns `null` if every attempt fails and the caller should
|
|
40
|
+
* reject the call (better than dispatching with `{}`).
|
|
41
|
+
*
|
|
42
|
+
* Usage at the streaming-client boundary:
|
|
43
|
+
* const args = repairAndParseArgs(jsonAccumulator);
|
|
44
|
+
* if (args == null) return reject("invalid JSON in tool_use");
|
|
45
|
+
*/
|
|
46
|
+
export declare function repairAndParseArgs(raw: string): {
|
|
47
|
+
input: Record<string, unknown>;
|
|
48
|
+
repaired: boolean;
|
|
49
|
+
notes: string[];
|
|
50
|
+
} | null;
|
|
51
|
+
export declare class ToolCallRepair {
|
|
52
|
+
private readonly opts;
|
|
53
|
+
constructor(opts: ToolCallRepairOptions);
|
|
54
|
+
/**
|
|
55
|
+
* Scavenge leaked tool calls from text/reasoning channels and merge
|
|
56
|
+
* into the declared list, deduped.
|
|
57
|
+
*
|
|
58
|
+
* @param declaredCalls Tool calls the model emitted structurally.
|
|
59
|
+
* @param reasoningText Optional reasoning_content / thinking text.
|
|
60
|
+
* @param contentText Optional plain text-channel content.
|
|
61
|
+
*/
|
|
62
|
+
process(declaredCalls: CapabilityInvocation[], reasoningText: string | null, contentText?: string | null): {
|
|
63
|
+
calls: CapabilityInvocation[];
|
|
64
|
+
report: RepairReport;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { scavengeToolCalls } from './scavenge.js';
|
|
2
|
+
import { repairTruncatedJson } from './truncation.js';
|
|
3
|
+
export { analyzeSchema, flattenSchema, nestArguments } from './flatten.js';
|
|
4
|
+
export { repairTruncatedJson } from './truncation.js';
|
|
5
|
+
export { scavengeToolCalls } from './scavenge.js';
|
|
6
|
+
/** Boundary-level helper: parse tool-use argument JSON with truncation
|
|
7
|
+
* recovery. Returns `null` if every attempt fails and the caller should
|
|
8
|
+
* reject the call (better than dispatching with `{}`).
|
|
9
|
+
*
|
|
10
|
+
* Usage at the streaming-client boundary:
|
|
11
|
+
* const args = repairAndParseArgs(jsonAccumulator);
|
|
12
|
+
* if (args == null) return reject("invalid JSON in tool_use");
|
|
13
|
+
*/
|
|
14
|
+
export function repairAndParseArgs(raw) {
|
|
15
|
+
const r = repairTruncatedJson(raw);
|
|
16
|
+
if (r.fallback)
|
|
17
|
+
return null;
|
|
18
|
+
try {
|
|
19
|
+
const parsed = JSON.parse(r.repaired);
|
|
20
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
21
|
+
return { input: parsed, repaired: r.changed, notes: r.notes };
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export class ToolCallRepair {
|
|
30
|
+
opts;
|
|
31
|
+
constructor(opts) {
|
|
32
|
+
this.opts = opts;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Scavenge leaked tool calls from text/reasoning channels and merge
|
|
36
|
+
* into the declared list, deduped.
|
|
37
|
+
*
|
|
38
|
+
* @param declaredCalls Tool calls the model emitted structurally.
|
|
39
|
+
* @param reasoningText Optional reasoning_content / thinking text.
|
|
40
|
+
* @param contentText Optional plain text-channel content.
|
|
41
|
+
*/
|
|
42
|
+
process(declaredCalls, reasoningText, contentText = null) {
|
|
43
|
+
const report = { scavenged: 0, duplicatesDropped: 0, notes: [] };
|
|
44
|
+
const combined = [reasoningText ?? '', contentText ?? ''].filter(Boolean).join('\n');
|
|
45
|
+
const scavenged = scavengeToolCalls(combined || null, {
|
|
46
|
+
allowedNames: this.opts.allowedToolNames,
|
|
47
|
+
maxCalls: this.opts.maxScavenge ?? 4,
|
|
48
|
+
});
|
|
49
|
+
const seenSignatures = new Set(declaredCalls.map(signature));
|
|
50
|
+
const merged = [...declaredCalls];
|
|
51
|
+
for (const sc of scavenged.calls) {
|
|
52
|
+
const sig = signature(sc);
|
|
53
|
+
if (seenSignatures.has(sig)) {
|
|
54
|
+
report.duplicatesDropped++;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
merged.push(sc);
|
|
58
|
+
report.scavenged++;
|
|
59
|
+
seenSignatures.add(sig);
|
|
60
|
+
}
|
|
61
|
+
report.notes.push(...scavenged.notes);
|
|
62
|
+
return { calls: merged, report };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function signature(call) {
|
|
66
|
+
return `${call.name}::${stableStringify(call.input)}`;
|
|
67
|
+
}
|
|
68
|
+
function stableStringify(value) {
|
|
69
|
+
if (value === null || typeof value !== 'object')
|
|
70
|
+
return JSON.stringify(value);
|
|
71
|
+
if (Array.isArray(value)) {
|
|
72
|
+
return `[${value.map(stableStringify).join(',')}]`;
|
|
73
|
+
}
|
|
74
|
+
const obj = value;
|
|
75
|
+
const keys = Object.keys(obj).sort();
|
|
76
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')}}`;
|
|
77
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CapabilityInvocation } from '../types.js';
|
|
2
|
+
export interface ScavengeOptions {
|
|
3
|
+
/** Allowlist of tool names the model is permitted to call. */
|
|
4
|
+
allowedNames: ReadonlySet<string>;
|
|
5
|
+
/** Cap on scavenged calls per pass — defence against runaway. */
|
|
6
|
+
maxCalls?: number;
|
|
7
|
+
}
|
|
8
|
+
export interface ScavengeResult {
|
|
9
|
+
calls: CapabilityInvocation[];
|
|
10
|
+
notes: string[];
|
|
11
|
+
}
|
|
12
|
+
export declare function scavengeToolCalls(text: string | null | undefined, opts: ScavengeOptions): ScavengeResult;
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scavenge tool calls that the model emitted as text instead of via the
|
|
3
|
+
* structured tool_use channel. Ported from reasonix (MIT) and adapted to
|
|
4
|
+
* Franklin's Anthropic-shape `CapabilityInvocation` (parsed `input` object
|
|
5
|
+
* + synthetic id).
|
|
6
|
+
*
|
|
7
|
+
* Triggers we've actually seen:
|
|
8
|
+
* - DeepSeek R1 leaks tool-call JSON into `reasoning_content` and forgets
|
|
9
|
+
* to populate `tool_calls`. The text channel ends up with raw JSON like
|
|
10
|
+
* `{"name":"Read","arguments":{...}}`.
|
|
11
|
+
* - DeepSeek V3.1 sometimes emits its chat-template DSML markup
|
|
12
|
+
* (`<|DSML|invoke …>`) in the content channel.
|
|
13
|
+
* - Smaller OpenAI-compatible models (some Qwen / Llama variants behind
|
|
14
|
+
* the BlockRun gateway) leak the OpenAI tool-call shape inline.
|
|
15
|
+
*
|
|
16
|
+
* All three are recoverable. This module turns the leaked text back into
|
|
17
|
+
* a `CapabilityInvocation` so the agent loop doesn't waste a turn telling
|
|
18
|
+
* the model "you forgot to call a tool".
|
|
19
|
+
*/
|
|
20
|
+
import { randomBytes } from 'node:crypto';
|
|
21
|
+
/** Bounds regex input — DSML matchers are O(n²) on adversarial input. */
|
|
22
|
+
const MAX_SCAVENGE_INPUT = 100 * 1024;
|
|
23
|
+
export function scavengeToolCalls(text, opts) {
|
|
24
|
+
if (!text)
|
|
25
|
+
return { calls: [], notes: [] };
|
|
26
|
+
if (text.length > MAX_SCAVENGE_INPUT) {
|
|
27
|
+
return {
|
|
28
|
+
calls: [],
|
|
29
|
+
notes: [`scavenge skipped: input too large (${text.length} chars)`],
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const max = opts.maxCalls ?? 4;
|
|
33
|
+
const notes = [];
|
|
34
|
+
const out = [];
|
|
35
|
+
// Pattern A — DSML invoke blocks (DeepSeek chat-template markup leaked
|
|
36
|
+
// into the content channel).
|
|
37
|
+
for (const invoke of iterateDsmlInvokes(text)) {
|
|
38
|
+
if (out.length >= max)
|
|
39
|
+
break;
|
|
40
|
+
if (!opts.allowedNames.has(invoke.name))
|
|
41
|
+
continue;
|
|
42
|
+
out.push(makeInvocation(invoke.name, invoke.args));
|
|
43
|
+
notes.push(`scavenged DSML call: ${invoke.name}`);
|
|
44
|
+
}
|
|
45
|
+
// Pattern B — raw JSON objects in the three canonical shapes. Strip
|
|
46
|
+
// DSML blocks first so their parameter payloads don't get re-scavenged
|
|
47
|
+
// as standalone JSON calls.
|
|
48
|
+
const nonDsml = stripDsmlBlocks(text);
|
|
49
|
+
for (const candidate of iterateJsonObjects(nonDsml)) {
|
|
50
|
+
if (out.length >= max)
|
|
51
|
+
break;
|
|
52
|
+
const call = coerceToInvocation(candidate, opts.allowedNames);
|
|
53
|
+
if (call) {
|
|
54
|
+
out.push(call);
|
|
55
|
+
notes.push(`scavenged call: ${call.name}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return { calls: out, notes };
|
|
59
|
+
}
|
|
60
|
+
function stripDsmlBlocks(text) {
|
|
61
|
+
let out = text;
|
|
62
|
+
out = out.replace(/<[||]DSML[||]function_calls>[\s\S]*?<\/?[||]DSML[||]function_calls>/g, '');
|
|
63
|
+
out = out.replace(/<[||]DSML[||]invoke\s+[^>]*>[\s\S]*?<\/[||]DSML[||]invoke>/g, '');
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
function* iterateDsmlInvokes(text) {
|
|
67
|
+
// `|` (U+FF5C) in practice; `|` (ASCII) as a fallback variant.
|
|
68
|
+
const INVOKE_RE = /<[||]DSML[||]invoke\s+name="([^"]+)">([\s\S]*?)<\/[||]DSML[||]invoke>/g;
|
|
69
|
+
for (const match of text.matchAll(INVOKE_RE)) {
|
|
70
|
+
const name = match[1];
|
|
71
|
+
const body = match[2];
|
|
72
|
+
if (!name || body === undefined)
|
|
73
|
+
continue;
|
|
74
|
+
yield { name, args: parseDsmlParameters(body) };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function parseDsmlParameters(body) {
|
|
78
|
+
const PARAM_RE = /<[||]DSML[||]parameter\s+name="([^"]+)"(?:\s+string="(true|false)")?\s*>([\s\S]*?)<\/[||]DSML[||]parameter>/g;
|
|
79
|
+
const args = {};
|
|
80
|
+
for (const m of body.matchAll(PARAM_RE)) {
|
|
81
|
+
const key = m[1];
|
|
82
|
+
const stringFlag = m[2];
|
|
83
|
+
const raw = (m[3] ?? '').trim();
|
|
84
|
+
if (!key)
|
|
85
|
+
continue;
|
|
86
|
+
if (stringFlag === 'false') {
|
|
87
|
+
try {
|
|
88
|
+
args[key] = JSON.parse(raw);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
// Fall through — preserve literal so info isn't lost.
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
args[key] = raw;
|
|
96
|
+
}
|
|
97
|
+
return args;
|
|
98
|
+
}
|
|
99
|
+
function* iterateJsonObjects(text) {
|
|
100
|
+
for (let i = 0; i < text.length; i++) {
|
|
101
|
+
if (text[i] !== '{')
|
|
102
|
+
continue;
|
|
103
|
+
let depth = 0;
|
|
104
|
+
let inString = false;
|
|
105
|
+
let escaped = false;
|
|
106
|
+
for (let j = i; j < text.length; j++) {
|
|
107
|
+
const c = text[j];
|
|
108
|
+
if (escaped) {
|
|
109
|
+
escaped = false;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (inString) {
|
|
113
|
+
if (c === '\\') {
|
|
114
|
+
escaped = true;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (c === '"')
|
|
118
|
+
inString = false;
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (c === '"')
|
|
122
|
+
inString = true;
|
|
123
|
+
else if (c === '{')
|
|
124
|
+
depth++;
|
|
125
|
+
else if (c === '}') {
|
|
126
|
+
depth--;
|
|
127
|
+
if (depth === 0) {
|
|
128
|
+
yield text.slice(i, j + 1);
|
|
129
|
+
i = j;
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function coerceToInvocation(candidateJson, allowedNames) {
|
|
137
|
+
let parsed;
|
|
138
|
+
try {
|
|
139
|
+
parsed = JSON.parse(candidateJson);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
if (!parsed || typeof parsed !== 'object')
|
|
145
|
+
return null;
|
|
146
|
+
const obj = parsed;
|
|
147
|
+
// Pattern 1 — { name, arguments } (Anthropic-ish flat form).
|
|
148
|
+
if (typeof obj.name === 'string' && allowedNames.has(obj.name)) {
|
|
149
|
+
return makeInvocation(obj.name, normalizeArgs(obj.arguments));
|
|
150
|
+
}
|
|
151
|
+
// Pattern 2 — OpenAI-style { type: "function", function: { name, arguments } }.
|
|
152
|
+
if (obj.type === 'function' &&
|
|
153
|
+
obj.function &&
|
|
154
|
+
typeof obj.function === 'object') {
|
|
155
|
+
const fn = obj.function;
|
|
156
|
+
if (typeof fn.name === 'string' && allowedNames.has(fn.name)) {
|
|
157
|
+
return makeInvocation(fn.name, normalizeArgs(fn.arguments));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// Pattern 3 — { tool_name, tool_args } (R1 free-form variant).
|
|
161
|
+
if (typeof obj.tool_name === 'string' && allowedNames.has(obj.tool_name)) {
|
|
162
|
+
return makeInvocation(obj.tool_name, normalizeArgs(obj.tool_args));
|
|
163
|
+
}
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
function normalizeArgs(raw) {
|
|
167
|
+
if (raw == null)
|
|
168
|
+
return {};
|
|
169
|
+
if (typeof raw === 'string') {
|
|
170
|
+
try {
|
|
171
|
+
const parsed = JSON.parse(raw);
|
|
172
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
173
|
+
return parsed;
|
|
174
|
+
}
|
|
175
|
+
return {};
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return {};
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (typeof raw === 'object' && !Array.isArray(raw)) {
|
|
182
|
+
return raw;
|
|
183
|
+
}
|
|
184
|
+
return {};
|
|
185
|
+
}
|
|
186
|
+
function makeInvocation(name, input) {
|
|
187
|
+
return {
|
|
188
|
+
type: 'tool_use',
|
|
189
|
+
id: `toolu_repair_${randomBytes(6).toString('hex')}`,
|
|
190
|
+
name,
|
|
191
|
+
input,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Truncated-JSON repair — ported from reasonix (MIT). Format-agnostic:
|
|
3
|
+
* works on any raw JSON argument string. Common trigger: model hits
|
|
4
|
+
* max_tokens mid-structure; the last useful argument is half-emitted.
|
|
5
|
+
*
|
|
6
|
+
* Local-only — never makes a continuation call. The agent loop owns
|
|
7
|
+
* budgets; this just patches what we have so the dispatcher can either
|
|
8
|
+
* parse it or report a clean fallback.
|
|
9
|
+
*/
|
|
10
|
+
export interface TruncationRepairResult {
|
|
11
|
+
repaired: string;
|
|
12
|
+
changed: boolean;
|
|
13
|
+
notes: string[];
|
|
14
|
+
/** True when all repair attempts failed and the result fell back to "{}". */
|
|
15
|
+
fallback: boolean;
|
|
16
|
+
}
|
|
17
|
+
export declare function repairTruncatedJson(input: string): TruncationRepairResult;
|