zidane 6.5.0 → 6.5.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.
Files changed (75) hide show
  1. package/dist/acp-cli.js +6 -6
  2. package/dist/{acp-B-AOovHz.js → acp-o-LQAjFw.js} +4 -5
  3. package/dist/{acp-B-AOovHz.js.map → acp-o-LQAjFw.js.map} +1 -1
  4. package/dist/acp.js +1 -1
  5. package/dist/{agent-SQ6rxfpT.js → agent-BVNkC1h4.js} +658 -10
  6. package/dist/agent-BVNkC1h4.js.map +1 -0
  7. package/dist/agent.js +1 -2
  8. package/dist/{anthropic-D3lkw5mv.js → anthropic-Dov2mC5e.js} +3 -3
  9. package/dist/{anthropic-D3lkw5mv.js.map → anthropic-Dov2mC5e.js.map} +1 -1
  10. package/dist/{auth-BzYbbdN_.js → auth-B8ZuBcKC.js} +5 -5
  11. package/dist/{auth-BzYbbdN_.js.map → auth-B8ZuBcKC.js.map} +1 -1
  12. package/dist/chat/pure.js +2 -2
  13. package/dist/chat.js +5 -5
  14. package/dist/{edit-utils-EGosADZq.js → context-breakdown-BLF10tOO.js} +154 -2
  15. package/dist/context-breakdown-BLF10tOO.js.map +1 -0
  16. package/dist/{context-transport-CDBatvQc.js → context-transport-D-daWOmp.js} +3 -3
  17. package/dist/{context-transport-CDBatvQc.js.map → context-transport-D-daWOmp.js.map} +1 -1
  18. package/dist/eval.js +1 -1
  19. package/dist/extensions.js +1 -1
  20. package/dist/headless.js +3 -3
  21. package/dist/index-CWBSrqI6.d.ts.map +1 -1
  22. package/dist/index.js +9 -10
  23. package/dist/index.js.map +1 -1
  24. package/dist/{login-XZDS4K2o.js → login-CR3fDHXh.js} +2 -2
  25. package/dist/{login-XZDS4K2o.js.map → login-CR3fDHXh.js.map} +1 -1
  26. package/dist/{mcp-D27rP47I.js → mcp-C6IkXNOS.js} +3 -3
  27. package/dist/{mcp-D27rP47I.js.map → mcp-C6IkXNOS.js.map} +1 -1
  28. package/dist/mcp.js +1 -1
  29. package/dist/{messages-C01kKGj0.js → messages-C_H9soi5.js} +2 -3
  30. package/dist/{messages-C01kKGj0.js.map → messages-C_H9soi5.js.map} +1 -1
  31. package/dist/{openai-compat-B3c_hzwf.js → openai-compat-CnHeo4Lz.js} +216 -3
  32. package/dist/openai-compat-CnHeo4Lz.js.map +1 -0
  33. package/dist/presets.js +1 -1
  34. package/dist/providers/anthropic.js +1 -1
  35. package/dist/providers/arcee.js +1 -1
  36. package/dist/providers/baseten.js +1 -1
  37. package/dist/providers/cerebras.js +1 -1
  38. package/dist/providers/local.js +1 -1
  39. package/dist/providers/openai-compat.js +1 -1
  40. package/dist/providers/openai.js +2 -2
  41. package/dist/providers/openrouter.js +1 -1
  42. package/dist/providers/xai.js +1 -1
  43. package/dist/{providers-z1vU0b2Q.js → providers-B6mFe7OD.js} +3 -3
  44. package/dist/{providers-z1vU0b2Q.js.map → providers-B6mFe7OD.js.map} +1 -1
  45. package/dist/providers.js +4 -4
  46. package/dist/restate.d.ts +178 -2
  47. package/dist/restate.d.ts.map +1 -1
  48. package/dist/restate.js +458 -4
  49. package/dist/restate.js.map +1 -1
  50. package/dist/{session-cr9VdoEO.js → session-VpLrNaFQ.js} +2 -2
  51. package/dist/{session-cr9VdoEO.js.map → session-VpLrNaFQ.js.map} +1 -1
  52. package/dist/session.js +2 -2
  53. package/dist/{stdio-O-m9WVkE.js → stdio-DzUUkkhS.js} +2 -2
  54. package/dist/{stdio-O-m9WVkE.js.map → stdio-DzUUkkhS.js.map} +1 -1
  55. package/dist/{stdio-loader-BSGQmG4L.js → stdio-loader-BILyUGmi.js} +2 -2
  56. package/dist/{stdio-loader-BSGQmG4L.js.map → stdio-loader-BILyUGmi.js.map} +1 -1
  57. package/dist/tools.js +1 -2
  58. package/dist/{transcript-anchors-D4IxJifV.js → transcript-anchors-DEIr0tJC.js} +5 -5
  59. package/dist/{transcript-anchors-D4IxJifV.js.map → transcript-anchors-DEIr0tJC.js.map} +1 -1
  60. package/dist/tui.js +8 -8
  61. package/dist/{turn-operations-CAvi8NYt.js → turn-operations-C3IijXMW.js} +2 -2
  62. package/dist/{turn-operations-CAvi8NYt.js.map → turn-operations-C3IijXMW.js.map} +1 -1
  63. package/dist/{xai-BPwMQSuF.js → xai-Du6Wfnlb.js} +2 -2
  64. package/dist/{xai-BPwMQSuF.js.map → xai-Du6Wfnlb.js.map} +1 -1
  65. package/docs/RESTATE.md +102 -3
  66. package/package.json +1 -1
  67. package/dist/agent-SQ6rxfpT.js.map +0 -1
  68. package/dist/aliasing-lVFbm81n.js +0 -217
  69. package/dist/aliasing-lVFbm81n.js.map +0 -1
  70. package/dist/context-breakdown-Dzo25N45.js +0 -155
  71. package/dist/context-breakdown-Dzo25N45.js.map +0 -1
  72. package/dist/edit-utils-EGosADZq.js.map +0 -1
  73. package/dist/openai-compat-B3c_hzwf.js.map +0 -1
  74. package/dist/tool-state-DTs-3ZHH.js +0 -653
  75. package/dist/tool-state-DTs-3ZHH.js.map +0 -1
package/dist/chat/pure.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as buildContextBreakdown } from "../context-breakdown-Dzo25N45.js";
1
+ import { t as buildContextBreakdown } from "../context-breakdown-BLF10tOO.js";
2
2
  import { a as formatDuration, c as previewLine, i as fmtTokens, l as shortId, n as compactPath, o as formatTaskStatus, r as fmtCost, s as formatTaskSummary, t as ageString } from "../format-BF745pLL.js";
3
3
  import { a as mergeReferences, n as collectReferences, o as mergeSuggestions, r as findActiveTrigger, t as applyInsert } from "../completion-core-BRo86R_L.js";
4
- import { $ as buildContextualDiff, A as createSkillsCompletionProvider, B as EDIT_TOOL_NAMES, C as chunkMarkdownForRender, D as splitMarkdownCodeBlocks, E as normalizeMarkdownCodeFences, F as COMMANDS_TRIGGER, H as isTurnHighlighted, I as createCommandsCompletionProvider, J as selectableTurnIds, L as blendHsl, M as FILES_TRIGGER, N as createFilesCompletionProvider, P as uniqueFilesFromReferences, Q as applyEditPayload, R as buildLinearRamp, S as MARKDOWN_RENDER_CHUNK_TARGET_BYTES, U as isUserBashEvent, V as isEditErrorResult, W as isVisible, Z as turnSelectionOwnership, _ as turnContextSize, _t as summarizeOutcomes, a as TOOL_DISPLAY, at as filetypeFromPath, b as filterModelCatalog, bt as createChatsCompletionProvider, c as MAX_TRANSCRIPT_EVENTS, ct as summarizeEditPayload, d as finalizeStreamingMarkdown, et as buildUnifiedDiff, f as finalizeStreamingMarkdownForOwner, i as turnAsText, it as extractEditPayload, j as uniqueSkillNamesFromReferences, k as SKILLS_TRIGGER, l as TRANSCRIPT_TRIM_TO_EVENTS, lt as tokenize, n as deleteTurnSafely, nt as computeInlineDiff, o as displayNameFor, ot as previewEditPayload, q as retagUserPromptEvents, r as truncateTurnsAt, rt as computeLineDiff, s as formatToolCall, st as splitLines, t as countNeighbors, u as capTranscriptEvents, v as splitPromptSegments, vt as CHATS_TRIGGER, x as indexOfEntry, xt as uniqueChatIdsFromReferences, y as buildModelCatalog, yt as chatReferenceTokensFromText, z as BASH_CALL_ID_PREFIX } from "../turn-operations-CAvi8NYt.js";
4
+ import { $ as buildContextualDiff, A as createSkillsCompletionProvider, B as EDIT_TOOL_NAMES, C as chunkMarkdownForRender, D as splitMarkdownCodeBlocks, E as normalizeMarkdownCodeFences, F as COMMANDS_TRIGGER, H as isTurnHighlighted, I as createCommandsCompletionProvider, J as selectableTurnIds, L as blendHsl, M as FILES_TRIGGER, N as createFilesCompletionProvider, P as uniqueFilesFromReferences, Q as applyEditPayload, R as buildLinearRamp, S as MARKDOWN_RENDER_CHUNK_TARGET_BYTES, U as isUserBashEvent, V as isEditErrorResult, W as isVisible, Z as turnSelectionOwnership, _ as turnContextSize, _t as summarizeOutcomes, a as TOOL_DISPLAY, at as filetypeFromPath, b as filterModelCatalog, bt as createChatsCompletionProvider, c as MAX_TRANSCRIPT_EVENTS, ct as summarizeEditPayload, d as finalizeStreamingMarkdown, et as buildUnifiedDiff, f as finalizeStreamingMarkdownForOwner, i as turnAsText, it as extractEditPayload, j as uniqueSkillNamesFromReferences, k as SKILLS_TRIGGER, l as TRANSCRIPT_TRIM_TO_EVENTS, lt as tokenize, n as deleteTurnSafely, nt as computeInlineDiff, o as displayNameFor, ot as previewEditPayload, q as retagUserPromptEvents, r as truncateTurnsAt, rt as computeLineDiff, s as formatToolCall, st as splitLines, t as countNeighbors, u as capTranscriptEvents, v as splitPromptSegments, vt as CHATS_TRIGGER, x as indexOfEntry, xt as uniqueChatIdsFromReferences, y as buildModelCatalog, yt as chatReferenceTokensFromText, z as BASH_CALL_ID_PREFIX } from "../turn-operations-C3IijXMW.js";
5
5
  import { a as searchHighlightRanges, c as searchSessionHistoryIndexAsync, d as searchSessionTurns, f as searchTurns, i as highlightSegments, l as searchSessionIndex, n as buildSessionSearchIndexAsync, o as searchSessionHistory, p as searchableTurnText, r as filterSessionSearchCatalog, s as searchSessionHistoryIndex, t as buildSessionSearchIndex, u as searchSessionIndexAsync } from "../history-search-C4bk1Wz_.js";
6
6
  export { BASH_CALL_ID_PREFIX, CHATS_TRIGGER, COMMANDS_TRIGGER, EDIT_TOOL_NAMES, FILES_TRIGGER, MARKDOWN_RENDER_CHUNK_TARGET_BYTES, MAX_TRANSCRIPT_EVENTS, SKILLS_TRIGGER, TOOL_DISPLAY, TRANSCRIPT_TRIM_TO_EVENTS, ageString, applyEditPayload, applyInsert, blendHsl, buildContextBreakdown, buildContextualDiff, buildLinearRamp, buildModelCatalog, buildSessionSearchIndex, buildSessionSearchIndexAsync, buildUnifiedDiff, capTranscriptEvents, chatReferenceTokensFromText, chunkMarkdownForRender, collectReferences, compactPath, computeInlineDiff, computeLineDiff, countNeighbors, createChatsCompletionProvider, createCommandsCompletionProvider, createFilesCompletionProvider, createSkillsCompletionProvider, deleteTurnSafely, displayNameFor, extractEditPayload, filetypeFromPath, filterModelCatalog, filterSessionSearchCatalog, finalizeStreamingMarkdown, finalizeStreamingMarkdownForOwner, findActiveTrigger, fmtCost, fmtTokens, formatDuration, formatTaskStatus, formatTaskSummary, formatToolCall, highlightSegments, indexOfEntry, isEditErrorResult, isTurnHighlighted, isUserBashEvent, isVisible, mergeReferences, mergeSuggestions, normalizeMarkdownCodeFences, previewEditPayload, previewLine, retagUserPromptEvents, searchHighlightRanges, searchSessionHistory, searchSessionHistoryIndex, searchSessionHistoryIndexAsync, searchSessionIndex, searchSessionIndexAsync, searchSessionTurns, searchTurns, searchableTurnText, selectableTurnIds, shortId, splitLines, splitMarkdownCodeBlocks, splitPromptSegments, summarizeEditPayload, summarizeOutcomes, tokenize, truncateTurnsAt, turnAsText, turnContextSize, turnSelectionOwnership, uniqueChatIdsFromReferences, uniqueFilesFromReferences, uniqueSkillNamesFromReferences };
