zidane 5.14.4 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{acp-24uU2WDs.js → acp-Irby04Us.js} +7 -8
- package/dist/{acp-24uU2WDs.js.map → acp-Irby04Us.js.map} +1 -1
- package/dist/acp-cli.js +7 -7
- package/dist/acp.d.ts +2 -3
- package/dist/acp.d.ts.map +1 -1
- package/dist/acp.js +1 -1
- package/dist/{agent-Cch2ayTt.js → agent-DkSmGkDM.js} +10871 -5411
- package/dist/agent-DkSmGkDM.js.map +1 -0
- package/dist/agent.d.ts +1 -2
- package/dist/agent.js +2 -2
- package/dist/{anthropic-RGqsJlC8.js → anthropic-CTHsdFG9.js} +46 -6
- package/dist/anthropic-CTHsdFG9.js.map +1 -0
- package/dist/{auth-C-ms5N2x.js → auth-BDSu_0t3.js} +13 -86
- package/dist/auth-BDSu_0t3.js.map +1 -0
- package/dist/chat/pure.d.ts +4 -4
- package/dist/chat/pure.js +4 -3
- package/dist/chat.d.ts +45 -8
- package/dist/chat.d.ts.map +1 -1
- package/dist/chat.js +9 -6
- package/dist/chat.js.map +1 -1
- package/dist/completion-core-CXYSVhZo.js +147 -0
- package/dist/completion-core-CXYSVhZo.js.map +1 -0
- package/dist/{context-breakdown-kO-pDsay.js → context-breakdown-Dzo25N45.js} +2 -23
- package/dist/context-breakdown-Dzo25N45.js.map +1 -0
- package/dist/contexts/daytona.d.ts +3 -3
- package/dist/contexts/daytona.js +1 -1
- package/dist/contexts/docker.d.ts +10 -2
- package/dist/contexts/docker.d.ts.map +1 -1
- package/dist/contexts/docker.js +142 -103
- package/dist/contexts/docker.js.map +1 -1
- package/dist/contexts/e2b.d.ts +2 -2
- package/dist/contexts/e2b.js +1 -1
- package/dist/contexts/sandbox.d.ts +1 -1
- package/dist/contexts/sandbox.js +4 -1
- package/dist/contexts/sandbox.js.map +1 -1
- package/dist/{contexts-Lzf5huID.js → contexts-Vone3qQQ.js} +26 -37
- package/dist/contexts-Vone3qQQ.js.map +1 -0
- package/dist/contexts.d.ts +3 -3
- package/dist/contexts.js +1 -1
- package/dist/errors.d.ts +1 -2
- package/dist/errors.js +1 -1
- package/dist/eval.d.ts +1 -1
- package/dist/eval.js +3 -3
- package/dist/exec-file-size-PXkr-MGA.js +63 -0
- package/dist/exec-file-size-PXkr-MGA.js.map +1 -0
- package/dist/extensions.d.ts +2 -0
- package/dist/extensions.js +2 -0
- package/dist/generate-data-WL_yGVL6.js +324 -0
- package/dist/generate-data-WL_yGVL6.js.map +1 -0
- package/dist/headless.d.ts +1 -1
- package/dist/headless.js +15 -10
- package/dist/headless.js.map +1 -1
- package/dist/index-B8UtiZy7.d.ts +14967 -0
- package/dist/index-B8UtiZy7.d.ts.map +1 -0
- package/dist/{index-B3ciFUZx.d.ts → index-DsPQbyUn.d.ts} +2 -2
- package/dist/index-DsPQbyUn.d.ts.map +1 -0
- package/dist/index.d.ts +6 -12
- package/dist/index.js +20 -43
- package/dist/index.js.map +1 -1
- package/dist/{logger-Ktm-lj1s.js → logger-DBX9uYOw.js} +108 -5
- package/dist/logger-DBX9uYOw.js.map +1 -0
- package/dist/login-DOF8pMVM.js +539 -0
- package/dist/login-DOF8pMVM.js.map +1 -0
- package/dist/{mcp-Dn5W65Lv.js → mcp-CcvuVXB9.js} +2 -2
- package/dist/{mcp-Dn5W65Lv.js.map → mcp-CcvuVXB9.js.map} +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +1 -1
- package/dist/{messages-YZQLKaz2.js → messages-CwujiS74.js} +4 -4
- package/dist/messages-CwujiS74.js.map +1 -0
- package/dist/{openai-compat-0Y7jcncn.js → openai-compat-BvgYGSR1.js} +7 -6
- package/dist/{openai-compat-0Y7jcncn.js.map → openai-compat-BvgYGSR1.js.map} +1 -1
- package/dist/output/stream-json.d.ts +1 -2
- package/dist/output/stream-json.d.ts.map +1 -1
- package/dist/output/terminal.d.ts +1 -2
- package/dist/output/terminal.d.ts.map +1 -1
- package/dist/{glob-DluQFSw1.js → output-cap-kBUHBlnq.js} +50 -2
- package/dist/output-cap-kBUHBlnq.js.map +1 -0
- package/dist/presets.d.ts +1 -2
- package/dist/presets.js +1 -1
- package/dist/providers/anthropic.d.ts +2 -2
- package/dist/providers/anthropic.js +2 -2
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/arcee.js +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/baseten.js +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/cerebras.js +1 -1
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/local.js +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai-compat.js +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openai.js +4 -4
- package/dist/providers/openai.js.map +1 -1
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/openrouter.js +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/providers/xai.js +1 -1
- package/dist/{providers-DgmdYGKm.js → providers-z6LDMAr3.js} +3 -3
- package/dist/{providers-DgmdYGKm.js.map → providers-z6LDMAr3.js.map} +1 -1
- package/dist/providers.d.ts +1 -1
- package/dist/providers.js +4 -4
- package/dist/{read-state-BymF41Jb.js → read-state-Dq_TXUX1.js} +2 -2
- package/dist/{read-state-BymF41Jb.js.map → read-state-Dq_TXUX1.js.map} +1 -1
- package/dist/{interpolate-BtIgcCuz.js → resolve-Cr8JSL_O.js} +562 -136
- package/dist/resolve-Cr8JSL_O.js.map +1 -0
- package/dist/restate.d.ts +2 -2
- package/dist/restate.js +2 -2
- package/dist/{sandbox-Dgy-m6UF.d.ts → sandbox-CgjG2VvQ.d.ts} +2 -2
- package/dist/{sandbox-Dgy-m6UF.d.ts.map → sandbox-CgjG2VvQ.d.ts.map} +1 -1
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/{session-CqrAFAKJ.js → session-CsdDIPY8.js} +108 -3
- package/dist/session-CsdDIPY8.js.map +1 -0
- package/dist/session.d.ts +2 -2
- package/dist/session.js +3 -3
- package/dist/skills-Bsb0rvWI.js +295 -0
- package/dist/skills-Bsb0rvWI.js.map +1 -0
- package/dist/skills.d.ts +2 -3
- package/dist/skills.js +3 -24
- package/dist/{errors-CkTvg97v.d.ts → timeout-8vSIRjzl.d.ts} +10 -2
- package/dist/timeout-8vSIRjzl.d.ts.map +1 -0
- package/dist/{timeout-kGGSXagK.js → timeout-BDetbuN6.js} +59 -2
- package/dist/timeout-BDetbuN6.js.map +1 -0
- package/dist/tool-formatters-DY0TDb1r.d.ts +378 -0
- package/dist/tool-formatters-DY0TDb1r.d.ts.map +1 -0
- package/dist/tools/fetch-url.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tools.d.ts +2 -3
- package/dist/tools.js +3 -4
- package/dist/{transcript-anchors-BHIgMlPq.d.ts → transcript-anchors-Cb-bDbNH.d.ts} +233 -640
- package/dist/transcript-anchors-Cb-bDbNH.d.ts.map +1 -0
- package/dist/{transcript-anchors-DsoBHg43.js → transcript-anchors-DSRPWjiH.js} +391 -961
- package/dist/transcript-anchors-DSRPWjiH.js.map +1 -0
- package/dist/tui.d.ts +335 -11
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +6375 -1892
- package/dist/tui.js.map +1 -1
- package/dist/{turn-operations-Dw02ZoSQ.d.ts → turn-operations-CgMROLsr.d.ts} +29 -4
- package/dist/turn-operations-CgMROLsr.d.ts.map +1 -0
- package/dist/{turn-operations-tG0vuBNc.js → turn-operations-Dq9Kx7m2.js} +321 -81
- package/dist/turn-operations-Dq9Kx7m2.js.map +1 -0
- package/dist/{types-BqdTeBaC.d.ts → types-BDccavwj.d.ts} +42 -1
- package/dist/types-BDccavwj.d.ts.map +1 -0
- package/dist/{types-CyVGdbia.js → types-BIarq1qE.js} +90 -2
- package/dist/types-BIarq1qE.js.map +1 -0
- package/dist/types.d.ts +5 -6
- package/dist/types.js +1 -1
- package/dist/{xai-tPdbAGkq.js → xai-B_e6TOA8.js} +2 -2
- package/dist/{xai-tPdbAGkq.js.map → xai-B_e6TOA8.js.map} +1 -1
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CHAT.md +7 -6
- package/docs/EXECUTION_CONTEXT.md +16 -0
- package/docs/EXTENSIONS.md +1063 -0
- package/docs/SKILL.md +16 -0
- package/docs/TUI.md +10 -3
- package/package.json +12 -3
- package/dist/agent-Cch2ayTt.js.map +0 -1
- package/dist/agent-EFWt6uQ_.d.ts +0 -6914
- package/dist/agent-EFWt6uQ_.d.ts.map +0 -1
- package/dist/anthropic-RGqsJlC8.js.map +0 -1
- package/dist/auth-C-ms5N2x.js.map +0 -1
- package/dist/context-breakdown-kO-pDsay.js.map +0 -1
- package/dist/contexts-Lzf5huID.js.map +0 -1
- package/dist/errors-CkTvg97v.d.ts.map +0 -1
- package/dist/glob-DluQFSw1.js.map +0 -1
- package/dist/glob-shell-rJMoCIGb.js +0 -21
- package/dist/glob-shell-rJMoCIGb.js.map +0 -1
- package/dist/index-B3ciFUZx.d.ts.map +0 -1
- package/dist/index-BtzE3Uaq.d.ts +0 -2738
- package/dist/index-BtzE3Uaq.d.ts.map +0 -1
- package/dist/index-tSzOaWNt.d.ts +0 -316
- package/dist/index-tSzOaWNt.d.ts.map +0 -1
- package/dist/interpolate-BtIgcCuz.js.map +0 -1
- package/dist/logger-DGiGf7DW.d.ts +0 -102
- package/dist/logger-DGiGf7DW.d.ts.map +0 -1
- package/dist/logger-Ktm-lj1s.js.map +0 -1
- package/dist/login-CCA-1lgK.js +0 -267
- package/dist/login-CCA-1lgK.js.map +0 -1
- package/dist/messages-YZQLKaz2.js.map +0 -1
- package/dist/policy-DcGlpaNs.d.ts +0 -129
- package/dist/policy-DcGlpaNs.d.ts.map +0 -1
- package/dist/presets-BQWYMHdd.js +0 -114
- package/dist/presets-BQWYMHdd.js.map +0 -1
- package/dist/run-summary-DkN8KsHM.d.ts +0 -249
- package/dist/run-summary-DkN8KsHM.d.ts.map +0 -1
- package/dist/session-CqrAFAKJ.js.map +0 -1
- package/dist/shell-quote-BmnhZmdM.js +0 -33
- package/dist/shell-quote-BmnhZmdM.js.map +0 -1
- package/dist/skills.js.map +0 -1
- package/dist/timeout-CpFm0jJ6.d.ts +0 -10
- package/dist/timeout-CpFm0jJ6.d.ts.map +0 -1
- package/dist/timeout-kGGSXagK.js.map +0 -1
- package/dist/tool-formatters-C6iLgc9f.d.ts +0 -1454
- package/dist/tool-formatters-C6iLgc9f.d.ts.map +0 -1
- package/dist/tools-CCd8e-HT.js +0 -1739
- package/dist/tools-CCd8e-HT.js.map +0 -1
- package/dist/transcript-anchors-BHIgMlPq.d.ts.map +0 -1
- package/dist/transcript-anchors-DsoBHg43.js.map +0 -1
- package/dist/turn-operations-Dw02ZoSQ.d.ts.map +0 -1
- package/dist/turn-operations-tG0vuBNc.js.map +0 -1
- package/dist/types-BqdTeBaC.d.ts.map +0 -1
- package/dist/types-CyVGdbia.js.map +0 -1
package/dist/chat.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { Q as
|
|
3
|
-
import { t as buildContextBreakdown } from "./context-breakdown-
|
|
1
|
+
import { $ as useMcpAuthState, $n as eventsFromTurns, $t as useUpdateCheck, A as runOAuthLogin, An as pruneTodosByRun, At as DEFAULT_THEME, B as saveMcpToolsCache, Bn as PLAN_MODE_DOCTRINE, Bt as createDiscoverySlot, C as projectsFilePath, Cn as TODO_STATUS_GLYPHS, Ct as SETTINGS_CHOICES, D as formatPathForCwd, Dn as getTodosForRun, E as writeProjects, En as getArchivedTodosForRun, Et as SettingsProvider, F as parseMcpsFile, Fn as COMMUNICATION_DOCTRINE, Ft as GRUVBOX_LIGHT, G as buildVisibleMcpRows, Gn as buildPlanSystem, Gt as useConfig, H as buildToolToggle, Hn as SUBAGENT_GUIDANCE, Ht as useDiscovery, I as clearMcpToolsCache, In as DOING_TASKS_DOCTRINE, It as CATPPUCCIN_FRAPPE, J as createFileMcpCredentialStore, Jn as createChatTurnsReadTool, Jt as useCompletion, K as indexOfServerRow, Kn as envSection, Kt as resolveConfig, L as loadMcpToolsCache, Ln as IDENTITY_PREFIX, Lt as CATPPUCCIN_LATTE, M as buildMcpServers, Mn as setTodosForRun, Mt as resolveTheme, N as defaultMcpsConfigPaths, Nn as useActiveTodos, Nt as VAPORWAVE_THEME, O as fetchOAuthRedirect, On as isTodoTool, Ot as useSettings, P as discoverProjectMcps, Pn as ACTIONS_WITH_CARE_DOCTRINE, Pt as GRUVBOX_DARK, Q as useMcpAuthDispatch, Qn as deriveSessionTitle, Qt as buildUpdateHint, R as mcpToolsCachePath, Rn as INTERACTION_GUIDANCE, Rt as CATPPUCCIN_MACCHIATO, S as matchesSafelistEntry, Sn as TODOWRITE_TOOL, St as SETTINGS_CATEGORIES, T as suggestSafelistEntries, Tn as createTodoTools, Tt as SETTINGS_TOGGLES, U as useMcpToolToggleMap, Un as TOKEN_DISCIPLINE_DOCTRINE, Ut as useDiscoveryOptional, V as subscribeMcpToolsCache, Vn as PLAN_MODE_DOCTRINE_NO_PROMPTS, Vt as DiscoveryProvider, W as useMcpToolToggleSet, Wn as buildBuildSystem, Wt as ConfigProvider, X as patchMcpCredential, Xn as compactSummaryEvent, Xt as bootProfileEnabled, Y as mcpCredentialsPath, Yt as tryOpenBrowser, Z as McpAuthProvider, Zn as createStateStore, Zt as bootTick, _ as useSafeModeQueue, _n as accentColor, _t as buildHints, a as useSurfaces, an as performInPlaceSelfUpdate, at as buildResumedToolResultsTurn, b as getSafelist, bn as TODOREAD_TOOL, bt as useEnabledToggleSet, c as useStreamBuffer, cn as chatAutoCompactBehavior, cr as titleFromTurns, ct as makeRequestInteraction, d as discoverProjectSkills, dn as BUILD_AGENT, dr as updateToolEventOutcomes, dt as useInteractionsActions, en as checkForUpdate, er as lastContextSizeFromTurns, et as getMcpAuthStatus, f as renderSession, fn as BUILTIN_AGENTS, ft as useInteractionsQueue, g as useSafeModeActions, gn as PLAN_AGENT, gt as truncateTrailing, h as SafeModeProvider, hn as DEFAULT_PERSIST_EXCLUDE_TOOLS, ht as hintsLength, i as useSelectStyle, in as parseSemver, ir as saveState, it as PRESENT_PLAN_TOOL, j as supportsOAuth, jn as selectActiveTodos, jt as resolveChipColor, k as oauthUsesManualCodePaste, kn as pickActiveRunId, kt as BUILTIN_THEMES, l as buildSkillsConfig, ln as discoverAgentsMd, lr as toolCallPreview, lt as pendingInteractionsFromTurns, m as writeSessionExport, mn as DEFAULT_BUDGET_EXCLUDE_TOOLS, mt as clipHintsToWidth, n as ThemeProvider, nn as detectLibc, nr as loadState, nt as ASK_USER_TOOL, o as useSyntaxStyles, on as performSelfUpdate, or as stripSpawnTokensLine, ot as createInteractionTools, p as resolveSessionExportTarget, pn as DEFAULT_AGENT_ID, pt as EMPTY_HINTS, q as parentServerName, qn as chatReferenceTokensForPrompt, qt as resolveStoragePaths, r as useColors, rn as detectPackageManager, rr as marginTopFor, rt as InteractionsProvider, s as useTheme, sn as resolvePlatformPackage, sr as sumRunCosts, st as isInteractionTool, t as computeTurnAnchors, tn as compareSemver, tr as listSessionMeta, tt as reduceMcpAuth, u as defaultSkillScanPaths, un as renderAgentsMdBlock, ur as toolResultText, ut as serializeInteractionResponse, v as IMPLICITLY_SAFE_TOOLS, vn as resolveAgentId, vt as shortChord, w as readProjects, wn as TODO_WRITE_COUNTS_METADATA_KEY, x as isOnSafelist, xn as TODOS_METADATA_KEY, xt as DEFAULT_SETTINGS, y as addToSafelist, yn as singleAgentRegistry, yt as listProjectFiles, z as refreshMcpToolsCatalog, zn as INTERACTION_GUIDANCE_NO_PROMPTS, zt as CATPPUCCIN_MOCHA } from "./transcript-anchors-DSRPWjiH.js";
|
|
2
|
+
import { $ as filterExtensionRegistry, At as DEFAULT_KEYBINDINGS, Bt as parseBindingSpec, Ft as formatBindingForDisplay, Ht as readKeybindingsRaw, I as EMPTY_EXTENSION_REGISTRY, It as groupBindings, Jt as inlineLoadedExtension, Kt as defaultExtensionScanPaths, Lt as keybindingsPath, Mt as KEYBINDING_DEF_BY_ACTION, Nt as KEYBINDING_KEY_COL_WIDTH, Pt as ensureKeybindingsFile, Q as disposeExtensionRegistry, Qt as defineExtension, Rt as matchesBinding, Ut as resolveExtensionKeybindings, Vt as readKeybindings, Wt as stripJsonComments, X as buildExtensionRegistry, Y as buildExtensionPreset, Z as composeExtensionPreset, Zt as scanExtensionDirectories, cn as effectiveContextWindow, et as mergeContributions, jt as KEYBINDING_DEFS, kt as resolveStorageDirs, ln as shouldAutoCompact, on as AUTO_COMPACT_MIN_GROWTH_FRACTION, qt as discoverExtensions, sn as OUTPUT_RESERVE_TOKENS, tt as partitionExtensionCatalog, zt as mergeKeybindings } from "./agent-DkSmGkDM.js";
|
|
3
|
+
import { t as buildContextBreakdown } from "./context-breakdown-Dzo25N45.js";
|
|
4
4
|
import { a as formatTaskStatus, c as shortId, i as formatDuration, n as compactPath, o as formatTaskSummary, r as fmtTokens, s as previewLine, t as ageString } from "./format-BNOXpl-1.js";
|
|
5
|
+
import { M as findGitRoot, j as projectUserPaths } from "./resolve-Cr8JSL_O.js";
|
|
5
6
|
import { appendDynamicSection } from "./prompt.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
7
|
+
import { d as executeCommand, f as parseCommandInvocation, i as shouldAutoGenerateTitle, n as cleanTitle, r as generateSessionTitle, t as generateStructuredData, u as commandSteps } from "./generate-data-WL_yGVL6.js";
|
|
8
|
+
import { a as mergeReferences, n as collectReferences, r as findActiveTrigger, t as applyInsert } from "./completion-core-CXYSVhZo.js";
|
|
9
|
+
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-BDSu_0t3.js";
|
|
10
|
+
import { $ as rewriteMultiEditHeader, A as buildLinearRamp, B as computeInlineDiff, C as SKILLS_TRIGGER, D as createFilesCompletionProvider, E as FILES_TRIGGER, F as selectableTurnIds, G as splitLines, H as extractEditPayload, I as turnSelectionOwnership, J as buildEditOutcomesAnnotation, K as summarizeEditPayload, L as applyEditPayload, M as isEditErrorResult, N as isTurnHighlighted, O as uniqueFilesFromReferences, P as isVisible, Q as resolveApprovalForPayload, R as buildContextualDiff, S as splitMarkdownCodeBlocks, T as uniqueSkillNamesFromReferences, U as filetypeFromPath, V as computeLineDiff, W as previewEditPayload, X as mergeApprovalAndBodyOutcomes, Y as maskToOutcomeKinds, Z as parseEditOutcomesFromResult, _ as filterModelCatalog, a as TOOL_DISPLAY, at as uniqueChatIdsFromReferences, b as chunkMarkdownForRender, c as MAX_TRANSCRIPT_EVENTS, d as finalizeStreamingMarkdown, et as stripEditOutcomesAnnotation, f as finalizeStreamingMarkdownForOwner, g as buildModelCatalog, h as splitPromptSegments, i as turnAsText, it as createChatsCompletionProvider, k as blendHsl, l as TRANSCRIPT_TRIM_TO_EVENTS, m as turnContextSize, n as deleteTurnSafely, nt as CHATS_TRIGGER, o as displayNameFor, q as tokenize, r as truncateTurnsAt, rt as chatReferenceTokensFromText, s as formatToolCall, t as countNeighbors, tt as summarizeOutcomes, u as capTranscriptEvents, v as indexOfEntry, w as createSkillsCompletionProvider, x as normalizeMarkdownCodeFences, y as MARKDOWN_RENDER_CHUNK_TARGET_BYTES, z as buildUnifiedDiff } from "./turn-operations-Dq9Kx7m2.js";
|
|
8
11
|
//#region src/chat/auto-update-cli.ts
|
|
9
12
|
const UPGRADE_HELP = `Usage: zidane upgrade [options]
|
|
10
13
|
|
|
@@ -227,6 +230,6 @@ function createActiveTodoAnchorHooks(options = {}) {
|
|
|
227
230
|
} };
|
|
228
231
|
}
|
|
229
232
|
//#endregion
|
|
230
|
-
export { ACTIONS_WITH_CARE_DOCTRINE, ASK_USER_TOOL, AUTO_COMPACT_MIN_GROWTH_FRACTION, BUILD_AGENT, BUILTIN_AGENTS, BUILTIN_PROVIDERS, BUILTIN_THEMES, CATPPUCCIN_FRAPPE, CATPPUCCIN_LATTE, CATPPUCCIN_MACCHIATO, CATPPUCCIN_MOCHA, CHATS_TRIGGER, COMMUNICATION_DOCTRINE, ConfigProvider, DEFAULT_AGENT_ID, DEFAULT_BUDGET_EXCLUDE_TOOLS, DEFAULT_KEYBINDINGS, DEFAULT_PERSIST_EXCLUDE_TOOLS, DEFAULT_SETTINGS, DEFAULT_THEME, DOING_TASKS_DOCTRINE, DiscoveryProvider, EMPTY_HINTS, FILES_TRIGGER, GRUVBOX_DARK, GRUVBOX_LIGHT, IDENTITY_PREFIX, IMPLICITLY_SAFE_TOOLS, INTERACTION_GUIDANCE, INTERACTION_GUIDANCE_NO_PROMPTS, InteractionsProvider, KEYBINDING_DEFS, KEYBINDING_DEF_BY_ACTION, KEYBINDING_KEY_COL_WIDTH, McpAuthProvider, OUTPUT_RESERVE_TOKENS, PLAN_AGENT, PLAN_MODE_DOCTRINE, PLAN_MODE_DOCTRINE_NO_PROMPTS, PRESENT_PLAN_TOOL, SETTINGS_CATEGORIES, SETTINGS_CHOICES, SETTINGS_TOGGLES, SKILLS_TRIGGER, SUBAGENT_GUIDANCE, SafeModeProvider, SettingsProvider, TODOREAD_TOOL, TODOS_METADATA_KEY, TODOWRITE_TOOL, TODO_STATUS_GLYPHS, TODO_WRITE_COUNTS_METADATA_KEY, TOKEN_DISCIPLINE_DOCTRINE, TOOL_DISPLAY, ThemeProvider, VAPORWAVE_THEME, accentColor, addToSafelist, ageString, anthropicDescriptor, applyApiKeyEnv, applyEditPayload, applyInsert, blendHsl, bootProfileEnabled, bootTick, buildBuildSystem, buildContextBreakdown, buildContextualDiff, buildEditOutcomesAnnotation, buildHints, buildLinearRamp, buildMcpServers, buildModelCatalog, buildPlanSystem, buildResumedToolResultsTurn, buildSkillsConfig, buildToolToggle, buildUnifiedDiff, buildUpdateHint, buildVisibleMcpRows, cerebrasDescriptor, chatAutoCompactBehavior, chatReferenceTokensForPrompt, chatReferenceTokensFromText, checkForUpdate, cleanTitle, clearMcpToolsCache, clipHintsToWidth, collectReferences, compactPath, compactSummaryEvent, compareSemver, computeInlineDiff, computeLineDiff, computeTurnAnchors, countNeighbors, createActiveTodoAnchorHooks, createChatTurnsReadTool, createChatsCompletionProvider, createDiscoverySlot, createFileMcpCredentialStore, createFilesCompletionProvider, createInteractionTools, createSkillsCompletionProvider, createStateStore, createTodoTools, credKeyOf, credentialsPath, defaultMcpsConfigPaths, defaultSkillScanPaths, deleteTurnSafely, deriveSessionTitle, detectAuth, detectLibc, detectPackageManager, discoverAgentsMd, discoverProjectMcps, discoverProjectSkills, displayNameFor, effectiveContextWindow, enabledModelOptions, ensureKeybindingsFile, envSection, eventsFromTurns, extractEditPayload, fetchOAuthRedirect, filetypeFromPath, filterModelCatalog, finalizeStreamingMarkdown, finalizeStreamingMarkdownForOwner, findActiveTrigger, findGitRoot, fmtTokens, formatBindingForDisplay, formatDuration, formatPathForCwd, formatTaskStatus, formatTaskSummary, formatToolCall, generateSessionTitle, getArchivedTodosForRun, getContextWindow, getMcpAuthStatus, getModelInfo, getSafelist, getTodosForRun, groupBindings, hintsLength, indexOfEntry, indexOfServerRow, isEditErrorResult, isInteractionTool, isOnSafelist, isTodoTool, isTurnHighlighted, isVisible, keybindingsPath, lastContextSizeFromTurns, listProjectFiles, listSessionMeta, loadMcpToolsCache, loadState, localDescriptor, makeRequestInteraction, marginTopFor, maskToOutcomeKinds, matchesBinding, matchesSafelistEntry, mcpCredentialsPath, mcpToolsCachePath, mergeApprovalAndBodyOutcomes, mergeKeybindings, mergeReferences, modelOptionsFor, modelSupportsReasoning, modelsForDescriptor, oauthUsesManualCodePaste, openaiDescriptor, openrouterDescriptor, parentServerName, parseBindingSpec, parseEditOutcomesFromResult, parseMcpsFile, parseSemver, patchMcpCredential, pendingInteractionsFromTurns, performInPlaceSelfUpdate, performSelfUpdate, piIdOf, pickActiveRunId, previewEditPayload, previewLine, projectUserPaths, projectsFilePath, pruneTodosByRun, readCredentials, readKeybindings, readProjects, readProviderCredential, reduceMcpAuth, refreshMcpToolsCatalog, removeProviderCredential, renderActiveTodoAnchor, renderAgentsMdBlock, renderSession, resolveAgentId, resolveApprovalForPayload, resolveChipColor, resolveConfig, resolvePlatformPackage, resolveSessionExportTarget, resolveStorageDirs, resolveStoragePaths, resolveTheme, restoreModelOptions, rewriteMultiEditHeader, runOAuthLogin, runUpdateCommand, saveMcpToolsCache, saveState, selectActiveTodos, selectableTurnIds, serializeInteractionResponse, setProviderCredential, setTodosForRun, shortChord, shortId, shouldAutoCompact, singleAgentRegistry, splitLines, splitMarkdownCodeBlocks, splitPromptSegments, stripEditOutcomesAnnotation, stripJsonComments, stripSpawnTokensLine, subscribeMcpToolsCache, suggestSafelistEntries, sumRunCosts, summarizeEditPayload, summarizeOutcomes, supportsOAuth, titleFromTurns, tokenize, toolCallPreview, toolResultText, truncateTrailing, truncateTurnsAt, tryOpenBrowser, turnAsText, turnContextSize, turnSelectionOwnership, uniqueChatIdsFromReferences, uniqueFilesFromReferences, uniqueSkillNamesFromReferences, updateToolEventOutcomes, useActiveTodos, useColors, useCompletion, useConfig, useDiscovery, useDiscoveryOptional, useEnabledToggleSet, useInteractionsActions, useInteractionsQueue, useMcpAuthDispatch, useMcpAuthState, useMcpToolToggleMap, useMcpToolToggleSet, useSafeModeActions, useSafeModeQueue, useSelectStyle, useSettings, useStreamBuffer, useSurfaces, useSyntaxStyles, useTheme, useUpdateCheck, writeCredentials, writeProjects, writeSessionExport };
|
|
233
|
+
export { ACTIONS_WITH_CARE_DOCTRINE, ASK_USER_TOOL, AUTO_COMPACT_MIN_GROWTH_FRACTION, BUILD_AGENT, BUILTIN_AGENTS, BUILTIN_PROVIDERS, BUILTIN_THEMES, CATPPUCCIN_FRAPPE, CATPPUCCIN_LATTE, CATPPUCCIN_MACCHIATO, CATPPUCCIN_MOCHA, CHATS_TRIGGER, COMMUNICATION_DOCTRINE, ConfigProvider, DEFAULT_AGENT_ID, DEFAULT_BUDGET_EXCLUDE_TOOLS, DEFAULT_KEYBINDINGS, DEFAULT_PERSIST_EXCLUDE_TOOLS, DEFAULT_SETTINGS, DEFAULT_THEME, DOING_TASKS_DOCTRINE, DiscoveryProvider, EMPTY_EXTENSION_REGISTRY, EMPTY_HINTS, FILES_TRIGGER, GRUVBOX_DARK, GRUVBOX_LIGHT, IDENTITY_PREFIX, IMPLICITLY_SAFE_TOOLS, INTERACTION_GUIDANCE, INTERACTION_GUIDANCE_NO_PROMPTS, InteractionsProvider, KEYBINDING_DEFS, KEYBINDING_DEF_BY_ACTION, KEYBINDING_KEY_COL_WIDTH, MARKDOWN_RENDER_CHUNK_TARGET_BYTES, MAX_TRANSCRIPT_EVENTS, McpAuthProvider, OUTPUT_RESERVE_TOKENS, PLAN_AGENT, PLAN_MODE_DOCTRINE, PLAN_MODE_DOCTRINE_NO_PROMPTS, PRESENT_PLAN_TOOL, SETTINGS_CATEGORIES, SETTINGS_CHOICES, SETTINGS_TOGGLES, SKILLS_TRIGGER, SUBAGENT_GUIDANCE, SafeModeProvider, SettingsProvider, TODOREAD_TOOL, TODOS_METADATA_KEY, TODOWRITE_TOOL, TODO_STATUS_GLYPHS, TODO_WRITE_COUNTS_METADATA_KEY, TOKEN_DISCIPLINE_DOCTRINE, TOOL_DISPLAY, TRANSCRIPT_TRIM_TO_EVENTS, ThemeProvider, VAPORWAVE_THEME, accentColor, addToSafelist, ageString, anthropicDescriptor, applyApiKeyEnv, applyEditPayload, applyInsert, blendHsl, bootProfileEnabled, bootTick, buildBuildSystem, buildContextBreakdown, buildContextualDiff, buildEditOutcomesAnnotation, buildExtensionPreset, buildExtensionRegistry, buildHints, buildLinearRamp, buildMcpServers, buildModelCatalog, buildPlanSystem, buildResumedToolResultsTurn, buildSkillsConfig, buildToolToggle, buildUnifiedDiff, buildUpdateHint, buildVisibleMcpRows, capTranscriptEvents, cerebrasDescriptor, chatAutoCompactBehavior, chatReferenceTokensForPrompt, chatReferenceTokensFromText, checkForUpdate, chunkMarkdownForRender, cleanTitle, clearMcpToolsCache, clipHintsToWidth, collectReferences, commandSteps, compactPath, compactSummaryEvent, compareSemver, composeExtensionPreset, computeInlineDiff, computeLineDiff, computeTurnAnchors, countNeighbors, createActiveTodoAnchorHooks, createChatTurnsReadTool, createChatsCompletionProvider, createDiscoverySlot, createFileMcpCredentialStore, createFilesCompletionProvider, createInteractionTools, createSkillsCompletionProvider, createStateStore, createTodoTools, credKeyOf, credentialsPath, defaultExtensionScanPaths, defaultMcpsConfigPaths, defaultSkillScanPaths, defineExtension, deleteTurnSafely, deriveSessionTitle, detectAuth, detectLibc, detectPackageManager, discoverAgentsMd, discoverExtensions, discoverProjectMcps, discoverProjectSkills, displayNameFor, disposeExtensionRegistry, effectiveContextWindow, enabledModelOptions, ensureKeybindingsFile, envSection, eventsFromTurns, executeCommand, extractEditPayload, fetchOAuthRedirect, filetypeFromPath, filterExtensionRegistry, filterModelCatalog, finalizeStreamingMarkdown, finalizeStreamingMarkdownForOwner, findActiveTrigger, findGitRoot, fmtTokens, formatBindingForDisplay, formatDuration, formatPathForCwd, formatTaskStatus, formatTaskSummary, formatToolCall, generateSessionTitle, generateStructuredData, getArchivedTodosForRun, getContextWindow, getMcpAuthStatus, getModelInfo, getSafelist, getTodosForRun, groupBindings, hintsLength, indexOfEntry, indexOfServerRow, inlineLoadedExtension, isEditErrorResult, isInteractionTool, isOnSafelist, isTodoTool, isTurnHighlighted, isVisible, keybindingsPath, lastContextSizeFromTurns, listProjectFiles, listSessionMeta, loadMcpToolsCache, loadState, localDescriptor, makeRequestInteraction, marginTopFor, maskToOutcomeKinds, matchesBinding, matchesSafelistEntry, mcpCredentialsPath, mcpToolsCachePath, mergeApprovalAndBodyOutcomes, mergeContributions, mergeKeybindings, mergeReferences, modelOptionsFor, modelSupportsReasoning, modelsForDescriptor, normalizeMarkdownCodeFences, oauthUsesManualCodePaste, openaiDescriptor, openrouterDescriptor, parentServerName, parseBindingSpec, parseCommandInvocation, parseEditOutcomesFromResult, parseMcpsFile, parseSemver, partitionExtensionCatalog, patchMcpCredential, pendingInteractionsFromTurns, performInPlaceSelfUpdate, performSelfUpdate, piIdOf, pickActiveRunId, previewEditPayload, previewLine, projectUserPaths, projectsFilePath, pruneTodosByRun, readCredentials, readKeybindings, readKeybindingsRaw, readProjects, readProviderCredential, reduceMcpAuth, refreshMcpToolsCatalog, removeProviderCredential, renderActiveTodoAnchor, renderAgentsMdBlock, renderSession, resolveAgentId, resolveApprovalForPayload, resolveChipColor, resolveConfig, resolveExtensionKeybindings, resolvePlatformPackage, resolveSessionExportTarget, resolveStorageDirs, resolveStoragePaths, resolveTheme, restoreModelOptions, rewriteMultiEditHeader, runOAuthLogin, runUpdateCommand, saveMcpToolsCache, saveState, scanExtensionDirectories, selectActiveTodos, selectableTurnIds, serializeInteractionResponse, setProviderCredential, setTodosForRun, shortChord, shortId, shouldAutoCompact, shouldAutoGenerateTitle, singleAgentRegistry, splitLines, splitMarkdownCodeBlocks, splitPromptSegments, stripEditOutcomesAnnotation, stripJsonComments, stripSpawnTokensLine, subscribeMcpToolsCache, suggestSafelistEntries, sumRunCosts, summarizeEditPayload, summarizeOutcomes, supportsOAuth, titleFromTurns, tokenize, toolCallPreview, toolResultText, truncateTrailing, truncateTurnsAt, tryOpenBrowser, turnAsText, turnContextSize, turnSelectionOwnership, uniqueChatIdsFromReferences, uniqueFilesFromReferences, uniqueSkillNamesFromReferences, updateToolEventOutcomes, useActiveTodos, useColors, useCompletion, useConfig, useDiscovery, useDiscoveryOptional, useEnabledToggleSet, useInteractionsActions, useInteractionsQueue, useMcpAuthDispatch, useMcpAuthState, useMcpToolToggleMap, useMcpToolToggleSet, useSafeModeActions, useSafeModeQueue, useSelectStyle, useSettings, useStreamBuffer, useSurfaces, useSyntaxStyles, useTheme, useUpdateCheck, writeCredentials, writeProjects, writeSessionExport };
|
|
231
234
|
|
|
232
235
|
//# sourceMappingURL=chat.js.map
|
package/dist/chat.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.js","names":[],"sources":["../src/chat/auto-update-cli.ts","../src/chat/todo-anchor.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// `zidane upgrade` subcommand — drop-in handler for consumer CLIs.\n//\n// Wraps `checkForUpdate` + `performSelfUpdate` + `performInPlaceSelfUpdate`\n// into a single function the host's `cli.ts` can call. The behavior layers:\n//\n// - no flags → check + run the package manager\n// - `--check` → check only, print the latest version + bail\n// - `--in-place` → skip the PM, download + atomic-rename the binary\n// - `--dry-run` → resolve everything but don't actually swap\n// - `--channel <tag>` → override dist-tag (defaults to `'latest'`)\n// - `--registry <url>`→ override the npm registry URL\n//\n// Pure I/O — writes to stdout/stderr, returns the exit code the caller\n// should pass to `process.exit`. No React, no OpenTUI; safe to call\n// before / instead of `runTui`.\n// ---------------------------------------------------------------------------\n\nimport {\n checkForUpdate,\n compareSemver,\n detectPackageManager,\n performInPlaceSelfUpdate,\n performSelfUpdate,\n resolvePlatformPackage,\n} from './auto-update'\n\nexport interface RunUpdateCommandOptions {\n /** Top-level package the user installs (e.g. `'zidane-tui'`). */\n packageName: string\n /** Inlined at build time. */\n currentVersion: string\n /** Args passed after `upgrade` (typically `process.argv.slice(3)`). */\n argv: readonly string[]\n /** Where to persist the TTL cache. Usually `paths.userDir`. */\n cacheDir?: string\n /** Default channel when `--channel` isn't passed. Defaults to `'latest'`. */\n defaultChannel?: string\n /**\n * Override the platform-package-name prefix used by `--in-place`.\n * Defaults to `'<packageName>-'`, matching the `zidane-tui-<key>` layout.\n */\n platformPackagePrefix?: string\n /** Override registry. Defaults to npmjs. */\n registry?: string\n /** stdout. Defaults to `process.stdout`. */\n stdout?: NodeJS.WritableStream\n /** stderr. Defaults to `process.stderr`. */\n stderr?: NodeJS.WritableStream\n}\n\nexport interface RunUpdateCommandResult {\n exitCode: number\n}\n\nconst UPGRADE_HELP = `Usage: zidane upgrade [options]\n\nUpdate the zidane CLI to the latest release.\n\nOptions:\n --check Print the latest version and exit (no install).\n --in-place Download the platform binary directly from npm\n and atomic-rename over the running binary.\n Skips the package manager. Refused on Volta.\n --dry-run Resolve everything but don't actually install.\n --channel <tag> dist-tag to query (default: latest).\n --registry <url> Override the npm registry.\n --package-manager <pm> Force npm | pnpm | yarn | bun | volta.\n --force Run the install even if we're already on latest,\n or the registry check failed.\n -h, --help Print this help.\n\nEnvironment:\n NO_UPDATE_NOTIFIER Silence the background check (set to \"1\").\n ZIDANE_NO_UPDATE Same, project-specific.\n`\n\n/**\n * Run the `upgrade` subcommand. Exit code contract:\n * - `0` — update succeeded, `--check` reported no update, or `--check`\n * reported an update (informational only).\n * - `1` — update failed (PM exit non-zero, in-place download failed,\n * registry returned non-2xx).\n * - `2` — argv parse error (unknown flag).\n */\nexport async function runUpdateCommand(options: RunUpdateCommandOptions): Promise<RunUpdateCommandResult> {\n const out = options.stdout ?? process.stdout\n const err = options.stderr ?? process.stderr\n const parsed = parseArgs(options.argv)\n if (parsed.kind === 'error') {\n err.write(`zidane upgrade: ${parsed.message}\\n`)\n err.write(UPGRADE_HELP)\n return { exitCode: 2 }\n }\n if (parsed.help) {\n out.write(UPGRADE_HELP)\n return { exitCode: 0 }\n }\n\n const channel = parsed.channel ?? options.defaultChannel ?? 'latest'\n const registry = parsed.registry ?? options.registry\n\n // Always force the check — user typed `upgrade`, env opt-outs shouldn't\n // get in the way.\n const status = await checkForUpdate({\n packageName: options.packageName,\n currentVersion: options.currentVersion,\n channel,\n registry,\n cacheDir: options.cacheDir,\n force: true,\n timeoutMs: 8000,\n })\n\n // `--check` is informational — degrade gracefully on registry errors\n // (offline laptop, restricted proxy) and exit 0 so the user can script\n // around it without quoting tricks.\n if (parsed.check) {\n if (status.source === 'error') {\n err.write(`Could not check \\`${channel}\\` (${status.error ?? 'unknown error'}). Current: v${options.currentVersion}.\\n`)\n return { exitCode: 0 }\n }\n if (!status.latest) {\n err.write(`Could not determine latest version on \\`${channel}\\`. Current: v${options.currentVersion}.\\n`)\n return { exitCode: 0 }\n }\n const cmp = compareSemver(status.latest, options.currentVersion)\n if (cmp > 0)\n out.write(`v${status.latest} is available on \\`${channel}\\` (current: v${options.currentVersion}).\\n`)\n else\n out.write(`Already on v${options.currentVersion} (latest on \\`${channel}\\` is v${status.latest}).\\n`)\n return { exitCode: 0 }\n }\n\n // Install path — a registry error means we don't KNOW if we need an\n // update. Refuse to spawn the PM blindly unless the user explicitly\n // asks via `--force`.\n if (status.source === 'error') {\n err.write(`zidane upgrade: registry check failed (${status.error ?? 'unknown error'})\\n`)\n if (!parsed.force) {\n err.write('Pass --force to attempt the install anyway.\\n')\n return { exitCode: 1 }\n }\n }\n\n if (status.latest && !parsed.force) {\n const cmp = compareSemver(status.latest, options.currentVersion)\n if (cmp <= 0) {\n out.write(`Already on v${options.currentVersion} (latest on \\`${channel}\\` is v${status.latest}).\\n`)\n return { exitCode: 0 }\n }\n }\n\n // ---------------------------------------------------------------------\n // In-place path\n // ---------------------------------------------------------------------\n\n if (parsed.inPlace) {\n const platformPkg = resolvePlatformPackage({\n prefix: options.platformPackagePrefix ?? `${options.packageName}-`,\n })\n if (!platformPkg) {\n err.write(`No prebuilt binary for ${process.platform}/${process.arch}. Run \\`${options.packageName}-upgrade\\` via your package manager instead.\\n`)\n return { exitCode: 1 }\n }\n out.write(`Downloading ${platformPkg}@${channel}…\\n`)\n const result = await performInPlaceSelfUpdate({\n packageName: platformPkg,\n channel,\n registry,\n dryRun: parsed.dryRun,\n })\n if (result.status === 'success') {\n const verb = parsed.dryRun ? 'Would install' : 'Installed'\n out.write(`${verb} v${result.installedVersion} at ${result.binaryPath}.\\n`)\n return { exitCode: 0 }\n }\n err.write(`In-place update failed: ${result.reason ?? 'unknown error'}\\n`)\n if (result.status === 'refused')\n err.write('Falling back to package-manager path (drop --in-place to retry).\\n')\n return { exitCode: 1 }\n }\n\n // ---------------------------------------------------------------------\n // Package-manager path\n // ---------------------------------------------------------------------\n\n const detected = detectPackageManager({ packageName: options.packageName, channel })\n if (detected.note)\n out.write(`${detected.note}\\n`)\n out.write(`Running: ${detected.argv.join(' ')}\\n`)\n if (parsed.dryRun)\n return { exitCode: 0 }\n\n const result = await performSelfUpdate({\n packageName: options.packageName,\n channel,\n packageManager: parsed.packageManager ?? 'auto',\n })\n if (result.spawnError) {\n err.write(`Failed to launch \\`${result.command.argv[0]}\\`: ${result.spawnError}\\n`)\n err.write('Is the package manager installed and on $PATH?\\n')\n return { exitCode: 1 }\n }\n return { exitCode: result.exitCode ?? 1 }\n}\n\n// ---------------------------------------------------------------------------\n// Argv parser — minimal, just enough to drop into the consumer's `cli.ts`.\n// We deliberately don't pull in commander/yargs for a 5-flag surface.\n// ---------------------------------------------------------------------------\n\ntype ParseResult\n = | {\n kind: 'ok'\n check: boolean\n inPlace: boolean\n dryRun: boolean\n force: boolean\n help: boolean\n channel?: string\n registry?: string\n packageManager?: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta'\n }\n | { kind: 'error', message: string }\n\nfunction parseArgs(argv: readonly string[]): ParseResult {\n let check = false\n let inPlace = false\n let dryRun = false\n let force = false\n let help = false\n let channel: string | undefined\n let registry: string | undefined\n let packageManager: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | undefined\n\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!\n switch (a) {\n case '--check': check = true; break\n case '--in-place':\n case '--inplace': inPlace = true; break\n case '--dry-run':\n case '--dryrun': dryRun = true; break\n case '--force': force = true; break\n case '-h':\n case '--help': help = true; break\n case '--channel':\n channel = argv[++i]\n if (!channel)\n return { kind: 'error', message: '--channel requires a value' }\n break\n case '--registry':\n registry = argv[++i]\n if (!registry)\n return { kind: 'error', message: '--registry requires a value' }\n break\n case '--package-manager':\n case '--pm': {\n const v = argv[++i]\n if (!v)\n return { kind: 'error', message: '--package-manager requires a value' }\n if (v !== 'npm' && v !== 'pnpm' && v !== 'yarn' && v !== 'bun' && v !== 'volta')\n return { kind: 'error', message: `unknown package manager: ${v}` }\n packageManager = v\n break\n }\n default:\n return { kind: 'error', message: `unknown argument: ${a}` }\n }\n }\n\n return { kind: 'ok', check, inPlace, dryRun, force, help, channel, registry, packageManager }\n}\n","import type { AgentHookMap } from '../agent'\nimport type { TodoItem } from './todos'\nimport { appendDynamicSection } from '../system-prompt'\nimport { selectActiveTodos } from './todos'\n\nexport interface ActiveTodoAnchorOptions {\n enabled?: boolean\n maxItems?: number\n heading?: string\n}\n\nexport function renderActiveTodoAnchor(\n todos: readonly TodoItem[],\n options: ActiveTodoAnchorOptions = {},\n): string {\n if (options.enabled === false || todos.length === 0)\n return ''\n const maxItems = Math.max(1, Math.floor(options.maxItems ?? 6))\n const heading = options.heading ?? 'Active Todo Anchor'\n const visible = todos.slice(0, maxItems)\n const lines = [`# ${heading}`, '<active_todos>']\n for (const item of visible)\n lines.push(`- [${item.status}] ${item.content}`)\n if (todos.length > visible.length)\n lines.push(`- ... ${todos.length - visible.length} more`)\n lines.push('</active_todos>')\n return lines.join('\\n')\n}\n\n/**\n * Optional chat-layer hook that keeps the live `todowrite` list visible in the\n * dynamic system prompt. It reads only live todos, never the archive, so an\n * auto-cleared completed plan is not reintroduced on later turns.\n */\nexport function createActiveTodoAnchorHooks(options: ActiveTodoAnchorOptions = {}): AgentHookMap {\n return {\n 'system:transform': (ctx) => {\n const state = selectActiveTodos(ctx.session)\n const anchor = renderActiveTodoAnchor(state.todos, options)\n if (anchor)\n ctx.system = appendDynamicSection(ctx.system, anchor)\n },\n }\n}\n"],"mappings":";;;;;;;;AAuDA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BrB,eAAsB,iBAAiB,SAAmE;CACxG,MAAM,MAAM,QAAQ,UAAU,QAAQ;CACtC,MAAM,MAAM,QAAQ,UAAU,QAAQ;CACtC,MAAM,SAAS,UA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A,SAAgB,uBACd,OACA,UAAmC,CAAC,GAC5B;CACR,IAAI,QAAQ,YAAY,SAAS,MAAM,WAAW,GAChD,OAAO;CACT,MAAM,WAAW,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,YAAY,CAAC,CAAC;CAC9D,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,UAAU,MAAM,MAAM,GAAG,QAAQ;CACvC,MAAM,QAAQ,CAAC,KAAK,WAAW,gBAAgB;CAC/C,KAAK,MAAM,QAAQ,SACjB,MAAM,KAAK,MAAM,KAAK,OAAO,IAAI,KAAK,SAAS;CACjD,IAAI,MAAM,SAAS,QAAQ,QACzB,MAAM,KAAK,SAAS,MAAM,SAAS,QAAQ,OAAO,MAAM;CAC1D,MAAM,KAAK,iBAAiB;CAC5B,OAAO,MAAM,KAAK,IAAI;AACxB;;;;;;AAOA,SAAgB,4BAA4B,UAAmC,CAAC,GAAiB;CAC/F,OAAO,EACL,qBAAqB,QAAQ;EAE3B,MAAM,SAAS,uBADD,kBAAkB,IAAI,OACM,EAAE,OAAO,OAAO;EAC1D,IAAI,QACF,IAAI,SAAS,qBAAqB,IAAI,QAAQ,MAAM;CACxD,EACF;AACF"}
|
|
1
|
+
{"version":3,"file":"chat.js","names":[],"sources":["../src/chat/auto-update-cli.ts","../src/chat/todo-anchor.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// `zidane upgrade` subcommand — drop-in handler for consumer CLIs.\n//\n// Wraps `checkForUpdate` + `performSelfUpdate` + `performInPlaceSelfUpdate`\n// into a single function the host's `cli.ts` can call. The behavior layers:\n//\n// - no flags → check + run the package manager\n// - `--check` → check only, print the latest version + bail\n// - `--in-place` → skip the PM, download + atomic-rename the binary\n// - `--dry-run` → resolve everything but don't actually swap\n// - `--channel <tag>` → override dist-tag (defaults to `'latest'`)\n// - `--registry <url>`→ override the npm registry URL\n//\n// Pure I/O — writes to stdout/stderr, returns the exit code the caller\n// should pass to `process.exit`. No React, no OpenTUI; safe to call\n// before / instead of `runTui`.\n// ---------------------------------------------------------------------------\n\nimport {\n checkForUpdate,\n compareSemver,\n detectPackageManager,\n performInPlaceSelfUpdate,\n performSelfUpdate,\n resolvePlatformPackage,\n} from './auto-update'\n\nexport interface RunUpdateCommandOptions {\n /** Top-level package the user installs (e.g. `'zidane-tui'`). */\n packageName: string\n /** Inlined at build time. */\n currentVersion: string\n /** Args passed after `upgrade` (typically `process.argv.slice(3)`). */\n argv: readonly string[]\n /** Where to persist the TTL cache. Usually `paths.userDir`. */\n cacheDir?: string\n /** Default channel when `--channel` isn't passed. Defaults to `'latest'`. */\n defaultChannel?: string\n /**\n * Override the platform-package-name prefix used by `--in-place`.\n * Defaults to `'<packageName>-'`, matching the `zidane-tui-<key>` layout.\n */\n platformPackagePrefix?: string\n /** Override registry. Defaults to npmjs. */\n registry?: string\n /** stdout. Defaults to `process.stdout`. */\n stdout?: NodeJS.WritableStream\n /** stderr. Defaults to `process.stderr`. */\n stderr?: NodeJS.WritableStream\n}\n\nexport interface RunUpdateCommandResult {\n exitCode: number\n}\n\nconst UPGRADE_HELP = `Usage: zidane upgrade [options]\n\nUpdate the zidane CLI to the latest release.\n\nOptions:\n --check Print the latest version and exit (no install).\n --in-place Download the platform binary directly from npm\n and atomic-rename over the running binary.\n Skips the package manager. Refused on Volta.\n --dry-run Resolve everything but don't actually install.\n --channel <tag> dist-tag to query (default: latest).\n --registry <url> Override the npm registry.\n --package-manager <pm> Force npm | pnpm | yarn | bun | volta.\n --force Run the install even if we're already on latest,\n or the registry check failed.\n -h, --help Print this help.\n\nEnvironment:\n NO_UPDATE_NOTIFIER Silence the background check (set to \"1\").\n ZIDANE_NO_UPDATE Same, project-specific.\n`\n\n/**\n * Run the `upgrade` subcommand. Exit code contract:\n * - `0` — update succeeded, `--check` reported no update, or `--check`\n * reported an update (informational only).\n * - `1` — update failed (PM exit non-zero, in-place download failed,\n * registry returned non-2xx).\n * - `2` — argv parse error (unknown flag).\n */\nexport async function runUpdateCommand(options: RunUpdateCommandOptions): Promise<RunUpdateCommandResult> {\n const out = options.stdout ?? process.stdout\n const err = options.stderr ?? process.stderr\n const parsed = parseArgs(options.argv)\n if (parsed.kind === 'error') {\n err.write(`zidane upgrade: ${parsed.message}\\n`)\n err.write(UPGRADE_HELP)\n return { exitCode: 2 }\n }\n if (parsed.help) {\n out.write(UPGRADE_HELP)\n return { exitCode: 0 }\n }\n\n const channel = parsed.channel ?? options.defaultChannel ?? 'latest'\n const registry = parsed.registry ?? options.registry\n\n // Always force the check — user typed `upgrade`, env opt-outs shouldn't\n // get in the way.\n const status = await checkForUpdate({\n packageName: options.packageName,\n currentVersion: options.currentVersion,\n channel,\n registry,\n cacheDir: options.cacheDir,\n force: true,\n timeoutMs: 8000,\n })\n\n // `--check` is informational — degrade gracefully on registry errors\n // (offline laptop, restricted proxy) and exit 0 so the user can script\n // around it without quoting tricks.\n if (parsed.check) {\n if (status.source === 'error') {\n err.write(`Could not check \\`${channel}\\` (${status.error ?? 'unknown error'}). Current: v${options.currentVersion}.\\n`)\n return { exitCode: 0 }\n }\n if (!status.latest) {\n err.write(`Could not determine latest version on \\`${channel}\\`. Current: v${options.currentVersion}.\\n`)\n return { exitCode: 0 }\n }\n const cmp = compareSemver(status.latest, options.currentVersion)\n if (cmp > 0)\n out.write(`v${status.latest} is available on \\`${channel}\\` (current: v${options.currentVersion}).\\n`)\n else\n out.write(`Already on v${options.currentVersion} (latest on \\`${channel}\\` is v${status.latest}).\\n`)\n return { exitCode: 0 }\n }\n\n // Install path — a registry error means we don't KNOW if we need an\n // update. Refuse to spawn the PM blindly unless the user explicitly\n // asks via `--force`.\n if (status.source === 'error') {\n err.write(`zidane upgrade: registry check failed (${status.error ?? 'unknown error'})\\n`)\n if (!parsed.force) {\n err.write('Pass --force to attempt the install anyway.\\n')\n return { exitCode: 1 }\n }\n }\n\n if (status.latest && !parsed.force) {\n const cmp = compareSemver(status.latest, options.currentVersion)\n if (cmp <= 0) {\n out.write(`Already on v${options.currentVersion} (latest on \\`${channel}\\` is v${status.latest}).\\n`)\n return { exitCode: 0 }\n }\n }\n\n // ---------------------------------------------------------------------\n // In-place path\n // ---------------------------------------------------------------------\n\n if (parsed.inPlace) {\n const platformPkg = resolvePlatformPackage({\n prefix: options.platformPackagePrefix ?? `${options.packageName}-`,\n })\n if (!platformPkg) {\n err.write(`No prebuilt binary for ${process.platform}/${process.arch}. Run \\`${options.packageName}-upgrade\\` via your package manager instead.\\n`)\n return { exitCode: 1 }\n }\n out.write(`Downloading ${platformPkg}@${channel}…\\n`)\n const result = await performInPlaceSelfUpdate({\n packageName: platformPkg,\n channel,\n registry,\n dryRun: parsed.dryRun,\n })\n if (result.status === 'success') {\n const verb = parsed.dryRun ? 'Would install' : 'Installed'\n out.write(`${verb} v${result.installedVersion} at ${result.binaryPath}.\\n`)\n return { exitCode: 0 }\n }\n err.write(`In-place update failed: ${result.reason ?? 'unknown error'}\\n`)\n if (result.status === 'refused')\n err.write('Falling back to package-manager path (drop --in-place to retry).\\n')\n return { exitCode: 1 }\n }\n\n // ---------------------------------------------------------------------\n // Package-manager path\n // ---------------------------------------------------------------------\n\n const detected = detectPackageManager({ packageName: options.packageName, channel })\n if (detected.note)\n out.write(`${detected.note}\\n`)\n out.write(`Running: ${detected.argv.join(' ')}\\n`)\n if (parsed.dryRun)\n return { exitCode: 0 }\n\n const result = await performSelfUpdate({\n packageName: options.packageName,\n channel,\n packageManager: parsed.packageManager ?? 'auto',\n })\n if (result.spawnError) {\n err.write(`Failed to launch \\`${result.command.argv[0]}\\`: ${result.spawnError}\\n`)\n err.write('Is the package manager installed and on $PATH?\\n')\n return { exitCode: 1 }\n }\n return { exitCode: result.exitCode ?? 1 }\n}\n\n// ---------------------------------------------------------------------------\n// Argv parser — minimal, just enough to drop into the consumer's `cli.ts`.\n// We deliberately don't pull in commander/yargs for a 5-flag surface.\n// ---------------------------------------------------------------------------\n\ntype ParseResult\n = | {\n kind: 'ok'\n check: boolean\n inPlace: boolean\n dryRun: boolean\n force: boolean\n help: boolean\n channel?: string\n registry?: string\n packageManager?: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta'\n }\n | { kind: 'error', message: string }\n\nfunction parseArgs(argv: readonly string[]): ParseResult {\n let check = false\n let inPlace = false\n let dryRun = false\n let force = false\n let help = false\n let channel: string | undefined\n let registry: string | undefined\n let packageManager: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | undefined\n\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!\n switch (a) {\n case '--check': check = true; break\n case '--in-place':\n case '--inplace': inPlace = true; break\n case '--dry-run':\n case '--dryrun': dryRun = true; break\n case '--force': force = true; break\n case '-h':\n case '--help': help = true; break\n case '--channel':\n channel = argv[++i]\n if (!channel)\n return { kind: 'error', message: '--channel requires a value' }\n break\n case '--registry':\n registry = argv[++i]\n if (!registry)\n return { kind: 'error', message: '--registry requires a value' }\n break\n case '--package-manager':\n case '--pm': {\n const v = argv[++i]\n if (!v)\n return { kind: 'error', message: '--package-manager requires a value' }\n if (v !== 'npm' && v !== 'pnpm' && v !== 'yarn' && v !== 'bun' && v !== 'volta')\n return { kind: 'error', message: `unknown package manager: ${v}` }\n packageManager = v\n break\n }\n default:\n return { kind: 'error', message: `unknown argument: ${a}` }\n }\n }\n\n return { kind: 'ok', check, inPlace, dryRun, force, help, channel, registry, packageManager }\n}\n","import type { AgentHookMap } from '../agent'\nimport type { TodoItem } from './todos'\nimport { appendDynamicSection } from '../system-prompt'\nimport { selectActiveTodos } from './todos'\n\nexport interface ActiveTodoAnchorOptions {\n enabled?: boolean\n maxItems?: number\n heading?: string\n}\n\nexport function renderActiveTodoAnchor(\n todos: readonly TodoItem[],\n options: ActiveTodoAnchorOptions = {},\n): string {\n if (options.enabled === false || todos.length === 0)\n return ''\n const maxItems = Math.max(1, Math.floor(options.maxItems ?? 6))\n const heading = options.heading ?? 'Active Todo Anchor'\n const visible = todos.slice(0, maxItems)\n const lines = [`# ${heading}`, '<active_todos>']\n for (const item of visible)\n lines.push(`- [${item.status}] ${item.content}`)\n if (todos.length > visible.length)\n lines.push(`- ... ${todos.length - visible.length} more`)\n lines.push('</active_todos>')\n return lines.join('\\n')\n}\n\n/**\n * Optional chat-layer hook that keeps the live `todowrite` list visible in the\n * dynamic system prompt. It reads only live todos, never the archive, so an\n * auto-cleared completed plan is not reintroduced on later turns.\n */\nexport function createActiveTodoAnchorHooks(options: ActiveTodoAnchorOptions = {}): AgentHookMap {\n return {\n 'system:transform': (ctx) => {\n const state = selectActiveTodos(ctx.session)\n const anchor = renderActiveTodoAnchor(state.todos, options)\n if (anchor)\n ctx.system = appendDynamicSection(ctx.system, anchor)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AAuDA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BrB,eAAsB,iBAAiB,SAAmE;CACxG,MAAM,MAAM,QAAQ,UAAU,QAAQ;CACtC,MAAM,MAAM,QAAQ,UAAU,QAAQ;CACtC,MAAM,SAAS,UAAU,QAAQ,IAAI;CACrC,IAAI,OAAO,SAAS,SAAS;EAC3B,IAAI,MAAM,mBAAmB,OAAO,QAAQ,GAAG;EAC/C,IAAI,MAAM,YAAY;EACtB,OAAO,EAAE,UAAU,EAAE;CACvB;CACA,IAAI,OAAO,MAAM;EACf,IAAI,MAAM,YAAY;EACtB,OAAO,EAAE,UAAU,EAAE;CACvB;CAEA,MAAM,UAAU,OAAO,WAAW,QAAQ,kBAAkB;CAC5D,MAAM,WAAW,OAAO,YAAY,QAAQ;CAI5C,MAAM,SAAS,MAAM,eAAe;EAClC,aAAa,QAAQ;EACrB,gBAAgB,QAAQ;EACxB;EACA;EACA,UAAU,QAAQ;EAClB,OAAO;EACP,WAAW;CACb,CAAC;CAKD,IAAI,OAAO,OAAO;EAChB,IAAI,OAAO,WAAW,SAAS;GAC7B,IAAI,MAAM,qBAAqB,QAAQ,MAAM,OAAO,SAAS,gBAAgB,eAAe,QAAQ,eAAe,IAAI;GACvH,OAAO,EAAE,UAAU,EA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BADD,kBAAkB,IAAI,OACM,EAAE,OAAO,OAAO;EAC1D,IAAI,QACF,IAAI,SAAS,qBAAqB,IAAI,QAAQ,MAAM;CACxD,EACF;AACF"}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
//#region src/chat/completion-core.ts
|
|
2
|
+
/**
|
|
3
|
+
* Resolve the provider trigger active at `cursor`, or `null` when none fits.
|
|
4
|
+
*
|
|
5
|
+
* Rules:
|
|
6
|
+
* - The trigger character must sit at position 0 of the buffer OR be
|
|
7
|
+
* preceded by whitespace. This prevents `http://` from triggering the
|
|
8
|
+
* `/`-bound skills provider mid-URL.
|
|
9
|
+
* - The cursor must be at or past the trigger position.
|
|
10
|
+
* - Nothing between the trigger and the cursor may be whitespace (the
|
|
11
|
+
* query is one contiguous token).
|
|
12
|
+
* - The query length is bounded — `maxQueryLength` defaults to 64 — so
|
|
13
|
+
* a runaway buffer scan can't pin the renderer.
|
|
14
|
+
*/
|
|
15
|
+
function findActiveTrigger(text, cursor, providers, options = {}) {
|
|
16
|
+
const multi = findActiveTriggers(text, cursor, providers, options);
|
|
17
|
+
if (!multi) return null;
|
|
18
|
+
return {
|
|
19
|
+
provider: multi.providers[0],
|
|
20
|
+
query: multi.query,
|
|
21
|
+
span: multi.span
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Multi-provider variant of {@link findActiveTrigger}: resolves ALL providers
|
|
26
|
+
* bound to the trigger char active at `cursor` (e.g. `/` → a commands provider
|
|
27
|
+
* AND the skills provider), sharing one query + span. The same trigger rules
|
|
28
|
+
* apply (start-of-buffer or whitespace-preceded, contiguous query, bounded
|
|
29
|
+
* length). Returns `null` when no trigger fits.
|
|
30
|
+
*/
|
|
31
|
+
function findActiveTriggers(text, cursor, providers, options = {}) {
|
|
32
|
+
if (providers.length === 0) return null;
|
|
33
|
+
const max = options.maxQueryLength ?? 64;
|
|
34
|
+
const safeCursor = Math.max(0, Math.min(cursor, text.length));
|
|
35
|
+
const isWhitespace = (ch) => ch === void 0 ? false : /\s/.test(ch);
|
|
36
|
+
const anyAllowsSpaces = providers.some((p) => p.allowSpacesInQuery === true);
|
|
37
|
+
let sawSpace = false;
|
|
38
|
+
for (let i = safeCursor - 1; i >= 0 && safeCursor - i <= max + 1; i--) {
|
|
39
|
+
const ch = text[i];
|
|
40
|
+
if (isWhitespace(ch)) {
|
|
41
|
+
if (ch === "\n" || ch === "\r" || !anyAllowsSpaces) return null;
|
|
42
|
+
sawSpace = true;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const matching = providers.filter((p) => p.trigger === ch && (!sawSpace || p.allowSpacesInQuery === true));
|
|
46
|
+
if (matching.length === 0) continue;
|
|
47
|
+
const before = i > 0 ? text[i - 1] : "";
|
|
48
|
+
if (before !== "" && !isWhitespace(before)) continue;
|
|
49
|
+
return {
|
|
50
|
+
providers: matching,
|
|
51
|
+
query: text.slice(i + 1, safeCursor),
|
|
52
|
+
span: {
|
|
53
|
+
start: i,
|
|
54
|
+
end: safeCursor
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Flatten several providers' suggestion lists into one, defaulting each
|
|
62
|
+
* item's `section` to its producing provider's `label` so a multi-provider
|
|
63
|
+
* popover can render group headers. Items that already carry a `section`
|
|
64
|
+
* are left as-is.
|
|
65
|
+
*/
|
|
66
|
+
function mergeSuggestions(groups) {
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const { provider, items } of groups) for (const item of items) out.push(item.section === void 0 ? {
|
|
69
|
+
...item,
|
|
70
|
+
section: provider.label
|
|
71
|
+
} : item);
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Replace `[span.start, span.end)` in `text` with `insertText`. Returns the
|
|
76
|
+
* mutated text and the new cursor position (end of insertion).
|
|
77
|
+
*/
|
|
78
|
+
function applyInsert(text, span, insertText) {
|
|
79
|
+
return {
|
|
80
|
+
text: text.slice(0, span.start) + insertText + text.slice(span.end),
|
|
81
|
+
cursor: span.start + insertText.length
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Merge reference lists from multiple providers into one ordered list with
|
|
86
|
+
* earlier-start-wins disambiguation when spans overlap. Ties broken by
|
|
87
|
+
* insertion order. Spans are sorted ascending so renderers can walk them
|
|
88
|
+
* sequentially with a cursor through the source string.
|
|
89
|
+
*/
|
|
90
|
+
function mergeReferences(refs) {
|
|
91
|
+
const sorted = [...refs].sort((a, b) => a.start - b.start);
|
|
92
|
+
const merged = [];
|
|
93
|
+
let lastEnd = -1;
|
|
94
|
+
for (const ref of sorted) {
|
|
95
|
+
if (ref.start < lastEnd) continue;
|
|
96
|
+
merged.push(ref);
|
|
97
|
+
lastEnd = ref.end;
|
|
98
|
+
}
|
|
99
|
+
return merged;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Collect every provider's references in one pass. Convenience wrapper —
|
|
103
|
+
* the TUI textarea component calls this on every keystroke to highlight
|
|
104
|
+
* in-prompt mentions.
|
|
105
|
+
*/
|
|
106
|
+
function collectReferences(text, providers, cursor = text.length) {
|
|
107
|
+
const ctx = {
|
|
108
|
+
text,
|
|
109
|
+
cursor
|
|
110
|
+
};
|
|
111
|
+
const refs = [];
|
|
112
|
+
for (const p of providers) for (const ref of p.parseReferences(text, ctx)) refs.push(ref);
|
|
113
|
+
return mergeReferences(refs);
|
|
114
|
+
}
|
|
115
|
+
async function resolveCompletionSubmit(text, providers, options = {}) {
|
|
116
|
+
const cursor = options.cursor ?? text.length;
|
|
117
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
118
|
+
const byProvider = /* @__PURE__ */ new Map();
|
|
119
|
+
for (const ref of collectReferences(text, providers, cursor)) {
|
|
120
|
+
const bucket = byProvider.get(ref.providerId) ?? [];
|
|
121
|
+
bucket.push(ref);
|
|
122
|
+
byProvider.set(ref.providerId, bucket);
|
|
123
|
+
}
|
|
124
|
+
const resolved = [];
|
|
125
|
+
for (const provider of providers) {
|
|
126
|
+
const refs = byProvider.get(provider.id);
|
|
127
|
+
if (!refs?.length) continue;
|
|
128
|
+
const ctx = {
|
|
129
|
+
text,
|
|
130
|
+
cursor,
|
|
131
|
+
references: refs
|
|
132
|
+
};
|
|
133
|
+
const next = provider.resolveReferences ? await provider.resolveReferences(refs, ctx, signal) : refs;
|
|
134
|
+
const submitCtx = {
|
|
135
|
+
text,
|
|
136
|
+
cursor,
|
|
137
|
+
references: next
|
|
138
|
+
};
|
|
139
|
+
await provider.onSubmit?.(submitCtx, signal);
|
|
140
|
+
resolved.push(...next);
|
|
141
|
+
}
|
|
142
|
+
return mergeReferences(resolved);
|
|
143
|
+
}
|
|
144
|
+
//#endregion
|
|
145
|
+
export { mergeReferences as a, findActiveTriggers as i, collectReferences as n, mergeSuggestions as o, findActiveTrigger as r, resolveCompletionSubmit as s, applyInsert as t };
|
|
146
|
+
|
|
147
|
+
//# sourceMappingURL=completion-core-CXYSVhZo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"completion-core-CXYSVhZo.js","names":[],"sources":["../src/chat/completion-core.ts"],"sourcesContent":["/**\n * Prompt autocompletion framework — pure core.\n *\n * Provider contract types + the renderer-agnostic span/reference helpers\n * (`findActiveTrigger`, `applyInsert`, `mergeReferences`, `collectReferences`).\n * No React, no node — so a browser-context renderer imports these via\n * `zidane/chat/pure`. The `useCompletion` React hook lives in `./completion`\n * (main barrel) and re-exports everything here for back-compat.\n *\n * Providers plug in by registering a `trigger` character (e.g. `/` for skills,\n * `@` for files) and exposing two operations:\n *\n * 1. `suggest(query)` — return ranked items for the live query.\n * 2. `parseReferences(text)` — find all references to the provider's\n * items in arbitrary text. Used to highlight in-prompt mentions and\n * drive submit-time side effects (activate the skill, attach the\n * file, …).\n */\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A discoverable, selectable thing — one row in the autocomplete popover.\n * `TItem` is provider-specific; consumers can inspect `data` when they\n * need the originating payload (e.g. the full `SkillConfig` for tooltips).\n */\nexport interface CompletionItem<TItem = unknown> {\n /** Stable identifier within the provider. Used as React key + selection equality. */\n id: string\n /** User-visible primary string (\"research\"). */\n label: string\n /** Optional one-line secondary string (\"In-depth research with citations\"). */\n description?: string\n /**\n * Text that replaces the active span (trigger + query) on commit. Usually\n * `${trigger}${label}` with a trailing space so the cursor lands ready\n * for the next token.\n */\n insertText: string\n /**\n * Optional section header for popovers that host several providers on one\n * trigger (e.g. `/` → Commands + Skills). When set, the renderer groups\n * items under this label; when absent, items render flat. The engine\n * defaults it to the producing provider's `label` in {@link mergeSuggestions}.\n */\n section?: string\n /** Original provider-specific payload. */\n data: TItem\n}\n\n/**\n * A reference to a provider item inside arbitrary prompt text. Producers:\n * `provider.parseReferences(text)`. Consumers: the TUI for highlighting,\n * the run flow for \"activate every referenced skill before agent.run()\".\n *\n * Spans are half-open `[start, end)` codepoint offsets into the source\n * string. Overlapping spans from the same or different providers are\n * caller-resolved — the helpers below ship a \"first wins\" merger.\n */\nexport interface CompletionReference<TItem = unknown> {\n providerId: string\n start: number\n end: number\n itemId: string\n data: TItem\n metadata?: Record<string, unknown>\n}\n\nexport interface CompletionSubmitContext<TItem = unknown> extends CompletionContext {\n references: readonly CompletionReference<TItem>[]\n}\n\n/**\n * Provider contract. Implementations decide their own ranking, fuzzy-match\n * rules, async loading behavior, and reference grammar.\n */\nexport interface CompletionProvider<TItem = unknown> {\n /** Stable id used for tagging references + React keys. */\n id: string\n /**\n * Single character that activates this provider. The engine considers a\n * trigger \"active\" when it appears at the start of the buffer or\n * immediately after whitespace, and is not closed by whitespace before\n * the cursor (so a trigger plus query is a contiguous token).\n */\n trigger: string\n /** Human-readable name. Reserved for future multi-provider popover headers. */\n label: string\n /**\n * Returns items for the active `query` (the text between the trigger and\n * the cursor, excluding the trigger itself). Synchronous return is the\n * common case; promises let providers paginate or hit a backend.\n *\n * `signal` is aborted when the query changes or the popover closes —\n * use it to cancel in-flight network calls.\n */\n suggest: (\n query: string,\n ctx: CompletionContext,\n signal: AbortSignal,\n ) => CompletionItem<TItem>[] | Promise<CompletionItem<TItem>[]>\n /**\n * Keep the trigger active across spaces (single line only — a newline\n * still closes it). Default false: a space ends the query token, which is\n * right for file/skill/chat mentions. The commands provider opts in so\n * `/deploy stag▌` can complete ARGUMENTS: its query becomes\n * `deploy stag` and it decides internally what to suggest. When the\n * query contains whitespace, only opted-in providers are consulted.\n */\n allowSpacesInQuery?: boolean\n /**\n * Find every reference to this provider's items in `text`. Pure: must not\n * mutate ctx. The TUI calls this on every keystroke for highlighting, so\n * keep it cheap (linear scan, no I/O).\n */\n parseReferences: (\n text: string,\n ctx: CompletionContext,\n ) => CompletionReference<TItem>[]\n /**\n * Optional submit-time resolver. Unlike `parseReferences`, this may do async\n * work and enrich references before the host turns them into attachments,\n * activated skills, or other side effects.\n *\n * Declared with method syntax (not a property arrow) on purpose: it makes the\n * `TItem`-typed params bivariant, so a heterogeneous `CompletionProvider`\n * collection (skills + files + extensions) stays assignable to\n * `CompletionProvider<unknown>[]`.\n */\n // eslint-disable-next-line ts/method-signature-style\n resolveReferences?(\n references: readonly CompletionReference<TItem>[],\n ctx: CompletionSubmitContext<TItem>,\n signal: AbortSignal,\n ): CompletionReference<TItem>[] | Promise<CompletionReference<TItem>[]>\n /** Optional submit-time side effect hook. Runs after references are resolved. */\n // eslint-disable-next-line ts/method-signature-style\n onSubmit?(\n submission: CompletionSubmitContext<TItem>,\n signal: AbortSignal,\n ): void | Promise<void>\n}\n\n/**\n * Read-only view of the active prompt buffer + cursor passed to provider\n * callbacks. Kept minimal so providers stay portable across renderers.\n */\nexport interface CompletionContext {\n /** Full prompt text. */\n text: string\n /** Codepoint offset of the cursor (0-based). */\n cursor: number\n}\n\n/**\n * Identified active trigger span. Returned by `findActiveTrigger` so\n * callers can show the popover, query the provider, and on commit replace\n * the span with the selected item's `insertText`.\n */\nexport interface ActiveTrigger<TItem = unknown> {\n provider: CompletionProvider<TItem>\n /** Substring after the trigger, up to the cursor. Empty if cursor sits right after the trigger. */\n query: string\n /** `[start, end)` — span covered by the trigger + query in the source. */\n span: { start: number, end: number }\n}\n\n// ---------------------------------------------------------------------------\n// Pure helpers — exported for unit tests + alternate renderers\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the provider trigger active at `cursor`, or `null` when none fits.\n *\n * Rules:\n * - The trigger character must sit at position 0 of the buffer OR be\n * preceded by whitespace. This prevents `http://` from triggering the\n * `/`-bound skills provider mid-URL.\n * - The cursor must be at or past the trigger position.\n * - Nothing between the trigger and the cursor may be whitespace (the\n * query is one contiguous token).\n * - The query length is bounded — `maxQueryLength` defaults to 64 — so\n * a runaway buffer scan can't pin the renderer.\n */\nexport function findActiveTrigger<TItem>(\n text: string,\n cursor: number,\n providers: readonly CompletionProvider<TItem>[],\n options: { maxQueryLength?: number } = {},\n): ActiveTrigger<TItem> | null {\n const multi = findActiveTriggers(text, cursor, providers, options)\n if (!multi)\n return null\n // Back-compat: the first matching provider is exactly what the old\n // `providers.find(...)` returned (filter preserves order).\n return { provider: multi.providers[0], query: multi.query, span: multi.span }\n}\n\n/** Like {@link ActiveTrigger} but carries EVERY provider bound to the active trigger char. */\nexport interface ActiveTriggers<TItem = unknown> {\n /** All providers whose `trigger` matches the active char, in registration order. */\n providers: readonly CompletionProvider<TItem>[]\n query: string\n span: { start: number, end: number }\n}\n\n/**\n * Multi-provider variant of {@link findActiveTrigger}: resolves ALL providers\n * bound to the trigger char active at `cursor` (e.g. `/` → a commands provider\n * AND the skills provider), sharing one query + span. The same trigger rules\n * apply (start-of-buffer or whitespace-preceded, contiguous query, bounded\n * length). Returns `null` when no trigger fits.\n */\nexport function findActiveTriggers<TItem>(\n text: string,\n cursor: number,\n providers: readonly CompletionProvider<TItem>[],\n options: { maxQueryLength?: number } = {},\n): ActiveTriggers<TItem> | null {\n if (providers.length === 0)\n return null\n const max = options.maxQueryLength ?? 64\n const safeCursor = Math.max(0, Math.min(cursor, text.length))\n // Whitespace test mirrors regex `\\s` so this surface agrees with the\n // built-in providers' `parseReferences` regex (which uses `\\s`). Without\n // this, pasting `text\\u00a0@README.md` would parse as a ref but the popover\n // wouldn't reopen on retype because NBSP wasn't recognized as a boundary.\n const isWhitespace = (ch: string | undefined) => ch === undefined ? false : /\\s/.test(ch)\n // Walk backward from the cursor to the nearest trigger char. Whitespace\n // normally closes the query token and ends the walk — unless a provider\n // opted into `allowSpacesInQuery` (argument completion), in which case\n // the walk continues across spaces (never newlines) and, once a trigger\n // is found, only space-tolerant providers are consulted for a spaced\n // query. Non-opted-in providers keep byte-identical behavior.\n const anyAllowsSpaces = providers.some(p => p.allowSpacesInQuery === true)\n let sawSpace = false\n for (let i = safeCursor - 1; i >= 0 && safeCursor - i <= max + 1; i--) {\n const ch = text[i]\n if (isWhitespace(ch)) {\n if (ch === '\\n' || ch === '\\r' || !anyAllowsSpaces)\n return null\n sawSpace = true\n continue\n }\n const matching = providers.filter(p => p.trigger === ch && (!sawSpace || p.allowSpacesInQuery === true))\n if (matching.length === 0)\n continue\n // Trigger must be at start of buffer or follow whitespace.\n const before = i > 0 ? text[i - 1] : ''\n if (before !== '' && !isWhitespace(before))\n continue\n const query = text.slice(i + 1, safeCursor)\n return {\n providers: matching,\n query,\n span: { start: i, end: safeCursor },\n }\n }\n return null\n}\n\n/**\n * Flatten several providers' suggestion lists into one, defaulting each\n * item's `section` to its producing provider's `label` so a multi-provider\n * popover can render group headers. Items that already carry a `section`\n * are left as-is.\n */\nexport function mergeSuggestions<TItem>(\n groups: readonly { provider: CompletionProvider<TItem>, items: readonly CompletionItem<TItem>[] }[],\n): CompletionItem<TItem>[] {\n const out: CompletionItem<TItem>[] = []\n for (const { provider, items } of groups) {\n for (const item of items)\n out.push(item.section === undefined ? { ...item, section: provider.label } : item)\n }\n return out\n}\n\n/**\n * Replace `[span.start, span.end)` in `text` with `insertText`. Returns the\n * mutated text and the new cursor position (end of insertion).\n */\nexport function applyInsert(\n text: string,\n span: { start: number, end: number },\n insertText: string,\n): { text: string, cursor: number } {\n const next = text.slice(0, span.start) + insertText + text.slice(span.end)\n return { text: next, cursor: span.start + insertText.length }\n}\n\n/**\n * Merge reference lists from multiple providers into one ordered list with\n * earlier-start-wins disambiguation when spans overlap. Ties broken by\n * insertion order. Spans are sorted ascending so renderers can walk them\n * sequentially with a cursor through the source string.\n */\nexport function mergeReferences<TItem>(\n refs: readonly CompletionReference<TItem>[],\n): CompletionReference<TItem>[] {\n const sorted = [...refs].sort((a, b) => a.start - b.start)\n const merged: CompletionReference<TItem>[] = []\n let lastEnd = -1\n for (const ref of sorted) {\n if (ref.start < lastEnd)\n continue\n merged.push(ref)\n lastEnd = ref.end\n }\n return merged\n}\n\n/**\n * Collect every provider's references in one pass. Convenience wrapper —\n * the TUI textarea component calls this on every keystroke to highlight\n * in-prompt mentions.\n */\nexport function collectReferences<TItem>(\n text: string,\n providers: readonly CompletionProvider<TItem>[],\n cursor = text.length,\n): CompletionReference<TItem>[] {\n const ctx: CompletionContext = { text, cursor }\n const refs: CompletionReference<TItem>[] = []\n for (const p of providers) {\n for (const ref of p.parseReferences(text, ctx))\n refs.push(ref)\n }\n return mergeReferences(refs)\n}\n\nexport async function resolveCompletionSubmit<TItem>(\n text: string,\n providers: readonly CompletionProvider<TItem>[],\n options: { cursor?: number, signal?: AbortSignal } = {},\n): Promise<CompletionReference<TItem>[]> {\n const cursor = options.cursor ?? text.length\n const signal = options.signal ?? new AbortController().signal\n const byProvider = new Map<string, CompletionReference<TItem>[]>()\n for (const ref of collectReferences(text, providers, cursor)) {\n const bucket = byProvider.get(ref.providerId) ?? []\n bucket.push(ref)\n byProvider.set(ref.providerId, bucket)\n }\n const resolved: CompletionReference<TItem>[] = []\n for (const provider of providers) {\n const refs = byProvider.get(provider.id)\n if (!refs?.length)\n continue\n const ctx: CompletionSubmitContext<TItem> = { text, cursor, references: refs }\n const next = provider.resolveReferences\n ? await provider.resolveReferences(refs, ctx, signal)\n : refs\n const submitCtx: CompletionSubmitContext<TItem> = { text, cursor, references: next }\n await provider.onSubmit?.(submitCtx, signal)\n resolved.push(...next)\n }\n return mergeReferences(resolved)\n}\n"],"mappings":";;;;;;;;;;;;;;AA0LA,SAAgB,kBACd,MACA,QACA,WACA,UAAuC,CAAC,GACX;CAC7B,MAAM,QAAQ,mBAAmB,MAAM,QAAQ,WAAW,OAAO;CACjE,IAAI,CAAC,OACH,OAAO;CAGT,OAAO;EAAE,UAAU,MAAM,UAAU;EAAI,OAAO,MAAM;EAAO,MAAM,MAAM;CAAK;AAC9E;;;;;;;;AAiBA,SAAgB,mBACd,MACA,QACA,WACA,UAAuC,CAAC,GACV;CAC9B,IAAI,UAAU,WAAW,GACvB,OAAO;CACT,MAAM,MAAM,QAAQ,kBAAkB;CACtC,MAAM,aAAa,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,KAAK,MAAM,CAAC;CAK5D,MAAM,gBAAgB,OAA2B,OAAO,KAAA,IAAY,QAAQ,KAAK,KAAK,EAAE;CAOxF,MAAM,kBAAkB,UAAU,MAAK,MAAK,EAAE,uBAAuB,IAAI;CACzE,IAAI,WAAW;CACf,KAAK,IAAI,IAAI,aAAa,GAAG,KAAK,KAAK,aAAa,KAAK,MAAM,GAAG,KAAK;EACrE,MAAM,KAAK,KAAK;EAChB,IAAI,aAAa,EAAE,GAAG;GACpB,IAAI,OAAO,QAAQ,OAAO,QAAQ,CAAC,iBACjC,OAAO;GACT,WAAW;GACX;EACF;EACA,MAAM,WAAW,UAAU,QAAO,MAAK,EAAE,YAAY,OAAO,CAAC,YAAY,EAAE,uBAAuB,KAAK;EACvG,IAAI,SAAS,WAAW,GACtB;EAEF,MAAM,SAAS,IAAI,IAAI,KAAK,IAAI,KAAK;EACrC,IAAI,WAAW,MAAM,CAAC,aAAa,MAAM,GACvC;EAEF,OAAO;GACL,WAAW;GACX,OAHY,KAAK,MAAM,IAAI,GAAG,UAG1B;GACJ,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D,MAAM,SAAS,WAAW,IAAI,IAAI,UAAU,KAAK,CAAC;EAClD,OAAO,KAAK,GAAG;EACf,WAAW,IAAI,IAAI,YAAY,MAAM;CACvC;CACA,MAAM,WAAyC,CAAC;CAChD,KAAK,MAAM,YAAY,WAAW;EAChC,MAAM,OAAO,WAAW,IAAI,SAAS,EAAE;EACvC,IAAI,CAAC,MAAM,QACT;EACF,MAAM,MAAsC;GAAE;GAAM;GAAQ,YAAY;EAAK;EAC7E,MAAM,OAAO,SAAS,oBAClB,MAAM,SAAS,kBAAkB,MAAM,KAAK,MAAM,IAClD;EACJ,MAAM,YAA4C;GAAE;GAAM;GAAQ,YAAY;EAAK;EACnF,MAAM,SAAS,WAAW,WAAW,MAAM;EAC3C,SAAS,KAAK,GAAG,IAAI;CACvB;CACA,OAAO,gBAAgB,QAAQ;AACjC"}
|
|
@@ -1,27 +1,5 @@
|
|
|
1
1
|
import { n as estimateTokens } from "./utils-ngQzYzZD.js";
|
|
2
2
|
//#region src/chat/context-breakdown.ts
|
|
3
|
-
/**
|
|
4
|
-
* Context-usage breakdown — pure transforms.
|
|
5
|
-
*
|
|
6
|
-
* Turns a {@link ContextSnapshot} (the raw pieces the agent assembled for a
|
|
7
|
-
* run: system prompt, wire tools, deferred tools, MCP tools/instructions,
|
|
8
|
-
* skills catalog, ...) plus the real last-turn token total into a categorized
|
|
9
|
-
* {@link ContextBreakdown} the TUI panel / GUI popover render.
|
|
10
|
-
*
|
|
11
|
-
* No React, no node — a browser-context renderer imports these via
|
|
12
|
-
* `zidane/chat/pure`. The snapshot is captured main-side (TUI direct, GUI in
|
|
13
|
-
* `main/chat`) because building it reads provider/agent state; only the pure
|
|
14
|
-
* shaping lives here.
|
|
15
|
-
*
|
|
16
|
-
* Accuracy: per-category counts are estimates when no provider `countTokens`
|
|
17
|
-
* is available — the heuristic ({@link estimateTokens}, ~4 bytes/token) sizes
|
|
18
|
-
* each static segment and the bar is reconciled so it always sums to the real
|
|
19
|
-
* last-turn total (`conversation = realTotal - sum(static)`). When a provider
|
|
20
|
-
* exposes exact counts (Anthropic, OpenAI), the caller passes them in via
|
|
21
|
-
* {@link ContextSnapshot.exact} and the corresponding categories drop their
|
|
22
|
-
* `estimated` flag. Exact buckets (free space, autocompact buffer) are never
|
|
23
|
-
* estimated.
|
|
24
|
-
*/
|
|
25
3
|
const LABELS = {
|
|
26
4
|
systemPrompt: "System prompt",
|
|
27
5
|
rules: "Rules (AGENTS.md)",
|
|
@@ -167,10 +145,11 @@ function buildContextBreakdown(snapshot) {
|
|
|
167
145
|
categories,
|
|
168
146
|
hasEstimates,
|
|
169
147
|
...snapshot.usage ? { usage: snapshot.usage } : {},
|
|
148
|
+
...snapshot.extensionSections?.length ? { extensionSections: snapshot.extensionSections } : {},
|
|
170
149
|
...snapshot.activeSkills?.length ? { activeSkills: snapshot.activeSkills } : {}
|
|
171
150
|
};
|
|
172
151
|
}
|
|
173
152
|
//#endregion
|
|
174
153
|
export { buildContextBreakdown as t };
|
|
175
154
|
|
|
176
|
-
//# sourceMappingURL=context-breakdown-
|
|
155
|
+
//# sourceMappingURL=context-breakdown-Dzo25N45.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-breakdown-Dzo25N45.js","names":[],"sources":["../src/chat/context-breakdown.ts"],"sourcesContent":["/**\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: sn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ACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { Ll as Logger } from "../index-B8UtiZy7.js";
|
|
2
|
+
import { s as ExecResult } from "../types-BDccavwj.js";
|
|
3
|
+
import { t as SandboxProvider } from "../sandbox-CgjG2VvQ.js";
|
|
4
4
|
import { Buffer } from "node:buffer";
|
|
5
5
|
|
|
6
6
|
//#region src/contexts/daytona.d.ts
|
package/dist/contexts/daytona.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { r as createLogger, t as consoleSink } from "../logger-DBX9uYOw.js";
|
|
2
2
|
import { Buffer } from "node:buffer";
|
|
3
3
|
//#region src/contexts/daytona.ts
|
|
4
4
|
/** Per-probe timeout for the readiness `true` command. */
|
|
@@ -1,9 +1,17 @@
|
|
|
1
|
-
import { c as ExecutionContext, p as SpawnConfig } from "../types-
|
|
1
|
+
import { c as ExecutionContext, p as SpawnConfig } from "../types-BDccavwj.js";
|
|
2
2
|
|
|
3
3
|
//#region src/contexts/docker.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* `readFile` transport cap: headroom above the whole-read tool ceiling
|
|
6
|
+
* (256MB in tools/whole-read-guard.ts) so tool policy — not the docker
|
|
7
|
+
* transport — decides read limits, keeping refusal behavior consistent
|
|
8
|
+
* across contexts. Still bounded: a probe-failure path can't buffer
|
|
9
|
+
* more than this into host memory.
|
|
10
|
+
*/
|
|
11
|
+
declare const READ_FILE_MAX_BUFFER: number;
|
|
4
12
|
declare function createDockerContext(config?: SpawnConfig): ExecutionContext;
|
|
5
13
|
/** Assemble dockerode `HostConfig.Binds` from the context's `mounts`. */
|
|
6
14
|
declare function buildBindSpecs(mounts: NonNullable<SpawnConfig['mounts']>): string[];
|
|
7
15
|
//#endregion
|
|
8
|
-
export { buildBindSpecs, createDockerContext };
|
|
16
|
+
export { READ_FILE_MAX_BUFFER, buildBindSpecs, createDockerContext };
|
|
9
17
|
//# sourceMappingURL=docker.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docker.d.ts","names":[],"sources":["../../src/contexts/docker.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"docker.d.ts","names":[],"sources":["../../src/contexts/docker.ts"],"mappings":";;;;;;;;;;cAwBa,oBAAA;AAAA,iBAmBG,mBAAA,CAAoB,MAAA,GAAS,WAAA,GAAc,gBAAgB;;iBAgZ3D,cAAA,CAAe,MAAA,EAAQ,WAAW,CAAC,WAAA"}
|