@genesislcap/ai-assistant 15.98.4 → 15.99.1

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.
@@ -27,6 +27,7 @@ __export(chat_driver_node_exports, {
27
27
  ANTHROPIC_CACHE_READ_MULTIPLIER: () => ANTHROPIC_CACHE_READ_MULTIPLIER,
28
28
  ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER: () => ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER,
29
29
  ANTHROPIC_CACHE_WRITE_5M_MULTIPLIER: () => ANTHROPIC_CACHE_WRITE_5M_MULTIPLIER,
30
+ ANTHROPIC_LONG_CONTEXT_THRESHOLD: () => ANTHROPIC_LONG_CONTEXT_THRESHOLD,
30
31
  AgenticActivityBus: () => AgenticActivityBus,
31
32
  AnthropicProvider: () => AnthropicProvider,
32
33
  AnthropicTransport: () => AnthropicTransport,
@@ -60,6 +61,7 @@ __export(chat_driver_node_exports, {
60
61
  agenticActivityBus: () => agenticActivityBus,
61
62
  aiServiceAccessRefusalOf: () => aiServiceAccessRefusalOf,
62
63
  aiServiceErrorCodeOf: () => aiServiceErrorCodeOf,
64
+ anthropicCacheReadMultiplierFor: () => anthropicCacheReadMultiplierFor,
63
65
  anthropicRatesFor: () => anthropicRatesFor,
64
66
  anthropicTokenCost: () => anthropicTokenCost,
65
67
  assembleDebugLog: () => assembleDebugLog,
@@ -1315,10 +1317,13 @@ var SUPPORTED_GEMINI_MODEL_IDS = [
1315
1317
  ];
1316
1318
  var SUPPORTED_ANTHROPIC_MODEL_IDS = [
1317
1319
  "claude-fable-5",
1320
+ "claude-opus-5-5",
1318
1321
  "claude-opus-4-8",
1319
1322
  "claude-opus-4-7",
1323
+ "claude-sonnet-5-5",
1320
1324
  "claude-sonnet-5",
1321
1325
  "claude-sonnet-4-6",
1326
+ "claude-haiku-5-5",
1322
1327
  "claude-haiku-4-5-20251001"
1323
1328
  ];
1324
1329
  var SUPPORTED_OPENAI_MODEL_IDS = [
@@ -1355,14 +1360,40 @@ function scaleTemperature(normalized, { defaultTemp, maxTemp }) {
1355
1360
 
1356
1361
  // ../../foundation-ai/dist/esm/utils/token-cost.js
1357
1362
  var TOKENS_PER_MILLION = 1e6;
1363
+ var ANTHROPIC_LONG_CONTEXT_THRESHOLD = 1e5;
1358
1364
  var ANTHROPIC_PRICING = {
1359
- "claude-haiku-4-5-20251001": { promptPerMillion: 1, candidatePerMillion: 5 },
1365
+ "claude-haiku-4-5-20251001": {
1366
+ kind: "flat",
1367
+ rate: { promptPerMillion: 1, candidatePerMillion: 5 }
1368
+ },
1369
+ // Haiku 5.5 has two rate cards chosen by prompt length; cache reads are 0.1× the input rate of
1370
+ // whichever card applies, like every other model here.
1371
+ "claude-haiku-5-5": {
1372
+ kind: "tiered",
1373
+ standard: { promptPerMillion: 0.1, candidatePerMillion: 0.5 },
1374
+ longContext: { promptPerMillion: 0.5, candidatePerMillion: 2.5 }
1375
+ },
1360
1376
  // Fable 5 — Anthropic's most capable widely-released model; priced above Opus tier.
1361
- "claude-fable-5": { promptPerMillion: 10, candidatePerMillion: 50 },
1377
+ "claude-fable-5": { kind: "flat", rate: { promptPerMillion: 10, candidatePerMillion: 50 } },
1378
+ // Opus 5.5 — $4 / $20, cheaper than Opus 4.8. Its cache reads are $0.20 / MTok, i.e. 0.05× the
1379
+ // input rate (as on Sonnet 5.5), NOT the 0.1× every older model reads at: the global
1380
+ // multiplier would bill its cache reads at double.
1381
+ "claude-opus-5-5": {
1382
+ kind: "flat",
1383
+ rate: { promptPerMillion: 4, candidatePerMillion: 20 },
1384
+ cacheReadMultiplier: 0.05
1385
+ },
1362
1386
  // Opus 4.7 / 4.8 — same $5 / $25 per MTok. Stated per model rather than shared through a
1363
1387
  // fall-through, so neither is ever "whatever was left over".
1364
- "claude-opus-4-8": { promptPerMillion: 5, candidatePerMillion: 25 },
1365
- "claude-opus-4-7": { promptPerMillion: 5, candidatePerMillion: 25 },
1388
+ "claude-opus-4-8": { kind: "flat", rate: { promptPerMillion: 5, candidatePerMillion: 25 } },
1389
+ "claude-opus-4-7": { kind: "flat", rate: { promptPerMillion: 5, candidatePerMillion: 25 } },
1390
+ // Sonnet 5.5 — same $2 / $10 as Sonnet 5, but its cache reads are $0.10 / MTok (0.05×, like
1391
+ // Opus 5.5), half of Sonnet 5's $0.20.
1392
+ "claude-sonnet-5-5": {
1393
+ kind: "flat",
1394
+ rate: { promptPerMillion: 2, candidatePerMillion: 10 },
1395
+ cacheReadMultiplier: 0.05
1396
+ },
1366
1397
  // Sonnet 5 is $2 / $10 — its OWN tier, and CHEAPER than the older Sonnet 4.6 below.
1367
1398
  //
1368
1399
  // This launched as an introductory rate through 2026-08-31, and an earlier version of this
@@ -1371,22 +1402,33 @@ var ANTHROPIC_PRICING = {
1371
1402
  // standard price and cancelled the scheduled increase, so that reasoning is dead and the old
1372
1403
  // figure over-charged every Sonnet 5 request by 50%.
1373
1404
  // https://platform.claude.com/docs/en/about-claude/pricing#model-pricing
1374
- "claude-sonnet-5": { promptPerMillion: 2, candidatePerMillion: 10 },
1405
+ "claude-sonnet-5": { kind: "flat", rate: { promptPerMillion: 2, candidatePerMillion: 10 } },
1375
1406
  // Sonnet 4.6 remains on the older $3 / $15 Sonnet tier — the newer model is the cheaper one.
1376
- "claude-sonnet-4-6": { promptPerMillion: 3, candidatePerMillion: 15 }
1407
+ "claude-sonnet-4-6": { kind: "flat", rate: { promptPerMillion: 3, candidatePerMillion: 15 } }
1377
1408
  };
1378
- function anthropicRatesFor(model) {
1379
- return ANTHROPIC_PRICING[model];
1409
+ function anthropicRatesFor(model, promptTokens = 0) {
1410
+ const pricing = ANTHROPIC_PRICING[model];
1411
+ if (pricing.kind === "flat") {
1412
+ return pricing.rate;
1413
+ }
1414
+ return promptTokens > ANTHROPIC_LONG_CONTEXT_THRESHOLD ? pricing.longContext : pricing.standard;
1380
1415
  }
1381
1416
  var ANTHROPIC_CACHE_READ_MULTIPLIER = 0.1;
1417
+ var DEFAULT_CACHE_READ_MULTIPLIER = 0.1;
1418
+ function anthropicCacheReadMultiplierFor(model) {
1419
+ var _a;
1420
+ return (_a = ANTHROPIC_PRICING[model].cacheReadMultiplier) !== null && _a !== void 0 ? _a : DEFAULT_CACHE_READ_MULTIPLIER;
1421
+ }
1382
1422
  var ANTHROPIC_CACHE_WRITE_5M_MULTIPLIER = 1.25;
1383
1423
  var ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER = 2;
1384
1424
  function anthropicTokenCost(model, usage) {
1385
- const { promptPerMillion, candidatePerMillion } = anthropicRatesFor(model);
1425
+ const promptTokens = usage.uncachedInputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
1426
+ const { promptPerMillion, candidatePerMillion } = anthropicRatesFor(model, promptTokens);
1427
+ const cacheReadMultiplier = anthropicCacheReadMultiplierFor(model);
1386
1428
  const m = TOKENS_PER_MILLION;
1387
1429
  const cacheWrite5mTokens = Math.max(0, usage.cacheWriteTokens - usage.cacheWrite1hTokens);
1388
1430
  const promptCost = usage.uncachedInputTokens / m * promptPerMillion;
1389
- const cacheReadCost = usage.cacheReadTokens / m * promptPerMillion * ANTHROPIC_CACHE_READ_MULTIPLIER;
1431
+ const cacheReadCost = usage.cacheReadTokens / m * promptPerMillion * cacheReadMultiplier;
1390
1432
  const cacheWriteCost = cacheWrite5mTokens / m * promptPerMillion * ANTHROPIC_CACHE_WRITE_5M_MULTIPLIER + usage.cacheWrite1hTokens / m * promptPerMillion * ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER;
1391
1433
  const candidateCost = usage.outputTokens / m * candidatePerMillion;
1392
1434
  const cacheReadFull = usage.cacheReadTokens / m * promptPerMillion;
@@ -2381,6 +2423,7 @@ var DEFAULT_MODEL = "claude-haiku-4-5-20251001";
2381
2423
  var DEFAULT_TIMEOUT = 3e5;
2382
2424
  var DEFAULT_STALL_TIMEOUT = 3e4;
2383
2425
  var DEFAULT_MAX_TOKENS = 4096;
2426
+ var CLAUDE_55_DEFAULT_MAX_TOKENS = 64e3;
2384
2427
  var ANTHROPIC_DEFAULT_TEMPERATURE = 1;
2385
2428
  var ANTHROPIC_MAX_TEMPERATURE = 1;
2386
2429
  function toAnthropicToolChoice(choice) {
@@ -2394,38 +2437,73 @@ function toAnthropicToolChoice(choice) {
2394
2437
  }
2395
2438
  var ANTHROPIC_CONTEXT_LIMITS = {
2396
2439
  "claude-fable-5": 1e6,
2440
+ "claude-opus-5-5": 1e6,
2397
2441
  "claude-opus-4-8": 1e6,
2398
2442
  "claude-opus-4-7": 1e6,
2443
+ "claude-sonnet-5-5": 1e6,
2399
2444
  "claude-sonnet-5": 1e6,
2400
2445
  "claude-sonnet-4-6": 1e6,
2446
+ "claude-haiku-5-5": 1e6,
2401
2447
  "claude-haiku-4-5-20251001": 2e5
2402
2448
  };
2403
2449
  var STRUCTURED_OUTPUT_TOOL_NAME = "emit_structured_response";
2404
2450
  var SERVER_SIDE_FALLBACK_BETA = "server-side-fallback-2026-06-01";
2451
+ var THINKING_BINDING_CONTROLS_BETA = "thinking-binding-controls-2026-08-01";
2405
2452
  function assertSupportedAnthropicModel(model) {
2406
2453
  if (!SUPPORTED_ANTHROPIC_MODEL_IDS.includes(model)) {
2407
2454
  throw new Error(`AnthropicTransport: unsupported model "${model}". Use one of: ${SUPPORTED_ANTHROPIC_MODEL_IDS.join(", ")}.`);
2408
2455
  }
2409
2456
  }
2457
+ function isClaude55(model) {
2458
+ return model === "claude-opus-5-5" || model === "claude-sonnet-5-5" || model === "claude-haiku-5-5";
2459
+ }
2410
2460
  function rejectsSamplingParams(model) {
2411
- return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-opus-4-7" || model === "claude-sonnet-5";
2461
+ return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-opus-4-7" || model === "claude-sonnet-5" || isClaude55(model);
2462
+ }
2463
+ function supportsForcedToolChoice(model) {
2464
+ return model !== "claude-opus-5-5" && model !== "claude-sonnet-5-5";
2412
2465
  }
2413
2466
  function supportsNativeStructuredOutput(model) {
2414
- return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-sonnet-5" || model === "claude-haiku-4-5-20251001";
2467
+ return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-sonnet-5" || model === "claude-haiku-4-5-20251001" || isClaude55(model);
2415
2468
  }
2416
2469
  function supportsAdaptiveThinking(model) {
2417
2470
  return model !== "claude-haiku-4-5-20251001";
2418
2471
  }
2419
2472
  function thinkingIsMandatory(model) {
2420
- return model === "claude-fable-5";
2473
+ return model === "claude-fable-5" || model === "claude-opus-5-5";
2474
+ }
2475
+ function defaultsToThinking(model) {
2476
+ return model === "claude-sonnet-5" || model === "claude-sonnet-5-5" || model === "claude-haiku-5-5" || thinkingIsMandatory(model);
2477
+ }
2478
+ function thinkingOff(model) {
2479
+ return model === "claude-sonnet-5-5" ? { type: "between_tools" } : { type: "disabled" };
2480
+ }
2481
+ var POLICY_OFF_EFFORT = {
2482
+ "claude-opus-5-5": "low"
2483
+ };
2484
+ function supportsFallbacks(model) {
2485
+ return model === "claude-fable-5" || model === "claude-opus-5-5" || model === "claude-sonnet-5-5";
2486
+ }
2487
+ function fallbackThinkingOff(model) {
2488
+ var _a;
2489
+ const known = SUPPORTED_ANTHROPIC_MODEL_IDS.includes(model);
2490
+ return (_a = known ? anthropicThinking(model, "off") : void 0) !== null && _a !== void 0 ? _a : {
2491
+ type: "disabled"
2492
+ };
2493
+ }
2494
+ function sendsBlockBinding(model) {
2495
+ return isClaude55(model);
2496
+ }
2497
+ function replaysThinking(model, thinking) {
2498
+ return !sendsBlockBinding(model) || !thinking || thinking.type === "adaptive";
2421
2499
  }
2422
2500
  function anthropicThinking(model, policy) {
2423
- const defaultsToThinking = model === "claude-sonnet-5" || thinkingIsMandatory(model);
2501
+ const thinksByDefault = defaultsToThinking(model);
2424
2502
  const adaptive = { type: "adaptive", display: "summarized" };
2425
2503
  if (policy === "off") {
2426
2504
  if (thinkingIsMandatory(model))
2427
2505
  return adaptive;
2428
- return defaultsToThinking ? { type: "disabled" } : void 0;
2506
+ return thinksByDefault ? thinkingOff(model) : void 0;
2429
2507
  }
2430
2508
  if (policy === "auto") {
2431
2509
  return supportsAdaptiveThinking(model) ? adaptive : void 0;
@@ -2433,10 +2511,10 @@ function anthropicThinking(model, policy) {
2433
2511
  if (policy !== void 0) {
2434
2512
  return supportsAdaptiveThinking(model) ? adaptive : void 0;
2435
2513
  }
2436
- return defaultsToThinking ? adaptive : void 0;
2514
+ return thinksByDefault ? adaptive : void 0;
2437
2515
  }
2438
2516
  function supportsEffort(model) {
2439
- return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-sonnet-5";
2517
+ return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-sonnet-5" || isClaude55(model);
2440
2518
  }
2441
2519
  var ANTHROPIC_EFFORT = {
2442
2520
  minimal: "low",
@@ -2446,13 +2524,60 @@ var ANTHROPIC_EFFORT = {
2446
2524
  max: "max"
2447
2525
  };
2448
2526
  function anthropicEffort(model, policy) {
2449
- if (policy === void 0 || policy === "auto" || policy === "off")
2527
+ if (policy === void 0)
2528
+ return void 0;
2529
+ if (policy === "auto")
2450
2530
  return void 0;
2531
+ if (policy === "off")
2532
+ return POLICY_OFF_EFFORT[model];
2451
2533
  if (!supportsEffort(model) || !supportsAdaptiveThinking(model))
2452
2534
  return void 0;
2453
2535
  return ANTHROPIC_EFFORT[policy];
2454
2536
  }
2455
2537
  var ANTHROPIC_PROVIDER_KEY = "anthropic";
2538
+ var PrefixFingerprint = class _PrefixFingerprint {
2539
+ constructor(systemPrompt, tools) {
2540
+ this.hash = FNV_OFFSET_BASIS;
2541
+ this.length = 0;
2542
+ this.fold(JSON.stringify([
2543
+ systemPrompt !== null && systemPrompt !== void 0 ? systemPrompt : "",
2544
+ (tools !== null && tools !== void 0 ? tools : []).map((t) => [t.name, t.description, t.parameters, !!t.enforceSchema])
2545
+ ]));
2546
+ }
2547
+ /** The fingerprint of a request body's messages as they will be sent. */
2548
+ static of(systemPrompt, tools, messages) {
2549
+ const fingerprint = new _PrefixFingerprint(systemPrompt, tools);
2550
+ for (const message of messages) {
2551
+ fingerprint.message(message.role);
2552
+ const blocks = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
2553
+ for (const block of blocks)
2554
+ fingerprint.block(block);
2555
+ }
2556
+ return fingerprint.key;
2557
+ }
2558
+ /** A new message of `role` starts. */
2559
+ message(role) {
2560
+ this.fold(`\0M:${role}`);
2561
+ }
2562
+ /** A block is added to the current message. */
2563
+ block(block) {
2564
+ this.fold(`\0B:${JSON.stringify(block, (k, v) => k === "cache_control" ? void 0 : v)}`);
2565
+ }
2566
+ get key() {
2567
+ return `${(this.hash >>> 0).toString(HEX_RADIX)}:${this.length}`;
2568
+ }
2569
+ // FNV-1a, 32-bit: a fingerprint, not a security boundary.
2570
+ fold(text) {
2571
+ for (let i = 0; i < text.length; i += 1) {
2572
+ this.hash ^= text.charCodeAt(i);
2573
+ this.hash = Math.imul(this.hash, FNV_PRIME);
2574
+ }
2575
+ this.length += text.length;
2576
+ }
2577
+ };
2578
+ var FNV_OFFSET_BASIS = 2166136261;
2579
+ var FNV_PRIME = 16777619;
2580
+ var HEX_RADIX = 16;
2456
2581
  var ResponseTruncatedError = class extends Error {
2457
2582
  constructor(model, maxTokens, outputTokens, toolNames) {
2458
2583
  super(`Response truncated at ${maxTokens != null ? `the max_tokens cap (${maxTokens})` : "the model's output-token limit"} for model ${model}` + (toolNames.length > 0 ? ` while emitting tool call(s): ${toolNames.join(", ")}` : "") + ". The output exceeds the per-response limit \u2014 raise the provider maxTokens (where configurable) or split the work into smaller outputs.");
@@ -2495,7 +2620,9 @@ var AnthropicTransport = class _AnthropicTransport {
2495
2620
  case void 0:
2496
2621
  return void 0;
2497
2622
  case "off":
2498
- return thinkingIsMandatory(this.model) ? `AnthropicTransport: thinkingPolicy 'off' ignored \u2014 ${this.model} always thinks and rejects an explicit disable. Reasoning tokens are still billed as output; switch model if you need them gone.` : void 0;
2623
+ if (!thinkingIsMandatory(this.model))
2624
+ return void 0;
2625
+ return POLICY_OFF_EFFORT[this.model] ? `AnthropicTransport: thinkingPolicy 'off' approximated \u2014 ${this.model} always thinks and rejects an explicit disable, so the turn runs at effort '${POLICY_OFF_EFFORT[this.model]}' instead. It may still think a little, billed as output.` : `AnthropicTransport: thinkingPolicy 'off' ignored \u2014 ${this.model} always thinks and rejects an explicit disable. Reasoning tokens are still billed as output; switch model if you need them gone.`;
2499
2626
  case "auto":
2500
2627
  return supportsAdaptiveThinking(this.model) ? void 0 : `AnthropicTransport: thinkingPolicy 'auto' ignored \u2014 ${this.model} does not support adaptive thinking, so this turn runs without reasoning. Use a Sonnet or Opus tier if the agent needs it.`;
2501
2628
  case "minimal":
@@ -2504,7 +2631,7 @@ var AnthropicTransport = class _AnthropicTransport {
2504
2631
  case "high":
2505
2632
  case "max":
2506
2633
  if (!supportsAdaptiveThinking(this.model) || !supportsEffort(this.model)) {
2507
- return `AnthropicTransport: thinkingPolicy '${policy}' ignored \u2014 ${this.model} predates output_config.effort, so this turn runs at its default posture. Use Opus 4.8, Sonnet 5, or Fable 5 to set reasoning depth.`;
2634
+ return `AnthropicTransport: thinkingPolicy '${policy}' ignored \u2014 ${this.model} predates output_config.effort, so this turn runs at its default posture. Use Opus 4.8 or later, Sonnet 5 or later, Haiku 5.5, or Fable 5 to set reasoning depth.`;
2508
2635
  }
2509
2636
  return void 0;
2510
2637
  default: {
@@ -2514,10 +2641,12 @@ var AnthropicTransport = class _AnthropicTransport {
2514
2641
  }
2515
2642
  }
2516
2643
  constructor(config = {}) {
2517
- var _a, _b, _c, _d;
2644
+ var _a, _b, _c, _d, _e;
2518
2645
  this.lifetimeCostUsd = 0;
2519
2646
  this.lifetimeSavingsUsd = 0;
2520
2647
  this.warnedThinkingClamped = false;
2648
+ this.warnedToolChoiceDowngraded = false;
2649
+ this.warnedFallbacksUnsupported = false;
2521
2650
  this.warnedUnknownServingModels = /* @__PURE__ */ new Set();
2522
2651
  const model = (_a = config.model) !== null && _a !== void 0 ? _a : DEFAULT_MODEL;
2523
2652
  assertSupportedAnthropicModel(model);
@@ -2528,6 +2657,10 @@ var AnthropicTransport = class _AnthropicTransport {
2528
2657
  logger.warn("AnthropicTransport: using claude-sonnet-4-6 \u2014 higher cost than Haiku; use for stronger reasoning or agent tasks.");
2529
2658
  } else if (model === "claude-opus-4-7" || model === "claude-opus-4-8") {
2530
2659
  logger.warn(`AnthropicTransport: using ${model} \u2014 significantly higher cost; reserve for tasks where Sonnet reliability is insufficient.`);
2660
+ } else if (model === "claude-opus-5-5") {
2661
+ logger.warn("AnthropicTransport: using claude-opus-5-5 \u2014 Opus tier ($4 / $20 per MTok) with thinking always on (effort defaults to medium). Reserve for tasks where Sonnet reliability is insufficient.");
2662
+ } else if (model === "claude-sonnet-5-5") {
2663
+ logger.warn("AnthropicTransport: using claude-sonnet-5-5 \u2014 standard Sonnet tier ($2 / $10 per MTok), higher cost than Haiku, and adaptive thinking runs by default so reasoning tokens add to output cost. Use for stronger reasoning or agent tasks.");
2531
2664
  } else if (model === "claude-fable-5") {
2532
2665
  logger.warn(`AnthropicTransport: using claude-fable-5 \u2014 Anthropic's most capable model, priced above Opus tier ($10 / $50 per MTok) with thinking always on. Reserve for the hardest reasoning/long-horizon work. Requires \u226530-day data retention (unavailable under ZDR) and may return stop_reason "refusal"; pair with an Opus 4.8 fallback.`);
2533
2666
  }
@@ -2535,7 +2668,8 @@ var AnthropicTransport = class _AnthropicTransport {
2535
2668
  this.stallTimeout = (_c = config.stallTimeout) !== null && _c !== void 0 ? _c : DEFAULT_STALL_TIMEOUT;
2536
2669
  this.apiKey = config.apiKey;
2537
2670
  this.serverEndpoint = config.serverEndpoint;
2538
- this.maxTokens = (_d = config.maxTokens) !== null && _d !== void 0 ? _d : DEFAULT_MAX_TOKENS;
2671
+ this.maxTokens = (_d = config.maxTokens) !== null && _d !== void 0 ? _d : isClaude55(model) ? CLAUDE_55_DEFAULT_MAX_TOKENS : DEFAULT_MAX_TOKENS;
2672
+ this.thinkingBlockBinding = (_e = config.thinkingBlockBinding) !== null && _e !== void 0 ? _e : "drop_block";
2539
2673
  }
2540
2674
  getConfig() {
2541
2675
  return {
@@ -2575,6 +2709,9 @@ var AnthropicTransport = class _AnthropicTransport {
2575
2709
  if (useNative) {
2576
2710
  body.output_config = Object.assign(Object.assign({}, body.output_config), { format: { type: "json_schema", schema: responseSchema } });
2577
2711
  } else if (useForcedTool) {
2712
+ if (!supportsForcedToolChoice(this.model)) {
2713
+ throw new Error(`AnthropicTransport: ${this.model} rejects forced tool_choice and must be listed in supportsNativeStructuredOutput.`);
2714
+ }
2578
2715
  body.tools = [
2579
2716
  {
2580
2717
  name: STRUCTURED_OUTPUT_TOOL_NAME,
@@ -2584,8 +2721,9 @@ var AnthropicTransport = class _AnthropicTransport {
2584
2721
  ];
2585
2722
  body.tool_choice = { type: "tool", name: STRUCTURED_OUTPUT_TOOL_NAME };
2586
2723
  }
2587
- if (this.model === "claude-sonnet-5")
2588
- body.thinking = { type: "disabled" };
2724
+ if (defaultsToThinking(this.model) && !thinkingIsMandatory(this.model)) {
2725
+ body.thinking = thinkingOff(this.model);
2726
+ }
2589
2727
  const response = yield this.post(body);
2590
2728
  if (useForcedTool) {
2591
2729
  const toolUse = ((_a = response.content) !== null && _a !== void 0 ? _a : []).find((b) => b.type === "tool_use" && b.name === STRUCTURED_OUTPUT_TOOL_NAME);
@@ -2597,32 +2735,33 @@ var AnthropicTransport = class _AnthropicTransport {
2597
2735
  // ── ChatTransport (multi-turn chat) ────────────────────────────────────
2598
2736
  sendChatMessage(history, userMessage, options) {
2599
2737
  return __awaiter(this, void 0, void 0, function* () {
2600
- var _a, _b, _c, _d, _e;
2601
- const reachableModels = /* @__PURE__ */ new Set([
2602
- this.model,
2603
- ...((_a = options === null || options === void 0 ? void 0 : options.fallbacks) !== null && _a !== void 0 ? _a : []).map((f) => f.model)
2604
- ]);
2605
- const messages = this.toAnthropicMessages(history, userMessage, options === null || options === void 0 ? void 0 : options.attachments, reachableModels);
2738
+ var _a, _b, _c, _d;
2739
+ let fallbacks = options === null || options === void 0 ? void 0 : options.fallbacks;
2740
+ if ((fallbacks === null || fallbacks === void 0 ? void 0 : fallbacks.length) && !supportsFallbacks(this.model)) {
2741
+ if (!this.warnedFallbacksUnsupported) {
2742
+ this.warnedFallbacksUnsupported = true;
2743
+ logger.warn(`AnthropicTransport: ${this.model} does not support server-side fallbacks; sending the request without them.`);
2744
+ }
2745
+ fallbacks = void 0;
2746
+ }
2747
+ const reachableModels = /* @__PURE__ */ new Set([this.model, ...(fallbacks !== null && fallbacks !== void 0 ? fallbacks : []).map((f) => f.model)]);
2748
+ const thinking = anthropicThinking(this.model, options === null || options === void 0 ? void 0 : options.thinkingPolicy);
2749
+ const messages = this.toAnthropicMessages(history, userMessage, options === null || options === void 0 ? void 0 : options.attachments, reachableModels, replaysThinking(this.model, thinking), this.replayFingerprint(options));
2606
2750
  const body = {
2607
2751
  model: this.model,
2608
2752
  // Per-turn override wins over the instance default; see ChatRequestOptions.maxTokens.
2609
- max_tokens: (_b = options === null || options === void 0 ? void 0 : options.maxTokens) !== null && _b !== void 0 ? _b : this.maxTokens,
2753
+ max_tokens: (_a = options === null || options === void 0 ? void 0 : options.maxTokens) !== null && _a !== void 0 ? _a : this.maxTokens,
2610
2754
  messages
2611
2755
  };
2612
2756
  if (options === null || options === void 0 ? void 0 : options.systemPrompt)
2613
2757
  body.system = options.systemPrompt;
2614
- if ((_c = options === null || options === void 0 ? void 0 : options.tools) === null || _c === void 0 ? void 0 : _c.length) {
2758
+ if ((_b = options === null || options === void 0 ? void 0 : options.tools) === null || _b === void 0 ? void 0 : _b.length) {
2615
2759
  body.tools = options.tools.map((t) => Object.assign({ name: t.name, description: t.description, input_schema: t.enforceSchema ? enforceAnthropicToolSchema(t.parameters, t.name) : t.parameters }, t.enforceSchema ? { strict: true } : {}));
2616
2760
  }
2617
- if ((_d = body.tools) === null || _d === void 0 ? void 0 : _d.length) {
2618
- const toolChoice = toAnthropicToolChoice(options === null || options === void 0 ? void 0 : options.toolChoice);
2619
- if (toolChoice)
2620
- body.tool_choice = toolChoice;
2621
- }
2761
+ const forcedToolNote = ((_c = body.tools) === null || _c === void 0 ? void 0 : _c.length) ? this.applyToolChoice(body, options === null || options === void 0 ? void 0 : options.toolChoice) : void 0;
2622
2762
  this.warnIfThinkingUnclampable(options === null || options === void 0 ? void 0 : options.thinkingPolicy);
2623
- const thinking = anthropicThinking(this.model, options === null || options === void 0 ? void 0 : options.thinkingPolicy);
2624
2763
  if (thinking)
2625
- body.thinking = thinking;
2764
+ body.thinking = this.withBlockBinding(thinking);
2626
2765
  const effort = anthropicEffort(this.model, options === null || options === void 0 ? void 0 : options.thinkingPolicy);
2627
2766
  if (effort)
2628
2767
  body.output_config = Object.assign(Object.assign({}, body.output_config), { effort });
@@ -2636,19 +2775,95 @@ var AnthropicTransport = class _AnthropicTransport {
2636
2775
  if ((options === null || options === void 0 ? void 0 : options.responseSchema) && supportsNativeStructuredOutput(this.model)) {
2637
2776
  body.output_config = Object.assign(Object.assign({}, body.output_config), { format: { type: "json_schema", schema: options.responseSchema } });
2638
2777
  }
2639
- if ((_e = options === null || options === void 0 ? void 0 : options.fallbacks) === null || _e === void 0 ? void 0 : _e.length) {
2640
- body.fallbacks = options.fallbacks.map((f) => f.maxTokens != null ? { model: f.model, max_tokens: f.maxTokens } : { model: f.model });
2778
+ if (fallbacks === null || fallbacks === void 0 ? void 0 : fallbacks.length) {
2779
+ const offOnEach = ((_d = body.thinking) === null || _d === void 0 ? void 0 : _d.type) === "between_tools";
2780
+ body.fallbacks = fallbacks.map((f) => Object.assign(Object.assign({ model: f.model }, f.maxTokens != null ? { max_tokens: f.maxTokens } : {}), offOnEach ? { thinking: fallbackThinkingOff(f.model) } : {}));
2641
2781
  }
2642
2782
  if (options === null || options === void 0 ? void 0 : options.cachePolicy) {
2643
2783
  this.applyCacheControl(body, options.cachePolicy);
2644
2784
  }
2785
+ if (forcedToolNote)
2786
+ this.appendTailContext(body, forcedToolNote);
2645
2787
  if (options === null || options === void 0 ? void 0 : options.tailContext) {
2646
2788
  this.appendTailContext(body, options.tailContext);
2647
2789
  }
2648
2790
  const response = yield this.post(body, options === null || options === void 0 ? void 0 : options.signal);
2649
- return this.fromAnthropicResponse(response, body.max_tokens);
2791
+ const message = this.fromAnthropicResponse(response, body.max_tokens, this.sentPrefix(options, body.messages));
2792
+ if (forcedToolNote && message.responseMeta) {
2793
+ message.responseMeta.toolChoiceDowngraded = true;
2794
+ message.responseMeta.toolChoiceNote = forcedToolNote;
2795
+ }
2796
+ return message;
2650
2797
  });
2651
2798
  }
2799
+ /** 5.5 family: the fingerprint a request folds its messages into as it rebuilds them. */
2800
+ replayFingerprint(options) {
2801
+ return sendsBlockBinding(this.model) ? new PrefixFingerprint(options === null || options === void 0 ? void 0 : options.systemPrompt, options === null || options === void 0 ? void 0 : options.tools) : void 0;
2802
+ }
2803
+ /** 5.5 family: the fingerprint of everything a request sent, stored with its thinking. */
2804
+ sentPrefix(options, messages) {
2805
+ return sendsBlockBinding(this.model) ? PrefixFingerprint.of(options === null || options === void 0 ? void 0 : options.systemPrompt, options === null || options === void 0 ? void 0 : options.tools, messages) : void 0;
2806
+ }
2807
+ /**
2808
+ * Set `tool_choice` from the caller's {@link ChatToolChoice}. `'required'`/`{ tool }` force a
2809
+ * tool call so a turn can only end via one (e.g. a sub-agent's completion tool); on a model that
2810
+ * rejects forcing they are downgraded (see `downgradeForcedToolChoice`), and the instruction
2811
+ * that replaces them is returned, to be appended after the stored messages.
2812
+ */
2813
+ applyToolChoice(body, choice) {
2814
+ const toolChoice = toAnthropicToolChoice(choice);
2815
+ if (!toolChoice)
2816
+ return void 0;
2817
+ const forced = toolChoice.type === "any" || toolChoice.type === "tool";
2818
+ if (forced && !supportsForcedToolChoice(this.model)) {
2819
+ return this.downgradeForcedToolChoice(toolChoice);
2820
+ }
2821
+ body.tool_choice = toolChoice;
2822
+ return void 0;
2823
+ }
2824
+ /**
2825
+ * Preserved thinking (5.5 family): say what a changed history does to replayed thinking, rather
2826
+ * than inheriting the account default (a 400 on accounts created on or after 2026-08-31).
2827
+ * Adaptive only — `between_tools` and `disabled` reject the field — and a fresh object, so the
2828
+ * shared `adaptive` constant in `anthropicThinking` is never mutated.
2829
+ */
2830
+ withBlockBinding(thinking) {
2831
+ if (thinking.type !== "adaptive" || !sendsBlockBinding(this.model) || this.thinkingBlockBinding === "omit") {
2832
+ return thinking;
2833
+ }
2834
+ return Object.assign(Object.assign({}, thinking), { block_binding: { prefix_mismatch_behavior: this.thinkingBlockBinding } });
2835
+ }
2836
+ /**
2837
+ * Stand-in for a forced tool call on a model that rejects `tool_choice` `any`/`tool` with a 400
2838
+ * (Opus 5.5, Sonnet 5.5). The request goes out with `tool_choice` omitted (`auto`), and an
2839
+ * instruction naming the tool is returned for the caller to append after the stored messages
2840
+ * (and to replay there on later requests, via `responseMeta.toolChoiceNote`).
2841
+ *
2842
+ * **The tools array is left exactly as the caller built it.** It renders first in the prompt, so
2843
+ * it heads both the prompt-cache prefix and the prefix preserved thinking is bound to. Rewriting
2844
+ * a tool only on forced turns (making it `strict`, say) would change those bytes every time an
2845
+ * agent moves between forced and `auto` turns: a cache miss, every replayed thinking block
2846
+ * dropped (or a 400 under `block_binding: 'error'`), and a tool that accepts different arguments
2847
+ * depending on the turn. Whether a tool's arguments are enforced is the caller's decision, made
2848
+ * once per tool with `enforceSchema`, and holds on every turn; a completion tool that is forced
2849
+ * is a good candidate for it.
2850
+ *
2851
+ * `auto` lets the model answer in text instead, so the caller is told: a one-time warning here,
2852
+ * and `responseMeta.toolChoiceDowngraded` on every affected response. The ChatDriver reads that
2853
+ * flag: a turn that answers in text is held open and asked for the call (a sub-agent's
2854
+ * completion nudge, a parent's forced-tool nudge) unless the agent's own `finishGuard` answers,
2855
+ * and a `{ tool }` turn that calls other tools only has those calls refused, naming the tool.
2856
+ */
2857
+ downgradeForcedToolChoice(toolChoice) {
2858
+ if (!this.warnedToolChoiceDowngraded) {
2859
+ this.warnedToolChoiceDowngraded = true;
2860
+ logger.warn(`AnthropicTransport: ${this.model} rejects a forced tool_choice; sending 'auto' with an instruction to call the tool instead. A reply may still come back without a tool call \u2014 check responseMeta.toolChoiceDowngraded.`);
2861
+ }
2862
+ if (toolChoice.type === "tool" && toolChoice.name) {
2863
+ return `<system-reminder>Respond to this turn by calling the \`${toolChoice.name}\` tool. Do not reply with text alone.</system-reminder>`;
2864
+ }
2865
+ return "<system-reminder>Respond to this turn by calling one of your tools. Do not reply with text alone.</system-reminder>";
2866
+ }
2652
2867
  /**
2653
2868
  * Place prompt-cache breakpoints on the outgoing request per the resolved {@link CachePolicy}.
2654
2869
  * A breakpoint is `cache_control: {type:'ephemeral'}` on a content block / tool / system block;
@@ -2743,16 +2958,18 @@ var AnthropicTransport = class _AnthropicTransport {
2743
2958
  * Consecutive same-role turns are merged by the API but we merge here to keep
2744
2959
  * the payload tidy.
2745
2960
  */
2746
- toAnthropicMessages(history, userMessage, attachments, reachableModels = /* @__PURE__ */ new Set([this.model])) {
2747
- var _a, _b, _c, _d;
2961
+ toAnthropicMessages(history, userMessage, attachments, reachableModels = /* @__PURE__ */ new Set([this.model]), replayThinking = true, fingerprint) {
2962
+ var _a, _b, _c, _d, _e;
2748
2963
  const messages = [];
2749
2964
  const pushBlock = (role, block) => {
2750
2965
  const last = messages[messages.length - 1];
2751
2966
  if (last && last.role === role && Array.isArray(last.content)) {
2752
2967
  last.content.push(block);
2753
- return;
2968
+ } else {
2969
+ messages.push({ role, content: [block] });
2970
+ fingerprint === null || fingerprint === void 0 ? void 0 : fingerprint.message(role);
2754
2971
  }
2755
- messages.push({ role, content: [block] });
2972
+ fingerprint === null || fingerprint === void 0 ? void 0 : fingerprint.block(block);
2756
2973
  };
2757
2974
  const splitAttachments = (atts) => {
2758
2975
  const images = [];
@@ -2778,8 +2995,11 @@ ${att.content}` });
2778
2995
  if (msg.role === "system" || msg.role === "system-event" || msg.role === "synthetic-user" || msg.role === "compacted-summary" || msg.category === "reasoning" || msg.category === "narration" || // Driver-authored prose no model produced — see ChatMessage.excludeFromProvider.
2779
2996
  msg.excludeFromProvider || msg.thinking)
2780
2997
  continue;
2998
+ if (msg.role === "assistant" && ((_a = msg.responseMeta) === null || _a === void 0 ? void 0 : _a.toolChoiceNote)) {
2999
+ pushBlock("user", { type: "text", text: msg.responseMeta.toolChoiceNote });
3000
+ }
2781
3001
  if (msg.toolResult) {
2782
- const resultImages = (_a = msg.toolResult.attachments) !== null && _a !== void 0 ? _a : [];
3002
+ const resultImages = (_b = msg.toolResult.attachments) !== null && _b !== void 0 ? _b : [];
2783
3003
  pushBlock("user", {
2784
3004
  type: "tool_result",
2785
3005
  tool_use_id: msg.toolResult.toolCallId,
@@ -2802,8 +3022,15 @@ ${att.content}` });
2802
3022
  });
2803
3023
  continue;
2804
3024
  }
2805
- if ((_b = msg.toolCalls) === null || _b === void 0 ? void 0 : _b.length) {
2806
- for (const block of this.reasoningToReplay(msg.toolCalls[0], reachableModels)) {
3025
+ if ((_c = msg.toolCalls) === null || _c === void 0 ? void 0 : _c.length) {
3026
+ for (const block of this.reasoningToReplay(
3027
+ msg.toolCalls[0],
3028
+ reachableModels,
3029
+ replayThinking,
3030
+ // The prefix as rebuilt so far, which ends where the request that produced this
3031
+ // thinking ended: what the thinking must have been produced against.
3032
+ fingerprint === null || fingerprint === void 0 ? void 0 : fingerprint.key
3033
+ )) {
2807
3034
  pushBlock("assistant", block);
2808
3035
  }
2809
3036
  if (msg.content) {
@@ -2814,13 +3041,13 @@ ${att.content}` });
2814
3041
  type: "tool_use",
2815
3042
  id: tc.id,
2816
3043
  name: tc.name,
2817
- input: (_c = tc.args) !== null && _c !== void 0 ? _c : {}
3044
+ input: (_d = tc.args) !== null && _d !== void 0 ? _d : {}
2818
3045
  });
2819
3046
  }
2820
3047
  continue;
2821
3048
  }
2822
3049
  const role = msg.role === "user" ? "user" : "assistant";
2823
- if (role === "user" && ((_d = msg.attachments) === null || _d === void 0 ? void 0 : _d.length)) {
3050
+ if (role === "user" && ((_e = msg.attachments) === null || _e === void 0 ? void 0 : _e.length)) {
2824
3051
  const { images, texts } = splitAttachments(msg.attachments);
2825
3052
  for (const image of images)
2826
3053
  pushBlock(role, image);
@@ -2874,8 +3101,12 @@ ${att.content}` });
2874
3101
  *
2875
3102
  * Boundaries themselves are always echoed: keeping them in place is the documented rule, and
2876
3103
  * with no thinking blocks around them they are inert rather than harmful.
3104
+ *
3105
+ * `replayThinking: false` (a 5.5 request with thinking turned off; see `replaysThinking`) replays
3106
+ * the boundaries only, and so does a 5.5 request that rebuilds a different prefix in front of the
3107
+ * reasoning than it was produced against (`prefixKey`; see `PrefixFingerprint`).
2877
3108
  */
2878
- reasoningToReplay(firstCall, reachableModels) {
3109
+ reasoningToReplay(firstCall, reachableModels, replayThinking = true, prefixKey) {
2879
3110
  var _a, _b, _c;
2880
3111
  const state = (_a = firstCall.providerMetadata) === null || _a === void 0 ? void 0 : _a[ANTHROPIC_PROVIDER_KEY];
2881
3112
  if (!state)
@@ -2883,7 +3114,8 @@ ${att.content}` });
2883
3114
  const boundaries = (_b = state.fallbacks) !== null && _b !== void 0 ? _b : [];
2884
3115
  const stickyToProducer = state.requestedModel === this.model && reachableModels.has(state.model);
2885
3116
  const vouched = state.model === this.model || stickyToProducer;
2886
- return [...boundaries, ...vouched ? (_c = state.reasoning) !== null && _c !== void 0 ? _c : [] : []];
3117
+ const bound = prefixKey === void 0 || state.prefixKey === prefixKey;
3118
+ return [...boundaries, ...vouched && replayThinking && bound ? (_c = state.reasoning) !== null && _c !== void 0 ? _c : [] : []];
2887
3119
  }
2888
3120
  /**
2889
3121
  * The model that actually served this response.
@@ -2947,8 +3179,8 @@ ${att.content}` });
2947
3179
  const cacheCreation = (_c = usage.cache_creation_input_tokens) !== null && _c !== void 0 ? _c : breakdown ? ((_d = breakdown.ephemeral_5m_input_tokens) !== null && _d !== void 0 ? _d : 0) + cacheCreation1h : 0;
2948
3180
  return this.logTokenUsage(model, (_e = usage.input_tokens) !== null && _e !== void 0 ? _e : 0, (_f = usage.output_tokens) !== null && _f !== void 0 ? _f : 0, cacheRead, cacheCreation, cacheCreation1h);
2949
3181
  }
2950
- fromAnthropicResponse(response, effectiveMaxTokens = this.maxTokens) {
2951
- var _a, _b, _c, _d, _e, _f, _g;
3182
+ fromAnthropicResponse(response, effectiveMaxTokens = this.maxTokens, prefixKey) {
3183
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
2952
3184
  let inputTokens;
2953
3185
  let outputTokens;
2954
3186
  let cacheReadTokens;
@@ -3021,6 +3253,8 @@ ${att.content}` });
3021
3253
  };
3022
3254
  if (fallbackBlocks.length > 0)
3023
3255
  state.fallbacks = fallbackBlocks;
3256
+ if (prefixKey !== void 0)
3257
+ state.prefixKey = prefixKey;
3024
3258
  toolCalls[0].providerMetadata = Object.assign(Object.assign({}, toolCalls[0].providerMetadata), { [ANTHROPIC_PROVIDER_KEY]: state });
3025
3259
  }
3026
3260
  if (response.stop_reason === "max_tokens" && toolCalls.length > 0) {
@@ -3048,6 +3282,16 @@ ${att.content}` });
3048
3282
  };
3049
3283
  if (response.stop_reason)
3050
3284
  responseMeta.finishReason = response.stop_reason;
3285
+ if ((_h = response.input_transformations) === null || _h === void 0 ? void 0 : _h.length) {
3286
+ responseMeta.inputTransformations = response.input_transformations.map((t) => Object.assign(Object.assign({ type: t.type }, t.path != null ? { path: t.path } : {}), t.reason != null ? { reason: t.reason } : {}));
3287
+ const dropped = response.input_transformations.filter((t) => t.type === "thinking_dropped");
3288
+ if (dropped.length) {
3289
+ logger.debug(`AnthropicTransport: ${dropped.length} thinking block(s) dropped by ${(_j = response.model) !== null && _j !== void 0 ? _j : this.model}: ${dropped.map((t) => {
3290
+ var _a2, _b2;
3291
+ return `${(_a2 = t.path) !== null && _a2 !== void 0 ? _a2 : "?"} (${(_b2 = t.reason) !== null && _b2 !== void 0 ? _b2 : "unknown"})`;
3292
+ }).join(", ")}`);
3293
+ }
3294
+ }
3051
3295
  base.responseMeta = responseMeta;
3052
3296
  return base;
3053
3297
  }
@@ -3079,9 +3323,13 @@ ${att.content}` });
3079
3323
  }
3080
3324
  post(body, signal) {
3081
3325
  return __awaiter(this, void 0, void 0, function* () {
3082
- var _a;
3326
+ var _a, _b;
3083
3327
  const { url, headers, credentials } = this.buildEndpoint();
3084
- const requestHeaders = ((_a = body.fallbacks) === null || _a === void 0 ? void 0 : _a.length) ? Object.assign(Object.assign({}, headers), { "anthropic-beta": [headers["anthropic-beta"], SERVER_SIDE_FALLBACK_BETA].filter(Boolean).join(",") }) : headers;
3328
+ const betas = [
3329
+ ((_a = body.fallbacks) === null || _a === void 0 ? void 0 : _a.length) ? SERVER_SIDE_FALLBACK_BETA : void 0,
3330
+ ((_b = body.thinking) === null || _b === void 0 ? void 0 : _b.type) === "adaptive" && body.thinking.block_binding ? THINKING_BINDING_CONTROLS_BETA : void 0
3331
+ ].filter((b) => Boolean(b));
3332
+ const requestHeaders = betas.length ? Object.assign(Object.assign({}, headers), { "anthropic-beta": [headers["anthropic-beta"], ...betas].filter(Boolean).join(",") }) : headers;
3085
3333
  return yield postWithRetry({
3086
3334
  url,
3087
3335
  headers: requestHeaders,
@@ -3114,7 +3362,7 @@ var MALFORMED_CALL_ANCHOR = "default_api.";
3114
3362
  var PRINT_WRAPPER_RE = /print\(\s*$/;
3115
3363
  var UNICODE_ESCAPE_DIGITS = 4;
3116
3364
  var HEX_ESCAPE_DIGITS = 2;
3117
- var HEX_RADIX = 16;
3365
+ var HEX_RADIX2 = 16;
3118
3366
  var MalformedFunctionCallParser = class {
3119
3367
  constructor(src) {
3120
3368
  this.src = src;
@@ -3235,7 +3483,7 @@ var MalformedFunctionCallParser = class {
3235
3483
  if (hex.length !== digits || !/^[0-9a-fA-F]+$/.test(hex))
3236
3484
  this.bail();
3237
3485
  this.pos += digits;
3238
- return String.fromCharCode(parseInt(hex, HEX_RADIX));
3486
+ return String.fromCharCode(parseInt(hex, HEX_RADIX2));
3239
3487
  }
3240
3488
  readNumber() {
3241
3489
  const start = this.pos;
@@ -5051,7 +5299,7 @@ var DEBUG_LOG_README = [
5051
5299
  "Timestamps are millisecond-resolution; entries that share the same millisecond are ordered by a fixed kind rank (event, then turn, then message), which is a heuristic and may not reflect exact causal order within that millisecond \u2014 e.g. a user message and the turn it triggered, or a final assistant message and its turn.end event, can appear in either order depending on whether they landed in the same millisecond. Read the logical structure of a turn rather than over-interpreting the micro-ordering of co-timestamped entries of different kinds.",
5052
5300
  "kind:'message' \u2014 the conversation. `role` is user/assistant/tool/system-event/synthetic-user; `agentName` says which agent produced it; `toolCalls`/`toolResult`/`interaction` carry tool and widget activity; `inputTokens`/`outputTokens`/`cost` are per-message LLM usage, where `inputTokens` is the WHOLE prompt for that request and `cacheReadTokens`/`cacheWriteTokens` BREAK IT DOWN rather than add to it \u2014 uncached input is `inputTokens` minus those two, and adding the cache fields to `inputTokens` counts the prompt twice. The cache fields are absent on providers that report no cache split (Gemini reports reads only, since implicit caching bills no write) and on messages persisted before they existed, so read them as 0 when missing. Each bucket bills at a different rate \u2014 cache reads a fraction of uncached input, cache writes a premium, output highest \u2014 so a large token count at a small cost means the prompt was mostly cache hits. `externalCostUsd` is any non-LLM cost a widget reported for its own external service calls (folded into the session cost total alongside `cost`). On model-produced assistant messages, `model` is the concrete model id that generated it (e.g. 'gemini-2.5-flash-lite') and `providerName` is the registry slot it resolved under (e.g. a tier name like 'high'/'low', or the default); together they attribute the message \u2014 and any tool calls it carries \u2014 to an exact model even across a mid-session vendor/tier switch, where one slot name can map to different models before and after the switch. Both are undefined on any entry that is NOT an LLM response: non-assistant roles (user/tool/system-event) and 'synthetic-user' echoes; assistant interaction/widget entries (empty content carrying an `interaction` \u2014 a rendered widget, not a model turn); driver-authored assistant fallbacks (the timeout, repeated-malformed-call, and empty-response apology messages); and messages restored from a session persisted before these fields existed. One partial case: on a genuine model turn whose provider exposes no `getStatus` (or reports no model), `providerName` is still set but `model` alone is undefined. A 'synthetic-user' message is a display-only echo of an interaction outcome (e.g. the answer a widget reported): it renders on the user's side of the chat and `agentName` is the agent that created it, but it is never sent to the LLM \u2014 so it has no matching 'turn' and the model learns the outcome only from the corresponding tool result. An echo of an answer an interceptor (such as an autopilot) gave is NOT synthetic-user: see the delegated-messages paragraph.",
5053
5301
  "The autopilot (GENC-1660) runs on a driver of its own, and everything it did is harvested into this log: entries with delegate: autopilot and an agentName ending in \u203A Autopilot are its turns (the decision message it was sent is the user message of its turn, so what it was shown is there verbatim; its systemPrompt is its grounding, such as the brief), its tool calls (widget_read, widget_act, hand_back, any read-only tools of its own, and its widget tools \u2014 reads with parameters that a widget type declares, routed to the interaction of that type being decided and refused with a reason when none is, offered on every decision so its tool list never changes; while one is open its tail starts with a line naming them) and their results (a read, view or widget tool, is capped at about 20,000 characters, cut with a note asking for less, and leaves its history at the end of the decision as a one-line note), and its own events. Its cost is already in the session total: it is booked as externalCostUsd on the interaction each decision answered, or, for a written question it answered, on the user message it sent on the user behalf (delegate: autopilot), so do not add its turns to that total. Spend that reached no message is recorded as autopilot.cost-dropped instead.",
5054
- "Delegated messages (GENC-1660): a message with a `delegate` field was written or sent ON THE USER'S BEHALF by a driver decorator, and `delegate` names it (e.g. autopilot). The platform stamps it; nothing else can. It renders as the assistant whatever its role. A delegated `user` message was NOT typed by the user: it is an answer given on their behalf, and the model read it with `delegateFraming` in brackets in front of the content (the stored `content` is the bare text). A delegated `assistant` message is display-only (`excludeFromProvider`): the decorator's narration note, or, when its answer carried no note, the widget's own echo of the answer (its `userMessage`), shown as the assistant and never as the person. A widget answer a decorator gave with a note is not echoed at all: the note already says what was chosen. To tell what the person decided from what was decided for them, read `interaction.answeredBy` and these fields, never the role alone. Driver notes: a `user` message with a `driverNote` field was written by the driver for the model, never by the user, and is hidden from the transcript; `driverNote: 'finish-guard'` is the agent's finishGuard holding the turn open after a prose reply, its content the guard's note in a `<system-reminder>`, and it follows a turn.finish-guard event; `driverNote: 'completion-nudge'` is the driver asking a sub-agent that replied in prose to call its completion tool.",
5302
+ "Delegated messages (GENC-1660): a message with a `delegate` field was written or sent ON THE USER'S BEHALF by a driver decorator, and `delegate` names it (e.g. autopilot). The platform stamps it; nothing else can. It renders as the assistant whatever its role. A delegated `user` message was NOT typed by the user: it is an answer given on their behalf, and the model read it with `delegateFraming` in brackets in front of the content (the stored `content` is the bare text). A delegated `assistant` message is display-only (`excludeFromProvider`): the decorator's narration note, or, when its answer carried no note, the widget's own echo of the answer (its `userMessage`), shown as the assistant and never as the person. A widget answer a decorator gave with a note is not echoed at all: the note already says what was chosen. To tell what the person decided from what was decided for them, read `interaction.answeredBy` and these fields, never the role alone. Driver notes: a `user` message with a `driverNote` field was written by the driver for the model, never by the user, and is hidden from the transcript; `driverNote: 'finish-guard'` is the agent's finishGuard holding the turn open after a prose reply, its content the guard's note in a `<system-reminder>`, and it follows a turn.finish-guard event; `driverNote: 'completion-nudge'` is the driver asking a sub-agent that replied in prose to call its completion tool; `driverNote: 'forced-tool-nudge'` is the driver asking a parent agent for the tool call its forced turn required, after a model that rejects forcing (responseMeta.toolChoiceDowngraded) replied in prose.",
5055
5303
  "Sub-agent messages appear inline. When a tool delegates to a sub-agent (via `requestSubAgent`), the sub-agent's whole conversation \u2014 its own assistant/tool messages, each with their own `content`/`thinking`/`toolCalls`/`toolResult` and per-message `model`/`providerName`/`inputTokens`/`outputTokens`/`cacheReadTokens`/`cacheWriteTokens`/`cost` \u2014 is hoisted into the timeline as ordinary kind:'message' entries, interleaved by timestamp right after the tool call that spawned them (so you read the delegation top-to-bottom). A hoisted entry is marked: `subAgentDepth` is its delegation depth (1 for a sub-agent, 2 for a sub-agent's sub-agent, \u2026), `subAgentOf` is the id of the parent tool call that spawned it (correlates it back even when two sub-agents run in one parent turn), `subAgentName` is the sub-agent's own name, and `agentName` is rewritten to a `\"<parent> \u203A <sub-agent>\"` breadcrumb (composing when nested, e.g. `\"UI Builder \u203A Planner \u203A Grounding\"`). The sub-agent's per-LLM-call snapshots also surface as kind:'turn' entries with an N-M `turnIndex`, and subagent.started/completed (or subagent.failed) events bracket the run. Per-message `cost` on hoisted entries is already part of the session total (it is summed from the un-flattened history), so summing the top-level timeline does NOT double-count.",
5056
5304
  "kind:'turn' \u2014 one LLM call. `turnIndex` is a string: a top-level turn is the bare counter ('0', '1', \u2026); a sub-agent's turns are numbered under the parent turn that activated them ('3-1', '3-2', \u2026, and a nested sub-agent contributes '3-2-1', \u2026), and `agentName` names the agent that ran the turn. `systemPrompt` and `toolNames` are what the model saw. A systemPrompt of '<repeated \u2014 identical to turn N>' was byte-identical to turn N and de-duplicated; the full prompt is shown whenever it changes (often because a stateful agent advanced), so prompt evolution is visible.",
5057
5305
  "kind:'turn'.`model`/`providerName`/`provider` \u2014 which model ran that call: the concrete model id, the registry slot it resolved under (a tier name like 'high'/'low', or the default), and the vendor. Recorded per CALL, so an agent whose `provider` selector varies by state \u2014 a flow that plans on a high tier and executes on a low one \u2014 has every step attributed, including calls that produced no message. `model` is the SERVING model where the provider reports one, so a turn answered by a server-side fallback names the model that answered rather than the one requested; it always matches the `model` on the message that call produced. Absent when the provider exposes no `getStatus` and the transport stamped nothing.",
@@ -5059,7 +5307,7 @@ var DEBUG_LOG_README = [
5059
5307
  "kind:'turn'.`agentSnapshot` \u2014 the active agent's own view of its internal state, captured at that turn. An agent opts into this by exposing a `getDebugSnapshot()` that returns JSON-serializable per-state info; stateful/flow agents wire it automatically, so you can watch a flow advance turn-by-turn (e.g. current step, cursor, collected fields, pending changes). Absent for agents that don't expose one.",
5060
5308
  "kind:'event' \u2014 a meta/lifecycle event. `type` names it (see below); `detail` carries structured data. `detail.placement` is the emitting UI instance: 'bubble' (collapsed), 'panel' (popped-out), or 'standalone'.",
5061
5309
  "Each 'event' also has an `importance`: 'high' (failures/limits \u2014 turn.error, tool.failed, subagent.failed, file.read-failed, suggestions.failed, context.threshold-crossed), 'normal' (session flow \u2014 connects, turns, retries, handoffs, agent/provider changes, interactions, sub-agent start/complete), or 'low' (skippable UI/bookkeeping noise \u2014 panel.toggled, attachment.added, driver.wired/unwired, context.updated, context.condensed). To skim, ignore importance:'low'; to triage a failure, filter to importance:'high' then read the nearby messages and turns. A 'high' turn.error is often preceded by one or more 'normal' turn.retry events for the same reason \u2014 read them together to see how many attempts were made before bailing. 'message' and 'turn' entries carry no importance \u2014 they are the substance, always read them.",
5062
- "Event types: assistant.connected/disconnected (mount + placement + whether the session was created or restored), assistant.popout/popin (window placement), driver.created/wired/unwired (which driver is live and why it stops/starts responding across a popout), state.changed (idle\u2194loading), turn.start/turn.end (turn boundary; turn.end carries durationMs), turn.retry (a recoverable in-turn retry \u2014 detail.reason plus attempt/maxAttempts; for malformed calls also finishMessage; for empty responses also the provider finishReason + thoughtsTokens + parts breakdown), turn.finish-guard (the model replied with no tool call and the agent's finishGuard hook answered \u2014 detail.action is continue (the turn was held open: detail.continuation counts the holds this turn and detail.note is the note stored as a hidden user message with driverNote finish-guard, the next message in the log; detail.source: 'completion-nudge' is instead the driver holding a SUB-AGENT's turn open because it replied in prose without calling its completion tool \u2014 detail.nudge of detail.maxNudges, the note stored with driverNote completion-nudge \u2014 and a sub-agent that still answers in prose after the last nudge fails as before) or end with detail.release: true (the agent was released on a prose answer); a plain end records nothing), turn.error (a turn failed or hit a guardrail \u2014 detail.reason is one of exception/malformed-function-call/empty-response/unknown-tool-limit/max-iterations/response-truncated/refusal/budget-exhausted/provider-refused/context-exhausted/ai-service-error, plus reason-specific diagnostics: attempts (for empty-response also finishReason + thoughtsTokens + a parts breakdown, distinguishing a thinking-only STOP from a truly empty turn), finishMessage, for response-truncated the model + maxTokens + outputTokens + tools, unknownTools (split into staleTools \u2014 real earlier this activation but retired by the current state or hidden behind an open exclusive fold \u2014 and hallucinatedTools \u2014 never advertised) + availableTools, iterations + limit, for budget-exhausted the budgetUsd + spentUsd figures reported by the proxy plus the resolved vendor, for provider-refused the kind (spend|auth) plus the upstream status and error type \u2014 the vendor refusing the ACCOUNT rather than us refusing to spend, so the remedy is a top-up or a key rotation rather than a raised cap, and the kind is the only place that distinction survives because the user-facing copy is deliberately cause-free, for context-exhausted the estimated contextTokens against the guard that stopped the turn plus the iterations reached \u2014 the driver ending a runaway tool loop at the edge of the context window rather than issuing a request the provider would reject, so the transcript survives intact and can still be compacted, for ai-service-error the code (one of AI_SERVICE_ERROR_CODES, e.g. NO_API_KEY) and the status the AI service answered with \u2014 its own text goes to the browser console only, or name + message for exceptions), tool.failed (a tool threw), tool.unresolved (the model called a tool that could not be dispatched \u2014 detail.kind is folded/fold-hidden/stale/unknown, plus tool + agent and, for the counted kinds, the consecutive streak; the recurring lead-up to an unknown-tool-limit turn.error), subagent.started/completed/failed (the lifecycle of a `requestSubAgent` delegation \u2014 detail.agent names the sub-agent; these bracket the sub-agent turns that appear as kind:turn entries with an N-M `turnIndex`; subagent.failed also carries detail.reason, one of max_iterations/malformed_tool_call/empty_response/unknown_tool_limit/timeout/response_truncated/refusal/budget_exhausted/provider_refused/context_exhausted/ai_service_error, and for timeout detail.cause: 'idle' when it was the sub-agent making no progress for `idleTimeoutMs` rather than the overall `timeoutMs` (absent for the latter); budget_exhausted and provider_refused are terminal for the PARENT turn too, and so is ai_service_error when the refusal is about the service rather than the request and came from the vendor the parent calls \u2014 the parent stops rather than calling the model again into the same wall; after context_exhausted the parent goes on, but its own next call is likely to stop on the same guard), agent.handoff (routing; from=null is the initial activation), agent.pinned/unpinned (forced routing), routing.decided (ONE PER ROUTING DECISION \u2014 see its own paragraph below), provider.selected (the resolved provider for the upcoming turns \u2014 detail.provider is the registry SLOT/tier name, detail.model the concrete model behind it and detail.vendor its vendor; emitted only when the slot CHANGES, so read the per-turn `model` for the model of any given call rather than assuming the nearest event still applies), interaction.requested/resolved (blocking user widgets \u2014 explain quiet gaps; note that when a sub-agent opens a widget, detail.agent \u2014 and the agentName on the interaction message \u2014 is the HOST agent that owns the widget, NOT the sub-agent that asked, because widgets render and resolve on the host driver; detail.ownerPath names the agents that actually asked, outermost first, the last being the one whose tool requested it, and detail.heldBy says who held it when it opened: user, or the id of the interceptor that claimed it, such as autopilot; on interaction.resolved, detail.answeredBy is who answered \u2014 the claimant id when it settled through its own hold, user for any other answer (a click counts as the person even on a widget a claimant held) \u2014 absent when it closed unanswered (a timeout or a stop), and absent too when it settled by itself other than through the hold of a claimant \u2014 a widget registered resolvesItself (one that does its work and settles on its own, asking the person nothing, such as a generation run), or one outcome its controller said settled itself (ctx.resolve with resolvedItself, such as a generation phase that failed outright before its review gate ever asked anything) \u2014 which then carries detail.resolvedItself: true instead, as the interaction message does \u2014 nobody answered it, and the platform cannot tell it finishing from the person interrupting it (a Skip), so only the result of the widget itself can say which; the same value is stamped on the interaction message as answeredBy and on the result the asking tool handler receives (absent there in the same cases), and when it is not user the tool result that interaction returned carries a decidedOnUsersBehalf record, so the model was told the choice was not made by the person; detail.edits, present only when non-zero, counts the editing actions a claimant ran on the widget before it was settled, whoever settled it, and those edits are stamped on the interaction message as edits, each with by, action, choice and args when it had some, in the order they ran, while a decidedOnUsersBehalf record carries their choice texts as edits, and when the person settled it after such edits the tool result carries an editedOnUsersBehalf record instead \u2014 the framing and those choice texts \u2014 so the model knows the widget was changed on the user behalf before the user answered, and that the user then confirmed it by finishing it), interaction.held (a claimant moved a pending interaction to the person or back to itself \u2014 detail.heldBy is the new holder, detail.claimant the interceptor; detail.late: true is an interceptor that declined it when it opened claiming it afterwards, such as the autopilot resumed while it was open; a widget held by anything but user was not answered by the person), interaction.claim-refused (a claim on a userOnly interaction, which stays with the person \u2014 detail.claimant + reason), autopilot.* (the autopilot, a decorator that answers interactions on behalf of the user \u2014 autopilot.claimed / autopilot.declined say whether it took each interaction and, for a decline, detail.reason: paused, other-flow, no-autopilot, unavailable, userOnly, policy or no-controller; one declined as paused that is still open when the person resumes the autopilot is looked at again, and the autopilot.claimed or autopilot.declined recorded for it then carries detail.onResume: true (a decline then can also be claimed-elsewhere, another interceptor having claimed it first); a restored mode looks at nothing; autopilot.decision-sent is what it was sent (detail.chars; detail.nothingEnabled: true when every action on the widget was unavailable \u2014 a gate whose controller said it was asking, such as a failed build the autopilot may not cancel \u2014 so it could only hand it back, which it may then do even after the person asked it to decide it itself; a widget whose controller says it is working (ctx.setWorking) is never sent a decision until it says it is asking, even when an action is enabled or the person resumes the autopilot); autopilot.acted is what it did (detail.action, detail.note, detail.finished); autopilot.handed-back is a decision it gave to the person (detail.reason and detail.trigger: model, no-decision or error); autopilot.paused / autopilot.resumed are mode changes (detail.scope, detail.trigger, detail.decideYourself when the person resumed during a hand-back; detail.trigger is restored when the mode came back with the session after a reload, applied once its flow re-activated, which starts nothing by itself); autopilot.carried is the mode, running or paused, going with the task to the agent that took it over, rather than ending with the flow as on any other change of flow owner: to the target of a hand-off, or back to its caller on the hand-back (detail.from, detail.to, detail.mode); a pause the person chose goes with it, and Stop and Clear still end it; a mode restored for the target of a hand-off applies to its caller when the reload hands back; autopilot.error is the wrapper itself failing; autopilot.refinement counts a refining action against its step \u2014 a written answer (reply) or a widget action declared refines, such as a regenerate with instructions, counted together (detail.action, detail.stepKey, detail.count, detail.limitReached, after which every refining action is withdrawn for that step: not listed, and refused; the decision and every relisting of its actions say how many are left at the step, as a line Refinements left at this step: N, wherever the widget has a refining action); autopilot.handback-presented is the turn-level hand-back, shown when a working turn ended needing the person with no widget to hand over (detail.why: max-iterations, context-exhausted, failure or question; detail.options; detail.choice once answered); autopilot.catch-up is the autopilot being given the whole visible transcript at once (detail.why: first, for its first decision in a flow or after a reload; size, when its own history passed its budget and was rebuilt short \u2014 detail.ownChars; or compacted, when a compaction removed the last message it had seen, so it reads the summary and everything since, short; in each, what it had sent on the user behalf is included and labelled as its own, since its own history does not hold it); autopilot.cost-dropped is autopilot spend that no message carries, so it is NOT in the session total (detail.costUsd and detail.why: handed-back, aborted or stale for a written question it answered that no reply was sent for \u2014 stale when a pause, a resume, a new turn or the end of its flow came before the answer landed, which then went nowhere \u2014 or no-recorder when the driver had no way to book a decision to its interaction); a hand-back trigger can also be budget (the decision passed its spend cap), watchdog (its work went quiet: no ready surface and no heartbeat, or its own decision stalled with no model call landing, which stops that decision) or detached (the autopilot was removed while it held the interaction, which went to the person with no reason shown). To debug one autopilot decision, follow its interactionId: interaction.requested (heldBy), autopilot.claimed, autopilot.decision-sent, autopilot.acted or autopilot.handed-back, interaction.invoked, interaction.resolved (answeredBy), then the next turn of the working agent), interaction.invoked (a claimant ran one of the actions the widget itself exposes, through its hold, the same code the button runs \u2014 detail.claimant, detail.action (an option id, select or reply) and detail.finished, whether that settled the interaction, and when it did not, the run is recorded as an edit; the choice and narration it recorded reach the result of the tool that asked as decidedOnUsersBehalf; the person's own programmatic action, from a host with no DOM to click, carries detail.by: user in place of detail.claimant, and is not recorded as an edit nor as a decision on their behalf, so what it settles is answered by user), interaction.step (a long action run as named steps through runSteps, which survive a reload \u2014 detail.step and detail.outcome: started, done, skipped when the step was already done before a reload, or resumed when it started before a reload and runs again with what it saved part-way, such as a job id it re-attaches to), interaction.checkpoint (the checkpoints a conversation keeps for its long actions: the one in flight, and each one a reload cut, held apart until a request of its own widget type takes it over, so a resumed flow that opens other long widgets first, which save their own, loses nothing \u2014 detail.action: resumed when a reload cut the work and a request of the same widget type that the registration sameWork agrees is the same work took it over, refused when sameWork said a new request is different work (detail.saved is the identity it kept; detail.kept: true, since it stays for a later request of that type, and is offered to every one until one agrees) or when runSteps found the handed-over checkpoint malformed and started fresh (detail.reason, detail.saved), or cleared when its flow ended, once per checkpoint, with detail.cut: true for one a reload cut that nothing took over), context.updated/threshold-crossed (token + cost), headless.attached (a HeadlessSession attached, for a host that drives the assistant with no screen \u2014 detail.label, what the host called itself, when it gave one) and headless.raw-resolved (that host settled an interaction raw, bypassing the widget's own actions: detail.interactionId and detail.component; the result went to the tool as given, so check what the widget would have enforced), context.condensed (a stale tool payload was collapsed out of the model-bound history by a `condenseWhen` declaration on the tool \u2014 detail.tool + toolCallId, target args|response, trigger (superseded:<key> or age:<n>), stubLen, and an estimated tokensSaved; stored history and this log keep the FULL payload, so the model-visible slice at any point is the full history minus the condensations recorded up to then), panel.toggled, attachment.added, file.read-failed, suggestions.failed.",
5310
+ "Event types: assistant.connected/disconnected (mount + placement + whether the session was created or restored), assistant.popout/popin (window placement), driver.created/wired/unwired (which driver is live and why it stops/starts responding across a popout), state.changed (idle\u2194loading), turn.start/turn.end (turn boundary; turn.end carries durationMs), turn.retry (a recoverable in-turn retry \u2014 detail.reason plus attempt/maxAttempts; for malformed calls also finishMessage; for empty responses also the provider finishReason + thoughtsTokens + parts breakdown), turn.finish-guard (the model replied with no tool call and the agent's finishGuard hook answered \u2014 detail.action is continue (the turn was held open: detail.continuation counts the holds this turn and detail.note is the note stored as a hidden user message with driverNote finish-guard, the next message in the log; detail.source: 'completion-nudge' is instead the driver holding a SUB-AGENT's turn open because it replied in prose without calling its completion tool \u2014 detail.nudge of detail.maxNudges, the note stored with driverNote completion-nudge \u2014 and a sub-agent that still answers in prose after the last nudge fails as before; detail.source: 'forced-tool-nudge' is the driver holding a PARENT agent's forced turn open after a model that rejects forcing answered in prose, the note stored with driverNote forced-tool-nudge, naming the tool when the turn was pinned to one) or end with detail.release: true (the agent was released on a prose answer); a plain end records nothing), turn.error (a turn failed or hit a guardrail \u2014 detail.reason is one of exception/malformed-function-call/empty-response/unknown-tool-limit/max-iterations/response-truncated/refusal/budget-exhausted/provider-refused/context-exhausted/ai-service-error, plus reason-specific diagnostics: attempts (for empty-response also finishReason + thoughtsTokens + a parts breakdown, distinguishing a thinking-only STOP from a truly empty turn), finishMessage, for response-truncated the model + maxTokens + outputTokens + tools, unknownTools (split into staleTools \u2014 real earlier this activation but retired by the current state or hidden behind an open exclusive fold \u2014 and hallucinatedTools \u2014 never advertised) + availableTools, iterations + limit, for budget-exhausted the budgetUsd + spentUsd figures reported by the proxy plus the resolved vendor, for provider-refused the kind (spend|auth) plus the upstream status and error type \u2014 the vendor refusing the ACCOUNT rather than us refusing to spend, so the remedy is a top-up or a key rotation rather than a raised cap, and the kind is the only place that distinction survives because the user-facing copy is deliberately cause-free, for context-exhausted the estimated contextTokens against the guard that stopped the turn plus the iterations reached \u2014 the driver ending a runaway tool loop at the edge of the context window rather than issuing a request the provider would reject, so the transcript survives intact and can still be compacted, for ai-service-error the code (one of AI_SERVICE_ERROR_CODES, e.g. NO_API_KEY) and the status the AI service answered with \u2014 its own text goes to the browser console only, or name + message for exceptions), tool.failed (a tool threw), tool.unresolved (the model called a tool that could not be dispatched \u2014 detail.kind is folded/fold-hidden/stale/unknown, plus tool + agent and, for the counted kinds, the consecutive streak; or kind pinned-elsewhere, a turn pinned to detail.pinned (toolChoice { tool }) that went out unforced because the model rejects forcing, and whose reply called only detail.tools: none of them was run, each was answered with a refusal naming the pinned tool, detail.nudge of detail.maxNudges, counted against the forced-tool nudge on a parent agent and the completion nudge on a sub-agent; the recurring lead-up to an unknown-tool-limit turn.error), subagent.started/completed/failed (the lifecycle of a `requestSubAgent` delegation \u2014 detail.agent names the sub-agent; these bracket the sub-agent turns that appear as kind:turn entries with an N-M `turnIndex`; subagent.failed also carries detail.reason, one of max_iterations/malformed_tool_call/empty_response/unknown_tool_limit/timeout/response_truncated/refusal/budget_exhausted/provider_refused/context_exhausted/ai_service_error, and for timeout detail.cause: 'idle' when it was the sub-agent making no progress for `idleTimeoutMs` rather than the overall `timeoutMs` (absent for the latter); budget_exhausted and provider_refused are terminal for the PARENT turn too, and so is ai_service_error when the refusal is about the service rather than the request and came from the vendor the parent calls \u2014 the parent stops rather than calling the model again into the same wall; after context_exhausted the parent goes on, but its own next call is likely to stop on the same guard), agent.handoff (routing; from=null is the initial activation), agent.pinned/unpinned (forced routing), routing.decided (ONE PER ROUTING DECISION \u2014 see its own paragraph below), provider.selected (the resolved provider for the upcoming turns \u2014 detail.provider is the registry SLOT/tier name, detail.model the concrete model behind it and detail.vendor its vendor; emitted only when the slot CHANGES, so read the per-turn `model` for the model of any given call rather than assuming the nearest event still applies), interaction.requested/resolved (blocking user widgets \u2014 explain quiet gaps; note that when a sub-agent opens a widget, detail.agent \u2014 and the agentName on the interaction message \u2014 is the HOST agent that owns the widget, NOT the sub-agent that asked, because widgets render and resolve on the host driver; detail.ownerPath names the agents that actually asked, outermost first, the last being the one whose tool requested it, and detail.heldBy says who held it when it opened: user, or the id of the interceptor that claimed it, such as autopilot; on interaction.resolved, detail.answeredBy is who answered \u2014 the claimant id when it settled through its own hold, user for any other answer (a click counts as the person even on a widget a claimant held) \u2014 absent when it closed unanswered (a timeout or a stop), and absent too when it settled by itself other than through the hold of a claimant \u2014 a widget registered resolvesItself (one that does its work and settles on its own, asking the person nothing, such as a generation run), or one outcome its controller said settled itself (ctx.resolve with resolvedItself, such as a generation phase that failed outright before its review gate ever asked anything) \u2014 which then carries detail.resolvedItself: true instead, as the interaction message does \u2014 nobody answered it, and the platform cannot tell it finishing from the person interrupting it (a Skip), so only the result of the widget itself can say which; the same value is stamped on the interaction message as answeredBy and on the result the asking tool handler receives (absent there in the same cases), and when it is not user the tool result that interaction returned carries a decidedOnUsersBehalf record, so the model was told the choice was not made by the person; detail.edits, present only when non-zero, counts the editing actions a claimant ran on the widget before it was settled, whoever settled it, and those edits are stamped on the interaction message as edits, each with by, action, choice and args when it had some, in the order they ran, while a decidedOnUsersBehalf record carries their choice texts as edits, and when the person settled it after such edits the tool result carries an editedOnUsersBehalf record instead \u2014 the framing and those choice texts \u2014 so the model knows the widget was changed on the user behalf before the user answered, and that the user then confirmed it by finishing it), interaction.held (a claimant moved a pending interaction to the person or back to itself \u2014 detail.heldBy is the new holder, detail.claimant the interceptor; detail.late: true is an interceptor that declined it when it opened claiming it afterwards, such as the autopilot resumed while it was open; a widget held by anything but user was not answered by the person), interaction.claim-refused (a claim on a userOnly interaction, which stays with the person \u2014 detail.claimant + reason), autopilot.* (the autopilot, a decorator that answers interactions on behalf of the user \u2014 autopilot.claimed / autopilot.declined say whether it took each interaction and, for a decline, detail.reason: paused, other-flow, no-autopilot, unavailable, userOnly, policy or no-controller; one declined as paused that is still open when the person resumes the autopilot is looked at again, and the autopilot.claimed or autopilot.declined recorded for it then carries detail.onResume: true (a decline then can also be claimed-elsewhere, another interceptor having claimed it first); a restored mode looks at nothing; autopilot.decision-sent is what it was sent (detail.chars; detail.nothingEnabled: true when every action on the widget was unavailable \u2014 a gate whose controller said it was asking, such as a failed build the autopilot may not cancel \u2014 so it could only hand it back, which it may then do even after the person asked it to decide it itself; a widget whose controller says it is working (ctx.setWorking) is never sent a decision until it says it is asking, even when an action is enabled or the person resumes the autopilot); autopilot.acted is what it did (detail.action, detail.note, detail.finished); autopilot.handed-back is a decision it gave to the person (detail.reason and detail.trigger: model, no-decision or error); autopilot.paused / autopilot.resumed are mode changes (detail.scope, detail.trigger, detail.decideYourself when the person resumed during a hand-back; detail.trigger is restored when the mode came back with the session after a reload, applied once its flow re-activated, which starts nothing by itself); autopilot.carried is the mode, running or paused, going with the task to the agent that took it over, rather than ending with the flow as on any other change of flow owner: to the target of a hand-off, or back to its caller on the hand-back (detail.from, detail.to, detail.mode); a pause the person chose goes with it, and Stop and Clear still end it; a mode restored for the target of a hand-off applies to its caller when the reload hands back; autopilot.error is the wrapper itself failing; autopilot.refinement counts a refining action against its step \u2014 a written answer (reply) or a widget action declared refines, such as a regenerate with instructions, counted together (detail.action, detail.stepKey, detail.count, detail.limitReached, after which every refining action is withdrawn for that step: not listed, and refused; the decision and every relisting of its actions say how many are left at the step, as a line Refinements left at this step: N, wherever the widget has a refining action); autopilot.handback-presented is the turn-level hand-back, shown when a working turn ended needing the person with no widget to hand over (detail.why: max-iterations, context-exhausted, failure or question; detail.options; detail.choice once answered); autopilot.catch-up is the autopilot being given the whole visible transcript at once (detail.why: first, for its first decision in a flow or after a reload; size, when its own history passed its budget and was rebuilt short \u2014 detail.ownChars; or compacted, when a compaction removed the last message it had seen, so it reads the summary and everything since, short; in each, what it had sent on the user behalf is included and labelled as its own, since its own history does not hold it); autopilot.cost-dropped is autopilot spend that no message carries, so it is NOT in the session total (detail.costUsd and detail.why: handed-back, aborted or stale for a written question it answered that no reply was sent for \u2014 stale when a pause, a resume, a new turn or the end of its flow came before the answer landed, which then went nowhere \u2014 or no-recorder when the driver had no way to book a decision to its interaction); a hand-back trigger can also be budget (the decision passed its spend cap), watchdog (its work went quiet: no ready surface and no heartbeat, or its own decision stalled with no model call landing, which stops that decision) or detached (the autopilot was removed while it held the interaction, which went to the person with no reason shown). To debug one autopilot decision, follow its interactionId: interaction.requested (heldBy), autopilot.claimed, autopilot.decision-sent, autopilot.acted or autopilot.handed-back, interaction.invoked, interaction.resolved (answeredBy), then the next turn of the working agent), interaction.invoked (a claimant ran one of the actions the widget itself exposes, through its hold, the same code the button runs \u2014 detail.claimant, detail.action (an option id, select or reply) and detail.finished, whether that settled the interaction, and when it did not, the run is recorded as an edit; the choice and narration it recorded reach the result of the tool that asked as decidedOnUsersBehalf; the person's own programmatic action, from a host with no DOM to click, carries detail.by: user in place of detail.claimant, and is not recorded as an edit nor as a decision on their behalf, so what it settles is answered by user), interaction.step (a long action run as named steps through runSteps, which survive a reload \u2014 detail.step and detail.outcome: started, done, skipped when the step was already done before a reload, or resumed when it started before a reload and runs again with what it saved part-way, such as a job id it re-attaches to), interaction.checkpoint (the checkpoints a conversation keeps for its long actions: the one in flight, and each one a reload cut, held apart until a request of its own widget type takes it over, so a resumed flow that opens other long widgets first, which save their own, loses nothing \u2014 detail.action: resumed when a reload cut the work and a request of the same widget type that the registration sameWork agrees is the same work took it over, refused when sameWork said a new request is different work (detail.saved is the identity it kept; detail.kept: true, since it stays for a later request of that type, and is offered to every one until one agrees) or when runSteps found the handed-over checkpoint malformed and started fresh (detail.reason, detail.saved), or cleared when its flow ended, once per checkpoint, with detail.cut: true for one a reload cut that nothing took over), context.updated/threshold-crossed (token + cost), headless.attached (a HeadlessSession attached, for a host that drives the assistant with no screen \u2014 detail.label, what the host called itself, when it gave one) and headless.raw-resolved (that host settled an interaction raw, bypassing the widget's own actions: detail.interactionId and detail.component; the result went to the tool as given, so check what the widget would have enforced), context.condensed (a stale tool payload was collapsed out of the model-bound history by a `condenseWhen` declaration on the tool \u2014 detail.tool + toolCallId, target args|response, trigger (superseded:<key> or age:<n>), stubLen, and an estimated tokensSaved; stored history and this log keep the FULL payload, so the model-visible slice at any point is the full history minus the condensations recorded up to then), panel.toggled, attachment.added, file.read-failed, suggestions.failed.",
5063
5311
  "Sub-agent meta events: a sub-agent's own turn.retry/turn.error/tool.failed/tool.unresolved/turn.finish-guard events are merged into this same timeline, tagged with `detail.subAgent` \u2014 a `\"<parent> \u203A <sub-agent>\"` breadcrumb that composes when nested (e.g. `\"UI Builder \u203A Planner \u203A Grounding\"`) \u2014 and interleaved by their original timestamps within the subagent.started\u2192completed/failed bracket. These are the per-attempt/per-failure signals that do NOT appear among the sub-agent's (hoisted) messages: a malformed/empty attempt that gets retried produces no message, and the stale-vs-hallucinated split and streak counts live only on the event. A sub-agent's high-volume, message-derivable events (turn.start/turn.end, provider.selected, context.updated) are intentionally NOT merged \u2014 read its hoisted messages for model/tokens/cost and turn-by-turn activity, and the bracketing subagent.* events for the run's span.",
5064
5312
  "`meta` holds context captured at export time: agentSummary (full agent configs), context (active model, contextTokens/contextLimit/contextUsagePercent for the last call, and the session totals \u2014 sessionCostUsd, sessionTokensConsumed, and the four-bucket sessionUsage lifted to the top of this log), activeDebugSnapshot (the active agent's `getDebugSnapshot()` taken fresh at export \u2014 reflects state NOW, which may have advanced beyond the last turn's agentSnapshot), debug (optional host-supplied debug state), host, and the export timestamp.",
5065
5313
  "Note the two different scopes in `meta.context`: `contextTokens` is the prompt size of the LAST call (against `contextLimit`, the model context window), while `sessionUsage`/`sessionTokensConsumed` are cumulative BILLED throughput. Every turn resends the conversation, so the cumulative figure counts each turn\u2019s prompt again in the next turn\u2019s and is expected to dwarf the context size \u2014 that is not double-counting.",
@@ -6162,6 +6410,13 @@ var MALFORMED_CALL_NUDGE = "IMPORTANT: Use only the structured function-call API
6162
6410
  var EMPTY_RESPONSE_NUDGE = "IMPORTANT: Your previous attempt returned nothing at all, which is never a valid response. Answer the user's last message now, in prose \u2014 even if all you can honestly say is that you cannot help with it and why. If a tool is the right way to answer, call it. Do not return an empty response.";
6163
6411
  var MAX_SETUP_TRANSPORT_RETRIES = 3;
6164
6412
  var MAX_SUB_AGENT_COMPLETION_NUDGES = 2;
6413
+ var MAX_FORCED_TOOL_NUDGES = 2;
6414
+ function forcedToolNudge(pinnedTool) {
6415
+ return pinnedTool ? `Your last reply did not call a tool, but this step must end in a call to \`${pinnedTool}\`. Call \`${pinnedTool}\` now; do not reply in prose.` : "Your last reply did not call a tool, but this step must end in a tool call. Call the tool the step asks for now; do not reply in prose.";
6416
+ }
6417
+ function pinnedToolRefusal(pinnedTool, calledTool) {
6418
+ return `\`${calledTool}\` was not run: this step must end in a call to \`${pinnedTool}\`. Call \`${pinnedTool}\` now.`;
6419
+ }
6165
6420
  var SUB_AGENT_COMPLETION_NUDGE = "You ended your turn in prose, but nothing you write in prose reaches your caller: your result is returned only through the tool that completes your task. Call it now with your result. If you cannot complete the task, call it anyway and say why.";
6166
6421
  var HARVESTED_SUBAGENT_EVENTS = /* @__PURE__ */ new Set([
6167
6422
  "turn.retry",
@@ -10239,6 +10494,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
10239
10494
  let closingCallMade = false;
10240
10495
  let finishGuardContinuations = 0;
10241
10496
  let completionNudges = 0;
10497
+ let forcedToolNudges = 0;
10242
10498
  let releasedByFinishGuard = false;
10243
10499
  while (iterations < this.maxToolIterations || this.closingCallNote() && !closingCallMade) {
10244
10500
  iterations += 1;
@@ -10355,6 +10611,7 @@ ${closing}` : "";
10355
10611
  ${tailBody}
10356
10612
  </system-reminder>` : void 0;
10357
10613
  const effectiveToolChoice = closing ? "none" : resolvedToolChoice ?? (this.isSubAgent ? "required" : void 0);
10614
+ const pinnedTool = typeof effectiveToolChoice === "object" ? effectiveToolChoice.tool : void 0;
10358
10615
  const turnSnapshot = this.turnRecorder.record({
10359
10616
  agentName: this.activeAgentName,
10360
10617
  agentLabel: this.activeAgentLabel,
@@ -10691,12 +10948,50 @@ ${tailBody}
10691
10948
  );
10692
10949
  continue;
10693
10950
  }
10951
+ if (!this.isSubAgent && verdict === void 0 && canContinue && response.responseMeta?.toolChoiceDowngraded && forcedToolNudges < MAX_FORCED_TOOL_NUDGES) {
10952
+ forcedToolNudges += 1;
10953
+ recordMetaEvent(this.sessionKey, "turn.finish-guard", {
10954
+ action: "continue",
10955
+ source: "forced-tool-nudge",
10956
+ agent: this.activeAgentName,
10957
+ nudge: forcedToolNudges,
10958
+ maxNudges: MAX_FORCED_TOOL_NUDGES
10959
+ });
10960
+ this.appendToHistory(
10961
+ finishGuardNoteMessage(forcedToolNudge(pinnedTool), "forced-tool-nudge")
10962
+ );
10963
+ continue;
10964
+ }
10694
10965
  if (verdict?.action === "end" && verdict.release) {
10695
10966
  releasedByFinishGuard = this.requestReleaseFromFinishGuard();
10696
10967
  }
10697
10968
  break;
10698
10969
  }
10699
10970
  const toolCalls = response.toolCalls;
10971
+ let refusePinnedMiss = false;
10972
+ if (pinnedTool && response.responseMeta?.toolChoiceDowngraded && toolCalls.length > 0 && this.toolHandlers[pinnedTool] && !toolCalls.some((tc) => tc.name === pinnedTool)) {
10973
+ if (this.isSubAgent && completionNudges < MAX_SUB_AGENT_COMPLETION_NUDGES) {
10974
+ completionNudges += 1;
10975
+ refusePinnedMiss = true;
10976
+ } else if (!this.isSubAgent && forcedToolNudges < MAX_FORCED_TOOL_NUDGES) {
10977
+ forcedToolNudges += 1;
10978
+ refusePinnedMiss = true;
10979
+ }
10980
+ if (refusePinnedMiss) {
10981
+ recordMetaEvent(this.sessionKey, "tool.unresolved", {
10982
+ kind: "pinned-elsewhere",
10983
+ agent: this.activeAgentName,
10984
+ pinned: pinnedTool,
10985
+ tools: toolCalls.map((tc) => tc.name),
10986
+ nudge: this.isSubAgent ? completionNudges : forcedToolNudges,
10987
+ maxNudges: this.isSubAgent ? MAX_SUB_AGENT_COMPLETION_NUDGES : MAX_FORCED_TOOL_NUDGES
10988
+ });
10989
+ }
10990
+ }
10991
+ if (response.responseMeta?.toolChoiceDowngraded && toolCalls.length > 0 && (!pinnedTool || toolCalls.some((tc) => tc.name === pinnedTool))) {
10992
+ if (this.isSubAgent) completionNudges = 0;
10993
+ else forcedToolNudges = 0;
10994
+ }
10700
10995
  const executedById = /* @__PURE__ */ new Map();
10701
10996
  const unknownToolIds = /* @__PURE__ */ new Set();
10702
10997
  const staleToolIds = /* @__PURE__ */ new Set();
@@ -10705,6 +11000,13 @@ ${tailBody}
10705
11000
  if (toolCalls.length > 0) {
10706
11001
  await Promise.all(
10707
11002
  toolCalls.map(async (tc) => {
11003
+ if (refusePinnedMiss && pinnedTool) {
11004
+ executedById.set(tc.id, {
11005
+ toolCallId: tc.id,
11006
+ content: pinnedToolRefusal(pinnedTool, tc.name)
11007
+ });
11008
+ return;
11009
+ }
10708
11010
  const fold = this.folds.foldFor(tc.name);
10709
11011
  if (fold) {
10710
11012
  const foldOps = this.folds.noteOp();
@@ -12775,16 +13077,16 @@ function describeInteraction(input) {
12775
13077
  }
12776
13078
 
12777
13079
  // src/state/persistence/diagnostics.ts
12778
- var FNV_OFFSET_BASIS = 2166136261;
12779
- var FNV_PRIME = 16777619;
13080
+ var FNV_OFFSET_BASIS2 = 2166136261;
13081
+ var FNV_PRIME2 = 16777619;
12780
13082
  var DIGEST_RADIX = 36;
12781
13083
  function configDigest(json) {
12782
- let a = FNV_OFFSET_BASIS;
12783
- let b = FNV_PRIME;
13084
+ let a = FNV_OFFSET_BASIS2;
13085
+ let b = FNV_PRIME2;
12784
13086
  for (let i = 0; i < json.length; i += 1) {
12785
13087
  const c = json.charCodeAt(i);
12786
- a = Math.imul(a ^ c, FNV_PRIME) >>> 0;
12787
- b = Math.imul(b ^ c, FNV_OFFSET_BASIS) >>> 0;
13088
+ a = Math.imul(a ^ c, FNV_PRIME2) >>> 0;
13089
+ b = Math.imul(b ^ c, FNV_OFFSET_BASIS2) >>> 0;
12788
13090
  }
12789
13091
  return [json.length, a, b].map((n) => n.toString(DIGEST_RADIX)).join("-");
12790
13092
  }
@@ -13867,6 +14169,7 @@ function collectRows(messages, depth, subAgentOf) {
13867
14169
  ANTHROPIC_CACHE_READ_MULTIPLIER,
13868
14170
  ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER,
13869
14171
  ANTHROPIC_CACHE_WRITE_5M_MULTIPLIER,
14172
+ ANTHROPIC_LONG_CONTEXT_THRESHOLD,
13870
14173
  AgenticActivityBus,
13871
14174
  AnthropicProvider,
13872
14175
  AnthropicTransport,
@@ -13900,6 +14203,7 @@ function collectRows(messages, depth, subAgentOf) {
13900
14203
  agenticActivityBus,
13901
14204
  aiServiceAccessRefusalOf,
13902
14205
  aiServiceErrorCodeOf,
14206
+ anthropicCacheReadMultiplierFor,
13903
14207
  anthropicRatesFor,
13904
14208
  anthropicTokenCost,
13905
14209
  assembleDebugLog,