package/dist/chat.js CHANGED
@@ -1,14 +1,14 @@
1
- import { $ as reduceMcpAuth, $n as DOING_TASKS_DOCTRINE, $t as toggleChainEntry, A as redirectUriFromAuthUrl, An as DEFAULT_AGENT_ID, At as resolveTheme, B as buildToolToggle, Bn as TODO_STATUS_GLYPHS, Bt as useDiscovery, C as projectsFilePath, Cn as performSelfUpdate, Cr as stripSpawnTokensLine, Ct as SETTINGS_TOGGLES, D as formatPathForCwd, Dn as renderAgentsMdBlock, Dr as toolResultText, Dt as BUILTIN_THEMES, E as writeProjects, En as discoverAgentsMd, Er as toolCallPreview, Et as useSettings, F as loadMcpToolsCache, Fn as resolveAgentId, Ft as CATPPUCCIN_LATTE, G as parentServerName, Gn as isTodoTool, Gt as resolveStoragePaths, H as useMcpToolToggleSet, Hn as createTodoTools, Ht as ConfigProvider, I as mcpToolsCachePath, In as singleAgentRegistry, It as CATPPUCCIN_MACCHIATO, J as patchMcpCredential, Jn as selectActiveTodos, Jt as chainsEqual, K as createFileMcpCredentialStore, Kn as pickActiveRunId, Kt as buildRunModel, L as refreshMcpToolsCatalog, Ln as TODOREAD_TOOL, Lt as CATPPUCCIN_MOCHA, M as runOAuthLogin, Mn as DEFAULT_PERSIST_EXCLUDE_TOOLS, Mt as GRUVBOX_DARK, N as supportsOAuth, Nn as PLAN_AGENT, Nt as GRUVBOX_LIGHT, O as fetchOAuthRedirect, On as BUILD_AGENT, Or as updateToolEventOutcomes, Ot as DEFAULT_THEME, P as clearMcpToolsCache, Pn as accentColor, Pt as CATPPUCCIN_FRAPPE, Q as getMcpAuthStatus, Qn as COMMUNICATION_DOCTRINE, Qt as sanitizeModelChain, R as saveMcpToolsCache, Rn as TODOS_METADATA_KEY, Rt as createDiscoverySlot, S as matchesSafelistEntry, Sn as performInPlaceSelfUpdate, St as SETTINGS_INPUTS, T as suggestSafelistEntries, Tn as chatAutoCompactBehavior, Tr as titleFromTurns, U as buildVisibleMcpRows, Un as getArchivedTodosForRun, Ut as useConfig, V as useMcpToolToggleMap, Vn as TODO_WRITE_COUNTS_METADATA_KEY, Vt as useDiscoveryOptional, W as indexOfServerRow, Wn as getTodosForRun, Wt as resolveConfig, X as useMcpAuthDispatch, Xn as useActiveTodos, Xt as providerKeySetChanged, Y as McpAuthProvider, Yn as setTodosForRun, Yt as filterChainFallbacks, Z as useMcpAuthState, Zn as ACTIONS_WITH_CARE_DOCTRINE, Zt as restoreChainFallbacks, _ as useSafeModeQueue, _n as checkForUpdate, _r as lastContextSizeFromTurns, _t as listProjectFiles, a as useSurfaces, an as removeMcpServer, ar as SUBAGENT_GUIDANCE, at as isInteractionTool, b as getSafelist, bn as detectPackageManager, br as marginTopFor, bt as SETTINGS_CATEGORIES, c as useStreamBuffer, cn as dedupMcpServersByName, cr as buildPlanSystem, ct as serializeInteractionResponse, d as discoverProjectSkills, dn as parseMcpsFile, dr as createChatTurnsReadTool, dt as EMPTY_HINTS, en as useCompletion, er as IDENTITY_PREFIX, et as ASK_USER_TOOL, f as renderSession, fn as tryOpenBrowser, ft as clipHintsToWidth, g as useSafeModeActions, gn as useUpdateCheck, gr as eventsFromTurns, gt as shortChord, h as SafeModeProvider, hn as buildUpdateHint, hr as deriveSessionTitle, ht as buildHints, i as useSelectStyle, in as mcpsWritePath, ir as PLAN_MODE_DOCTRINE_NO_PROMPTS, it as createInteractionTools, j as oauthUsesManualCodePaste, jn as DEFAULT_BUDGET_EXCLUDE_TOOLS, jt as VAPORWAVE_THEME, k as normalizeRedirectPaste, kn as BUILTIN_AGENTS, kr as usageByModel, kt as resolveChipColor, l as buildSkillsConfig, ln as defaultMcpsConfigPaths, lr as envSection, lt as useInteractionsActions, m as writeSessionExport, mn as bootTick, mr as createStateStore, mt as truncateTrailing, n as ThemeProvider, nn as hasClaudeCodeSetup, nr as INTERACTION_GUIDANCE_NO_PROMPTS, nt as PRESENT_PLAN_TOOL, o as useSyntaxStyles, on as upsertMcpServer, or as TOKEN_DISCIPLINE_DOCTRINE, ot as makeRequestInteraction, p as resolveSessionExportTarget, pn as bootProfileEnabled, pr as compactSummaryEvent, pt as hintsLength, q as mcpCredentialsPath, qn as pruneTodosByRun, qt as chainPositionOf, r as useColors, rn as importFromClaudeCode, rr as PLAN_MODE_DOCTRINE, rt as buildResumedToolResultsTurn, s as useTheme, sn as buildMcpServers, sr as buildBuildSystem, st as pendingInteractionsFromTurns, t as computeTurnAnchors, tn as countClaudeSessionFiles, tr as INTERACTION_GUIDANCE, tt as InteractionsProvider, u as defaultSkillScanPaths, un as discoverProjectMcps, ur as chatReferenceTokensForPrompt, ut as useInteractionsQueue, v as IMPLICITLY_SAFE_TOOLS, vn as compareSemver, vr as listSessionMeta, vt as useEnabledToggleSet, w as readProjects, wn as resolvePlatformPackage, wr as sumRunCosts, wt as SettingsProvider, x as isOnSafelist, xn as parseSemver, xr as saveState, xt as SETTINGS_CHOICES, y as addToSafelist, yn as detectLibc, yr as loadState, yt as DEFAULT_SETTINGS, z as subscribeMcpToolsCache, zn as TODOWRITE_TOOL, zt as DiscoveryProvider } from "./transcript-anchors-D4IxJifV.js";
2
- import { $t as readKeybindings, Cn as effectiveContextWindow, G as EMPTY_EXTENSION_REGISTRY, Gt as KEYBINDING_KEY_COL_WIDTH, Ht as DEFAULT_KEYBINDINGS, Jt as groupBindings, Kt as ensureKeybindingsFile, Qt as parseBindingSpec, Sn as OUTPUT_RESERVE_TOKENS, Ut as KEYBINDING_DEFS, Wt as KEYBINDING_DEF_BY_ACTION, Xt as matchesBinding, Yt as keybindingsPath, Zt as mergeKeybindings, an as defaultExtensionScanPaths, at as composeExtensionPreset, en as readKeybindingsRaw, fn as defineExtension, it as buildExtensionRegistry, lt as mergeContributions, nn as stripJsonComments, on as discoverExtensions, ot as disposeExtensionRegistry, qt as formatBindingForDisplay, rt as buildExtensionPreset, sn as inlineLoadedExtension, st as filterExtensionRegistry, tn as resolveExtensionKeybindings, un as scanExtensionDirectories, ut as partitionExtensionCatalog, wn as shouldAutoCompact, xn as AUTO_COMPACT_MIN_GROWTH_FRACTION } from "./agent-SQ6rxfpT.js";
3
- import { t as buildContextBreakdown } from "./context-breakdown-Dzo25N45.js";
1
+ import { $ as reduceMcpAuth, $n as DOING_TASKS_DOCTRINE, $t as toggleChainEntry, A as redirectUriFromAuthUrl, An as DEFAULT_AGENT_ID, At as resolveTheme, B as buildToolToggle, Bn as TODO_STATUS_GLYPHS, Bt as useDiscovery, C as projectsFilePath, Cn as performSelfUpdate, Cr as stripSpawnTokensLine, Ct as SETTINGS_TOGGLES, D as formatPathForCwd, Dn as renderAgentsMdBlock, Dr as toolResultText, Dt as BUILTIN_THEMES, E as writeProjects, En as discoverAgentsMd, Er as toolCallPreview, Et as useSettings, F as loadMcpToolsCache, Fn as resolveAgentId, Ft as CATPPUCCIN_LATTE, G as parentServerName, Gn as isTodoTool, Gt as resolveStoragePaths, H as useMcpToolToggleSet, Hn as createTodoTools, Ht as ConfigProvider, I as mcpToolsCachePath, In as singleAgentRegistry, It as CATPPUCCIN_MACCHIATO, J as patchMcpCredential, Jn as selectActiveTodos, Jt as chainsEqual, K as createFileMcpCredentialStore, Kn as pickActiveRunId, Kt as buildRunModel, L as refreshMcpToolsCatalog, Ln as TODOREAD_TOOL, Lt as CATPPUCCIN_MOCHA, M as runOAuthLogin, Mn as DEFAULT_PERSIST_EXCLUDE_TOOLS, Mt as GRUVBOX_DARK, N as supportsOAuth, Nn as PLAN_AGENT, Nt as GRUVBOX_LIGHT, O as fetchOAuthRedirect, On as BUILD_AGENT, Or as updateToolEventOutcomes, Ot as DEFAULT_THEME, P as clearMcpToolsCache, Pn as accentColor, Pt as CATPPUCCIN_FRAPPE, Q as getMcpAuthStatus, Qn as COMMUNICATION_DOCTRINE, Qt as sanitizeModelChain, R as saveMcpToolsCache, Rn as TODOS_METADATA_KEY, Rt as createDiscoverySlot, S as matchesSafelistEntry, Sn as performInPlaceSelfUpdate, St as SETTINGS_INPUTS, T as suggestSafelistEntries, Tn as chatAutoCompactBehavior, Tr as titleFromTurns, U as buildVisibleMcpRows, Un as getArchivedTodosForRun, Ut as useConfig, V as useMcpToolToggleMap, Vn as TODO_WRITE_COUNTS_METADATA_KEY, Vt as useDiscoveryOptional, W as indexOfServerRow, Wn as getTodosForRun, Wt as resolveConfig, X as useMcpAuthDispatch, Xn as useActiveTodos, Xt as providerKeySetChanged, Y as McpAuthProvider, Yn as setTodosForRun, Yt as filterChainFallbacks, Z as useMcpAuthState, Zn as ACTIONS_WITH_CARE_DOCTRINE, Zt as restoreChainFallbacks, _ as useSafeModeQueue, _n as checkForUpdate, _r as lastContextSizeFromTurns, _t as listProjectFiles, a as useSurfaces, an as removeMcpServer, ar as SUBAGENT_GUIDANCE, at as isInteractionTool, b as getSafelist, bn as detectPackageManager, br as marginTopFor, bt as SETTINGS_CATEGORIES, c as useStreamBuffer, cn as dedupMcpServersByName, cr as buildPlanSystem, ct as serializeInteractionResponse, d as discoverProjectSkills, dn as parseMcpsFile, dr as createChatTurnsReadTool, dt as EMPTY_HINTS, en as useCompletion, er as IDENTITY_PREFIX, et as ASK_USER_TOOL, f as renderSession, fn as tryOpenBrowser, ft as clipHintsToWidth, g as useSafeModeActions, gn as useUpdateCheck, gr as eventsFromTurns, gt as shortChord, h as SafeModeProvider, hn as buildUpdateHint, hr as deriveSessionTitle, ht as buildHints, i as useSelectStyle, in as mcpsWritePath, ir as PLAN_MODE_DOCTRINE_NO_PROMPTS, it as createInteractionTools, j as oauthUsesManualCodePaste, jn as DEFAULT_BUDGET_EXCLUDE_TOOLS, jt as VAPORWAVE_THEME, k as normalizeRedirectPaste, kn as BUILTIN_AGENTS, kr as usageByModel, kt as resolveChipColor, l as buildSkillsConfig, ln as defaultMcpsConfigPaths, lr as envSection, lt as useInteractionsActions, m as writeSessionExport, mn as bootTick, mr as createStateStore, mt as truncateTrailing, n as ThemeProvider, nn as hasClaudeCodeSetup, nr as INTERACTION_GUIDANCE_NO_PROMPTS, nt as PRESENT_PLAN_TOOL, o as useSyntaxStyles, on as upsertMcpServer, or as TOKEN_DISCIPLINE_DOCTRINE, ot as makeRequestInteraction, p as resolveSessionExportTarget, pn as bootProfileEnabled, pr as compactSummaryEvent, pt as hintsLength, q as mcpCredentialsPath, qn as pruneTodosByRun, qt as chainPositionOf, r as useColors, rn as importFromClaudeCode, rr as PLAN_MODE_DOCTRINE, rt as buildResumedToolResultsTurn, s as useTheme, sn as buildMcpServers, sr as buildBuildSystem, st as pendingInteractionsFromTurns, t as computeTurnAnchors, tn as countClaudeSessionFiles, tr as INTERACTION_GUIDANCE, tt as InteractionsProvider, u as defaultSkillScanPaths, un as discoverProjectMcps, ur as chatReferenceTokensForPrompt, ut as useInteractionsQueue, v as IMPLICITLY_SAFE_TOOLS, vn as compareSemver, vr as listSessionMeta, vt as useEnabledToggleSet, w as readProjects, wn as resolvePlatformPackage, wr as sumRunCosts, wt as SettingsProvider, x as isOnSafelist, xn as parseSemver, xr as saveState, xt as SETTINGS_CHOICES, y as addToSafelist, yn as detectLibc, yr as loadState, yt as DEFAULT_SETTINGS, z as subscribeMcpToolsCache, zn as TODOWRITE_TOOL, zt as DiscoveryProvider } from "./transcript-anchors-DEIr0tJC.js";
2
+ import { t as buildContextBreakdown } from "./context-breakdown-BLF10tOO.js";
3
+ import { $t as groupBindings, Dn as OUTPUT_RESERVE_TOKENS, En as AUTO_COMPACT_MIN_GROWTH_FRACTION, Jt as KEYBINDING_DEFS, On as effectiveContextWindow, Qt as formatBindingForDisplay, Xt as KEYBINDING_KEY_COL_WIDTH, Y as EMPTY_EXTENSION_REGISTRY, Yt as KEYBINDING_DEF_BY_ACTION, Zt as ensureKeybindingsFile, _n as defineExtension, an as readKeybindingsRaw, ct as buildExtensionRegistry, dn as discoverExtensions, dt as filterExtensionRegistry, en as keybindingsPath, fn as inlineLoadedExtension, hn as scanExtensionDirectories, in as readKeybindings, kn as shouldAutoCompact, lt as composeExtensionPreset, mt as partitionExtensionCatalog, nn as mergeKeybindings, on as resolveExtensionKeybindings, pt as mergeContributions, qt as DEFAULT_KEYBINDINGS, rn as parseBindingSpec, sn as stripJsonComments, st as buildExtensionPreset, tn as matchesBinding, un as defaultExtensionScanPaths, ut as disposeExtensionRegistry } from "./agent-BVNkC1h4.js";
4
4
  import { a as formatDuration, c as previewLine, i as fmtTokens, l as shortId, n as compactPath, o as formatTaskStatus, r as fmtCost, s as formatTaskSummary, t as ageString } from "./format-BF745pLL.js";
5
5
  import { R as projectUserPaths, z as findGitRoot } from "./skills-Cp9vnBwd.js";
6
6
  import { p as resolveStorageDirs } from "./plugins-2PMTVcp-.js";
7
7
  import { appendDynamicSection } from "./prompt.js";
8
8
  import { a as generateStructuredData, c as shouldAutoGenerateTitle, g as parseCommandInvocation, h as executeCommand, i as tokenEndingAtCursor, m as commandSteps, n as patchInlineGhost, o as cleanTitle, r as resolveInlineSuggestion, s as generateSessionTitle, t as createPathAutocompleteProvider } from "./inline-autocomplete-D0MPvBaS.js";
9
9
  import { a as mergeReferences, n as collectReferences, o as mergeSuggestions, r as findActiveTrigger, t as applyInsert } from "./completion-core-BRo86R_L.js";
10
- import { C as restoreModelOptions, S as piIdOf, _ as modelOptionsFor, a as readProviderCredential, b as openaiDescriptor, c as writeCredentials, d as cerebrasDescriptor, f as credKeyOf, g as localDescriptor, h as getModelInfo, i as readCredentials, l as BUILTIN_PROVIDERS, m as getContextWindow, n as applyApiKeyEnv, o as removeProviderCredential, p as enabledModelOptions, r as credentialsPath, s as setProviderCredential, t as detectAuth, u as anthropicDescriptor, v as modelSupportsReasoning, x as openrouterDescriptor, y as modelsForDescriptor } from "./auth-BzYbbdN_.js";
11
- import { $ as buildContextualDiff, A as createSkillsCompletionProvider, C as chunkMarkdownForRender, D as splitMarkdownCodeBlocks, E as normalizeMarkdownCodeFences, F as COMMANDS_TRIGGER, H as isTurnHighlighted, I as createCommandsCompletionProvider, J as selectableTurnIds, L as blendHsl, M as FILES_TRIGGER, N as createFilesCompletionProvider, P as uniqueFilesFromReferences, Q as applyEditPayload, R as buildLinearRamp, S as MARKDOWN_RENDER_CHUNK_TARGET_BYTES, V as isEditErrorResult, W as isVisible, Y as selectionAfterTurnRemoval, Z as turnSelectionOwnership, _ as turnContextSize, _t as summarizeOutcomes, a as TOOL_DISPLAY, at as filetypeFromPath, b as filterModelCatalog, bt as createChatsCompletionProvider, c as MAX_TRANSCRIPT_EVENTS, ct as summarizeEditPayload, d as finalizeStreamingMarkdown, dt as maskToOutcomeKinds, et as buildUnifiedDiff, f as finalizeStreamingMarkdownForOwner, ft as mergeApprovalAndBodyOutcomes, gt as stripEditOutcomesAnnotation, ht as rewriteMultiEditHeader, i as turnAsText, it as extractEditPayload, j as uniqueSkillNamesFromReferences, k as SKILLS_TRIGGER, l as TRANSCRIPT_TRIM_TO_EVENTS, lt as tokenize, mt as resolveApprovalForPayload, n as deleteTurnSafely, nt as computeInlineDiff, o as displayNameFor, ot as previewEditPayload, pt as parseEditOutcomesFromResult, r as truncateTurnsAt, rt as computeLineDiff, s as formatToolCall, st as splitLines, t as countNeighbors, u as capTranscriptEvents, ut as buildEditOutcomesAnnotation, v as splitPromptSegments, vt as CHATS_TRIGGER, x as indexOfEntry, xt as uniqueChatIdsFromReferences, y as buildModelCatalog, yt as chatReferenceTokensFromText } from "./turn-operations-CAvi8NYt.js";
10
+ import { C as restoreModelOptions, S as piIdOf, _ as modelOptionsFor, a as readProviderCredential, b as openaiDescriptor, c as writeCredentials, d as cerebrasDescriptor, f as credKeyOf, g as localDescriptor, h as getModelInfo, i as readCredentials, l as BUILTIN_PROVIDERS, m as getContextWindow, n as applyApiKeyEnv, o as removeProviderCredential, p as enabledModelOptions, r as credentialsPath, s as setProviderCredential, t as detectAuth, u as anthropicDescriptor, v as modelSupportsReasoning, x as openrouterDescriptor, y as modelsForDescriptor } from "./auth-B8ZuBcKC.js";
11
+ import { $ as buildContextualDiff, A as createSkillsCompletionProvider, C as chunkMarkdownForRender, D as splitMarkdownCodeBlocks, E as normalizeMarkdownCodeFences, F as COMMANDS_TRIGGER, H as isTurnHighlighted, I as createCommandsCompletionProvider, J as selectableTurnIds, L as blendHsl, M as FILES_TRIGGER, N as createFilesCompletionProvider, P as uniqueFilesFromReferences, Q as applyEditPayload, R as buildLinearRamp, S as MARKDOWN_RENDER_CHUNK_TARGET_BYTES, V as isEditErrorResult, W as isVisible, Y as selectionAfterTurnRemoval, Z as turnSelectionOwnership, _ as turnContextSize, _t as summarizeOutcomes, a as TOOL_DISPLAY, at as filetypeFromPath, b as filterModelCatalog, bt as createChatsCompletionProvider, c as MAX_TRANSCRIPT_EVENTS, ct as summarizeEditPayload, d as finalizeStreamingMarkdown, dt as maskToOutcomeKinds, et as buildUnifiedDiff, f as finalizeStreamingMarkdownForOwner, ft as mergeApprovalAndBodyOutcomes, gt as stripEditOutcomesAnnotation, ht as rewriteMultiEditHeader, i as turnAsText, it as extractEditPayload, j as uniqueSkillNamesFromReferences, k as SKILLS_TRIGGER, l as TRANSCRIPT_TRIM_TO_EVENTS, lt as tokenize, mt as resolveApprovalForPayload, n as deleteTurnSafely, nt as computeInlineDiff, o as displayNameFor, ot as previewEditPayload, pt as parseEditOutcomesFromResult, r as truncateTurnsAt, rt as computeLineDiff, s as formatToolCall, st as splitLines, t as countNeighbors, u as capTranscriptEvents, ut as buildEditOutcomesAnnotation, v as splitPromptSegments, vt as CHATS_TRIGGER, x as indexOfEntry, xt as uniqueChatIdsFromReferences, y as buildModelCatalog, yt as chatReferenceTokensFromText } from "./turn-operations-C3IijXMW.js";
12
12
  import { a as searchHighlightRanges, c as searchSessionHistoryIndexAsync, d as searchSessionTurns, f as searchTurns, i as highlightSegments, l as searchSessionIndex, n as buildSessionSearchIndexAsync, o as searchSessionHistory, p as searchableTurnText, r as filterSessionSearchCatalog, s as searchSessionHistoryIndex, t as buildSessionSearchIndex, u as searchSessionIndexAsync } from "./history-search-C4bk1Wz_.js";
13
13
  //#region src/chat/auto-update-cli.ts
14
14
  const UPGRADE_HELP = `Usage: zidane upgrade [options]
@@ -1,3 +1,4 @@
1
+ import { n as estimateTokens } from "./utils-ngQzYzZD.js";
1
2
  //#region src/tools/edit-utils.ts
2
3
  /**
3
4
  * Internal helpers shared between the `edit` and `multi_edit` tools.
@@ -229,6 +230,157 @@ function isOpeningContext(chars, i) {
229
230
  return prev === " " || prev === " " || prev === "\n" || prev === "\r" || prev === "(" || prev === "[" || prev === "{" || prev === "—" || prev === "–";
230
231
  }
231
232
  //#endregion
232
- export { styleReplacementForVia as i, resolveOldString as n, stripLineNumberPrefixes as r, describeVia as t };
233
+ //#region src/chat/context-breakdown.ts
234
+ const LABELS = {
235
+ systemPrompt: "System prompt",
236
+ rules: "Rules (AGENTS.md)",
237
+ tools: "Tool definitions",
238
+ mcpTools: "MCP tools",
239
+ mcpInstructions: "MCP instructions",
240
+ skills: "Skills",
241
+ subagentDefs: "Subagent definitions",
242
+ conversation: "Conversation",
243
+ mcpToolsDeferred: "MCP tools (deferred)",
244
+ toolsDeferred: "System tools (deferred)",
245
+ autocompactBuffer: "Autocompact buffer",
246
+ freeSpace: "Free space"
247
+ };
248
+ /** Sum the heuristic token sizes of a list of strings. */
249
+ function sumEstimate(parts) {
250
+ let total = 0;
251
+ for (const p of parts) total += estimateTokens(p);
252
+ return total;
253
+ }
254
+ function mcpGroupTokens(group) {
255
+ const items = group.tools.map((t) => ({
256
+ id: `${group.server}:${t.name}`,
257
+ label: t.name,
258
+ tokens: estimateTokens(t.json),
259
+ estimated: true
260
+ }));
261
+ let total = 0;
262
+ for (const it of items) total += it.tokens;
263
+ return {
264
+ total,
265
+ items
266
+ };
267
+ }
268
+ /**
269
+ * Shape a {@link ContextSnapshot} into a render-ready {@link ContextBreakdown}.
270
+ *
271
+ * Live categories (system prompt, tools, MCP tools/instructions, skills,
272
+ * memory, subagent defs, conversation) sum to `snapshot.used` — `conversation`
273
+ * absorbs the remainder so the bar matches the provider-reported total exactly.
274
+ * Deferred + autocompact + free-space buckets follow.
275
+ *
276
+ * When `snapshot.exact` carries provider counts, the matching categories use
277
+ * them (system, tools) and drop their `estimated` flag; everything else stays
278
+ * on the heuristic.
279
+ */
280
+ function buildContextBreakdown(snapshot) {
281
+ const exact = snapshot.exact;
282
+ const systemExact = typeof exact?.system === "number";
283
+ const rulesTokens = snapshot.rulesBlock ? estimateTokens(snapshot.rulesBlock) : 0;
284
+ const rulesItems = (snapshot.rulesFiles ?? []).map((f) => ({
285
+ id: f.path,
286
+ label: f.path,
287
+ tokens: 0,
288
+ estimated: false
289
+ }));
290
+ const skillsTokens = snapshot.skillsCatalog ? estimateTokens(snapshot.skillsCatalog) : 0;
291
+ const mcpInstructionsTokens = snapshot.mcpInstructions ? estimateTokens(snapshot.mcpInstructions) : 0;
292
+ const subagentTokens = snapshot.subagentDefs ? estimateTokens(snapshot.subagentDefs) : 0;
293
+ const embeddedSubsections = rulesTokens + skillsTokens + mcpInstructionsTokens + subagentTokens;
294
+ const systemTotal = systemExact ? exact.system : estimateTokens(snapshot.system);
295
+ const baseSystemTokens = Math.max(0, systemTotal - embeddedSubsections);
296
+ const nativeToolsEst = sumEstimate(snapshot.toolsJson);
297
+ const mcpDisclosed = snapshot.mcpGroups.map(mcpGroupTokens);
298
+ const mcpToolsEst = mcpDisclosed.reduce((a, g) => a + g.total, 0);
299
+ let nativeToolsTokens = nativeToolsEst;
300
+ let mcpToolsTokens = mcpToolsEst;
301
+ let toolsEstimated = true;
302
+ if (systemExact && typeof exact?.systemAndTools === "number") {
303
+ const exactToolsTotal = Math.max(0, exact.systemAndTools - exact.system);
304
+ const estTotal = nativeToolsEst + mcpToolsEst;
305
+ if (estTotal > 0) {
306
+ nativeToolsTokens = Math.round(exactToolsTotal * (nativeToolsEst / estTotal));
307
+ mcpToolsTokens = exactToolsTotal - nativeToolsTokens;
308
+ } else {
309
+ nativeToolsTokens = exactToolsTotal;
310
+ mcpToolsTokens = 0;
311
+ }
312
+ toolsEstimated = false;
313
+ }
314
+ const live = [];
315
+ const push = (id, tokens, estimated, items) => {
316
+ if (tokens <= 0 && !items?.length) return;
317
+ live.push({
318
+ id,
319
+ label: LABELS[id],
320
+ tokens: Math.max(0, tokens),
321
+ estimated,
322
+ ...items?.length ? { items } : {}
323
+ });
324
+ };
325
+ push("systemPrompt", baseSystemTokens, !systemExact);
326
+ push("rules", rulesTokens, true, rulesItems);
327
+ push("skills", skillsTokens, true);
328
+ push("mcpInstructions", mcpInstructionsTokens, true);
329
+ push("subagentDefs", subagentTokens, true);
330
+ push("tools", nativeToolsTokens, toolsEstimated);
331
+ push("mcpTools", mcpToolsTokens, toolsEstimated, mcpDisclosed.flatMap((g) => g.items));
332
+ const accountedStatic = live.reduce((a, c) => a + c.tokens, 0);
333
+ push("conversation", Math.max(0, snapshot.used - accountedStatic), !(systemExact && !toolsEstimated));
334
+ const deferred = [];
335
+ const deferredNativeTools = sumEstimate(snapshot.deferredToolsJson);
336
+ if (deferredNativeTools > 0) deferred.push({
337
+ id: "toolsDeferred",
338
+ label: LABELS.toolsDeferred,
339
+ tokens: deferredNativeTools,
340
+ estimated: true,
341
+ deferred: true
342
+ });
343
+ const deferredMcp = snapshot.deferredMcpGroups.map(mcpGroupTokens);
344
+ const deferredMcpTotal = deferredMcp.reduce((a, g) => a + g.total, 0);
345
+ if (deferredMcpTotal > 0) deferred.push({
346
+ id: "mcpToolsDeferred",
347
+ label: LABELS.mcpToolsDeferred,
348
+ tokens: deferredMcpTotal,
349
+ estimated: true,
350
+ deferred: true,
351
+ items: deferredMcp.flatMap((g) => g.items)
352
+ });
353
+ if (snapshot.autocompactBuffer > 0) deferred.push({
354
+ id: "autocompactBuffer",
355
+ label: LABELS.autocompactBuffer,
356
+ tokens: snapshot.autocompactBuffer,
357
+ estimated: false,
358
+ deferred: true
359
+ });
360
+ const free = Math.max(0, snapshot.effectiveWindow - snapshot.used);
361
+ deferred.push({
362
+ id: "freeSpace",
363
+ label: LABELS.freeSpace,
364
+ tokens: free,
365
+ estimated: false,
366
+ deferred: true
367
+ });
368
+ const categories = [...live, ...deferred];
369
+ const hasEstimates = live.some((c) => c.estimated && c.tokens > 0);
370
+ const fraction = snapshot.effectiveWindow > 0 ? Math.max(0, Math.min(1, snapshot.used / snapshot.effectiveWindow)) : 0;
371
+ return {
372
+ modelId: snapshot.modelId,
373
+ used: snapshot.used,
374
+ effectiveWindow: snapshot.effectiveWindow,
375
+ fraction,
376
+ categories,
377
+ hasEstimates,
378
+ ...snapshot.usage ? { usage: snapshot.usage } : {},
379
+ ...snapshot.extensionSections?.length ? { extensionSections: snapshot.extensionSections } : {},
380
+ ...snapshot.activeSkills?.length ? { activeSkills: snapshot.activeSkills } : {}
381
+ };
382
+ }
383
+ //#endregion
384
+ export { styleReplacementForVia as a, stripLineNumberPrefixes as i, describeVia as n, resolveOldString as r, buildContextBreakdown as t };
233
385
 
234
- //# sourceMappingURL=edit-utils-EGosADZq.js.map
386
+ //# sourceMappingURL=context-breakdown-BLF10tOO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-breakdown-BLF10tOO.js","names":[],"sources":["../src/tools/edit-utils.ts","../src/chat/context-breakdown.ts"],"sourcesContent":["/**\n * Internal helpers shared between the `edit` and `multi_edit` tools.\n *\n * Not part of the public API — intentionally not re-exported from `tools/index.ts`\n * or the package barrel.\n */\n\n/**\n * Count exact (non-overlapping) occurrences of `needle` in `haystack`.\n * Returns 0 for an empty needle — both edit tools reject empty `old_string`\n * up front, so this branch is defensive rather than semantic.\n */\nexport function countExactMatches(haystack: string, needle: string): number {\n if (needle.length === 0)\n return 0\n let count = 0\n let idx = 0\n while (true) {\n const next = haystack.indexOf(needle, idx)\n if (next === -1)\n break\n count++\n idx = next + needle.length\n }\n return count\n}\n\n// ---------------------------------------------------------------------------\n// Curly-quote normalization + SDK-sanitization fallbacks\n// ---------------------------------------------------------------------------\n//\n// Models can't reliably emit Unicode curly quotes, and the Anthropic API\n// silently sanitizes a handful of XML-like tags before they hit the model\n// (`<name>` → `<n>`, etc.). When `old_string` doesn't match exactly, we retry\n// against the same content with both transforms applied so an \"old_string not\n// found\" failure that's only typographical resolves on the second pass.\n//\n// Mirrors the Claude Code Edit tool's recovery strategy. Verbatim port of the\n// quote constants and the desanitization table; the resolve loop below is\n// reorganized to share state between exact / quote-normalized / desanitized.\n\nexport const LEFT_SINGLE_CURLY_QUOTE = '\\u2018'\nexport const RIGHT_SINGLE_CURLY_QUOTE = '\\u2019'\nexport const LEFT_DOUBLE_CURLY_QUOTE = '\\u201C'\nexport const RIGHT_DOUBLE_CURLY_QUOTE = '\\u201D'\n\n/** Map curly quotes (any of the four) to their straight ASCII equivalents. */\nexport function normalizeQuotes(str: string): string {\n return str\n .replaceAll(LEFT_SINGLE_CURLY_QUOTE, '\\'')\n .replaceAll(RIGHT_SINGLE_CURLY_QUOTE, '\\'')\n .replaceAll(LEFT_DOUBLE_CURLY_QUOTE, '\"')\n .replaceAll(RIGHT_DOUBLE_CURLY_QUOTE, '\"')\n}\n\n/**\n * Substitutions Anthropic's API applies to assistant output before the model\n * sees it. The model emits the sanitized form; the file on disk contains the\n * unsanitized form. We undo the substitutions on `old_string` so the search\n * lands on the actual file contents.\n *\n * Verbatim from `claude-code/tools/FileEditTool/utils.ts`.\n */\nconst DESANITIZATIONS: ReadonlyArray<readonly [string, string]> = [\n ['<fnr>', '<function_results>'],\n ['<n>', '<name>'],\n ['</n>', '</name>'],\n ['<o>', '<output>'],\n ['</o>', '</output>'],\n ['<e>', '<error>'],\n ['</e>', '</error>'],\n ['<s>', '<system>'],\n ['</s>', '</system>'],\n ['<r>', '<result>'],\n ['</r>', '</result>'],\n ['< META_START >', '<META_START>'],\n ['< META_END >', '<META_END>'],\n ['< EOT >', '<EOT>'],\n ['< META >', '<META>'],\n ['< SOS >', '<SOS>'],\n ['\\n\\nH:', '\\n\\nHuman:'],\n ['\\n\\nA:', '\\n\\nAssistant:'],\n]\n\n/**\n * Apply the SDK desanitization table to a string. Exported so the edit tools\n * can apply it to `new_string` whenever `old_string` matched via a\n * desanitize-class fallback — keeps the file's unsanitized form on disk\n * instead of writing the model's abbreviated form back.\n */\nexport function desanitize(s: string): string {\n let out = s\n for (const [from, to] of DESANITIZATIONS)\n out = out.replaceAll(from, to)\n return out\n}\n\n/**\n * Strip line-number prefixes from each line of a needle, used as a recovery\n * fallback when the model pastes a `read_file` chunk verbatim into\n * `old_string` — the on-disk file doesn't carry the metadata prefix.\n *\n * Accepts three separator characters so a model that learned on a different\n * agent stack still works here: `\\t` (Claude Code compact, our default),\n * `|`, and `→`. Pattern: optional leading whitespace, 1-9 digits, then one\n * of `\\t | →`. The 9-digit ceiling covers files up to ~1B lines without\n * overshooting into legitimate `\\d{N}<sep>` content like Markdown table\n * cells with long numeric IDs.\n */\nconst LINE_NUMBER_PREFIX_RE = /^[ \\t]*\\d{1,9}[\\t|\\u2192]/gm\nexport function stripLineNumberPrefixes(s: string): string {\n return s.replace(LINE_NUMBER_PREFIX_RE, '')\n}\n\n/**\n * Locate the actual substring in `haystack` that corresponds to `needle`,\n * recovering from typographical mismatch on six escalating fallbacks:\n *\n * 1. Exact substring match (the happy path — no transformation).\n * 2. Curly-quote normalization on both sides — when the model emits straight\n * quotes but the file has curly ones (or vice versa), the slice of the\n * file at the matched position carries the file's actual typography.\n * 3. Anthropic-sanitization undo on the needle — the model's `<n>` becomes\n * the file's `<name>`, etc.\n * 4. Combined: desanitize + quote normalization on the needle.\n * 5. Line-number-prefix strip — when the model pasted a numbered `read_file`\n * chunk verbatim into `old_string` and the file carries no such prefix.\n * 6. Combined: line-number strip + quote normalization — paste-back of a\n * numbered chunk against a file whose typography differs from the model's.\n *\n * Returns `{ actual, occurrences }` — `actual` is the string that exists in\n * the file (use this to do the actual replace; preserves the file's\n * typography). `occurrences` is the count of those matches in the file.\n *\n * Fallbacks 3-4 (desanitize-class) only fire when the transformed needle is\n * UNIQUE in the file — they rewrite the needle's meaning rather than its\n * typography, so an ambiguous match risks silently retargeting the wrong\n * text (see the inline comment at step 3).\n *\n * Returns `null` when no recovery worked.\n */\nexport interface ResolvedMatch {\n actual: string\n occurrences: number\n /** Recovery path — `'exact'` when no transformation was applied. */\n via: 'exact' | 'quotes' | 'desanitize' | 'quotes+desanitize' | 'line-numbers' | 'quotes+line-numbers'\n}\n\n/**\n * Search `target` in `normFile` and slice the matching span out of the\n * original `haystack`, counting all non-overlapping occurrences. `normFile`\n * is the haystack with whatever transform (quotes / desanitize / combined)\n * was applied to make the indices align — slicing the original haystack\n * preserves the file's actual typography so `replace_all` writes back the\n * file's form, not the model's.\n *\n * Pre-condition: `normFile.length === haystack.length` (every transform\n * we use is one-to-one). Returns null on miss.\n */\nfunction locateAndCount(\n haystack: string,\n normFile: string,\n target: string,\n via: ResolvedMatch['via'],\n): ResolvedMatch | null {\n const idx = normFile.indexOf(target)\n if (idx === -1)\n return null\n const actual = haystack.slice(idx, idx + target.length)\n let occ = 0\n let cursor = 0\n while (true) {\n const next = normFile.indexOf(target, cursor)\n if (next === -1)\n break\n occ++\n cursor = next + target.length\n }\n return { actual, occurrences: occ, via }\n}\n\nexport function resolveOldString(haystack: string, needle: string): ResolvedMatch | null {\n // 1. Exact match — happy path.\n const exact = countExactMatches(haystack, needle)\n if (exact > 0)\n return { actual: needle, occurrences: exact, via: 'exact' }\n\n // 2. Curly-quote normalization. Either side can carry curly quotes:\n // model emitted straight + file has curly, OR model emitted curly +\n // file has straight. Normalize both and look there. Slice the original\n // haystack to recover the actual file-side typography.\n const normNeedle = normalizeQuotes(needle)\n const normFile = normalizeQuotes(haystack)\n if (normNeedle !== needle || normFile !== haystack) {\n const m = locateAndCount(haystack, normFile, normNeedle, 'quotes')\n if (m)\n return m\n }\n\n // 3. Desanitize the needle — model-side substitution undo (`<n>` → `<name>`,\n // etc.) The file always has the unsanitized form; only the model emits\n // the abbreviated version.\n //\n // Desanitize-class fallbacks additionally require a UNIQUE transformed\n // match. Unlike the quote / line-number transforms (typography-only /\n // verbatim paste-back), this one rewrites the needle's meaning — a model\n // that genuinely meant the literal `<n>` against a file full of `<name>`\n // would otherwise silently retarget every occurrence under `replace_all`.\n // A unique hit bounds the blast radius to one visible replacement.\n const desan = desanitize(needle)\n if (desan !== needle) {\n const desanCount = countExactMatches(haystack, desan)\n if (desanCount === 1)\n return { actual: desan, occurrences: desanCount, via: 'desanitize' }\n }\n\n // 4. Combined: desanitize + quote normalization. Hit when the model\n // emitted both sanitized tokens and straight quotes, but the file has\n // the unsanitized form with curly quotes. Same uniqueness requirement\n // as #3.\n const combo = desanitize(normNeedle)\n if (combo !== needle) {\n const m = locateAndCount(haystack, normFile, combo, 'quotes+desanitize')\n if (m && m.occurrences === 1)\n return m\n }\n\n // 5. Line-number-prefix strip. When `read_file` returns line-numbered\n // output and the model pasted the chunk verbatim into `old_string`,\n // the on-disk file doesn't carry those prefixes. Strip them and\n // retry; the file-side `actual` is the prefix-free needle so the\n // replacement lands on real bytes.\n //\n // Guard against a needle that strips down to whitespace-only (e.g.\n // `1\\t\\n2\\t\\n3\\t` → `\\n\\n`). Searching for `\\n\\n` would match arbitrary\n // blank-line patterns anywhere in the file — a high false-positive risk.\n // Require the stripped needle to carry at least one non-whitespace\n // character before we trust the result.\n const stripped = stripLineNumberPrefixes(needle)\n if (stripped !== needle && stripped.trim().length > 0) {\n const count = countExactMatches(haystack, stripped)\n if (count > 0)\n return { actual: stripped, occurrences: count, via: 'line-numbers' }\n\n // 6. Combined: line-number strip + curly-quote normalization. The\n // typography mismatch may live in the file, the needle, or both.\n const strippedNorm = normalizeQuotes(stripped)\n if (strippedNorm !== stripped || normFile !== haystack) {\n const m = locateAndCount(haystack, normFile, strippedNorm, 'quotes+line-numbers')\n if (m)\n return m\n }\n }\n\n return null\n}\n\n/**\n * Short human-readable label for a recovery path, used by `edit` /\n * `multi_edit` to flag non-exact matches in their result messages — when a\n * fallback mistargets, the model (and the user reading the transcript) can\n * see WHICH transform fired instead of silently trusting the edit.\n */\nexport function describeVia(via: ResolvedMatch['via']): string {\n switch (via) {\n case 'exact': return 'exact match'\n case 'quotes': return 'curly-quote normalization'\n case 'desanitize': return 'sanitization recovery (e.g. <n> → <name>)'\n case 'quotes+desanitize': return 'sanitization recovery + curly-quote normalization'\n case 'line-numbers': return 'line-number-prefix stripping'\n case 'quotes+line-numbers': return 'line-number-prefix stripping + curly-quote normalization'\n }\n}\n\n/**\n * Apply the same recovery transforms used to find `old_string` to\n * `new_string`, so the file gets back its native form: desanitize when\n * the model emitted `<n>` for `<name>`, strip line-number prefixes when\n * the match required them, then re-curlify when the match required\n * quote normalization. Shared between `edit` and `multi_edit`.\n */\nexport function styleReplacementForVia(\n replacement: string,\n via: ResolvedMatch['via'],\n actual: string,\n): string {\n let out = replacement\n if (via === 'desanitize' || via === 'quotes+desanitize')\n out = desanitize(out)\n if (via === 'line-numbers' || via === 'quotes+line-numbers')\n out = stripLineNumberPrefixes(out)\n if (via === 'quotes' || via === 'quotes+desanitize' || via === 'quotes+line-numbers')\n out = preserveQuoteStyle(actual, out)\n return out\n}\n\n/**\n * When `old_string` matched via curly-quote normalization, re-style\n * `new_string` so the file's typography is preserved across the edit.\n * Detects whether the matched file region had curly singles, doubles, or\n * both, and applies the matching curlification to the replacement.\n *\n * Apostrophes in contractions (`don't`, `it's`) get the right-single curly\n * quote regardless of opening context — that's the canonical typographer's\n * convention for English. Other quotes use a simple\n * preceded-by-whitespace-or-opening-punctuation heuristic.\n */\nexport function preserveQuoteStyle(actual: string, replacement: string): string {\n const hasDouble = actual.includes(LEFT_DOUBLE_CURLY_QUOTE) || actual.includes(RIGHT_DOUBLE_CURLY_QUOTE)\n const hasSingle = actual.includes(LEFT_SINGLE_CURLY_QUOTE) || actual.includes(RIGHT_SINGLE_CURLY_QUOTE)\n if (!hasDouble && !hasSingle)\n return replacement\n\n let out = replacement\n if (hasDouble)\n out = applyCurly(out, '\"', LEFT_DOUBLE_CURLY_QUOTE, RIGHT_DOUBLE_CURLY_QUOTE, false)\n if (hasSingle)\n out = applyCurly(out, '\\'', LEFT_SINGLE_CURLY_QUOTE, RIGHT_SINGLE_CURLY_QUOTE, true)\n return out\n}\n\nfunction applyCurly(\n s: string,\n straight: string,\n left: string,\n right: string,\n contractionAware: boolean,\n): string {\n const chars = [...s]\n const result: string[] = []\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] !== straight) {\n result.push(chars[i])\n continue\n }\n if (contractionAware) {\n const prev = i > 0 ? chars[i - 1] : ''\n const next = i < chars.length - 1 ? chars[i + 1] : ''\n // Letter-quote-letter is a contraction, not a quote — always right.\n if (/\\p{L}/u.test(prev) && /\\p{L}/u.test(next)) {\n result.push(right)\n continue\n }\n }\n result.push(isOpeningContext(chars, i) ? left : right)\n }\n return result.join('')\n}\n\nfunction isOpeningContext(chars: string[], i: number): boolean {\n if (i === 0)\n return true\n const prev = chars[i - 1]\n return prev === ' ' || prev === '\\t' || prev === '\\n' || prev === '\\r'\n || prev === '(' || prev === '[' || prev === '{'\n || prev === '\\u2014' || prev === '\\u2013' // em / en dash\n}\n","/**\n * Context-usage breakdown — pure transforms.\n *\n * Turns a {@link ContextSnapshot} (the raw pieces the agent assembled for a\n * run: system prompt, wire tools, deferred tools, MCP tools/instructions,\n * skills catalog, ...) plus the real last-turn token total into a categorized\n * {@link ContextBreakdown} the TUI panel / GUI popover render.\n *\n * No React, no node — a browser-context renderer imports these via\n * `zidane/chat/pure`. The snapshot is captured main-side (TUI direct, GUI in\n * `main/chat`) because building it reads provider/agent state; only the pure\n * shaping lives here.\n *\n * Accuracy: per-category counts are estimates when no provider `countTokens`\n * is available — the heuristic ({@link estimateTokens}, ~4 bytes/token) sizes\n * each static segment and the bar is reconciled so it always sums to the real\n * last-turn total (`conversation = realTotal - sum(static)`). When a provider\n * exposes exact counts (Anthropic, OpenAI), the caller passes them in via\n * {@link ContextSnapshot.exact} and the corresponding categories drop their\n * `estimated` flag. Exact buckets (free space, autocompact buffer) are never\n * estimated.\n */\n\nimport type { SessionTurn } from '../types'\nimport { estimateTokens } from '../compact/utils'\n\n/**\n * Stable identifiers for each breakdown category. Drives swatch color +\n * ordering in both UIs. `*Deferred` buckets are tools/MCP that exist but are\n * NOT currently on the wire (lazy disclosure); `autocompactBuffer` is the\n * reserved output headroom; `freeSpace` is the remaining window.\n */\nexport type ContextCategoryId\n = | 'systemPrompt'\n | 'rules'\n | 'tools'\n | 'mcpTools'\n | 'mcpInstructions'\n | 'skills'\n | 'subagentDefs'\n | 'conversation'\n | 'mcpToolsDeferred'\n | 'toolsDeferred'\n | 'autocompactBuffer'\n | 'freeSpace'\n\n/**\n * Exact last-turn token usage split (provider-reported — always exact). Drives\n * the cache breakdown shown below the categories. `cacheRead + cacheCreation +\n * input` equals the live context total (`used`).\n */\nexport interface ContextUsageSplit {\n /** Fresh, uncached input tokens this turn. */\n input: number\n /** Tokens served from the prompt cache (the cached prefix). */\n cacheRead: number\n /** Tokens written to the cache this turn. */\n cacheCreation: number\n /** Assistant output tokens (not part of the input window; informational). */\n output: number\n}\n\n/** One display row contributed by an extension to the context panel. */\nexport interface ContextExtensionRow {\n label: string\n value: string\n}\n\n/** Extension-owned context panel section. Core treats rows as opaque display data. */\nexport interface ContextExtensionSection {\n id: string\n label: string\n /** Optional section-title foreground color. UIs fall back to their theme accent. */\n accentColor?: string\n rows: readonly ContextExtensionRow[]\n}\n\n/** Data exposed to extension context-breakdown contributors. */\nexport interface ContextBreakdownContributionContext {\n turns: readonly SessionTurn[]\n}\n\n/** Extension hook for adding opaque rows to the context panel. */\nexport type ContextBreakdownContributor\n = (ctx: ContextBreakdownContributionContext) =>\n | ContextExtensionSection\n | readonly ContextExtensionSection[]\n | null\n | undefined\n | Promise<ContextExtensionSection | readonly ContextExtensionSection[] | null | undefined>\n\n/** One expandable child row under a category (e.g. a single MCP tool / memory file). */\nexport interface ContextItem {\n /** Stable-ish key for rendering (tool name, file path). */\n id: string\n /** Display label. */\n label: string\n /** Token count for this item. */\n tokens: number\n /** True when `tokens` came from the heuristic rather than an exact count. */\n estimated: boolean\n}\n\n/** One category row in the breakdown. */\nexport interface ContextCategory {\n id: ContextCategoryId\n /** Display label (e.g. \"Tool definitions\"). */\n label: string\n /** Token count for the category. */\n tokens: number\n /** True when `tokens` came from the heuristic rather than an exact count. */\n estimated: boolean\n /**\n * True for buckets that are NOT counted against the live window total\n * (deferred tools, free space, autocompact buffer) — the UI renders these\n * dimmed / below a divider, mirroring Claude Code's layout.\n */\n deferred?: boolean\n /** Optional expandable child rows (per MCP tool, per memory file, ...). */\n items?: ContextItem[]\n}\n\n/** The shaped, render-ready breakdown. */\nexport interface ContextBreakdown {\n /** Model id the snapshot was built for. */\n modelId: string\n /**\n * Real last-turn context size (provider-reported `input + cacheRead +\n * cacheCreation`) — the SAME number the footer/orb shows. The non-deferred\n * categories always sum to this.\n */\n used: number\n /** Effective window (raw - output reserve), the bar's denominator. */\n effectiveWindow: number\n /** `used / effectiveWindow`, clamped to [0, 1]. */\n fraction: number\n /** Live categories (sum to `used`) followed by deferred + free-space buckets. */\n categories: ContextCategory[]\n /** True when ANY live category is estimated (drives the panel's footnote). */\n hasEstimates: boolean\n /**\n * Exact last-turn usage split (cache read / write / fresh input / output),\n * when the host supplied it. Always exact — rendered as an informational\n * section below the categories. Absent when no usage is available yet.\n */\n usage?: ContextUsageSplit\n /** Extension-owned context panel sections. */\n extensionSections?: readonly ContextExtensionSection[]\n /**\n * Names of currently-active skills. Informational — an activated skill's body\n * lands in the conversation (tool-results), so its tokens are already counted\n * under Conversation; this just surfaces \"which skills are loaded\". Empty/absent\n * when none are active.\n */\n activeSkills?: string[]\n}\n\n/** Host-supplied options for `agent.getContextBreakdown`. */\nexport interface ContextBreakdownOptions {\n /**\n * Effective context window (`rawWindow - outputReserve`) for the active\n * model, resolved by the host via the chat model registry. Drives free-space\n * + fraction. When omitted, defaults to `used` (no headroom shown).\n */\n effectiveWindow?: number\n /**\n * Active model id — used for the exact `countTokens` call + the header label.\n * Only consulted on the PRE-RUN path (no snapshot yet); once a run has fired,\n * the snapshot's own model wins. When omitted, the provider default is used.\n */\n model?: string\n /** Tokens reserved for output (autocompact buffer). Defaults to 0. */\n autocompactBuffer?: number\n /**\n * Auto-compact threshold as a fraction of the window (0–1), when enabled.\n * When set, the \"Autocompact buffer\" bucket represents the ENTIRE tail from\n * the threshold to the end of the window (`(1 − threshold) × window`) rather\n * than just the reserved-output tokens — so the bar/row show exactly where\n * compaction fires. When omitted, `autocompactBuffer` is used as-is.\n */\n compactThreshold?: number\n /** Abort signal forwarded to the provider's `countTokens`. */\n signal?: AbortSignal\n}\n\n/** Tools grouped by MCP server, for the expandable per-server rows. */\nexport interface ContextMcpGroup {\n server: string\n /** Wire tool specs for this server (their JSON size is measured). */\n tools: { name: string, json: string }[]\n}\n\n/**\n * Exact per-segment counts from a provider's `countTokens`, when available.\n * Each field is the count of the cumulative payload up to and including that\n * segment, so categories are derived by differencing (see\n * {@link buildContextBreakdown}). Any subset may be present; missing fields\n * fall back to the heuristic for that category.\n */\nexport interface ContextExactCounts {\n /** Tokens for system prompt alone. */\n system?: number\n /** Tokens for system + tools (so tools = systemAndTools - system). */\n systemAndTools?: number\n /** Tokens for the full payload (system + tools + messages) = the real total. */\n full?: number\n}\n\n/**\n * Raw inputs captured at agent prompt-assembly time. Everything here is what\n * actually went on (or was withheld from) the wire for the last run.\n */\nexport interface ContextSnapshot {\n modelId: string\n /** Full rendered system prompt (marker-stripped, as sent). */\n system: string\n /**\n * Host-composed base system BEFORE the agent appended skills / searchable /\n * MCP-instructions catalogs. Includes the rules block. The \"System prompt\"\n * (base doctrine) bucket = base − rules − env-noise. Defaults to `system`\n * when not provided (back-compat).\n */\n baseSystem?: string\n /** Rendered AGENTS.md/CLAUDE.md rules block (a substring of `baseSystem`). */\n rulesBlock?: string\n /** Source files behind the rules block, for per-file rows. */\n rulesFiles?: { path: string, source: string }[]\n /** Wire tool specs currently disclosed to the model, as JSON strings. */\n toolsJson: string[]\n /** Lazy tool entries NOT currently disclosed (deferred), as JSON strings. */\n deferredToolsJson: string[]\n /** MCP tools grouped by server (disclosed ones). */\n mcpGroups: ContextMcpGroup[]\n /** Deferred (undisclosed) MCP tools grouped by server. */\n deferredMcpGroups: ContextMcpGroup[]\n /** Rendered MCP instructions block, if any. */\n mcpInstructions?: string\n /** Rendered skills catalog text, if any. */\n skillsCatalog?: string\n /** Searchable / subagent (spawn) tool definitions text, if any. */\n subagentDefs?: string\n /** Memory / rules files in context. */\n /** Real last-turn total (input + cacheRead + cacheCreation). */\n used: number\n /** Effective window (raw - output reserve). */\n effectiveWindow: number\n /** Tokens reserved for output (autocompact buffer). */\n autocompactBuffer: number\n /** Exact per-segment counts from the provider, when available. */\n exact?: ContextExactCounts\n /** Exact last-turn usage split, when available (passed straight through). */\n usage?: ContextUsageSplit\n /** Extension-owned context panel sections. */\n extensionSections?: readonly ContextExtensionSection[]\n /** Names of currently-active skills (passed straight through). */\n activeSkills?: string[]\n}\n\nconst LABELS: Record<ContextCategoryId, string> = {\n systemPrompt: 'System prompt',\n rules: 'Rules (AGENTS.md)',\n tools: 'Tool definitions',\n mcpTools: 'MCP tools',\n mcpInstructions: 'MCP instructions',\n skills: 'Skills',\n subagentDefs: 'Subagent definitions',\n conversation: 'Conversation',\n mcpToolsDeferred: 'MCP tools (deferred)',\n toolsDeferred: 'System tools (deferred)',\n autocompactBuffer: 'Autocompact buffer',\n freeSpace: 'Free space',\n}\n\n/** Sum the heuristic token sizes of a list of strings. */\nfunction sumEstimate(parts: readonly string[]): number {\n let total = 0\n for (const p of parts)\n total += estimateTokens(p)\n return total\n}\n\nfunction mcpGroupTokens(group: ContextMcpGroup): { total: number, items: ContextItem[] } {\n const items: ContextItem[] = group.tools.map(t => ({\n id: `${group.server}:${t.name}`,\n label: t.name,\n tokens: estimateTokens(t.json),\n estimated: true,\n }))\n let total = 0\n for (const it of items)\n total += it.tokens\n return { total, items }\n}\n\n/**\n * Shape a {@link ContextSnapshot} into a render-ready {@link ContextBreakdown}.\n *\n * Live categories (system prompt, tools, MCP tools/instructions, skills,\n * memory, subagent defs, conversation) sum to `snapshot.used` — `conversation`\n * absorbs the remainder so the bar matches the provider-reported total exactly.\n * Deferred + autocompact + free-space buckets follow.\n *\n * When `snapshot.exact` carries provider counts, the matching categories use\n * them (system, tools) and drop their `estimated` flag; everything else stays\n * on the heuristic.\n */\nexport function buildContextBreakdown(snapshot: ContextSnapshot): ContextBreakdown {\n const exact = snapshot.exact\n const systemExact = typeof exact?.system === 'number'\n\n // --- System-embedded sub-sections (heuristic) ----------------------------\n // The exact `count_tokens` system number covers the WHOLE system text. The\n // appended catalogs (rules / skills / MCP instructions / subagent defs) all\n // live inside it, so we size each heuristically and let the \"System prompt\"\n // (base doctrine) bucket absorb the remainder — keeping the system group's\n // sum exact while still attributing each section.\n const rulesTokens = snapshot.rulesBlock ? estimateTokens(snapshot.rulesBlock) : 0\n const rulesItems: ContextItem[] = (snapshot.rulesFiles ?? []).map(f => ({\n id: f.path,\n label: f.path,\n // Per-file size isn't separable from the rendered block; show the path only\n // (tokens 0, not estimated — there's nothing to estimate) so the row lists\n // sources without implying a per-file count or a `~` marker.\n tokens: 0,\n estimated: false,\n }))\n const skillsTokens = snapshot.skillsCatalog ? estimateTokens(snapshot.skillsCatalog) : 0\n const mcpInstructionsTokens = snapshot.mcpInstructions ? estimateTokens(snapshot.mcpInstructions) : 0\n const subagentTokens = snapshot.subagentDefs ? estimateTokens(snapshot.subagentDefs) : 0\n const embeddedSubsections = rulesTokens + skillsTokens + mcpInstructionsTokens + subagentTokens\n\n // System TOTAL (whole system text) — exact when available.\n const systemTotal = systemExact ? exact!.system! : estimateTokens(snapshot.system)\n // Base doctrine = system total minus the attributed sub-sections.\n const baseSystemTokens = Math.max(0, systemTotal - embeddedSubsections)\n\n // --- Native tool definitions (non-MCP, disclosed) ------------------------\n // When exact `systemAndTools` is available it covers BOTH native + MCP tools,\n // so we split that combined number proportionally by heuristic weight rather\n // than claiming exactness per sub-bucket.\n const nativeToolsEst = sumEstimate(snapshot.toolsJson)\n const mcpDisclosed = snapshot.mcpGroups.map(mcpGroupTokens)\n const mcpToolsEst = mcpDisclosed.reduce((a, g) => a + g.total, 0)\n\n let nativeToolsTokens = nativeToolsEst\n let mcpToolsTokens = mcpToolsEst\n let toolsEstimated = true\n if (systemExact && typeof exact?.systemAndTools === 'number') {\n const exactToolsTotal = Math.max(0, exact.systemAndTools - exact.system!)\n const estTotal = nativeToolsEst + mcpToolsEst\n if (estTotal > 0) {\n nativeToolsTokens = Math.round(exactToolsTotal * (nativeToolsEst / estTotal))\n mcpToolsTokens = exactToolsTotal - nativeToolsTokens\n }\n else {\n nativeToolsTokens = exactToolsTotal\n mcpToolsTokens = 0\n }\n toolsEstimated = false\n }\n\n // --- Live categories -----------------------------------------------------\n // Detailed split. The system-embedded sub-sections (rules / skills / MCP\n // instructions / subagent defs) are heuristic; the \"System prompt\" base\n // bucket carries the exact remainder so the whole system group still sums to\n // the exact system count. Tools/MCP-tools/conversation are split as before.\n const live: ContextCategory[] = []\n const push = (id: ContextCategoryId, tokens: number, estimated: boolean, items?: ContextItem[]) => {\n if (tokens <= 0 && !items?.length)\n return\n live.push({ id, label: LABELS[id], tokens: Math.max(0, tokens), estimated, ...(items?.length ? { items } : {}) })\n }\n\n // System group: base doctrine (exact remainder) + attributed sub-sections.\n push('systemPrompt', baseSystemTokens, !systemExact)\n push('rules', rulesTokens, true, rulesItems)\n push('skills', skillsTokens, true)\n push('mcpInstructions', mcpInstructionsTokens, true)\n push('subagentDefs', subagentTokens, true)\n // Tools.\n push('tools', nativeToolsTokens, toolsEstimated)\n push('mcpTools', mcpToolsTokens, toolsEstimated, mcpDisclosed.flatMap(g => g.items))\n\n // --- Conversation = remainder (keeps the bar summing to `used`) ----------\n const accountedStatic = live.reduce((a, c) => a + c.tokens, 0)\n const conversationTokens = Math.max(0, snapshot.used - accountedStatic)\n // Exact when both system AND tools were exactly counted — then the remainder\n // (used − exactSystem − exactTools) is itself exact, since `used` is the\n // provider-reported total.\n const conversationEstimated = !(systemExact && !toolsEstimated)\n push('conversation', conversationTokens, conversationEstimated)\n\n // --- Deferred buckets (not counted against `used`) -----------------------\n const deferred: ContextCategory[] = []\n const deferredNativeTools = sumEstimate(snapshot.deferredToolsJson)\n if (deferredNativeTools > 0) {\n deferred.push({ id: 'toolsDeferred', label: LABELS.toolsDeferred, tokens: deferredNativeTools, estimated: true, deferred: true })\n }\n const deferredMcp = snapshot.deferredMcpGroups.map(mcpGroupTokens)\n const deferredMcpTotal = deferredMcp.reduce((a, g) => a + g.total, 0)\n if (deferredMcpTotal > 0) {\n deferred.push({\n id: 'mcpToolsDeferred',\n label: LABELS.mcpToolsDeferred,\n tokens: deferredMcpTotal,\n estimated: true,\n deferred: true,\n items: deferredMcp.flatMap(g => g.items),\n })\n }\n\n // --- Autocompact buffer + free space (exact) -----------------------------\n if (snapshot.autocompactBuffer > 0) {\n deferred.push({ id: 'autocompactBuffer', label: LABELS.autocompactBuffer, tokens: snapshot.autocompactBuffer, estimated: false, deferred: true })\n }\n const free = Math.max(0, snapshot.effectiveWindow - snapshot.used)\n deferred.push({ id: 'freeSpace', label: LABELS.freeSpace, tokens: free, estimated: false, deferred: true })\n\n const categories = [...live, ...deferred]\n const hasEstimates = live.some(c => c.estimated && c.tokens > 0)\n const fraction = snapshot.effectiveWindow > 0\n ? Math.max(0, Math.min(1, snapshot.used / snapshot.effectiveWindow))\n : 0\n\n return {\n modelId: snapshot.modelId,\n used: snapshot.used,\n effectiveWindow: snapshot.effectiveWindow,\n fraction,\n categories,\n hasEstimates,\n ...(snapshot.usage ? { usage: snapshot.usage } : {}),\n ...(snapshot.extensionSections?.length ? { extensionSections: snapshot.extensionSections } : {}),\n ...(snapshot.activeSkills?.length ? { activeSkills: snapshot.activeSkills } : {}),\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,kBAAkB,UAAkB,QAAwB;CAC1E,IAAI,OAAO,WAAW,GACpB,OAAO;CACT,IAAI,QAAQ;CACZ,IAAI,MAAM;CACV,OAAO,MAAM;EACX,MAAM,OAAO,SAAS,QAAQ,QAAQ,GAAG;EACzC,IAAI,SAAS,IACX;EACF;EACA,MAAM,OAAO,OAAO;CACtB;CACA,OAAO;AACT;;AAsBA,SAAgB,gBAAgB,KAAqB;CACnD,OAAO,IACJ,WAAA,KAAoC,GAAI,CAAC,CACzC,WAAA,KAAqC,GAAI,CAAC,CAC1C,WAAA,KAAoC,IAAG,CAAC,CACxC,WAAA,KAAqC,IAAG;AAC7C;;;;;;;;;AAUA,MAAM,kBAA4D;CAChE,CAAC,SAAS,oBAAoB;CAC9B,CAAC,OAAO,QAAQ;CAChB,CAAC,QAAQ,SAAS;CAClB,CAAC,OAAO,UAAU;CAClB,CAAC,QAAQ,WAAW;CACpB,CAAC,OAAO,SAAS;CACjB,CAAC,QAAQ,UAAU;CACnB,CAAC,OAAO,UAAU;CAClB,CAAC,QAAQ,WAAW;CACpB,CAAC,OAAO,UAAU;CAClB,CAAC,QAAQ,WAAW;CACpB,CAAC,kBAAkB,cAAc;CACjC,CAAC,gBAAgB,YAAY;CAC7B,CAAC,WAAW,OAAO;CACnB,CAAC,YAAY,QAAQ;CACrB,CAAC,WAAW,OAAO;CACnB,CAAC,UAAU,YAAY;CACvB,CAAC,UAAU,gBAAgB;AAC7B;;;;;;;AAQA,SAAgB,WAAW,GAAmB;CAC5C,IAAI,MAAM;CACV,KAAK,MAAM,CAAC,MAAM,OAAO,iBACvB,MAAM,IAAI,WAAW,MAAM,EAAE;CAC/B,OAAO;AACT;;;;;;;;;;;;;AAcA,MAAM,wBAAwB;AAC9B,SAAgB,w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kB,SAAS,IAAI;CACjE,SAAS,KAAK;EAAE,IAAI;EAAa,OAAO,OAAO;EAAW,QAAQ;EAAM,WAAW;EAAO,UAAU;CAAK,CAAC;CAE1G,MAAM,aAAa,CAAC,GAAG,MAAM,GAAG,QAAQ;CACxC,MAAM,eAAe,KAAK,MAAK,MAAK,EAAE,aAAa,EAAE,SAAS,CAAC;CAC/D,MAAM,WAAW,SAAS,kBAAkB,IACxC,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,SAAS,OAAO,SAAS,eAAe,CAAC,IACjE;CAEJ,OAAO;EACL,SAAS,SAAS;EAClB,MAAM,SAAS;EACf,iBAAiB,SAAS;EAC1B;EACA;EACA;EACA,GAAI,SAAS,QAAQ,EAAE,OAAO,SAAS,MAAM,IAAI,CAAC;EAClD,GAAI,SAAS,mBAAmB,SAAS,EAAE,mBAAmB,SAAS,kBAAkB,IAAI,CAAC;EAC9F,GAAI,SAAS,cAAc,SAAS,EAAE,cAAc,SAAS,aAAa,IAAI,CAAC;CACjF;AACF"}
@@ -1,4 +1,4 @@
1
- import { r as createStderrLineEmitter } from "./mcp-D27rP47I.js";
1
+ import { r as createStderrLineEmitter } from "./mcp-C6IkXNOS.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  //#region src/mcp/context-transport.ts
4
4
  /**
@@ -10,7 +10,7 @@ import { Buffer } from "node:buffer";
10
10
  async function createContextStdioTransport(options) {
11
11
  const { name, context, handle, command, cwd, env, hooks } = options;
12
12
  if (!context.execStream) throw new Error(`MCP server "${name}" is configured with \`scope: 'context'\`, but the '${context.type}' execution context does not support live streams (\`execStream\`). Use \`scope: 'host'\` for this server, or switch to a context that advertises \`capabilities.stream\`.`);
13
- const { ReadBuffer, serializeMessage } = await import("./stdio-O-m9WVkE.js").then((n) => n.r);
13
+ const { ReadBuffer, serializeMessage } = await import("./stdio-DzUUkkhS.js").then((n) => n.r);
14
14
  const readBuffer = new ReadBuffer();
15
15
  let stream = null;
16
16
  let closed = false;
@@ -81,4 +81,4 @@ async function createContextStdioTransport(options) {
81
81
  //#endregion
82
82
  export { createContextStdioTransport };
83
83
 
84
- //# sourceMappingURL=context-transport-CDBatvQc.js.map
84
+ //# sourceMappingURL=context-transport-D-daWOmp.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-transport-CDBatvQc.js","names":[],"sources":["../src/mcp/context-transport.ts"],"sourcesContent":["/**\n * An MCP `Transport` that speaks stdio JSON-RPC to a server running INSIDE\n * an `ExecutionContext`, rather than as a child of the host process.\n *\n * Why this exists\n * ---------------\n * An MCP server is an ordinary program. When it calls `fs.readFileSync` or\n * `fs.writeFile`, those hit whatever filesystem it was spawned on. The\n * default `StdioClientTransport` spawns on the HOST, so with a sandboxed\n * execution context (Daytona / E2B / Docker) the agent's own tools and its\n * MCP servers end up looking at two different filesystems: a path the model\n * discovered via `list_files` does not exist for the MCP server, and an MCP\n * write lands somewhere `read_file` cannot see.\n *\n * Routing the server through `ExecutionContext.execStream` puts both on the\n * same filesystem. Note what this does NOT buy: isolation. Remote-transport\n * MCP servers are unreachable by this mechanism by construction, so\n * \"everything the agent touches runs in the execution context\" can never be\n * a true invariant. This is about coherence, not containment.\n *\n * Framing\n * -------\n * Delegated to the SDK's own `ReadBuffer` / `serializeMessage`, the exact\n * pair `StdioClientTransport` uses. That matters beyond code reuse:\n * `ReadBuffer` concatenates raw bytes and only decodes at newline\n * boundaries, so a multibyte codepoint split across two chunks survives.\n * Decoding each chunk independently would corrupt it irrecoverably — which\n * is precisely why `StreamHandle` carries bytes rather than strings.\n */\n\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from '../agent'\nimport type { ExecutionContext, ExecutionHandle } from '../contexts/types'\nimport { Buffer } from 'node:buffer'\nimport { createStderrLineEmitter } from './index'\n\n/**\n * Structural subset of the MCP SDK's `Transport` that we implement. Declared\n * locally rather than imported as a type so this module keeps the optional\n * peer-dependency contract (see the note atop `./index.ts`) — the SDK is only\n * ever touched through a runtime `await import(...)`.\n */\nexport interface ContextStdioTransportLike {\n /**\n * Brand marking this transport's process as living OUTSIDE the host.\n * `stdioPidOf` keys off it to refuse handing any pid from here to\n * `killStdioChild`, which signals host pids: a sandbox pid like `77`\n * names a real, unrelated host process. Termination for this transport\n * goes through `StreamHandle.kill()`, which signals inside the context.\n */\n readonly __contextScoped: true\n start: () => Promise<void>\n send: (message: unknown) => Promise<void>\n close: () => Promise<void>\n onclose?: () => void\n onerror?: (error: Error) => void\n onmessage?: (message: unknown) => void\n}\n\nexport interface ContextStdioTransportOptions {\n /** Server name, used for `mcp:warn` attribution. */\n name: string\n context: ExecutionContext\n handle: ExecutionHandle\n /** Full command line, run through the context's shell. */\n command: string\n cwd?: string\n env?: Record<string, string>\n hooks?: Hookable<AgentHooks>\n}\n\n/**\n * Build the transport. Throws if the context can't stream — deliberately\n * loudly, because the alternative (quietly spawning on the host) would\n * reintroduce the split-filesystem bug this transport exists to fix, and\n * would do it invisibly.\n */\nexport async function createContextStdioTransport(\n options: ContextStdioTransportOptions,\n): Promise<ContextStdioTransportLike> {\n const { name, context, handle, command, cwd, env, hooks } = options\n\n if (!context.execStream) {\n throw new Error(\n `MCP server \"${name}\" is configured with \\`scope: 'context'\\`, but the `\n + `'${context.type}' execution context does not support live streams `\n + `(\\`execStream\\`). Use \\`scope: 'host'\\` for this server, or switch to a `\n + `context that advertises \\`capabilities.stream\\`.`,\n )\n }\n\n const { ReadBuffer, serializeMessage } = await import('@modelcontextprotocol/sdk/shared/stdio.js')\n\n const readBuffer = new ReadBuffer()\n let stream: Awaited<ReturnType<NonNullable<ExecutionContext['execStream']>>> | null = null\n let closed = false\n\n const transport: ContextStdioTransportLike = {\n __contextScoped: true,\n\n async start() {\n if (stream)\n throw new Error(`MCP context transport for \"${name}\" already started`)\n\n // cwd is defaulted HERE, not left to the context: process and docker\n // fall back to `handle.cwd` on their own, but the sandbox providers\n // forward `cwd` only when set, so their SDK default would win (E2B's\n // `/home/user`, Daytona's PTY login dir). A `scope: 'context'` server\n // without an explicit `cwd` — e.g. server-filesystem rooted at '.' —\n // would then serve the workspace on two contexts and the home\n // directory on the others: the exact silent path divergence this\n // transport exists to close. Redundant-but-harmless on contexts that\n // already default to `handle.cwd`.\n stream = await context.execStream!(handle, command, {\n cwd: cwd ?? handle.cwd,\n ...(env !== undefined ? { env } : {}),\n })\n\n const active = stream\n\n // stdout → framed JSON-RPC. Runs detached from `start()`; awaiting it\n // would never resolve, since the server lives as long as the session.\n void (async () => {\n try {\n for await (const chunk of active.stdout) {\n readBuffer.append(Buffer.from(chunk))\n for (;;) {\n // A malformed frame must not kill the pump: report it and keep\n // reading. Servers that interleave stray output with protocol\n // frames (a PTY-backed context that lost the `stty raw` race,\n // a server logging to stdout) would otherwise wedge the\n // connection permanently on the first bad line.\n let message: unknown\n try {\n message = readBuffer.readMessage()\n }\n catch (err) {\n transport.onerror?.(err instanceof Error ? err : new Error(String(err)))\n continue\n }\n if (message === null)\n break\n transport.onmessage?.(message)\n }\n }\n }\n catch (err) {\n if (!closed)\n transport.onerror?.(err instanceof Error ? err : new Error(String(err)))\n }\n })()\n\n // stderr → `mcp:warn`, when the context provides it separately. A\n // PTY-backed context cannot split it from the terminal stream, so it\n // redirects to a file and may surface it here out-of-band (Daytona\n // polls) or not at all — absence is expected, not an error.\n if (active.stderr) {\n const emitter = createStderrLineEmitter(name, hooks)\n // Streaming decoder for the same reason `ReadBuffer` exists on the\n // stdout side: a per-chunk decode corrupts any multibyte codepoint\n // split across a chunk boundary. Diagnostic-only here, but free to\n // get right.\n const decoder = new TextDecoder('utf-8')\n void (async () => {\n try {\n for await (const chunk of active.stderr!)\n emitter.push(decoder.decode(chunk, { stream: true }))\n }\n catch {\n // Diagnostic channel — a failure here must not surface as a\n // protocol error.\n }\n finally {\n emitter.push(decoder.decode())\n emitter.flush()\n }\n })()\n }\n\n // The child dying is the connection ending. Surface it once.\n void active.exited.then(() => {\n if (closed)\n return\n closed = true\n transport.onclose?.()\n })\n },\n\n async send(message: unknown) {\n if (!stream)\n throw new Error(`MCP context transport for \"${name}\" not started`)\n await stream.write(new TextEncoder().encode(serializeMessage(message as never)))\n },\n\n async close() {\n if (closed) {\n // Still ensure the child is gone: `closed` may have been set by the\n // exit watcher, but an explicit close after a half-dead stream\n // should not leave a process running in the sandbox.\n await stream?.kill()\n return\n }\n closed = true\n readBuffer.clear()\n await stream?.kill()\n transport.onclose?.()\n },\n }\n\n return transport\n}\n"],"mappings":";;;;;;;;;AA6EA,eAAsB,4BACpB,SACoC;CACpC,MAAM,EAAE,MAAM,SAAS,QAAQ,SAAS,KAAK,KAAK,UAAU;CAE5D,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,eAAe,KAAK,sDACd,QAAQ,KAAK,2KAGrB;CAGF,MAAM,EAAE,YAAY,qBAAqB,MAAM,OAAO,sBAA4C,CAAA,MAAA,MAAA,EAAA,CAAA;CAElG,MAAM,aAAa,IAAI,WAAW;CAClC,IAAI,SAAkF;CACtF,IAAI,SAAS;CAEb,MAAM,YAAuC;EAC3C,iBAAiB;EAEjB,MAAM,QAAQ;GACZ,IAAI,QACF,MAAM,IAAI,MAAM,8BAA8B,KAAK,kBAAkB;GAWvE,SAAS,MAAM,QAAQ,WAAY,QAAQ,SAAS;IAClD,KAAK,OAAO,OAAO;IACnB,GAAI,QAAQ,KAAA,IAAY,EAAE,IAAI,IAAI,CAAC;GACrC,CAAC;GAED,MAAM,SAAS;GAIf,CAAM,YAAY;IAChB,IAAI;KACF,WAAW,MAAM,SAAS,OAAO,QAAQ;MACvC,WAAW,OAAO,OAAO,KAAK,KAAK,CAAC;MACpC,SAAS;OAMP,IAAI;OACJ,IAAI;QACF,UAAU,WAAW,YAAY;OACnC,SACO,KAAK;QACV,UAAU,UAAU,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC;QACvE;OACF;OACA,IAAI,YAAY,MACd;OACF,UAAU,YAAY,OAAO;MAC/B;KACF;IACF,SACO,KAAK;KACV,IAAI,CAAC,QACH,UAAU,UAAU,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC;IAC3E;GACF,EAAA,CAAG;GAMH,IAAI,OAAO,QAAQ;IACjB,MAAM,UAAU,wBAAwB,MAAM,KAAK;IAKnD,MAAM,UAAU,IAAI,YAAY,OAAO;IACvC,CAAM,YAAY;KAChB,IAAI;MACF,WAAW,MAAM,SAAS,OAAO,QAC/B,QAAQ,KAAK,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC,CAAC;KACxD,QACM,CAGN,UACQ;MACN,QAAQ,KAAK,QAAQ,OAAO,CAAC;MAC7B,QAAQ,MAAM;KAChB;IACF,EAAA,CAAG;GACL;GAGA,OAAY,OAAO,WAAW;IAC5B,IAAI,QACF;IACF,SAAS;IACT,UAAU,UAAU;GACtB,CAAC;EACH;EAEA,MAAM,KAAK,SAAkB;GAC3B,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,8BAA8B,KAAK,cAAc;GACnE,MAAM,OAAO,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,iBAAiB,OAAgB,CAAC,CAAC;EACjF;EAEA,MAAM,QAAQ;GACZ,IAAI,QAAQ;IAIV,MAAM,QAAQ,KAAK;IACnB;GACF;GACA,SAAS;GACT,WAAW,MAAM;GACjB,MAAM,QAAQ,KAAK;GACnB,UAAU,UAAU;EACtB;CACF;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"context-transport-D-daWOmp.js","names":[],"sources":["../src/mcp/context-transport.ts"],"sourcesContent":["/**\n * An MCP `Transport` that speaks stdio JSON-RPC to a server running INSIDE\n * an `ExecutionContext`, rather than as a child of the host process.\n *\n * Why this exists\n * ---------------\n * An MCP server is an ordinary program. When it calls `fs.readFileSync` or\n * `fs.writeFile`, those hit whatever filesystem it was spawned on. The\n * default `StdioClientTransport` spawns on the HOST, so with a sandboxed\n * execution context (Daytona / E2B / Docker) the agent's own tools and its\n * MCP servers end up looking at two different filesystems: a path the model\n * discovered via `list_files` does not exist for the MCP server, and an MCP\n * write lands somewhere `read_file` cannot see.\n *\n * Routing the server through `ExecutionContext.execStream` puts both on the\n * same filesystem. Note what this does NOT buy: isolation. Remote-transport\n * MCP servers are unreachable by this mechanism by construction, so\n * \"everything the agent touches runs in the execution context\" can never be\n * a true invariant. This is about coherence, not containment.\n *\n * Framing\n * -------\n * Delegated to the SDK's own `ReadBuffer` / `serializeMessage`, the exact\n * pair `StdioClientTransport` uses. That matters beyond code reuse:\n * `ReadBuffer` concatenates raw bytes and only decodes at newline\n * boundaries, so a multibyte codepoint split across two chunks survives.\n * Decoding each chunk independently would corrupt it irrecoverably — which\n * is precisely why `StreamHandle` carries bytes rather than strings.\n */\n\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from '../agent'\nimport type { ExecutionContext, ExecutionHandle } from '../contexts/types'\nimport { Buffer } from 'node:buffer'\nimport { createStderrLineEmitter } from './index'\n\n/**\n * Structural subset of the MCP SDK's `Transport` that we implement. Declared\n * locally rather than imported as a type so this module keeps the optional\n * peer-dependency contract (see the note atop `./index.ts`) — the SDK is only\n * ever touched through a runtime `await import(...)`.\n */\nexport interface ContextStdioTransportLike {\n /**\n * Brand marking this transport's process as living OUTSIDE the host.\n * `stdioPidOf` keys off it to refuse handing any pid from here to\n * `killStdioChild`, which signals host pids: a sandbox pid like `77`\n * names a real, unrelated host process. Termination for this transport\n * goes through `StreamHandle.kill()`, which signals inside the context.\n */\n readonly __contextScoped: true\n start: () => Promise<void>\n send: (message: unknown) => Promise<void>\n close: () => Promise<void>\n onclose?: () => void\n onerror?: (error: Error) => void\n onmessage?: (message: unknown) => void\n}\n\nexport interface ContextStdioTransportOptions {\n /** Server name, used for `mcp:warn` attribution. */\n name: string\n context: ExecutionContext\n handle: ExecutionHandle\n /** Full command line, run through the context's shell. */\n command: string\n cwd?: string\n env?: Record<string, string>\n hooks?: Hookable<AgentHooks>\n}\n\n/**\n * Build the transport. Throws if the context can't stream — deliberately\n * loudly, because the alternative (quietly spawning on the host) would\n * reintroduce the split-filesystem bug this transport exists to fix, and\n * would do it invisibly.\n */\nexport async function createContextStdioTransport(\n options: ContextStdioTransportOptions,\n): Promise<ContextStdioTransportLike> {\n const { name, context, handle, command, cwd, env, hooks } = options\n\n if (!context.execStream) {\n throw new Error(\n `MCP server \"${name}\" is configured with \\`scope: 'context'\\`, but the `\n + `'${context.type}' execution context does not support live streams `\n + `(\\`execStream\\`). Use \\`scope: 'host'\\` for this server, or switch to a `\n + `context that advertises \\`capabilities.stream\\`.`,\n )\n }\n\n const { ReadBuffer, serializeMessage } = await import('@modelcontextprotocol/sdk/shared/stdio.js')\n\n const readBuffer = new ReadBuffer()\n let stream: Awaited<ReturnType<NonNullable<ExecutionContext['execStream']>>> | null = null\n let closed = false\n\n const transport: ContextStdioTransportLike = {\n __contextScoped: true,\n\n async start() {\n if (stream)\n throw new Error(`MCP context transport for \"${name}\" already started`)\n\n // cwd is defaulted HERE, not left to the context: process and docker\n // fall back to `handle.cwd` on their own, but the sandbox providers\n // forward `cwd` only when set, so their SDK default would win (E2B's\n // `/home/user`, Daytona's PTY login dir). A `scope: 'context'` server\n // without an explicit `cwd` — e.g. server-filesystem rooted at '.' —\n // would then serve the workspace on two contexts and the home\n // directory on the others: the exact silent path divergence this\n // transport exists to close. Redundant-but-harmless on contexts that\n // already default to `handle.cwd`.\n stream = await context.execStream!(handle, command, {\n cwd: cwd ?? handle.cwd,\n ...(env !== undefined ? { env } : {}),\n })\n\n const active = stream\n\n // stdout → framed JSON-RPC. Runs detached from `start()`; awaiting it\n // would never resolve, since the server lives as long as the session.\n void (async () => {\n try {\n for await (const chunk of active.stdout) {\n readBuffer.append(Buffer.from(chunk))\n for (;;) {\n // A malformed frame must not kill the pump: report it and keep\n // reading. Servers that interleave stray output with protocol\n // frames (a PTY-backed context that lost the `stty raw` race,\n // a server logging to stdout) would otherwise wedge the\n // connection permanently on the first bad line.\n let message: unknown\n try {\n message = readBuffer.readMessage()\n }\n catch (err) {\n transport.onerror?.(err instanceof Error ? err : new Error(String(err)))\n continue\n }\n if (message === null)\n break\n transport.onmessage?.(message)\n }\n }\n }\n catch (err) {\n if (!closed)\n transport.onerror?.(err instanceof Error ? err : new Error(String(err)))\n }\n })()\n\n // stderr → `mcp:warn`, when the context provides it separately. A\n // PTY-backed context cannot split it from the terminal stream, so it\n // redirects to a file and may surface it here out-of-band (Daytona\n // polls) or not at all — absence is expected, not an error.\n if (active.stderr) {\n const emitter = createStderrLineEmitter(name, hooks)\n // Streaming decoder for the same reason `ReadBuffer` exists on the\n // stdout side: a per-chunk decode corrupts any multibyte codepoint\n // split across a chunk boundary. Diagnostic-only here, but free to\n // get right.\n const decoder = new TextDecoder('utf-8')\n void (async () => {\n try {\n for await (const chunk of active.stderr!)\n emitter.push(decoder.decode(chunk, { stream: true }))\n }\n catch {\n // Diagnostic channel — a failure here must not surface as a\n // protocol error.\n }\n finally {\n emitter.push(decoder.decode())\n emitter.flush()\n }\n })()\n }\n\n // The child dying is the connection ending. Surface it once.\n void active.exited.then(() => {\n if (closed)\n return\n closed = true\n transport.onclose?.()\n })\n },\n\n async send(message: unknown) {\n if (!stream)\n throw new Error(`MCP context transport for \"${name}\" not started`)\n await stream.write(new TextEncoder().encode(serializeMessage(message as never)))\n },\n\n async close() {\n if (closed) {\n // Still ensure the child is gone: `closed` may have been set by the\n // exit watcher, but an explicit close after a half-dead stream\n // should not leave a process running in the sandbox.\n await stream?.kill()\n return\n }\n closed = true\n readBuffer.clear()\n await stream?.kill()\n transport.onclose?.()\n },\n }\n\n return transport\n}\n"],"mappings":";;;;;;;;;AA6EA,eAAsB,4BACpB,SACoC;CACpC,MAAM,EAAE,MAAM,SAAS,QAAQ,SAAS,KAAK,KAAK,UAAU;CAE5D,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,eAAe,KAAK,sDACd,QAAQ,KAAK,2KAGrB;CAGF,MAAM,EAAE,YAAY,qBAAqB,MAAM,OAAO,sBAA4C,CAAA,MAAA,MAAA,EAAA,CAAA;CAElG,M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AC3B,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,8BAA8B,KAAK,cAAc;GACnE,MAAM,OAAO,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,iBAAiB,OAAgB,CAAC,CAAC;EACjF;EAEA,MAAM,QAAQ;GACZ,IAAI,QAAQ;IAIV,MAAM,QAAQ,KAAK;IACnB;GACF;GACA,SAAS;GACT,WAAW,MAAM;GACjB,MAAM,QAAQ,KAAK;GACnB,UAAU,UAAU;EACtB;CACF;CAEA,OAAO;AACT"}
package/dist/eval.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { r as createProcessContext } from "./contexts-DWVt7MvF.js";
2
2
  import { t as alwaysQuote } from "./shell-quote-BmnhZmdM.js";
3
- import { d as createMemoryStore, t as createSession } from "./session-cr9VdoEO.js";
3
+ import { d as createMemoryStore, t as createSession } from "./session-VpLrNaFQ.js";
4
4
  import { headlessEventToJsonl, runHeadless } from "./headless.js";
5
5
  import { join, relative, resolve } from "node:path";
6
6
  import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
@@ -1,2 +1,2 @@
1
- import { $ as removeInstalledExtension, G as EMPTY_EXTENSION_REGISTRY, J as fetchExtensionSource, K as createExtensionPromptBridge, Q as readExtensionInstallProvenance, X as listExtensionCandidates, Y as installExtensionFromSpec, Z as parseExtensionInstallSource, _n as resolveExtensionConfig, an as defaultExtensionScanPaths, at as composeExtensionPreset, bn as toWireConfigSchema, cn as isExtensionDefinition, ct as filterRegistryPlugins, dt as createExtensionHostRuntimeBridge, et as updateInstalledExtension, fn as defineExtension, ft as createWorkspaceSurface, gn as isValidExtensionConfigValue, hn as isValidExtensionConfigItem, in as ENTRY_CANDIDATES, it as buildExtensionRegistry, ln as parseExtensionScanPathEnv, lt as mergeContributions, mn as coerceExtensionConfigInput, nt as discoverAndBuildExtensionRegistry, on as discoverExtensions, ot as disposeExtensionRegistry, pn as clampExtensionConfigNumber, q as ExtensionInstallError, rn as registerExtensionHostModules, rt as buildExtensionPreset, sn as inlineLoadedExtension, st as filterExtensionRegistry, tt as createExtensionHud, un as scanExtensionDirectories, ut as partitionExtensionCatalog, vn as resolveExtensionConfigValue, yn as sanitizeExtensionConfigActionPatch } from "./agent-SQ6rxfpT.js";
1
+ import { $ as installExtensionFromSpec, Cn as resolveExtensionConfigValue, Q as fetchExtensionSource, Sn as resolveExtensionConfig, Tn as toWireConfigSchema, X as createExtensionPromptBridge, Y as EMPTY_EXTENSION_REGISTRY, Z as ExtensionInstallError, _n as defineExtension, at as createExtensionHud, bn as isValidExtensionConfigItem, cn as registerExtensionHostModules, ct as buildExtensionRegistry, dn as discoverExtensions, dt as filterExtensionRegistry, et as listExtensionCandidates, fn as inlineLoadedExtension, ft as filterRegistryPlugins, gt as createWorkspaceSurface, hn as scanExtensionDirectories, ht as createExtensionHostRuntimeBridge, it as updateInstalledExtension, ln as ENTRY_CANDIDATES, lt as composeExtensionPreset, mn as parseExtensionScanPathEnv, mt as partitionExtensionCatalog, nt as readExtensionInstallProvenance, ot as discoverAndBuildExtensionRegistry, pn as isExtensionDefinition, pt as mergeContributions, rt as removeInstalledExtension, st as buildExtensionPreset, tt as parseExtensionInstallSource, un as defaultExtensionScanPaths, ut as disposeExtensionRegistry, vn as clampExtensionConfigNumber, wn as sanitizeExtensionConfigActionPatch, xn as isValidExtensionConfigValue, yn as coerceExtensionConfigInput } from "./agent-BVNkC1h4.js";
2
2
  export { EMPTY_EXTENSION_REGISTRY, ENTRY_CANDIDATES, ExtensionInstallError, buildExtensionPreset, buildExtensionRegistry, clampExtensionConfigNumber, coerceExtensionConfigInput, composeExtensionPreset, createExtensionHostRuntimeBridge, createExtensionHud, createExtensionPromptBridge, createWorkspaceSurface, defaultExtensionScanPaths, defineExtension, discoverAndBuildExtensionRegistry, discoverExtensions, disposeExtensionRegistry, fetchExtensionSource, filterExtensionRegistry, filterRegistryPlugins, inlineLoadedExtension, installExtensionFromSpec, isExtensionDefinition, isValidExtensionConfigItem, isValidExtensionConfigValue, listExtensionCandidates, mergeContributions, parseExtensionInstallSource, parseExtensionScanPathEnv, partitionExtensionCatalog, readExtensionInstallProvenance, registerExtensionHostModules, removeInstalledExtension, resolveExtensionConfig, resolveExtensionConfigValue, sanitizeExtensionConfigActionPatch, scanExtensionDirectories, toWireConfigSchema, updateInstalledExtension };
package/dist/headless.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { a as isWireTurn, i as documentBlockMarker, l as toolResultToText, n as assertResolvedMediaBlock } from "./types-BIarq1qE.js";
2
- import { gt as basic_default, t as createAgent } from "./agent-SQ6rxfpT.js";
2
+ import { bt as basic_default, t as createAgent } from "./agent-BVNkC1h4.js";
3
3
  import { r as createProcessContext } from "./contexts-DWVt7MvF.js";
4
4
  import { t as audioFormatFromMediaType } from "./media-sniff-UKijEaiQ.js";
5
- import { c as ensureToolResultPairing, g as toAnthropic } from "./messages-C01kKGj0.js";
6
- import { d as createMemoryStore, t as createSession } from "./session-cr9VdoEO.js";
5
+ import { c as ensureToolResultPairing, g as toAnthropic } from "./messages-C_H9soi5.js";
6
+ import { d as createMemoryStore, t as createSession } from "./session-VpLrNaFQ.js";
7
7
  import { t as createRunSummaryCollector } from "./run-summary-BU_NgwUT.js";
8
8
  //#region src/headless.ts
9
9
  function exitCodeForHeadlessResult(result) {