@ponythewhite/base-context 1.0.6 → 1.0.8
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/CHANGELOG.md +25 -0
- package/dist/base-context-runtime/pyproject.toml +1 -1
- package/dist/base-context-runtime/src/rlm/__init__.py +3 -0
- package/dist/base-context-runtime/src/rlm/harness.py +86 -48
- package/dist/base-context-runtime/test/test_harness.py +215 -140
- package/dist/base-context-runtime/uv.lock +1 -1
- package/dist/build-info.json +1 -1
- package/dist/bundle/amazon-bedrock.js +3 -3
- package/dist/bundle/{anthropic-UV5GZDGU.js → anthropic-5PSCZEER.js} +2 -7
- package/dist/bundle/{azure-openai-responses-WSNPXLYC.js → azure-openai-responses-AYTLJR33.js} +2 -2
- package/dist/bundle/{bundled-modules-MEACET4U.js → bundled-modules-IGMJH2MU.js} +5 -5
- package/dist/bundle/{chunk-UPVDERMD.js → chunk-2IPDSTDR.js} +11 -9
- package/dist/bundle/chunk-D3KOF57W.js +22040 -0
- package/dist/bundle/{chunk-QKI6KEGP.js → chunk-EXEFSSF4.js} +1509 -577
- package/dist/bundle/{chunk-VSIYFWYI.js → chunk-KT2BNEPE.js} +21 -8
- package/dist/bundle/{chunk-KTNETTHI.js → chunk-Q3MBSBEB.js} +3 -101
- package/dist/bundle/{chunk-LFPWHI42.js → chunk-QKIFBA7N.js} +2 -2
- package/dist/bundle/{chunk-LIZVVGHR.js → chunk-RVJVXZCS.js} +13 -10
- package/dist/bundle/{cli-main-ANUJY7Y4.js → cli-main-BUK7QTHO.js} +4 -4
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/{google-T32FMD4G.js → google-HTMCUJ7X.js} +2 -2
- package/dist/bundle/{google-vertex-56KP6I3B.js → google-vertex-ZQO65AXF.js} +2 -2
- package/dist/bundle/{main-4GIKOHIT.js → main-2FWHT2WZ.js} +5 -5
- package/dist/bundle/{mistral-WGBMYIVU.js → mistral-SB7LU56G.js} +1 -1
- package/dist/bundle/{openai-codex-responses-PIV2RQ3G.js → openai-codex-responses-5CEW4VN3.js} +53 -27
- package/dist/bundle/{openai-completions-64C3JPR4.js → openai-completions-BAZJQSS2.js} +1 -1
- package/dist/bundle/{openai-responses-UI7RSTDV.js → openai-responses-VHOE427P.js} +48 -5
- package/dist/core/agent-session.d.ts +6 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +189 -31
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/canonical-context.d.ts +8 -0
- package/dist/core/canonical-context.d.ts.map +1 -1
- package/dist/core/canonical-context.js +37 -5
- package/dist/core/canonical-context.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +2 -2
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +31 -13
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/context-epoch.d.ts +1 -1
- package/dist/core/context-epoch.d.ts.map +1 -1
- package/dist/core/context-epoch.js +20 -12
- package/dist/core/context-epoch.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/history-index-worker.d.ts.map +1 -1
- package/dist/core/history-index-worker.js +29 -8
- package/dist/core/history-index-worker.js.map +1 -1
- package/dist/core/history-index.d.ts +11 -1
- package/dist/core/history-index.d.ts.map +1 -1
- package/dist/core/history-index.js +2 -1
- package/dist/core/history-index.js.map +1 -1
- package/dist/core/inference-coordinator.d.ts.map +1 -1
- package/dist/core/inference-coordinator.js +110 -13
- package/dist/core/inference-coordinator.js.map +1 -1
- package/dist/core/kernel/bootstrap.d.ts.map +1 -1
- package/dist/core/kernel/bootstrap.js +97 -107
- package/dist/core/kernel/bootstrap.js.map +1 -1
- package/dist/core/kernel/repl-manager.d.ts.map +1 -1
- package/dist/core/kernel/repl-manager.js +11 -0
- package/dist/core/kernel/repl-manager.js.map +1 -1
- package/dist/core/kernel/shared.d.ts +2 -0
- package/dist/core/kernel/shared.d.ts.map +1 -1
- package/dist/core/kernel/shared.js.map +1 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +4 -1
- package/dist/core/messages.js.map +1 -1
- package/dist/core/prompts/rlm.d.ts.map +1 -1
- package/dist/core/prompts/rlm.js +4 -2
- package/dist/core/prompts/rlm.js.map +1 -1
- package/dist/core/public-context.d.ts.map +1 -1
- package/dist/core/public-context.js +16 -0
- package/dist/core/public-context.js.map +1 -1
- package/dist/core/refinement/refinement.d.ts +19 -5
- package/dist/core/refinement/refinement.d.ts.map +1 -1
- package/dist/core/refinement/refinement.js +90 -35
- package/dist/core/refinement/refinement.js.map +1 -1
- package/dist/core/request-view-selection.d.ts +12 -4
- package/dist/core/request-view-selection.d.ts.map +1 -1
- package/dist/core/request-view-selection.js +242 -100
- package/dist/core/request-view-selection.js.map +1 -1
- package/dist/core/retained-tool-output.d.ts +28 -0
- package/dist/core/retained-tool-output.d.ts.map +1 -0
- package/dist/core/retained-tool-output.js +102 -0
- package/dist/core/retained-tool-output.js.map +1 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/selective-recovery.d.ts +47 -3
- package/dist/core/selective-recovery.d.ts.map +1 -1
- package/dist/core/selective-recovery.js +428 -109
- package/dist/core/selective-recovery.js.map +1 -1
- package/dist/core/session-history-index.d.ts +3 -1
- package/dist/core/session-history-index.d.ts.map +1 -1
- package/dist/core/session-history-index.js +1 -1
- package/dist/core/session-history-index.js.map +1 -1
- package/dist/core/settings-manager.d.ts +5 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +3 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.d.ts +3 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +3 -3
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/task-frame.d.ts +1 -1
- package/dist/core/task-frame.d.ts.map +1 -1
- package/dist/core/task-frame.js +21 -1
- package/dist/core/task-frame.js.map +1 -1
- package/dist/core/task-state-reader.d.ts +10 -2
- package/dist/core/task-state-reader.d.ts.map +1 -1
- package/dist/core/task-state-reader.js +75 -9
- package/dist/core/task-state-reader.js.map +1 -1
- package/dist/core/tools/ipython.d.ts +5 -0
- package/dist/core/tools/ipython.d.ts.map +1 -1
- package/dist/core/tools/ipython.js +59 -17
- package/dist/core/tools/ipython.js.map +1 -1
- package/dist/core/tools/prime-context.d.ts.map +1 -1
- package/dist/core/tools/prime-context.js +1 -1
- package/dist/core/tools/prime-context.js.map +1 -1
- package/dist/core/view-units.d.ts +4 -0
- package/dist/core/view-units.d.ts.map +1 -1
- package/dist/core/view-units.js +28 -19
- package/dist/core/view-units.js.map +1 -1
- package/dist/installer.mjs +98 -77
- package/dist/modes/interactive/components/refinement-outcome-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/refinement-outcome-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +5 -5
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/skills/skill-creator/SKILL.md +18 -1
- package/docs/settings.md +45 -0
- package/docs/skills.md +77 -2
- package/package.json +4 -4
- package/skills/skill-creator/SKILL.md +18 -1
- package/dist/bundle/chunk-W46VZFI6.js +0 -21681
package/dist/core/sdk.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAiE,MAAM,kCAAkC,CAAC;AACxH,OAAO,EAAE,kBAAkB,EAA4B,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAC/G,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,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AO,CAAC,iBAAiB,EAAE,qBAAqB,EAAE,CAAC;YAC1D,CAAC;QACF,CAAC;QAAC,OAAO,YAAY,EAAE,CAAC;YACvB,IAAI,YAAY,KAAK,KAAK,IAAI,CAAC,KAAK,YAAY,cAAc,IAAI,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;gBACrG,MAAM,KAAK,CAAC;YACb,MAAM,IAAI,cAAc,CAAC,CAAC,KAAK,EAAE,YAAY,CAAC,EAAE,qCAAqC,CAAC,CAAC;QACxF,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AAAA,CACD","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type AgentOutputLimits, type ThinkingLevel } from \"@ponythewhite/base-context-agent\";\nimport { clampThinkingLevel, type Message, type Model, supportsFastMode } from \"@ponythewhite/base-context-ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport type { AgentAutonomousConfig } from \"./autonomous.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { createNativeInferenceStream } from \"./inference-coordinator.js\";\nimport { McpManager } from \"./mcp/mcp-manager.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { readSessionBootstrap } from \"./session-bootstrap.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateIpythonTool,\n\tcreatePrimeContextTool,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions extends AgentSessionCreationOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.base-context */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json).\n\t * Existing host Codex subscriptions can be injected with\n\t * AuthStorage.fromStorage(readOnlyBackend, { existingOpenAICodexSubscription: true }).\n\t * This retains the built-in owned dispatcher; it does not enable OAuth login/refresh.\n\t */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Undefined restores a saved explicit choice; null leaves the session unselected. */\n\tmodel?: Model<any> | null;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (ipython and prime_context)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, Base Context enables the default built-in tools (ipython and prime_context)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** MCP integration manager. When omitted, MCP host handlers are not wired. */\n\tmcpManager?: McpManager;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Override complete native invocation output limits from settings. */\n\tinvocationOutputLimits?: AgentOutputLimits;\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Host-side autonomous continuation policy. */\n\tautonomous?: AgentAutonomousConfig;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Diagnostic when the selected session or saved model cannot be used. */\n\tmodelFallbackMessage?: string;\n}\n\nexport type { AgentSessionRuntimeConfig } from \"./agent-session-config.js\";\nexport * from \"./agent-session-runtime.js\";\nexport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type {\n\tRlmMaxSubagentsStatus,\n\tRlmRootAdmission,\n\tRlmSubagentCapacity,\n\tRlmSubagentCapacityReservation,\n} from \"./rlm-max-subagents.js\";\nexport type {\n\tCreateRlmSubagentRuntimeOptions,\n\tRlmChildAdmission,\n\tRlmSubagentRuntime,\n\tSubagentRuntimeHost,\n} from \"./rlm-runtime.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport { createBashTool, createEditTool, createIpythonTool, createPrimeContextTool, withFileMutationQueue };\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@ponythewhite/base-context-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"ipython\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst contextMode = options.contextMode;\n\tif (options.requestTokenBudget)\n\t\toptions = { ...options, requestTokenBudget: structuredClone(options.requestTokenBudget) };\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager =\n\t\toptions.sessionManager ?? (await SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir)));\n\n\tlet session: AgentSession | undefined;\n\ttry {\n\t\t// Ensure MCP providers are registered and built-in MCP skills are gated by\n\t\t// auth even on the bare SDK path (not just the CLI's createAgentSessionServices).\n\t\tconst mcpManager =\n\t\t\toptions.mcpManager ??\n\t\t\tnew McpManager({ authStorage, getUserServers: () => settingsManager.getGlobalMcpServers() });\n\t\tmodelRegistry.setOnOAuthProvidersReset(() => mcpManager.registerUserProviders());\n\n\t\tif (!resourceLoader) {\n\t\t\tresourceLoader = new DefaultResourceLoader({\n\t\t\t\tcwd,\n\t\t\t\tagentDir,\n\t\t\t\tsettingsManager,\n\t\t\t\textraBuiltinSkillOverrides: () => mcpManager.getDisabledBuiltinSkillOverrides(),\n\t\t\t});\n\t\t\tawait resourceLoader.reload();\n\t\t\ttime(\"resourceLoader.reload\");\n\t\t}\n\n\t\tconst {\n\t\t\tcontext: existingSession,\n\t\t\thasExistingSession,\n\t\t\thasThinkingEntry,\n\t\t\thasServiceTierEntry,\n\t\t} = await readSessionBootstrap(sessionManager, settingsManager.getCanonicalContextLimits(), {\n\t\t\tallowPendingToolPublic: options.requestTokenBudget !== undefined,\n\t\t\tinitialContextMode: contextMode ?? settingsManager.getContextMode(),\n\t\t});\n\n\t\tlet model = options.model ?? undefined;\n\t\tlet modelFallbackMessage: string | undefined;\n\n\t\tif (options.model === undefined && hasExistingSession && existingSession.model) {\n\t\t\tconst saved = existingSession.model;\n\t\t\tconst restoredModel = modelRegistry.find(saved.provider, saved.modelId);\n\t\t\tmodel = restoredModel;\n\t\t\tif (!restoredModel) {\n\t\t\t\tmodelFallbackMessage = `Could not restore model ${saved.provider}/${saved.modelId}. Use /model to select a supported model.`;\n\t\t\t} else if (!modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${saved.provider}/${saved.modelId} needs authentication. Use /login to configure this provider.`;\n\t\t\t}\n\t\t} else if (options.model === undefined) {\n\t\t\tconst result = await findInitialModel({\n\t\t\t\tscopedModels: [],\n\t\t\t\tisContinuing: hasExistingSession,\n\t\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\t\tmodelRegistry,\n\t\t\t});\n\t\t\tmodel = result.model;\n\t\t\tif (model && !modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`;\n\t\t\t} else if (!model) {\n\t\t\t\tconst provider = settingsManager.getDefaultProvider();\n\t\t\t\tconst modelId = settingsManager.getDefaultModel();\n\t\t\t\tmodelFallbackMessage =\n\t\t\t\t\tprovider && modelId\n\t\t\t\t\t\t? `Selected model ${provider}/${modelId} is unavailable. Use /model to select a supported model.`\n\t\t\t\t\t\t: formatNoModelsAvailableMessage();\n\t\t\t}\n\t\t}\n\n\t\tlet thinkingLevel = options.thinkingLevel;\n\n\t\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\t\tthinkingLevel = hasThinkingEntry\n\t\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t\t}\n\n\t\tif (thinkingLevel === undefined) {\n\t\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t\t}\n\n\t\tif (!model) {\n\t\t\tthinkingLevel = \"off\";\n\t\t} else {\n\t\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t\t}\n\n\t\tconst serviceTierPreference =\n\t\t\toptions.serviceTier ??\n\t\t\t(hasServiceTierEntry ? existingSession.serviceTier : settingsManager.getDefaultServiceTier());\n\t\tconst serviceTier =\n\t\t\tserviceTierPreference === \"priority\" && (!model || !supportsFastMode(model))\n\t\t\t\t? \"default\"\n\t\t\t\t: serviceTierPreference;\n\n\t\tconst allowedToolNames =\n\t\t\toptions.allowedToolNames ?? options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\t\tconst includeGoals = options.includeGoals ?? (options.tools !== undefined || options.noTools !== \"all\");\n\t\tconst initialActiveToolNames: string[] =\n\t\t\toptions.initialActiveToolNames ??\n\t\t\t(options.tools ? [...options.tools] : options.noTools ? [] : [\"ipython\", \"prime_context\"]);\n\n\t\tlet agent: Agent;\n\n\t\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\t\tconst converted = convertToLlm(messages);\n\t\t\tif (!settingsManager.getBlockImages()) {\n\t\t\t\treturn converted;\n\t\t\t}\n\t\t\treturn converted.map((msg) => {\n\t\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\t\tconst content = msg.content;\n\t\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn msg;\n\t\t\t});\n\t\t};\n\n\t\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\t\tagent = new Agent({\n\t\t\tinitialState: {\n\t\t\t\tsystemPrompt: \"\",\n\t\t\t\tmodel,\n\t\t\t\tthinkingLevel,\n\t\t\t\tserviceTier,\n\t\t\t\ttools: [],\n\t\t\t},\n\t\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\t\tstreamFn: createNativeInferenceStream(async (model, _context, options) => {\n\t\t\t\tif (!modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!auth.ok) {\n\t\t\t\t\tthrow new Error(auth.error);\n\t\t\t\t}\n\t\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\t\treturn {\n\t\t\t\t\t...options,\n\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\tauthSourceToken: auth.sourceToken,\n\t\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\t\theaders: auth.headers || options?.headers ? { ...auth.headers, ...options?.headers } : undefined,\n\t\t\t\t};\n\t\t\t}),\n\t\t\tonPayload: async (payload, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\t\treturn payload;\n\t\t\t\t}\n\t\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t\t},\n\t\t\tonResponse: async (response, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait runner.emit({\n\t\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: response.headers,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsessionId: sessionManager.getSessionId(),\n\t\t\ttransformContext: async (messages) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner) return messages;\n\t\t\t\treturn runner.emitContext(messages);\n\t\t\t},\n\t\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\t\ttransport: settingsManager.getTransport(),\n\t\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\t});\n\n\t\tif (hasExistingSession) {\n\t\t\tagent.state.messages = existingSession.messages;\n\t\t\tif (!hasThinkingEntry) {\n\t\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t\t}\n\t\t} else {\n\t\t\tif (model) {\n\t\t\t\tawait sessionManager.appendModelChange(model.provider, model.id);\n\t\t\t}\n\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t\tif (!hasServiceTierEntry) {\n\t\t\tawait sessionManager.appendServiceTierChange(serviceTierPreference);\n\t\t}\n\n\t\tsession = new AgentSession({\n\t\t\tinvocationOutputLimits: options.invocationOutputLimits,\n\t\t\trequestTokenBudget: options.requestTokenBudget,\n\t\t\tcontextMode,\n\t\t\tagent,\n\t\t\tsessionManager,\n\t\t\tsettingsManager,\n\t\t\tserviceTierPreference,\n\t\t\tcwd,\n\t\t\t// Only the explicit dir — the default may not match injected custom storage.\n\t\t\tagentDir: options.agentDir,\n\t\t\tscopedModels: options.scopedModels,\n\t\t\tresourceLoader,\n\t\t\tcustomTools: options.customTools,\n\t\t\tmodelRegistry,\n\t\t\tmcpManager,\n\t\t\tinitialActiveToolNames,\n\t\t\tallowedToolNames,\n\t\t\tincludeGoals,\n\t\t\tincludeCompactSkill: options.includeCompactSkill,\n\t\t\trlmHeartbeatController: options.rlmHeartbeatController,\n\t\t\tagentMessageController: options.agentMessageController,\n\t\t\tagentObserveController: options.agentObserveController,\n\t\t\textensionRunnerRef,\n\t\t\trlmDepth: options.rlmDepth,\n\t\t\trlmMaxDepth: options.rlmMaxDepth,\n\t\t\trlmSessionDir: options.rlmSessionDir,\n\t\t\trlmParentNodeId: options.rlmParentNodeId,\n\t\t\trlmParentAgent: options.rlmParentAgent,\n\t\t\trlmChildAdmission: options.rlmChildAdmission,\n\t\t\trlmSubagentCapacity: options.rlmSubagentCapacity,\n\t\t\trlmRootAdmission: options.rlmRootAdmission,\n\t\t\tsemanticParentSessionId: options.semanticParentSessionId,\n\t\t\tsemanticSpawnedByRequestId: options.semanticSpawnedByRequestId,\n\t\t\tsubagentRuntimeHost: options.subagentRuntimeHost,\n\t\t\tsessionStartEvent: options.sessionStartEvent,\n\t\t\tprewarmIpythonKernel: options.prewarmIpythonKernel,\n\t\t\tautonomous: options.autonomous,\n\t\t\tserializedRefine: options.serializedRefine,\n\t\t\tinitialGoal: options.initialGoal,\n\t\t});\n\t\tawait session.initialize();\n\t\tconst extensionsResult = resourceLoader.getExtensions();\n\n\t\treturn {\n\t\t\tsession,\n\t\t\textensionsResult,\n\t\t\tmodelFallbackMessage,\n\t\t};\n\t} catch (error) {\n\t\ttry {\n\t\t\tconst admitted = options.rlmChildAdmission?.session ?? options.rlmRootAdmission?.session;\n\t\t\tconst failedSession = session ?? (admitted?.sessionManager === sessionManager ? admitted : undefined);\n\t\t\tif (failedSession) await failedSession.disposeAsync();\n\t\t\telse {\n\t\t\t\tawait sessionManager.close();\n\t\t\t\tawait options.rlmChildAdmission?.confirmUnboundCleanup();\n\t\t\t}\n\t\t} catch (cleanupError) {\n\t\t\tif (cleanupError === error || (error instanceof AggregateError && error.errors.includes(cleanupError)))\n\t\t\t\tthrow error;\n\t\t\tthrow new AggregateError([error, cleanupError], \"Session creation and cleanup failed\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAiE,MAAM,kCAAkC,CAA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,MAAM,aAAa,CAAC,YAAY,EAAE,CAAC;iBACjD,CAAC;gBACL,MAAM,cAAc,CAAC,KAAK,EAAE,CAAC;gBAC7B,MAAM,OAAO,CAAC,iBAAiB,EAAE,qBAAqB,EAAE,CAAC;YAC1D,CAAC;QACF,CAAC;QAAC,OAAO,YAAY,EAAE,CAAC;YACvB,IAAI,YAAY,KAAK,KAAK,IAAI,CAAC,KAAK,YAAY,cAAc,IAAI,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;gBACrG,MAAM,KAAK,CAAC;YACb,MAAM,IAAI,cAAc,CAAC,CAAC,KAAK,EAAE,YAAY,CAAC,EAAE,qCAAqC,CAAC,CAAC;QACxF,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AAAA,CACD","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type AgentOutputLimits, type ThinkingLevel } from \"@ponythewhite/base-context-agent\";\nimport { clampThinkingLevel, type Message, type Model, supportsFastMode } from \"@ponythewhite/base-context-ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport type { AgentAutonomousConfig } from \"./autonomous.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { createNativeInferenceStream } from \"./inference-coordinator.js\";\nimport { McpManager } from \"./mcp/mcp-manager.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { readSessionBootstrap } from \"./session-bootstrap.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateIpythonTool,\n\tcreatePrimeContextTool,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions extends AgentSessionCreationOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.base-context */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json).\n\t * Existing host Codex subscriptions can be injected with\n\t * AuthStorage.fromStorage(readOnlyBackend, { existingOpenAICodexSubscription: true }).\n\t * This retains the built-in owned dispatcher; it does not enable OAuth login/refresh.\n\t */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Undefined restores a saved explicit choice; null leaves the session unselected. */\n\tmodel?: Model<any> | null;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (ipython and prime_context)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, Base Context enables the default built-in tools (ipython and prime_context)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** MCP integration manager. When omitted, MCP host handlers are not wired. */\n\tmcpManager?: McpManager;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Override complete native invocation output limits from settings. */\n\tinvocationOutputLimits?: AgentOutputLimits;\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Host-side autonomous continuation policy. */\n\tautonomous?: AgentAutonomousConfig;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Diagnostic when the selected session or saved model cannot be used. */\n\tmodelFallbackMessage?: string;\n}\n\nexport type { AgentSessionRuntimeConfig } from \"./agent-session-config.js\";\nexport * from \"./agent-session-runtime.js\";\nexport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type {\n\tRlmMaxSubagentsStatus,\n\tRlmRootAdmission,\n\tRlmSubagentCapacity,\n\tRlmSubagentCapacityReservation,\n} from \"./rlm-max-subagents.js\";\nexport type {\n\tCreateRlmSubagentRuntimeOptions,\n\tRlmChildAdmission,\n\tRlmSubagentRuntime,\n\tSubagentRuntimeHost,\n} from \"./rlm-runtime.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport { createBashTool, createEditTool, createIpythonTool, createPrimeContextTool, withFileMutationQueue };\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@ponythewhite/base-context-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"ipython\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst contextMode = options.contextMode;\n\tif (options.requestTokenBudget)\n\t\toptions = { ...options, requestTokenBudget: structuredClone(options.requestTokenBudget) };\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager =\n\t\toptions.sessionManager ?? (await SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir)));\n\n\tlet session: AgentSession | undefined;\n\ttry {\n\t\t// Ensure MCP providers are registered and built-in MCP skills are gated by\n\t\t// auth even on the bare SDK path (not just the CLI's createAgentSessionServices).\n\t\tconst mcpManager =\n\t\t\toptions.mcpManager ??\n\t\t\tnew McpManager({ authStorage, getUserServers: () => settingsManager.getGlobalMcpServers() });\n\t\tmodelRegistry.setOnOAuthProvidersReset(() => mcpManager.registerUserProviders());\n\n\t\tif (!resourceLoader) {\n\t\t\tresourceLoader = new DefaultResourceLoader({\n\t\t\t\tcwd,\n\t\t\t\tagentDir,\n\t\t\t\tsettingsManager,\n\t\t\t\textraBuiltinSkillOverrides: () => mcpManager.getDisabledBuiltinSkillOverrides(),\n\t\t\t});\n\t\t\tawait resourceLoader.reload();\n\t\t\ttime(\"resourceLoader.reload\");\n\t\t}\n\n\t\tconst {\n\t\t\tcontext: existingSession,\n\t\t\thasExistingSession,\n\t\t\thasThinkingEntry,\n\t\t\thasServiceTierEntry,\n\t\t} = await readSessionBootstrap(sessionManager, settingsManager.getCanonicalContextLimits(), {\n\t\t\tpurpose: \"read\",\n\t\t\tinitialContextMode: contextMode ?? settingsManager.getContextMode(),\n\t\t});\n\n\t\tlet model = options.model ?? undefined;\n\t\tlet modelFallbackMessage: string | undefined;\n\n\t\tif (options.model === undefined && hasExistingSession && existingSession.model) {\n\t\t\tconst saved = existingSession.model;\n\t\t\tconst restoredModel = modelRegistry.find(saved.provider, saved.modelId);\n\t\t\tmodel = restoredModel;\n\t\t\tif (!restoredModel) {\n\t\t\t\tmodelFallbackMessage = `Could not restore model ${saved.provider}/${saved.modelId}. Use /model to select a supported model.`;\n\t\t\t} else if (!modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${saved.provider}/${saved.modelId} needs authentication. Use /login to configure this provider.`;\n\t\t\t}\n\t\t} else if (options.model === undefined) {\n\t\t\tconst result = await findInitialModel({\n\t\t\t\tscopedModels: [],\n\t\t\t\tisContinuing: hasExistingSession,\n\t\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\t\tmodelRegistry,\n\t\t\t});\n\t\t\tmodel = result.model;\n\t\t\tif (model && !modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`;\n\t\t\t} else if (!model) {\n\t\t\t\tconst provider = settingsManager.getDefaultProvider();\n\t\t\t\tconst modelId = settingsManager.getDefaultModel();\n\t\t\t\tmodelFallbackMessage =\n\t\t\t\t\tprovider && modelId\n\t\t\t\t\t\t? `Selected model ${provider}/${modelId} is unavailable. Use /model to select a supported model.`\n\t\t\t\t\t\t: formatNoModelsAvailableMessage();\n\t\t\t}\n\t\t}\n\n\t\tlet thinkingLevel = options.thinkingLevel;\n\n\t\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\t\tthinkingLevel = hasThinkingEntry\n\t\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t\t}\n\n\t\tif (thinkingLevel === undefined) {\n\t\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t\t}\n\n\t\tif (!model) {\n\t\t\tthinkingLevel = \"off\";\n\t\t} else {\n\t\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t\t}\n\n\t\tconst serviceTierPreference =\n\t\t\toptions.serviceTier ??\n\t\t\t(hasServiceTierEntry ? existingSession.serviceTier : settingsManager.getDefaultServiceTier());\n\t\tconst serviceTier =\n\t\t\tserviceTierPreference === \"priority\" && (!model || !supportsFastMode(model))\n\t\t\t\t? \"default\"\n\t\t\t\t: serviceTierPreference;\n\n\t\tconst allowedToolNames =\n\t\t\toptions.allowedToolNames ?? options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\t\tconst includeGoals = options.includeGoals ?? (options.tools !== undefined || options.noTools !== \"all\");\n\t\tconst initialActiveToolNames: string[] =\n\t\t\toptions.initialActiveToolNames ??\n\t\t\t(options.tools ? [...options.tools] : options.noTools ? [] : [\"ipython\", \"prime_context\"]);\n\n\t\tlet agent: Agent;\n\n\t\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\t\tconst converted = convertToLlm(messages);\n\t\t\tif (!settingsManager.getBlockImages()) {\n\t\t\t\treturn converted;\n\t\t\t}\n\t\t\treturn converted.map((msg) => {\n\t\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\t\tconst content = msg.content;\n\t\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn msg;\n\t\t\t});\n\t\t};\n\n\t\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\t\tagent = new Agent({\n\t\t\tinitialState: {\n\t\t\t\tsystemPrompt: \"\",\n\t\t\t\tmodel,\n\t\t\t\tthinkingLevel,\n\t\t\t\tserviceTier,\n\t\t\t\ttools: [],\n\t\t\t},\n\t\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\t\tstreamFn: createNativeInferenceStream(async (model, _context, options) => {\n\t\t\t\tif (!modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!auth.ok) {\n\t\t\t\t\tthrow new Error(auth.error);\n\t\t\t\t}\n\t\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\t\treturn {\n\t\t\t\t\t...options,\n\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\tauthSourceToken: auth.sourceToken,\n\t\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\t\theaders: auth.headers || options?.headers ? { ...auth.headers, ...options?.headers } : undefined,\n\t\t\t\t};\n\t\t\t}),\n\t\t\tonPayload: async (payload, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\t\treturn payload;\n\t\t\t\t}\n\t\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t\t},\n\t\t\tonResponse: async (response, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait runner.emit({\n\t\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: response.headers,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsessionId: sessionManager.getSessionId(),\n\t\t\ttransformContext: async (messages) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner) return messages;\n\t\t\t\treturn runner.emitContext(messages);\n\t\t\t},\n\t\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\t\ttransport: settingsManager.getTransport(),\n\t\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\t});\n\n\t\tif (hasExistingSession) {\n\t\t\tagent.state.messages = existingSession.messages;\n\t\t\tif (!hasThinkingEntry) {\n\t\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t\t}\n\t\t} else {\n\t\t\tif (model) {\n\t\t\t\tawait sessionManager.appendModelChange(model.provider, model.id);\n\t\t\t}\n\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t\tif (!hasServiceTierEntry) {\n\t\t\tawait sessionManager.appendServiceTierChange(serviceTierPreference);\n\t\t}\n\n\t\tsession = new AgentSession({\n\t\t\tinvocationOutputLimits: options.invocationOutputLimits,\n\t\t\trequestTokenBudget: options.requestTokenBudget,\n\t\t\tcontextMode,\n\t\t\tagent,\n\t\t\tsessionManager,\n\t\t\tsettingsManager,\n\t\t\tserviceTierPreference,\n\t\t\tcwd,\n\t\t\t// Only the explicit dir — the default may not match injected custom storage.\n\t\t\tagentDir: options.agentDir,\n\t\t\tscopedModels: options.scopedModels,\n\t\t\tresourceLoader,\n\t\t\tcustomTools: options.customTools,\n\t\t\tmodelRegistry,\n\t\t\tmcpManager,\n\t\t\tinitialActiveToolNames,\n\t\t\tallowedToolNames,\n\t\t\tincludeGoals,\n\t\t\tincludeCompactSkill: options.includeCompactSkill,\n\t\t\trlmHeartbeatController: options.rlmHeartbeatController,\n\t\t\tagentMessageController: options.agentMessageController,\n\t\t\tagentObserveController: options.agentObserveController,\n\t\t\textensionRunnerRef,\n\t\t\trlmDepth: options.rlmDepth,\n\t\t\trlmMaxDepth: options.rlmMaxDepth,\n\t\t\trlmSessionDir: options.rlmSessionDir,\n\t\t\trlmParentNodeId: options.rlmParentNodeId,\n\t\t\trlmParentAgent: options.rlmParentAgent,\n\t\t\trlmChildAdmission: options.rlmChildAdmission,\n\t\t\trlmSubagentCapacity: options.rlmSubagentCapacity,\n\t\t\trlmRootAdmission: options.rlmRootAdmission,\n\t\t\tsemanticParentSessionId: options.semanticParentSessionId,\n\t\t\tsemanticSpawnedByRequestId: options.semanticSpawnedByRequestId,\n\t\t\tsubagentRuntimeHost: options.subagentRuntimeHost,\n\t\t\tsessionStartEvent: options.sessionStartEvent,\n\t\t\tprewarmIpythonKernel: options.prewarmIpythonKernel,\n\t\t\tautonomous: options.autonomous,\n\t\t\tserializedRefine: options.serializedRefine,\n\t\t\tinitialGoal: options.initialGoal,\n\t\t});\n\t\tawait session.initialize();\n\t\tconst extensionsResult = resourceLoader.getExtensions();\n\n\t\treturn {\n\t\t\tsession,\n\t\t\textensionsResult,\n\t\t\tmodelFallbackMessage,\n\t\t};\n\t} catch (error) {\n\t\ttry {\n\t\t\tconst admitted = options.rlmChildAdmission?.session ?? options.rlmRootAdmission?.session;\n\t\t\tconst failedSession = session ?? (admitted?.sessionManager === sessionManager ? admitted : undefined);\n\t\t\tif (failedSession) await failedSession.disposeAsync();\n\t\t\telse {\n\t\t\t\tawait sessionManager.close();\n\t\t\t\tawait options.rlmChildAdmission?.confirmUnboundCleanup();\n\t\t\t}\n\t\t} catch (cleanupError) {\n\t\t\tif (cleanupError === error || (error instanceof AggregateError && error.errors.includes(cleanupError)))\n\t\t\t\tthrow error;\n\t\t\tthrow new AggregateError([error, cleanupError], \"Session creation and cleanup failed\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type Static, Type } from "typebox";
|
|
2
|
+
import type { SourceSnapshotRef } from "./request-events.js";
|
|
2
3
|
import { type SessionHistoryReadView } from "./session-history-index.js";
|
|
3
4
|
export interface NativeRecoveryLimits {
|
|
4
5
|
maxBytes: number;
|
|
@@ -11,6 +12,9 @@ export declare const DEFAULT_NATIVE_RECOVERY_LIMITS: Readonly<NativeRecoveryLimi
|
|
|
11
12
|
declare const operationSchema: Type.TObject<{
|
|
12
13
|
action: Type.TUnion<[Type.TLiteral<"read">, Type.TLiteral<"search">, Type.TLiteral<"recover">]>;
|
|
13
14
|
ref: Type.TOptional<Type.TString>;
|
|
15
|
+
cursor: Type.TOptional<Type.TString>;
|
|
16
|
+
startByte: Type.TOptional<Type.TInteger>;
|
|
17
|
+
endByte: Type.TOptional<Type.TInteger>;
|
|
14
18
|
revision: Type.TOptional<Type.TString>;
|
|
15
19
|
sourceSessionId: Type.TOptional<Type.TString>;
|
|
16
20
|
field: Type.TOptional<Type.TString>;
|
|
@@ -24,6 +28,9 @@ declare const operationSchema: Type.TObject<{
|
|
|
24
28
|
export declare const nativeRecoveryInputSchema: Type.TUnion<[Type.TObject<{
|
|
25
29
|
action: Type.TUnion<[Type.TLiteral<"read">, Type.TLiteral<"search">, Type.TLiteral<"recover">]>;
|
|
26
30
|
ref: Type.TOptional<Type.TString>;
|
|
31
|
+
cursor: Type.TOptional<Type.TString>;
|
|
32
|
+
startByte: Type.TOptional<Type.TInteger>;
|
|
33
|
+
endByte: Type.TOptional<Type.TInteger>;
|
|
27
34
|
revision: Type.TOptional<Type.TString>;
|
|
28
35
|
sourceSessionId: Type.TOptional<Type.TString>;
|
|
29
36
|
field: Type.TOptional<Type.TString>;
|
|
@@ -41,6 +48,9 @@ export declare const nativeRecoveryInputSchema: Type.TUnion<[Type.TObject<{
|
|
|
41
48
|
requests: Type.TArray<Type.TObject<{
|
|
42
49
|
action: Type.TUnion<[Type.TLiteral<"read">, Type.TLiteral<"search">, Type.TLiteral<"recover">]>;
|
|
43
50
|
ref: Type.TOptional<Type.TString>;
|
|
51
|
+
cursor: Type.TOptional<Type.TString>;
|
|
52
|
+
startByte: Type.TOptional<Type.TInteger>;
|
|
53
|
+
endByte: Type.TOptional<Type.TInteger>;
|
|
44
54
|
revision: Type.TOptional<Type.TString>;
|
|
45
55
|
sourceSessionId: Type.TOptional<Type.TString>;
|
|
46
56
|
field: Type.TOptional<Type.TString>;
|
|
@@ -55,6 +65,9 @@ export declare const nativeRecoveryInputSchema: Type.TUnion<[Type.TObject<{
|
|
|
55
65
|
/** Provider-facing tools require an object root; execute still applies the strict union above. */
|
|
56
66
|
export declare const nativeRecoveryToolSchema: Type.TObject<{
|
|
57
67
|
ref: Type.TOptional<Type.TString>;
|
|
68
|
+
cursor: Type.TOptional<Type.TString>;
|
|
69
|
+
startByte: Type.TOptional<Type.TInteger>;
|
|
70
|
+
endByte: Type.TOptional<Type.TInteger>;
|
|
58
71
|
revision: Type.TOptional<Type.TString>;
|
|
59
72
|
sourceSessionId: Type.TOptional<Type.TString>;
|
|
60
73
|
field: Type.TOptional<Type.TString>;
|
|
@@ -67,6 +80,9 @@ export declare const nativeRecoveryToolSchema: Type.TObject<{
|
|
|
67
80
|
name: Type.TOptional<Type.TString>;
|
|
68
81
|
requests: Type.TOptional<Type.TArray<Type.TObject<{
|
|
69
82
|
ref: Type.TOptional<Type.TString>;
|
|
83
|
+
cursor: Type.TOptional<Type.TString>;
|
|
84
|
+
startByte: Type.TOptional<Type.TInteger>;
|
|
85
|
+
endByte: Type.TOptional<Type.TInteger>;
|
|
70
86
|
revision: Type.TOptional<Type.TString>;
|
|
71
87
|
sourceSessionId: Type.TOptional<Type.TString>;
|
|
72
88
|
field: Type.TOptional<Type.TString>;
|
|
@@ -95,8 +111,12 @@ export interface NativeRecoverySource {
|
|
|
95
111
|
entryId: string;
|
|
96
112
|
revision: string;
|
|
97
113
|
field: string;
|
|
98
|
-
startLine
|
|
99
|
-
endLine
|
|
114
|
+
startLine?: number;
|
|
115
|
+
endLine?: number;
|
|
116
|
+
startByte?: number;
|
|
117
|
+
endByte?: number;
|
|
118
|
+
prefixOmitted?: boolean;
|
|
119
|
+
suffixOmitted?: boolean;
|
|
100
120
|
}
|
|
101
121
|
export interface NativeRecoveryRecord extends Omit<NativeRecoverySource, "entryId"> {
|
|
102
122
|
ref: string;
|
|
@@ -108,6 +128,8 @@ export interface NativeRecoveryResult {
|
|
|
108
128
|
status: NativeRecoveryStatus;
|
|
109
129
|
coverage: NativeRecoveryCoverage;
|
|
110
130
|
records: NativeRecoveryRecord[];
|
|
131
|
+
cursor?: string;
|
|
132
|
+
exhausted?: boolean;
|
|
111
133
|
reason?: string;
|
|
112
134
|
}
|
|
113
135
|
export interface NativeRecoveryResponse {
|
|
@@ -145,7 +167,29 @@ export declare function nativeRecoveryMetadata(response: NativeRecoveryResponse)
|
|
|
145
167
|
export declare function createNativeRecoveryRefusal(status: "not_authorized" | "unavailable" | "budget_refused", reason: string, maxBytes?: number): NativeRecoveryResponse;
|
|
146
168
|
/** Shared runtime admission for the native tool and Python host bridge. */
|
|
147
169
|
export declare function parseNativeRecoveryInput(value: unknown): NativeRecoveryInput;
|
|
170
|
+
interface RecoveryCursorState {
|
|
171
|
+
source: SourceSnapshotRef;
|
|
172
|
+
operation: NativeRecoveryOperation;
|
|
173
|
+
after: number;
|
|
174
|
+
entryId?: string;
|
|
175
|
+
field: number;
|
|
176
|
+
byte: number;
|
|
177
|
+
line: number;
|
|
178
|
+
overlap: string;
|
|
179
|
+
unavailable: boolean;
|
|
180
|
+
matched: boolean;
|
|
181
|
+
}
|
|
182
|
+
/** Session-owned, ephemeral searches. No read lease or canonical body survives a call. */
|
|
183
|
+
export declare class NativeRecoveryCursorStore {
|
|
184
|
+
private readonly states;
|
|
185
|
+
private generation;
|
|
186
|
+
clear(): void;
|
|
187
|
+
get(id: string): RecoveryCursorState | undefined;
|
|
188
|
+
delete(id: string): void;
|
|
189
|
+
get version(): number;
|
|
190
|
+
save(state: RecoveryCursorState, version: number, id?: string): string;
|
|
191
|
+
}
|
|
148
192
|
/** The caller captures ONE server branch before entering this service, including for a batch. */
|
|
149
|
-
export declare function recoverCapturedHistory(view: SessionHistoryReadView, input: NativeRecoveryInput, limits?: NativeRecoveryLimits, signal?: AbortSignal): Promise<NativeRecoveryResponse>;
|
|
193
|
+
export declare function recoverCapturedHistory(view: SessionHistoryReadView, input: NativeRecoveryInput, limits?: NativeRecoveryLimits, signal?: AbortSignal, cursors?: NativeRecoveryCursorStore): Promise<NativeRecoveryResponse>;
|
|
150
194
|
export {};
|
|
151
195
|
//# sourceMappingURL=selective-recovery.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selective-recovery.d.ts","sourceRoot":"","sources":["../../src/core/selective-recovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAM5C,OAAO,EAA+B,KAAK,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAItG,MAAM,WAAW,oBAAoB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,0GAA0G;AAC1G,eAAO,MAAM,8BAA8B,EAAE,QAAQ,CAAC,oBAAoB,CAKxE,CAAC;AAIH,QAAA,MAAM,eAAe;;;;;;;;;;;EA4BpB,CAAC;AAEF,wGAAwG;AACxG,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAcpC,CAAC;AAMH,kGAAkG;AAClG,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;EAQpC,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG,MAAM,CAAC,OAAO,yBAAyB,CAAC,CAAC;AAC3E,MAAM,MAAM,uBAAuB,GAAG,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AACrE,MAAM,MAAM,oBAAoB,GAC7B,OAAO,GACP,eAAe,GACf,SA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EAAE,CAAC;IAChC,OAAO,EAAE,oBAAoB,EAAE,CAAC;IAChC,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,6FAA6F;AAC7F,qBAAa,2BAA4B,SAAQ,KAAK;IACrD,QAAQ,CAAC,MAAM,oBAAoB;IACnC,cAGC;CACD;AAED,wBAAgB,+BAA+B,CAC9C,QAAQ,EAAE,sBAAsB,EAChC,QAAQ,SAA0C,GAChD,MAAM,CAMR;AAED,qFAAqF;AACrF,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,sBAAsB;;;;;;;;;;EAYtE;AAED,sFAAsF;AACtF,wBAAgB,2BAA2B,CAC1C,MAAM,EAAE,gBAAgB,GAAG,aAAa,GAAG,gBAAgB,EAC3D,MAAM,EAAE,MAAM,EACd,QAAQ,SAA0C,GAChD,sBAAsB,CAgBxB;AAsJD,2EAA2E;AAC3E,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,mBAAmB,CAS5E;AAED,iGAAiG;AACjG,wBAAsB,sBAAsB,CAC3C,IAAI,EAAE,sBAAsB,EAC5B,KAAK,EAAE,mBAAmB,EAC1B,MAAM,GAAE,oBAAqD,EAC7D,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,sBAAsB,CAAC,CA2NjC","sourcesContent":["import { StringEnum } from \"@ponythewhite/base-context-ai\";\nimport { type Static, Type } from \"typebox\";\nimport { Value } from \"typebox/value\";\nimport { AGENT_RESULT_CUSTOM_TYPE } from \"./agent-results.js\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport type { IndexedSourceEvent } from \"./history-index.js\";\nimport { SELECTED_SKILL_CUSTOM_TYPE, selectedSkillCapture } from \"./selected-skills.js\";\nimport { hydrateCapturedHistoryEntry, type SessionHistoryReadView } from \"./session-history-index.js\";\nimport type { SessionEntry } from \"./session-manager.js\";\nimport { projectTaskStateSource } from \"./task-state.js\";\n\nexport interface NativeRecoveryLimits {\n\tmaxBytes: number;\n\tmaxSourceBytes: number;\n\tmaxItems: number;\n\tmaxRequests: number;\n}\n\n/** Defaults match bounded index pages and 64KiB payload parts; all admission units are bytes or items. */\nexport const DEFAULT_NATIVE_RECOVERY_LIMITS: Readonly<NativeRecoveryLimits> = Object.freeze({\n\tmaxBytes: 64 * 1024,\n\tmaxSourceBytes: 1024 * 1024,\n\tmaxItems: 16,\n\tmaxRequests: 8,\n});\n\nconst exactString = Type.String({ minLength: 1, maxLength: 512 });\nconst byteLimit = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });\nconst operationSchema = Type.Object(\n\t{\n\t\taction: Type.Union([Type.Literal(\"read\"), Type.Literal(\"search\"), Type.Literal(\"recover\")]),\n\t\tref: Type.Optional(exactString),\n\t\trevision: Type.Optional(exactString),\n\t\tsourceSessionId: Type.Optional(exactString),\n\t\tfield: Type.Optional(exactString),\n\t\tneed: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: 8192,\n\t\t\t\tdescription:\n\t\t\t\t\t\"Literal text selector; alias of query. Prefer one field. If both are supplied, use identical text.\",\n\t\t\t}),\n\t\t),\n\t\tquery: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: 8192,\n\t\t\t\tdescription:\n\t\t\t\t\t\"Literal text selector; alias of need. Prefer one field. If both are supplied, use identical text.\",\n\t\t\t}),\n\t\t),\n\t\tstartLine: Type.Optional(byteLimit),\n\t\tendLine: Type.Optional(byteLimit),\n\t\tmaxBytes: Type.Optional(byteLimit),\n\t},\n\t{ additionalProperties: false },\n);\n\n/** A ref is a case-sensitive entry ID, never a path. Lines are one-based within each selected field. */\nexport const nativeRecoveryInputSchema = Type.Union([\n\toperationSchema,\n\tType.Object(\n\t\t{ action: Type.Literal(\"skill\"), name: exactString, maxBytes: Type.Optional(byteLimit) },\n\t\t{ additionalProperties: false },\n\t),\n\tType.Object(\n\t\t{\n\t\t\taction: Type.Literal(\"batch\"),\n\t\t\trequests: Type.Array(operationSchema, { minItems: 1, maxItems: 8 }),\n\t\t\tmaxBytes: Type.Optional(byteLimit),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n]);\nconst providerOperationSchema = Type.Object(\n\t{ ...operationSchema.properties, action: StringEnum([\"read\", \"search\", \"recover\"] as const) },\n\t{ additionalProperties: false },\n);\n\n/** Provider-facing tools require an object root; execute still applies the strict union above. */\nexport const nativeRecoveryToolSchema = Type.Object(\n\t{\n\t\t...providerOperationSchema.properties,\n\t\taction: StringEnum([\"read\", \"search\", \"recover\", \"batch\", \"skill\"] as const),\n\t\tname: Type.Optional(exactString),\n\t\trequests: Type.Optional(Type.Array(providerOperationSchema, { minItems: 1, maxItems: 8 })),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type NativeRecoveryInput = Static<typeof nativeRecoveryInputSchema>;\nexport type NativeRecoveryOperation = Static<typeof operationSchema>;\nexport type NativeRecoveryStatus =\n\t| \"found\"\n\t| \"complete-miss\"\n\t| \"partial\"\n\t| \"not_authorized\"\n\t| \"unavailable\"\n\t| \"budget_refused\";\nexport type NativeRecoveryCoverage = \"complete\" | \"partial\" | \"unknown\";\nexport interface NativeRecoveryScope {\n\tkind: \"branch\";\n\t/** Missing coordinates mean capture was unavailable, not whole-source authority. */\n\tsourceSessionId?: string;\n\tleafId?: string | null;\n\tsourceSequence?: number;\n\tprojection: \"public-text-only\";\n}\nexport interface NativeRecoverySource {\n\tsourceSessionId: string;\n\tentryId: string;\n\trevision: string;\n\tfield: string;\n\tstartLine: number;\n\tendLine: number;\n}\nexport interface NativeRecoveryRecord extends Omit<NativeRecoverySource, \"entryId\"> {\n\tref: string;\n\tkind: string;\n\ttext: string;\n}\nexport interface NativeRecoveryResult {\n\trequestIndex: number;\n\tstatus: NativeRecoveryStatus;\n\tcoverage: NativeRecoveryCoverage;\n\trecords: NativeRecoveryRecord[];\n\treason?: string;\n}\nexport interface NativeRecoveryResponse {\n\tkind: \"native-recovery\";\n\tversion: 1;\n\tnativeRecovery: 1;\n\tauthority: \"tool-data\";\n\tfreshness: \"unknown\";\n\tscope: NativeRecoveryScope;\n\tstatus: NativeRecoveryStatus;\n\tcoverage: NativeRecoveryCoverage;\n\tsources: NativeRecoverySource[];\n\tresults: NativeRecoveryResult[];\n\treason?: string;\n}\n\n/** A cap smaller than the refusal envelope cannot be satisfied by returning clipped JSON. */\nexport class NativeRecoveryBudgetRefusal extends Error {\n\treadonly status = \"budget_refused\";\n\tconstructor() {\n\t\tsuper(\"Native recovery byte or item budget refused\");\n\t\tthis.name = \"NativeRecoveryBudgetRefusal\";\n\t}\n}\n\nexport function stringifyNativeRecoveryResponse(\n\tresponse: NativeRecoveryResponse,\n\tmaxBytes = DEFAULT_NATIVE_RECOVERY_LIMITS.maxBytes,\n): string {\n\ttry {\n\t\treturn stringifyBoundedJson(response, maxBytes);\n\t} catch {\n\t\tthrow new NativeRecoveryBudgetRefusal();\n\t}\n}\n\n/** Tool details carry reference metadata, not a second copy of the selected body. */\nexport function nativeRecoveryMetadata(response: NativeRecoveryResponse) {\n\treturn {\n\t\tkind: response.kind,\n\t\tversion: response.version,\n\t\tnativeRecovery: response.nativeRecovery,\n\t\tscope: response.scope,\n\t\tsources: response.sources,\n\t\tcoverage: response.coverage,\n\t\tauthority: response.authority,\n\t\tfreshness: response.freshness,\n\t\tstatus: response.status,\n\t};\n}\n\n/** Callers use fixed public reason codes, never raw exceptions or source locators. */\nexport function createNativeRecoveryRefusal(\n\tstatus: \"not_authorized\" | \"unavailable\" | \"budget_refused\",\n\treason: string,\n\tmaxBytes = DEFAULT_NATIVE_RECOVERY_LIMITS.maxBytes,\n): NativeRecoveryResponse {\n\tconst response: NativeRecoveryResponse = {\n\t\tkind: \"native-recovery\",\n\t\tversion: 1,\n\t\tnativeRecovery: 1,\n\t\tauthority: \"tool-data\",\n\t\tfreshness: \"unknown\",\n\t\tscope: { kind: \"branch\", projection: \"public-text-only\" },\n\t\tstatus,\n\t\tcoverage: \"unknown\",\n\t\tsources: [],\n\t\tresults: [],\n\t\treason,\n\t};\n\tstringifyNativeRecoveryResponse(response, maxBytes);\n\treturn response;\n}\n\ninterface PublicField {\n\tfield: string;\n\ttext: string;\n}\nfunction object(value: unknown): Record<string, unknown> | undefined {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n}\n\n/** Select known public string fields; never traverse executed-input/provider envelopes, signatures or thinking. */\nfunction publicFields(\n\tentry: SessionEntry,\n\tmaxItems: number,\n\tqualification?: IndexedSourceEvent[\"qualification\"],\n): PublicField[] | undefined {\n\tif (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\treturn typeof entry.summary === \"string\" ? [{ field: \"/summary\", text: entry.summary }] : undefined;\n\t}\n\tif (\n\t\tentry.type === \"custom\" &&\n\t\tentry.customType === AGENT_RESULT_CUSTOM_TYPE &&\n\t\tqualification === \"native-recovery\"\n\t) {\n\t\tconst findings = object(entry.data)?.findings;\n\t\treturn typeof findings === \"string\" ? [{ field: \"/data/findings\", text: findings }] : undefined;\n\t}\n\tlet content: unknown;\n\tlet field: string;\n\tlet role: unknown;\n\tif (\n\t\t(entry.type === \"custom\" || entry.type === \"custom_message\") &&\n\t\tqualification === \"native-recovery\" &&\n\t\tentry.customType === SELECTED_SKILL_CUSTOM_TYPE\n\t) {\n\t\tconst skill = selectedSkillCapture(entry);\n\t\tif (skill)\n\t\t\treturn [\n\t\t\t\t{ field: entry.type === \"custom\" ? \"/data/content\" : \"/content\", text: skill.content },\n\t\t\t\t{\n\t\t\t\t\tfield: `/${entry.type === \"custom\" ? \"data\" : \"details\"}/baseContextSelectedSkill/descriptor`,\n\t\t\t\t\ttext: JSON.stringify({ ...skill.descriptor, sourceInfo: undefined }),\n\t\t\t\t},\n\t\t\t];\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\tcontent = entry.content;\n\t\tfield = \"/content\";\n\t\trole = \"custom\";\n\t} else if (entry.type === \"message\") {\n\t\tconst message = object(entry.message);\n\t\tif (!message || ![\"user\", \"assistant\", \"toolResult\", \"custom\"].includes(String(message.role))) return undefined;\n\t\tcontent = message.content;\n\t\trole = message.role;\n\t\tfield = \"/message/content\";\n\t} else return undefined;\n\tif (typeof content === \"string\") {\n\t\treturn role === \"user\" || role === \"custom\" ? [{ field, text: content }] : undefined;\n\t}\n\tif (!Array.isArray(content)) return undefined;\n\tif (content.length > maxItems) throw new NativeRecoveryBudgetRefusal();\n\tconst fields: PublicField[] = [];\n\tfor (let i = 0; i < content.length; i++) {\n\t\tconst block = object(content[i]);\n\t\tif (!block) return undefined;\n\t\tif (block.type === \"text\" && typeof block.text === \"string\") {\n\t\t\tif (fields.length >= maxItems) throw new NativeRecoveryBudgetRefusal();\n\t\t\tfields.push({ field: `${field}/${i}/text`, text: block.text });\n\t\t} else if (block.type === \"thinking\" && role === \"assistant\" && typeof block.thinking === \"string\") {\n\t\t\t// Thinking is unsupported by this v1 projection; this does not classify all thinking text as private.\n\t\t} else if (\n\t\t\tblock.type === \"toolCall\" &&\n\t\t\trole === \"assistant\" &&\n\t\t\ttypeof block.id === \"string\" &&\n\t\t\ttypeof block.name === \"string\" &&\n\t\t\tobject(block.arguments)\n\t\t) {\n\t\t\t// Assistant-authored string arguments are public action data, not executed-input/auth envelopes.\n\t\t\tconst arguments_ = block.arguments as Record<string, unknown>;\n\t\t\tlet visited = 0;\n\t\t\tfor (const key in arguments_) {\n\t\t\t\tif (!Object.hasOwn(arguments_, key)) continue;\n\t\t\t\tif (++visited > maxItems) throw new NativeRecoveryBudgetRefusal();\n\t\t\t\tconst value = arguments_[key];\n\t\t\t\t// v1 does not select nested/non-string argument fields; it does not label them private.\n\t\t\t\tif (typeof value !== \"string\") continue;\n\t\t\t\tif (fields.length >= maxItems) throw new NativeRecoveryBudgetRefusal();\n\t\t\t\tconst escaped = key.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n\t\t\t\tfields.push({ field: `${field}/${i}/arguments/${escaped}`, text: value });\n\t\t\t}\n\t\t} else if (\n\t\t\tblock.type === \"image\" &&\n\t\t\trole !== \"assistant\" &&\n\t\t\ttypeof block.data === \"string\" &&\n\t\t\ttypeof block.mimeType === \"string\"\n\t\t) {\n\t\t\t// This API selects text only; it makes no lossless multimodal claim.\n\t\t} else return undefined;\n\t}\n\treturn fields;\n}\n\nfunction outcome(\n\trequestIndex: number,\n\tstatus: NativeRecoveryStatus,\n\tcoverage: NativeRecoveryCoverage = \"unknown\",\n\trecords: NativeRecoveryRecord[] = [],\n\treason?: string,\n): NativeRecoveryResult {\n\treturn { requestIndex, status, coverage, records, ...(reason ? { reason } : {}) };\n}\n\nfunction assemble(scope: NativeRecoveryScope, results: NativeRecoveryResult[]): NativeRecoveryResponse {\n\tconst statuses = new Set(results.map((result) => result.status));\n\tconst status =\n\t\tstatuses.size === 1\n\t\t\t? results[0].status\n\t\t\t: results.every((result) => result.status === \"found\" || result.status === \"complete-miss\")\n\t\t\t\t? \"found\"\n\t\t\t\t: \"partial\";\n\tconst coverage = results.every((result) => result.coverage === \"complete\")\n\t\t? \"complete\"\n\t\t: results.some((result) => result.coverage === \"partial\")\n\t\t\t? \"partial\"\n\t\t\t: \"unknown\";\n\treturn {\n\t\tkind: \"native-recovery\",\n\t\tversion: 1,\n\t\tnativeRecovery: 1,\n\t\tauthority: \"tool-data\",\n\t\tfreshness: \"unknown\",\n\t\tscope,\n\t\tstatus,\n\t\tcoverage,\n\t\tresults,\n\t\tsources: results.flatMap((result) =>\n\t\t\tresult.records.map((record) => ({\n\t\t\t\tsourceSessionId: record.sourceSessionId,\n\t\t\t\tentryId: record.ref,\n\t\t\t\trevision: record.revision,\n\t\t\t\tfield: record.field,\n\t\t\t\tstartLine: record.startLine,\n\t\t\t\tendLine: record.endLine,\n\t\t\t})),\n\t\t),\n\t};\n}\n\n/** Shared runtime admission for the native tool and Python host bridge. */\nexport function parseNativeRecoveryInput(value: unknown): NativeRecoveryInput {\n\tlet request: NativeRecoveryInput;\n\ttry {\n\t\trequest = JSON.parse(stringifyBoundedJson(value, 128 * 1024)) as NativeRecoveryInput;\n\t} catch {\n\t\tthrow new NativeRecoveryBudgetRefusal();\n\t}\n\tif (!Value.Check(nativeRecoveryInputSchema, request)) throw new Error(\"Invalid native recovery request\");\n\treturn request;\n}\n\n/** The caller captures ONE server branch before entering this service, including for a batch. */\nexport async function recoverCapturedHistory(\n\tview: SessionHistoryReadView,\n\tinput: NativeRecoveryInput,\n\tlimits: NativeRecoveryLimits = DEFAULT_NATIVE_RECOVERY_LIMITS,\n\tsignal?: AbortSignal,\n): Promise<NativeRecoveryResponse> {\n\tconst cap = { ...limits };\n\tfor (const key of [\"maxBytes\", \"maxSourceBytes\", \"maxItems\", \"maxRequests\"] as const) {\n\t\tif (!Number.isSafeInteger(cap[key]) || cap[key] < 1) throw new NativeRecoveryBudgetRefusal();\n\t\tcap[key] = Math.min(cap[key], DEFAULT_NATIVE_RECOVERY_LIMITS[key]);\n\t}\n\t// Bound and detach input before schema traversal or the first await. Unknown selectors are rejected.\n\tlet request: NativeRecoveryInput;\n\ttry {\n\t\trequest = parseNativeRecoveryInput(input);\n\t} catch (error) {\n\t\treturn createNativeRecoveryRefusal(\n\t\t\terror instanceof NativeRecoveryBudgetRefusal ? \"budget_refused\" : \"unavailable\",\n\t\t\t\"invalid_request\",\n\t\t\tcap.maxBytes,\n\t\t);\n\t}\n\tconst maxBytes = Math.min(cap.maxBytes, request.maxBytes ?? cap.maxBytes);\n\tconst { sessionId: sourceSessionId, leafId, sourceSequence } = view.source;\n\tconst scope: NativeRecoveryScope = {\n\t\tkind: \"branch\",\n\t\tprojection: \"public-text-only\",\n\t\tsourceSessionId,\n\t\tleafId,\n\t\tsourceSequence,\n\t};\n\tif (request.action === \"skill\")\n\t\treturn createNativeRecoveryRefusal(\"not_authorized\", \"native_skill_selection_owner_required\", maxBytes);\n\tconst operations = request.action === \"batch\" ? request.requests : [request];\n\tconst results = operations.map((_, i) => outcome(i, \"budget_refused\", \"unknown\", [], \"not_admitted\"));\n\t// Reserve an explicit result for EVERY requested operation before touching canonical payloads.\n\tstringifyNativeRecoveryResponse(assemble(scope, results), maxBytes);\n\tif (operations.length > cap.maxRequests) return assemble(scope, results);\n\tlet sourceBytes = 0;\n\tlet examined = 0;\n\tlet selectedItems = 0;\n\tconst cache = new Map<string, { revision: string; entry: SessionEntry }>();\n\n\tasync function fieldsFor(metadata: IndexedSourceEvent, requestedField?: string): Promise<PublicField[] | undefined> {\n\t\tsignal?.throwIfAborted();\n\t\tlet cached = cache.get(metadata.id);\n\t\tif (cached && cached.revision !== metadata.revision) throw new Error(\"Captured revision changed\");\n\t\tif (!cached) {\n\t\t\tif (++examined > cap.maxItems || metadata.locator.length > cap.maxSourceBytes - sourceBytes) {\n\t\t\t\tthrow new NativeRecoveryBudgetRefusal();\n\t\t\t}\n\t\t\tsourceBytes += metadata.locator.length;\n\t\t\tconst hydrated = await hydrateCapturedHistoryEntry(metadata, metadata.locator.length, async (id, options) => {\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\treturn view.readPayload(id, options);\n\t\t\t});\n\t\t\tsignal?.throwIfAborted();\n\t\t\tcached = { revision: metadata.revision, entry: hydrated.entry };\n\t\t\tcache.set(metadata.id, cached);\n\t\t}\n\t\tif (requestedField === \"/nativeOrigin/submitted/text\") {\n\t\t\tif (\n\t\t\t\tcached.entry.type !== \"message\" ||\n\t\t\t\tmetadata.qualification !== \"native-admission\" ||\n\t\t\t\tmetadata.retention === \"retained-import\"\n\t\t\t)\n\t\t\t\treturn undefined;\n\t\t\t// Reuse the existing exact native-input qualification, not generic origin traversal.\n\t\t\t// The first qualifying projection is submitted.text; return before visiting content parts.\n\t\t\tfor (const projection of projectTaskStateSource({\n\t\t\t\tsessionId: sourceSessionId,\n\t\t\t\tsequence: metadata.sequence,\n\t\t\t\trevision: metadata.revision,\n\t\t\t\tqualification: metadata.qualification,\n\t\t\t\tretention: metadata.retention,\n\t\t\t\tentry: cached.entry,\n\t\t\t})) {\n\t\t\t\tif (\n\t\t\t\t\tprojection.source.field === requestedField &&\n\t\t\t\t\tprojection.authority === \"user\" &&\n\t\t\t\t\tprojection.attribution === \"source-backed\" &&\n\t\t\t\t\ttypeof projection.text === \"string\"\n\t\t\t\t) {\n\t\t\t\t\treturn [{ field: requestedField, text: projection.text }];\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\treturn publicFields(cached.entry, cap.maxItems, metadata.qualification);\n\t}\n\n\tasync function recover(operation: NativeRecoveryOperation, i: number): Promise<NativeRecoveryResult> {\n\t\tif (operation.sourceSessionId !== undefined && operation.sourceSessionId !== scope.sourceSessionId) {\n\t\t\treturn outcome(i, \"not_authorized\", \"unknown\", [], \"source_not_in_capture\");\n\t\t}\n\t\tif (\n\t\t\t(operation.need !== undefined && operation.query !== undefined && operation.need !== operation.query) ||\n\t\t\t(operation.endLine !== undefined && operation.endLine < (operation.startLine ?? 1))\n\t\t) {\n\t\t\treturn outcome(i, \"unavailable\", \"unknown\", [], \"conflicting_selection\");\n\t\t}\n\t\tconst needle = operation.need ?? operation.query;\n\t\tlet candidates: IndexedSourceEvent[];\n\t\tlet coverage: NativeRecoveryCoverage;\n\t\tif (operation.ref !== undefined) {\n\t\t\tconst metadata = await view.get(operation.ref);\n\t\t\tif (!metadata || metadata.id !== operation.ref) {\n\t\t\t\treturn outcome(i, \"not_authorized\", \"unknown\", [], \"ref_not_in_captured_branch\");\n\t\t\t}\n\t\t\tif (operation.revision !== undefined && operation.revision !== metadata.revision) {\n\t\t\t\treturn outcome(i, \"unavailable\", \"unknown\", [], \"revision_mismatch\");\n\t\t\t}\n\t\t\tcandidates = [metadata];\n\t\t\tcoverage = \"complete\";\n\t\t} else {\n\t\t\tif (\n\t\t\t\toperation.action === \"read\" ||\n\t\t\t\tneedle === undefined ||\n\t\t\t\toperation.revision !== undefined ||\n\t\t\t\toperation.field !== undefined ||\n\t\t\t\toperation.startLine !== undefined ||\n\t\t\t\toperation.endLine !== undefined\n\t\t\t) {\n\t\t\t\treturn outcome(i, \"unavailable\", \"unknown\", [], \"exact_selection_requires_ref\");\n\t\t\t}\n\t\t\tif (Buffer.byteLength(needle) > 8192) throw new NativeRecoveryBudgetRefusal();\n\t\t\tif (examined >= cap.maxItems) throw new NativeRecoveryBudgetRefusal();\n\t\t\tconst page = await view.search(needle, cap.maxItems - examined);\n\t\t\tcandidates = page.events;\n\t\t\t// Search indexes token conjunctions, including non-public strings. It is not an exhaustive\n\t\t\t// literal-substring search even when its indexed text coverage is reported complete.\n\t\t\tcoverage =\n\t\t\t\tpage.coverage === \"partial\" || page.truncated || page.indexedThrough < sourceSequence\n\t\t\t\t\t? \"partial\"\n\t\t\t\t\t: \"unknown\";\n\t\t}\n\t\tconst records: NativeRecoveryRecord[] = [];\n\t\tlet unavailable = false;\n\t\tlet beyondWindow = false;\n\t\tlet needWindow = false;\n\t\tfor (const metadata of candidates) {\n\t\t\tconst fields = await fieldsFor(metadata, operation.field);\n\t\t\tif (!fields || (operation.field !== undefined && !fields.some((field) => field.field === operation.field))) {\n\t\t\t\tunavailable = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const selected of fields) {\n\t\t\t\tif (operation.field !== undefined && operation.field !== selected.field) continue;\n\t\t\t\tconst lines = selected.text.split(\"\\n\");\n\t\t\t\tlet startLine = operation.startLine ?? 1;\n\t\t\t\tlet endLine = Math.min(operation.endLine ?? lines.length, lines.length);\n\t\t\t\tif (needle !== undefined && operation.startLine === undefined && operation.endLine === undefined) {\n\t\t\t\t\tconst first = selected.text.indexOf(needle);\n\t\t\t\t\tif (first < 0) continue;\n\t\t\t\t\t// Select whole exact lines containing the first literal occurrence, including every\n\t\t\t\t\t// line of a multiline needle. A required huge line is refused, never prefix-clipped.\n\t\t\t\t\tstartLine = selected.text.slice(0, first).split(\"\\n\").length;\n\t\t\t\t\tendLine = startLine + needle.split(\"\\n\").length - 1;\n\t\t\t\t\tif (startLine > 1 || endLine < lines.length) needWindow = true;\n\t\t\t\t}\n\t\t\t\tif (startLine > lines.length) continue;\n\t\t\t\tconst text = lines.slice(startLine - 1, endLine).join(\"\\n\");\n\t\t\t\tif (needle !== undefined && !text.includes(needle)) continue;\n\t\t\t\tif (operation.endLine !== undefined && operation.endLine > lines.length) beyondWindow = true;\n\t\t\t\tif (selectedItems + records.length >= cap.maxItems) throw new NativeRecoveryBudgetRefusal();\n\t\t\t\trecords.push({\n\t\t\t\t\tref: metadata.id,\n\t\t\t\t\trevision: metadata.revision,\n\t\t\t\t\tsourceSessionId,\n\t\t\t\t\tkind: metadata.kind,\n\t\t\t\t\tfield: selected.field,\n\t\t\t\t\tstartLine,\n\t\t\t\t\tendLine,\n\t\t\t\t\ttext,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (operation.ref !== undefined && unavailable)\n\t\t\treturn outcome(i, \"unavailable\", \"unknown\", [], \"unsupported_public_field\");\n\t\tif (unavailable || beyondWindow || needWindow) coverage = \"partial\";\n\t\tconst status = coverage === \"complete\" ? (records.length ? \"found\" : \"complete-miss\") : \"partial\";\n\t\treturn outcome(\n\t\t\ti,\n\t\t\tstatus,\n\t\t\tcoverage,\n\t\t\trecords,\n\t\t\tcoverage === \"unknown\"\n\t\t\t\t? \"candidate_search_not_exhaustive\"\n\t\t\t\t: unavailable\n\t\t\t\t\t? \"unsupported_public_shape\"\n\t\t\t\t\t: beyondWindow\n\t\t\t\t\t\t? \"requested_end_beyond_source\"\n\t\t\t\t\t\t: needWindow\n\t\t\t\t\t\t\t? \"need_window\"\n\t\t\t\t\t\t\t: undefined,\n\t\t);\n\t}\n\n\tfor (let i = 0; i < operations.length; i++) {\n\t\ttry {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tconst result = await recover(operations[i], i);\n\t\t\tsignal?.throwIfAborted();\n\t\t\tstringifyBoundedJson(result, Math.min(maxBytes, operations[i].maxBytes ?? maxBytes));\n\t\t\tresults[i] = result;\n\t\t\tstringifyNativeRecoveryResponse(assemble(scope, results), maxBytes);\n\t\t\tselectedItems += result.records.length;\n\t\t} catch (error) {\n\t\t\tconst budget =\n\t\t\t\terror instanceof NativeRecoveryBudgetRefusal ||\n\t\t\t\t(error instanceof Error && /budget|limit/i.test(error.message));\n\t\t\tresults[i] = outcome(\n\t\t\t\ti,\n\t\t\t\tbudget ? \"budget_refused\" : \"unavailable\",\n\t\t\t\t\"unknown\",\n\t\t\t\t[],\n\t\t\t\tbudget ? \"operation_budget\" : signal?.aborted ? \"aborted\" : \"canonical_source_unavailable\",\n\t\t\t);\n\t\t}\n\t}\n\tconst response = assemble(scope, results);\n\tstringifyNativeRecoveryResponse(response, maxBytes);\n\treturn response;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"selective-recovery.d.ts","sourceRoot":"","sources":["../../src/core/selective-recovery.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAK5C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAS7D,OAAO,EAA+B,KAAK,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAItG,MAAM,WAAW,oBAAoB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,0GAA0G;AAC1G,eAAO,MAAM,8BAA8B,EAAE,QAAQ,CAAC,oBAAoB,CAKxE,CAAC;AAIH,QAAA,MAAM,eAAe;;;;;;;;;;;;;;EA+BpB,CAAC;AAEF,wGAAwG;AACxG,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAcpC,CAAC;AAMH,kGAAkG;AAClG,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAQpC,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG,MAAM,CAAC,O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OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,OAAO,CAAC;IACrB,OAAO,EAAE,OAAO,CAAC;CACjB;AAED,0FAA0F;AAC1F,qBAAa,yBAAyB;IACrC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA0C;IACjE,OAAO,CAAC,UAAU,CAAK;IACvB,KAAK,IAAI,IAAI,CAGZ;IACD,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,mBAAmB,GAAG,SAAS,CAE/C;IACD,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAEvB;IACD,IAAI,OAAO,IAAI,MAAM,CAEpB;IACD,IAAI,CAAC,KAAK,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,GAAE,MAAqB,GAAG,MAAM,CAMnF;CACD;AAED,iGAAiG;AACjG,wBAAsB,sBAAsB,CAC3C,IAAI,EAAE,sBAAsB,EAC5B,KAAK,EAAE,mBAAmB,EAC1B,MAAM,GAAE,oBAAqD,EAC7D,MAAM,CAAC,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,yBAAyB,GACjC,OAAO,CAAC,sBAAsB,CAAC,CAkgBjC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { StringEnum } from \"@ponythewhite/base-context-ai\";\nimport { type Static, Type } from \"typebox\";\nimport { Value } from \"typebox/value\";\nimport { AGENT_RESULT_CUSTOM_TYPE } from \"./agent-results.js\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport type { IndexedSourceEvent } from \"./history-index.js\";\nimport type { SourceSnapshotRef } from \"./request-events.js\";\nimport {\n\tdecodedTextWindow,\n\tPUBLIC_TEXT_WINDOW_BYTES,\n\ttype RetainedToolOutput,\n\treadRetainedToolOutput,\n\tretainedToolOutput,\n} from \"./retained-tool-output.js\";\nimport { SELECTED_SKILL_CUSTOM_TYPE, selectedSkillCapture } from \"./selected-skills.js\";\nimport { hydrateCapturedHistoryEntry, type SessionHistoryReadView } from \"./session-history-index.js\";\nimport { getSessionArtifactPathForFile, type SessionEntry } from \"./session-manager.js\";\nimport { projectTaskStateSource } from \"./task-state.js\";\n\nexport interface NativeRecoveryLimits {\n\tmaxBytes: number;\n\tmaxSourceBytes: number;\n\tmaxItems: number;\n\tmaxRequests: number;\n}\n\n/** Defaults match bounded index pages and 64KiB payload parts; all admission units are bytes or items. */\nexport const DEFAULT_NATIVE_RECOVERY_LIMITS: Readonly<NativeRecoveryLimits> = Object.freeze({\n\tmaxBytes: 64 * 1024,\n\tmaxSourceBytes: 1024 * 1024,\n\tmaxItems: 16,\n\tmaxRequests: 8,\n});\n\nconst exactString = Type.String({ minLength: 1, maxLength: 512 });\nconst byteLimit = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });\nconst operationSchema = Type.Object(\n\t{\n\t\taction: Type.Union([Type.Literal(\"read\"), Type.Literal(\"search\"), Type.Literal(\"recover\")]),\n\t\tref: Type.Optional(exactString),\n\t\tcursor: Type.Optional(exactString),\n\t\tstartByte: Type.Optional(Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER })),\n\t\tendByte: Type.Optional(byteLimit),\n\t\trevision: Type.Optional(exactString),\n\t\tsourceSessionId: Type.Optional(exactString),\n\t\tfield: Type.Optional(exactString),\n\t\tneed: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: 8192,\n\t\t\t\tdescription:\n\t\t\t\t\t\"Literal text selector; alias of query. Prefer one field. If both are supplied, use identical text.\",\n\t\t\t}),\n\t\t),\n\t\tquery: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: 8192,\n\t\t\t\tdescription:\n\t\t\t\t\t\"Literal text selector; alias of need. Prefer one field. If both are supplied, use identical text.\",\n\t\t\t}),\n\t\t),\n\t\tstartLine: Type.Optional(byteLimit),\n\t\tendLine: Type.Optional(byteLimit),\n\t\tmaxBytes: Type.Optional(byteLimit),\n\t},\n\t{ additionalProperties: false },\n);\n\n/** A ref is a case-sensitive entry ID, never a path. Lines are one-based within each selected field. */\nexport const nativeRecoveryInputSchema = Type.Union([\n\toperationSchema,\n\tType.Object(\n\t\t{ action: Type.Literal(\"skill\"), name: exactString, maxBytes: Type.Optional(byteLimit) },\n\t\t{ additionalProperties: false },\n\t),\n\tType.Object(\n\t\t{\n\t\t\taction: Type.Literal(\"batch\"),\n\t\t\trequests: Type.Array(operationSchema, { minItems: 1, maxItems: 8 }),\n\t\t\tmaxBytes: Type.Optional(byteLimit),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n]);\nconst providerOperationSchema = Type.Object(\n\t{ ...operationSchema.properties, action: StringEnum([\"read\", \"search\", \"recover\"] as const) },\n\t{ additionalProperties: false },\n);\n\n/** Provider-facing tools require an object root; execute still applies the strict union above. */\nexport const nativeRecoveryToolSchema = Type.Object(\n\t{\n\t\t...providerOperationSchema.properties,\n\t\taction: StringEnum([\"read\", \"search\", \"recover\", \"batch\", \"skill\"] as const),\n\t\tname: Type.Optional(exactString),\n\t\trequests: Type.Optional(Type.Array(providerOperationSchema, { minItems: 1, maxItems: 8 })),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type NativeRecoveryInput = Static<typeof nativeRecoveryInputSchema>;\nexport type NativeRecoveryOperation = Static<typeof operationSchema>;\nexport type NativeRecoveryStatus =\n\t| \"found\"\n\t| \"complete-miss\"\n\t| \"partial\"\n\t| \"not_authorized\"\n\t| \"unavailable\"\n\t| \"budget_refused\";\nexport type NativeRecoveryCoverage = \"complete\" | \"partial\" | \"unknown\";\nexport interface NativeRecoveryScope {\n\tkind: \"branch\";\n\t/** Missing coordinates mean capture was unavailable, not whole-source authority. */\n\tsourceSessionId?: string;\n\tleafId?: string | null;\n\tsourceSequence?: number;\n\tprojection: \"public-text-only\";\n}\nexport interface NativeRecoverySource {\n\tsourceSessionId: string;\n\tentryId: string;\n\trevision: string;\n\tfield: string;\n\tstartLine?: number;\n\tendLine?: number;\n\tstartByte?: number;\n\tendByte?: number;\n\tprefixOmitted?: boolean;\n\tsuffixOmitted?: boolean;\n}\nexport interface NativeRecoveryRecord extends Omit<NativeRecoverySource, \"entryId\"> {\n\tref: string;\n\tkind: string;\n\ttext: string;\n}\nexport interface NativeRecoveryResult {\n\trequestIndex: number;\n\tstatus: NativeRecoveryStatus;\n\tcoverage: NativeRecoveryCoverage;\n\trecords: NativeRecoveryRecord[];\n\tcursor?: string;\n\texhausted?: boolean;\n\treason?: string;\n}\nexport interface NativeRecoveryResponse {\n\tkind: \"native-recovery\";\n\tversion: 1;\n\tnativeRecovery: 1;\n\tauthority: \"tool-data\";\n\tfreshness: \"unknown\";\n\tscope: NativeRecoveryScope;\n\tstatus: NativeRecoveryStatus;\n\tcoverage: NativeRecoveryCoverage;\n\tsources: NativeRecoverySource[];\n\tresults: NativeRecoveryResult[];\n\treason?: string;\n}\n\n/** A cap smaller than the refusal envelope cannot be satisfied by returning clipped JSON. */\nexport class NativeRecoveryBudgetRefusal extends Error {\n\treadonly status = \"budget_refused\";\n\tconstructor() {\n\t\tsuper(\"Native recovery byte or item budget refused\");\n\t\tthis.name = \"NativeRecoveryBudgetRefusal\";\n\t}\n}\n\nexport function stringifyNativeRecoveryResponse(\n\tresponse: NativeRecoveryResponse,\n\tmaxBytes = DEFAULT_NATIVE_RECOVERY_LIMITS.maxBytes,\n): string {\n\ttry {\n\t\treturn stringifyBoundedJson(response, maxBytes);\n\t} catch {\n\t\tthrow new NativeRecoveryBudgetRefusal();\n\t}\n}\n\n/** Tool details carry reference metadata, not a second copy of the selected body. */\nexport function nativeRecoveryMetadata(response: NativeRecoveryResponse) {\n\treturn {\n\t\tkind: response.kind,\n\t\tversion: response.version,\n\t\tnativeRecovery: response.nativeRecovery,\n\t\tscope: response.scope,\n\t\tsources: response.sources,\n\t\tcoverage: response.coverage,\n\t\tauthority: response.authority,\n\t\tfreshness: response.freshness,\n\t\tstatus: response.status,\n\t};\n}\n\n/** Callers use fixed public reason codes, never raw exceptions or source locators. */\nexport function createNativeRecoveryRefusal(\n\tstatus: \"not_authorized\" | \"unavailable\" | \"budget_refused\",\n\treason: string,\n\tmaxBytes = DEFAULT_NATIVE_RECOVERY_LIMITS.maxBytes,\n): NativeRecoveryResponse {\n\tconst response: NativeRecoveryResponse = {\n\t\tkind: \"native-recovery\",\n\t\tversion: 1,\n\t\tnativeRecovery: 1,\n\t\tauthority: \"tool-data\",\n\t\tfreshness: \"unknown\",\n\t\tscope: { kind: \"branch\", projection: \"public-text-only\" },\n\t\tstatus,\n\t\tcoverage: \"unknown\",\n\t\tsources: [],\n\t\tresults: [],\n\t\treason,\n\t};\n\tstringifyNativeRecoveryResponse(response, maxBytes);\n\treturn response;\n}\n\ninterface PublicField {\n\tfield: string;\n\ttext: string;\n\tretained?: RetainedToolOutput;\n\tunavailable?: boolean;\n}\nfunction object(value: unknown): Record<string, unknown> | undefined {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n}\n\n/** Select known public string fields; never traverse executed-input/provider envelopes, signatures or thinking. */\nfunction publicFields(\n\tentry: SessionEntry,\n\tmaxItems: number,\n\tqualification?: IndexedSourceEvent[\"qualification\"],\n): PublicField[] | undefined {\n\tif (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\treturn typeof entry.summary === \"string\" ? [{ field: \"/summary\", text: entry.summary }] : undefined;\n\t}\n\tif (\n\t\tentry.type === \"custom\" &&\n\t\tentry.customType === AGENT_RESULT_CUSTOM_TYPE &&\n\t\tqualification === \"native-recovery\"\n\t) {\n\t\tconst findings = object(entry.data)?.findings;\n\t\treturn typeof findings === \"string\" ? [{ field: \"/data/findings\", text: findings }] : undefined;\n\t}\n\tlet content: unknown;\n\tlet field: string;\n\tlet role: unknown;\n\tif (\n\t\t(entry.type === \"custom\" || entry.type === \"custom_message\") &&\n\t\tqualification === \"native-recovery\" &&\n\t\tentry.customType === SELECTED_SKILL_CUSTOM_TYPE\n\t) {\n\t\tconst skill = selectedSkillCapture(entry);\n\t\tif (skill)\n\t\t\treturn [\n\t\t\t\t{ field: entry.type === \"custom\" ? \"/data/content\" : \"/content\", text: skill.content },\n\t\t\t\t{\n\t\t\t\t\tfield: `/${entry.type === \"custom\" ? \"data\" : \"details\"}/baseContextSelectedSkill/descriptor`,\n\t\t\t\t\ttext: JSON.stringify({ ...skill.descriptor, sourceInfo: undefined }),\n\t\t\t\t},\n\t\t\t];\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\tcontent = entry.content;\n\t\tfield = \"/content\";\n\t\trole = \"custom\";\n\t} else if (entry.type === \"message\") {\n\t\tconst message = object(entry.message);\n\t\tif (!message || ![\"user\", \"assistant\", \"toolResult\", \"custom\"].includes(String(message.role))) return undefined;\n\t\tcontent = message.content;\n\t\trole = message.role;\n\t\tfield = \"/message/content\";\n\t} else return undefined;\n\tif (typeof content === \"string\") {\n\t\treturn role === \"user\" || role === \"custom\" ? [{ field, text: content }] : undefined;\n\t}\n\tif (!Array.isArray(content)) return undefined;\n\tif (content.length > maxItems) throw new NativeRecoveryBudgetRefusal();\n\tconst fields: PublicField[] = [];\n\tfor (let i = 0; i < content.length; i++) {\n\t\tconst block = object(content[i]);\n\t\tif (!block) return undefined;\n\t\tif (block.type === \"text\" && typeof block.text === \"string\") {\n\t\t\tif (fields.length >= maxItems) throw new NativeRecoveryBudgetRefusal();\n\t\t\tfields.push({ field: `${field}/${i}/text`, text: block.text });\n\t\t} else if (block.type === \"thinking\" && role === \"assistant\" && typeof block.thinking === \"string\") {\n\t\t\t// Thinking is unsupported by this v1 projection; this does not classify all thinking text as private.\n\t\t} else if (\n\t\t\tblock.type === \"toolCall\" &&\n\t\t\trole === \"assistant\" &&\n\t\t\ttypeof block.id === \"string\" &&\n\t\t\ttypeof block.name === \"string\" &&\n\t\t\tobject(block.arguments)\n\t\t) {\n\t\t\t// Assistant-authored string arguments are public action data, not executed-input/auth envelopes.\n\t\t\tconst arguments_ = block.arguments as Record<string, unknown>;\n\t\t\tlet visited = 0;\n\t\t\tfor (const key in arguments_) {\n\t\t\t\tif (!Object.hasOwn(arguments_, key)) continue;\n\t\t\t\tif (++visited > maxItems) throw new NativeRecoveryBudgetRefusal();\n\t\t\t\tconst value = arguments_[key];\n\t\t\t\t// v1 does not select nested/non-string argument fields; it does not label them private.\n\t\t\t\tif (typeof value !== \"string\") continue;\n\t\t\t\tif (fields.length >= maxItems) throw new NativeRecoveryBudgetRefusal();\n\t\t\t\tconst escaped = key.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n\t\t\t\tfields.push({ field: `${field}/${i}/arguments/${escaped}`, text: value });\n\t\t\t}\n\t\t} else if (\n\t\t\tblock.type === \"image\" &&\n\t\t\trole !== \"assistant\" &&\n\t\t\ttypeof block.data === \"string\" &&\n\t\t\ttypeof block.mimeType === \"string\"\n\t\t) {\n\t\t\t// This API selects text only; it makes no lossless multimodal claim.\n\t\t} else return undefined;\n\t}\n\treturn fields;\n}\n\nfunction outcome(\n\trequestIndex: number,\n\tstatus: NativeRecoveryStatus,\n\tcoverage: NativeRecoveryCoverage = \"unknown\",\n\trecords: NativeRecoveryRecord[] = [],\n\treason?: string,\n): NativeRecoveryResult {\n\treturn { requestIndex, status, coverage, records, ...(reason ? { reason } : {}) };\n}\n\nfunction assemble(scope: NativeRecoveryScope, results: NativeRecoveryResult[]): NativeRecoveryResponse {\n\tconst statuses = new Set(results.map((result) => result.status));\n\tconst status =\n\t\tstatuses.size === 1\n\t\t\t? results[0].status\n\t\t\t: results.every((result) => result.status === \"found\" || result.status === \"complete-miss\")\n\t\t\t\t? \"found\"\n\t\t\t\t: \"partial\";\n\tconst coverage = results.every((result) => result.coverage === \"complete\")\n\t\t? \"complete\"\n\t\t: results.some((result) => result.coverage === \"partial\")\n\t\t\t? \"partial\"\n\t\t\t: \"unknown\";\n\treturn {\n\t\tkind: \"native-recovery\",\n\t\tversion: 1,\n\t\tnativeRecovery: 1,\n\t\tauthority: \"tool-data\",\n\t\tfreshness: \"unknown\",\n\t\tscope,\n\t\tstatus,\n\t\tcoverage,\n\t\tresults,\n\t\tsources: results.flatMap((result) =>\n\t\t\tresult.records.map((record) => ({\n\t\t\t\tsourceSessionId: record.sourceSessionId,\n\t\t\t\tentryId: record.ref,\n\t\t\t\trevision: record.revision,\n\t\t\t\tfield: record.field,\n\t\t\t\tstartLine: record.startLine,\n\t\t\t\tendLine: record.endLine,\n\t\t\t\tstartByte: record.startByte,\n\t\t\t\tendByte: record.endByte,\n\t\t\t\tprefixOmitted: record.prefixOmitted,\n\t\t\t\tsuffixOmitted: record.suffixOmitted,\n\t\t\t})),\n\t\t),\n\t};\n}\n\n/** Shared runtime admission for the native tool and Python host bridge. */\nexport function parseNativeRecoveryInput(value: unknown): NativeRecoveryInput {\n\tlet request: NativeRecoveryInput;\n\ttry {\n\t\trequest = JSON.parse(stringifyBoundedJson(value, 128 * 1024)) as NativeRecoveryInput;\n\t} catch {\n\t\tthrow new NativeRecoveryBudgetRefusal();\n\t}\n\tif (!Value.Check(nativeRecoveryInputSchema, request)) throw new Error(\"Invalid native recovery request\");\n\treturn request;\n}\n\ninterface RecoveryCursorState {\n\tsource: SourceSnapshotRef;\n\toperation: NativeRecoveryOperation;\n\tafter: number;\n\tentryId?: string;\n\tfield: number;\n\tbyte: number;\n\tline: number;\n\toverlap: string;\n\tunavailable: boolean;\n\tmatched: boolean;\n}\n\n/** Session-owned, ephemeral searches. No read lease or canonical body survives a call. */\nexport class NativeRecoveryCursorStore {\n\tprivate readonly states = new Map<string, RecoveryCursorState>();\n\tprivate generation = 0;\n\tclear(): void {\n\t\tthis.states.clear();\n\t\tthis.generation++;\n\t}\n\tget(id: string): RecoveryCursorState | undefined {\n\t\treturn this.states.get(id);\n\t}\n\tdelete(id: string): void {\n\t\tthis.states.delete(id);\n\t}\n\tget version(): number {\n\t\treturn this.generation;\n\t}\n\tsave(state: RecoveryCursorState, version: number, id: string = randomUUID()): string {\n\t\tif (version !== this.generation) throw new Error(\"Expired recovery cursor\");\n\t\tthis.states.delete(id);\n\t\tthis.states.set(id, structuredClone(state));\n\t\twhile (this.states.size > 16) this.states.delete(this.states.keys().next().value!);\n\t\treturn id;\n\t}\n}\n\n/** The caller captures ONE server branch before entering this service, including for a batch. */\nexport async function recoverCapturedHistory(\n\tview: SessionHistoryReadView,\n\tinput: NativeRecoveryInput,\n\tlimits: NativeRecoveryLimits = DEFAULT_NATIVE_RECOVERY_LIMITS,\n\tsignal?: AbortSignal,\n\tcursors?: NativeRecoveryCursorStore,\n): Promise<NativeRecoveryResponse> {\n\tconst cap = { ...limits };\n\tfor (const key of [\"maxBytes\", \"maxSourceBytes\", \"maxItems\", \"maxRequests\"] as const) {\n\t\tif (!Number.isSafeInteger(cap[key]) || cap[key] < 1) throw new NativeRecoveryBudgetRefusal();\n\t\tcap[key] = Math.min(cap[key], DEFAULT_NATIVE_RECOVERY_LIMITS[key]);\n\t}\n\tlet request: NativeRecoveryInput;\n\ttry {\n\t\trequest = parseNativeRecoveryInput(input);\n\t} catch (error) {\n\t\treturn createNativeRecoveryRefusal(\n\t\t\terror instanceof NativeRecoveryBudgetRefusal ? \"budget_refused\" : \"unavailable\",\n\t\t\t\"invalid_request\",\n\t\t\tcap.maxBytes,\n\t\t);\n\t}\n\tconst maxBytes = Math.min(cap.maxBytes, request.maxBytes ?? cap.maxBytes);\n\tif (request.action === \"skill\")\n\t\treturn createNativeRecoveryRefusal(\"not_authorized\", \"native_skill_selection_owner_required\", maxBytes);\n\tconst operations = request.action === \"batch\" ? request.requests : [request];\n\tconst version = cursors?.version ?? 0;\n\tconst resumed = operations.map((operation) => (operation.cursor ? cursors?.get(operation.cursor) : undefined));\n\tconst anchor = resumed.find(Boolean)?.source;\n\tif (anchor) {\n\t\tif (resumed.some((state) => state && JSON.stringify(state.source) !== JSON.stringify(anchor)))\n\t\t\treturn createNativeRecoveryRefusal(\"unavailable\", \"conflicting_selection\", maxBytes);\n\t\ttry {\n\t\t\tif (!view.atSnapshot) throw new Error(\"Captured source is unavailable\");\n\t\t\tview = await view.atSnapshot(anchor);\n\t\t} catch {\n\t\t\treturn createNativeRecoveryRefusal(\"unavailable\", \"cursor_source_unavailable\", maxBytes);\n\t\t}\n\t}\n\tconst { sessionId: sourceSessionId, leafId, sourceSequence } = view.source;\n\tconst scope: NativeRecoveryScope = {\n\t\tkind: \"branch\",\n\t\tprojection: \"public-text-only\",\n\t\tsourceSessionId,\n\t\tleafId,\n\t\tsourceSequence,\n\t};\n\tconst results = operations.map((_, i) => outcome(i, \"budget_refused\", \"unknown\", [], \"not_admitted\"));\n\tstringifyNativeRecoveryResponse(assemble(scope, results), maxBytes);\n\tif (operations.length > cap.maxRequests) return assemble(scope, results);\n\tlet sourceBytes = 0;\n\tlet examined = 0;\n\tlet selectedItems = 0;\n\tconst cache = new Map<string, { revision: string; entry: SessionEntry }>();\n\n\tasync function fieldsFor(metadata: IndexedSourceEvent, requestedField?: string): Promise<PublicField[] | undefined> {\n\t\tsignal?.throwIfAborted();\n\t\tlet cached = cache.get(metadata.id);\n\t\tif (cached && cached.revision !== metadata.revision) throw new Error(\"Captured revision changed\");\n\t\tif (!cached) {\n\t\t\tif (metadata.locator.length > cap.maxSourceBytes - sourceBytes) throw new NativeRecoveryBudgetRefusal();\n\t\t\tsourceBytes += metadata.locator.length;\n\t\t\tconst hydrated = await hydrateCapturedHistoryEntry(metadata, metadata.locator.length, (id, options) =>\n\t\t\t\tview.readPayload(id, options),\n\t\t\t);\n\t\t\tsignal?.throwIfAborted();\n\t\t\tcached = { revision: metadata.revision, entry: hydrated.entry };\n\t\t\tcache.set(metadata.id, cached);\n\t\t}\n\t\tif (requestedField === \"/nativeOrigin/submitted/text\") {\n\t\t\tif (\n\t\t\t\tcached.entry.type !== \"message\" ||\n\t\t\t\tmetadata.qualification !== \"native-admission\" ||\n\t\t\t\tmetadata.retention === \"retained-import\"\n\t\t\t)\n\t\t\t\treturn undefined;\n\t\t\tfor (const projection of projectTaskStateSource({\n\t\t\t\tsessionId: sourceSessionId,\n\t\t\t\tsequence: metadata.sequence,\n\t\t\t\trevision: metadata.revision,\n\t\t\t\tqualification: metadata.qualification,\n\t\t\t\tretention: metadata.retention,\n\t\t\t\tentry: cached.entry,\n\t\t\t})) {\n\t\t\t\tif (\n\t\t\t\t\tprojection.source.field === requestedField &&\n\t\t\t\t\tprojection.authority === \"user\" &&\n\t\t\t\t\tprojection.attribution === \"source-backed\" &&\n\t\t\t\t\ttypeof projection.text === \"string\"\n\t\t\t\t)\n\t\t\t\t\treturn [{ field: requestedField, text: projection.text }];\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\tconst fields = publicFields(cached.entry, DEFAULT_NATIVE_RECOVERY_LIMITS.maxItems, metadata.qualification);\n\t\tif (cached.entry.type === \"message\") {\n\t\t\tconst message = object(cached.entry.message);\n\t\t\tconst retained =\n\t\t\t\tmessage?.role === \"toolResult\" ? retainedToolOutput(object(message.details)?.retainedOutput) : undefined;\n\t\t\tconst field = fields?.find((field) => field.field === retained?.field);\n\t\t\tif (field && retained) {\n\t\t\t\tif (metadata.qualification === \"native-tool-execution\" && metadata.retention !== \"retained-import\")\n\t\t\t\t\tfield.retained = retained;\n\t\t\t\telse field.unavailable = true; // A preview is not the complete retained field, nor artifact authority.\n\t\t\t}\n\t\t}\n\t\treturn fields;\n\t}\n\n\tasync function recover(supplied: NativeRecoveryOperation, i: number): Promise<NativeRecoveryResult> {\n\t\tconst saved = resumed[i];\n\t\tif (supplied.cursor && !saved) return outcome(i, \"unavailable\", \"unknown\", [], \"expired_cursor\");\n\t\tif (saved && supplied.action === \"read\") return outcome(i, \"unavailable\", \"unknown\", [], \"conflicting_selection\");\n\t\tconst operation = saved ? { ...saved.operation, maxBytes: supplied.maxBytes } : supplied;\n\t\tconst needle = operation.need ?? operation.query;\n\t\tif (\n\t\t\tsaved &&\n\t\t\tObject.entries(supplied).some(\n\t\t\t\t([key, value]) =>\n\t\t\t\t\t![\"action\", \"cursor\", \"maxBytes\"].includes(key) &&\n\t\t\t\t\tvalue !==\n\t\t\t\t\t\t(key === \"need\" || key === \"query\" ? needle : saved.operation[key as keyof NativeRecoveryOperation]),\n\t\t\t)\n\t\t)\n\t\t\treturn outcome(i, \"unavailable\", \"unknown\", [], \"conflicting_selection\");\n\t\tif (operation.sourceSessionId !== undefined && operation.sourceSessionId !== sourceSessionId)\n\t\t\treturn outcome(i, \"not_authorized\", \"unknown\", [], \"source_not_in_capture\");\n\t\tif (\n\t\t\t(operation.need !== undefined && operation.query !== undefined && operation.need !== operation.query) ||\n\t\t\t(operation.endLine !== undefined && operation.endLine < (operation.startLine ?? 1)) ||\n\t\t\t(operation.endByte !== undefined && operation.endByte <= (operation.startByte ?? 0)) ||\n\t\t\t((operation.startByte !== undefined || operation.endByte !== undefined) &&\n\t\t\t\t(operation.startLine !== undefined || operation.endLine !== undefined))\n\t\t)\n\t\t\treturn outcome(i, \"unavailable\", \"unknown\", [], \"conflicting_selection\");\n\t\tif (\n\t\t\toperation.ref === undefined &&\n\t\t\t(operation.action === \"read\" ||\n\t\t\t\tneedle === undefined ||\n\t\t\t\toperation.revision !== undefined ||\n\t\t\t\toperation.startLine !== undefined ||\n\t\t\t\toperation.endLine !== undefined ||\n\t\t\t\toperation.startByte !== undefined ||\n\t\t\t\toperation.endByte !== undefined)\n\t\t)\n\t\t\treturn outcome(i, \"unavailable\", \"unknown\", [], \"exact_selection_requires_ref\");\n\t\tif (needle !== undefined && Buffer.byteLength(needle) > 8192) throw new NativeRecoveryBudgetRefusal();\n\t\tconst searching = needle !== undefined;\n\t\tconst continuable = operation.action !== \"read\" && searching;\n\t\tconst state: RecoveryCursorState = saved\n\t\t\t? structuredClone(saved)\n\t\t\t: {\n\t\t\t\t\tsource: { ...view.source },\n\t\t\t\t\toperation: { ...operation, cursor: undefined, maxBytes: undefined },\n\t\t\t\t\tafter: 0,\n\t\t\t\t\tfield: 0,\n\t\t\t\t\tbyte: 0,\n\t\t\t\t\tline: 1,\n\t\t\t\t\toverlap: \"\",\n\t\t\t\t\tunavailable: false,\n\t\t\t\t\tmatched: false,\n\t\t\t\t};\n\t\tconst records: NativeRecoveryRecord[] = [];\n\t\tlet partialWindow = false;\n\t\tlet reason: string | undefined;\n\t\tlet exhausted = false;\n\t\tlet windows = 0;\n\t\tconst cursorId = supplied.cursor ?? randomUUID();\n\t\tconst progress = (complete: boolean): NativeRecoveryResult => ({\n\t\t\t...outcome(\n\t\t\t\ti,\n\t\t\t\tcomplete && !state.unavailable && !partialWindow\n\t\t\t\t\t? records.length || state.matched\n\t\t\t\t\t\t? \"found\"\n\t\t\t\t\t\t: \"complete-miss\"\n\t\t\t\t\t: \"partial\",\n\t\t\t\tcomplete && !state.unavailable && !partialWindow ? \"complete\" : \"partial\",\n\t\t\t\trecords,\n\t\t\t\treason,\n\t\t\t),\n\t\t\t...(continuable ? { exhausted: complete, ...(!complete && cursors ? { cursor: cursorId } : {}) } : {}),\n\t\t});\n\t\tconst reserve = () => {\n\t\t\tconst candidate = progress(false);\n\t\t\tcandidate.reason = \"canonical_source_unavailable\";\n\t\t\tstringifyBoundedJson(candidate, Math.min(maxBytes, supplied.maxBytes ?? maxBytes));\n\t\t\tconst prospective = [...results];\n\t\t\tprospective[i] = candidate;\n\t\t\tstringifyNativeRecoveryResponse(assemble(scope, prospective), maxBytes);\n\t\t};\n\t\treserve(); // Keep cursor/status space before examining any source material.\n\t\tconst admit = (record: NativeRecoveryRecord): boolean => {\n\t\t\tif (selectedItems + records.length >= cap.maxItems) return false;\n\t\t\trecords.push(record);\n\t\t\ttry {\n\t\t\t\treserve();\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\trecords.pop();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t};\n\t\tconst resetField = () => {\n\t\t\tstate.byte = 0;\n\t\t\tstate.line = 1;\n\t\t\tstate.overlap = \"\";\n\t\t};\n\t\tconst nextEntry = (metadata: IndexedSourceEvent) => {\n\t\t\tstate.after = metadata.sequence;\n\t\t\tdelete state.entryId;\n\t\t\tstate.field = 0;\n\t\t\tresetField();\n\t\t};\n\t\twhile (!exhausted) {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tif (examined >= cap.maxItems) {\n\t\t\t\treason = \"scan_limit\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlet metadata: IndexedSourceEvent | undefined;\n\t\t\tlet afterPage: number | null | undefined;\n\t\t\tif (state.entryId || operation.ref) {\n\t\t\t\tmetadata = await view.get(state.entryId ?? operation.ref!);\n\t\t\t\tif (!metadata) return outcome(i, \"not_authorized\", \"unknown\", records, \"ref_not_in_captured_branch\");\n\t\t\t\tif (operation.revision !== undefined && metadata.revision !== operation.revision)\n\t\t\t\t\treturn outcome(i, \"unavailable\", \"unknown\", records, \"revision_mismatch\");\n\t\t\t} else {\n\t\t\t\tconst page = await view.page(state.after, 1, { scan: true });\n\t\t\t\tif (page.coverage !== \"complete\" || page.indexedThrough < sourceSequence) state.unavailable = true;\n\t\t\t\tmetadata = page.events[0];\n\t\t\t\tafterPage = page.nextAfter;\n\t\t\t\tif (!metadata) {\n\t\t\t\t\texamined++;\n\t\t\t\t\tif (afterPage === null) {\n\t\t\t\t\t\texhausted = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (afterPage <= state.after) throw new Error(\"History scan did not advance\");\n\t\t\t\t\tstate.after = afterPage;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\texamined++;\n\t\t\tstate.entryId = metadata.id;\n\t\t\tif (\n\t\t\t\t!operation.ref &&\n\t\t\t\t![\"message\", \"custom_message\", \"compaction\", \"branch_summary\", \"custom\"].includes(metadata.kind)\n\t\t\t) {\n\t\t\t\tnextEntry(metadata);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (metadata.locator.length > cap.maxSourceBytes) {\n\t\t\t\tif (operation.action === \"read\")\n\t\t\t\t\treturn outcome(\n\t\t\t\t\t\ti,\n\t\t\t\t\t\toperation.startByte !== undefined || operation.endByte !== undefined\n\t\t\t\t\t\t\t? \"unavailable\"\n\t\t\t\t\t\t\t: \"budget_refused\",\n\t\t\t\t\t\t\"unknown\",\n\t\t\t\t\t\t[],\n\t\t\t\t\t\t\"field_window_unsupported\",\n\t\t\t\t\t);\n\t\t\t\tstate.unavailable = true;\n\t\t\t\treason = \"field_window_unsupported\";\n\t\t\t\tnextEntry(metadata);\n\t\t\t\tif (operation.ref) exhausted = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!cache.has(metadata.id) && metadata.locator.length > cap.maxSourceBytes - sourceBytes) {\n\t\t\t\treason = \"source_limit\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlet fields: PublicField[] | undefined;\n\t\t\ttry {\n\t\t\t\tfields = await fieldsFor(metadata, operation.field);\n\t\t\t} catch (error) {\n\t\t\t\tstate.unavailable = true;\n\t\t\t\treason =\n\t\t\t\t\terror instanceof NativeRecoveryBudgetRefusal\n\t\t\t\t\t\t? \"unsupported_public_shape\"\n\t\t\t\t\t\t: \"canonical_source_unavailable\";\n\t\t\t\tnextEntry(metadata);\n\t\t\t\tif (operation.ref) exhausted = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!fields || (operation.field !== undefined && !fields.some((field) => field.field === operation.field))) {\n\t\t\t\tif (operation.ref) return outcome(i, \"unavailable\", \"unknown\", records, \"unsupported_public_field\");\n\t\t\t\tif (!fields) state.unavailable = true;\n\t\t\t\tnextEntry(metadata);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet paused = false;\n\t\t\tfor (; state.field < fields.length; state.field++, resetField()) {\n\t\t\t\tconst field = fields[state.field];\n\t\t\t\tif (operation.field !== undefined && field.field !== operation.field) continue;\n\t\t\t\tif (field.unavailable) {\n\t\t\t\t\tstate.unavailable = true;\n\t\t\t\t\treason = \"retained_output_unavailable\";\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst total = field.retained?.byteLength ?? Buffer.byteLength(field.text);\n\t\t\t\tif (field.retained && !field.retained.captureComplete) {\n\t\t\t\t\tstate.unavailable = true;\n\t\t\t\t\treason = \"capture_incomplete\";\n\t\t\t\t}\n\t\t\t\tif (state.byte === 0 && operation.startByte !== undefined) state.byte = operation.startByte;\n\t\t\t\tif (operation.endByte !== undefined && operation.endByte > total) {\n\t\t\t\t\tpartialWindow = true;\n\t\t\t\t\treason = \"requested_end_beyond_source\";\n\t\t\t\t}\n\t\t\t\tconst byteSelection = operation.startByte !== undefined || operation.endByte !== undefined;\n\t\t\t\tlet readText = \"\";\n\t\t\t\tlet readStart = state.byte;\n\t\t\t\tlet readLine: number | undefined = byteSelection && state.byte > 0 ? undefined : state.line;\n\t\t\t\twhile (state.byte < total || (total === 0 && state.byte === 0)) {\n\t\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\t\tif (++windows > cap.maxItems) {\n\t\t\t\t\t\tpaused = true;\n\t\t\t\t\t\treason = \"scan_limit\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst allowance = field.retained\n\t\t\t\t\t\t? Math.min(PUBLIC_TEXT_WINDOW_BYTES, cap.maxSourceBytes - sourceBytes - 4)\n\t\t\t\t\t\t: PUBLIC_TEXT_WINDOW_BYTES;\n\t\t\t\t\tif (allowance < 4) {\n\t\t\t\t\t\tpaused = true;\n\t\t\t\t\t\treason = \"source_limit\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst stop = Math.min(total, operation.endByte ?? total, state.byte + allowance);\n\t\t\t\t\tif (stop < state.byte) break;\n\t\t\t\t\tlet window: { text: string; startByte: number; endByte: number };\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (field.retained) {\n\t\t\t\t\t\t\tif (!view.source.sessionFile) throw new Error(\"Retained output owner unavailable\");\n\t\t\t\t\t\t\tconst selected = await readRetainedToolOutput(\n\t\t\t\t\t\t\t\tgetSessionArtifactPathForFile(view.source.sessionFile, sourceSessionId),\n\t\t\t\t\t\t\t\tfield.retained,\n\t\t\t\t\t\t\t\tstate.byte,\n\t\t\t\t\t\t\t\tstop - state.byte,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tsourceBytes += selected.sourceBytes;\n\t\t\t\t\t\t\twindow = selected;\n\t\t\t\t\t\t} else window = decodedTextWindow(field.text, state.byte, stop);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tstate.unavailable = true;\n\t\t\t\t\t\treason = \"retained_output_unavailable\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst startLine = state.line;\n\t\t\t\t\tconst combined = state.overlap + window.text;\n\t\t\t\t\tconst combinedStart = window.startByte - Buffer.byteLength(state.overlap);\n\t\t\t\t\tconst combinedLine = startLine - (state.overlap.match(/\\n/g)?.length ?? 0);\n\t\t\t\t\tlet text = window.text;\n\t\t\t\t\tlet startByte = window.startByte;\n\t\t\t\t\tlet endByte = window.endByte;\n\t\t\t\t\tlet recordLine: number | undefined = byteSelection && state.byte > 0 ? undefined : startLine;\n\t\t\t\t\tlet selected = !searching;\n\t\t\t\t\tif (searching) {\n\t\t\t\t\t\tconst lines = combined.split(\"\\n\");\n\t\t\t\t\t\tconst skip = Math.max(0, (operation.startLine ?? 1) - combinedLine);\n\t\t\t\t\t\tconst take = Math.min(lines.length, (operation.endLine ?? Infinity) - combinedLine + 1);\n\t\t\t\t\t\tconst prefix = lines.slice(0, skip).join(\"\\n\") + (skip ? \"\\n\" : \"\");\n\t\t\t\t\t\tconst selectedText = lines.slice(skip, Math.max(skip, take)).join(\"\\n\");\n\t\t\t\t\t\tconst localMatch = selectedText.indexOf(needle!);\n\t\t\t\t\t\tconst first = localMatch < 0 ? -1 : prefix.length + localMatch;\n\t\t\t\t\t\tselected = first >= 0;\n\t\t\t\t\t\tif (selected) {\n\t\t\t\t\t\t\tconst start = Math.max(prefix.length, first === 0 ? 0 : combined.lastIndexOf(\"\\n\", first - 1) + 1);\n\t\t\t\t\t\t\tconst newline = combined.indexOf(\"\\n\", first + needle!.length);\n\t\t\t\t\t\t\ttext = combined.slice(\n\t\t\t\t\t\t\t\tstart,\n\t\t\t\t\t\t\t\tMath.min(prefix.length + selectedText.length, newline < 0 ? combined.length : newline),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tstartByte = combinedStart + Buffer.byteLength(combined.slice(0, start));\n\t\t\t\t\t\t\tendByte = startByte + Buffer.byteLength(text);\n\t\t\t\t\t\t\trecordLine =\n\t\t\t\t\t\t\t\tbyteSelection && (operation.startByte ?? 0) > 0\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: combinedLine + (combined.slice(0, start).match(/\\n/g)?.length ?? 0);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tBuffer.byteLength(text) > Math.max(Buffer.byteLength(needle!) + 256, Math.floor(maxBytes / 8))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tconst matchByte = Buffer.byteLength(combined.slice(start, first));\n\t\t\t\t\t\t\t\tconst excerpt = decodedTextWindow(\n\t\t\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t\t\t\tMath.max(0, matchByte - 128),\n\t\t\t\t\t\t\t\t\tmatchByte + Buffer.byteLength(needle!) + 128,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (recordLine !== undefined)\n\t\t\t\t\t\t\t\t\trecordLine += decodedTextWindow(text, 0, excerpt.startByte).text.match(/\\n/g)?.length ?? 0;\n\t\t\t\t\t\t\t\ttext = excerpt.text;\n\t\t\t\t\t\t\t\tstartByte += excerpt.startByte;\n\t\t\t\t\t\t\t\tendByte = startByte + Buffer.byteLength(text);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (!byteSelection) {\n\t\t\t\t\t\tconst lines = text.split(\"\\n\");\n\t\t\t\t\t\tconst skip = Math.max(0, (operation.startLine ?? 1) - startLine);\n\t\t\t\t\t\tconst take = Math.min(lines.length, (operation.endLine ?? Infinity) - startLine + 1);\n\t\t\t\t\t\tselected = take > skip;\n\t\t\t\t\t\tif (selected) {\n\t\t\t\t\t\t\tconst prefix = lines.slice(0, skip).join(\"\\n\") + (skip ? \"\\n\" : \"\");\n\t\t\t\t\t\t\tstartByte += Buffer.byteLength(prefix);\n\t\t\t\t\t\t\ttext = lines.slice(skip, take).join(\"\\n\");\n\t\t\t\t\t\t\tendByte = startByte + Buffer.byteLength(text);\n\t\t\t\t\t\t\trecordLine = startLine + skip;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (selected) {\n\t\t\t\t\t\tif (!searching) {\n\t\t\t\t\t\t\tif (!readText) {\n\t\t\t\t\t\t\t\treadStart = startByte;\n\t\t\t\t\t\t\t\treadLine = recordLine;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treadText += text;\n\t\t\t\t\t\t\ttext = readText;\n\t\t\t\t\t\t\tstartByte = readStart;\n\t\t\t\t\t\t\trecordLine = readLine;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst record: NativeRecoveryRecord = {\n\t\t\t\t\t\t\tref: metadata.id,\n\t\t\t\t\t\t\trevision: metadata.revision,\n\t\t\t\t\t\t\tsourceSessionId,\n\t\t\t\t\t\t\tkind: metadata.kind,\n\t\t\t\t\t\t\tfield: field.field,\n\t\t\t\t\t\t\tstartByte,\n\t\t\t\t\t\t\tendByte,\n\t\t\t\t\t\t\tprefixOmitted: startByte > 0,\n\t\t\t\t\t\t\tsuffixOmitted: endByte < total,\n\t\t\t\t\t\t\t...(recordLine === undefined\n\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t: { startLine: recordLine, endLine: recordLine + (text.match(/\\n/g)?.length ?? 0) }),\n\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst done =\n\t\t\t\t\t\t\tsearching ||\n\t\t\t\t\t\t\twindow.endByte >= total ||\n\t\t\t\t\t\t\t(operation.endByte !== undefined && stop >= operation.endByte) ||\n\t\t\t\t\t\t\t(operation.endLine !== undefined &&\n\t\t\t\t\t\t\t\tstartLine + (window.text.match(/\\n/g)?.length ?? 0) > operation.endLine);\n\t\t\t\t\t\tif (done) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\toperation.endLine !== undefined &&\n\t\t\t\t\t\t\t\twindow.endByte >= total &&\n\t\t\t\t\t\t\t\tstartLine + (window.text.match(/\\n/g)?.length ?? 0) < operation.endLine\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tpartialWindow = true;\n\t\t\t\t\t\t\t\treason = \"requested_end_beyond_source\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!admit(record)) {\n\t\t\t\t\t\t\t\tpaused = true;\n\t\t\t\t\t\t\t\treason = \"output_limit\";\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstate.matched = true;\n\t\t\t\t\t\t\tif (searching && (startByte > 0 || endByte < total) && operation.ref) {\n\t\t\t\t\t\t\t\tpartialWindow = true;\n\t\t\t\t\t\t\t\treason = \"need_window\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (Buffer.byteLength(readText) > maxBytes) throw new NativeRecoveryBudgetRefusal();\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\twindow.endByte <= state.byte ||\n\t\t\t\t\t\twindow.endByte >= total ||\n\t\t\t\t\t\t(operation.endByte !== undefined && window.endByte >= operation.endByte)\n\t\t\t\t\t)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tstate.byte = window.endByte;\n\t\t\t\t\tstate.line += window.text.match(/\\n/g)?.length ?? 0;\n\t\t\t\t\tlet tail = searching ? combined.slice(-needle!.length - 2) : \"\";\n\t\t\t\t\tif (tail.charCodeAt(0) >= 0xdc00 && tail.charCodeAt(0) <= 0xdfff) tail = tail.slice(1);\n\t\t\t\t\tstate.overlap = searching\n\t\t\t\t\t\t? decodedTextWindow(tail, Math.max(0, Buffer.byteLength(tail) - Buffer.byteLength(needle!) - 3)).text\n\t\t\t\t\t\t: \"\";\n\t\t\t\t}\n\t\t\t\tif (paused) break;\n\t\t\t}\n\t\t\tif (paused) break;\n\t\t\tnextEntry(metadata);\n\t\t\tif (operation.ref || afterPage === null) {\n\t\t\t\texhausted = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tsignal?.throwIfAborted();\n\t\tif (!exhausted && continuable && cursors) cursors.save(state, version, cursorId);\n\t\telse if (supplied.cursor && exhausted) cursors?.delete(supplied.cursor);\n\t\tif (!searching && !exhausted && records.length === 0)\n\t\t\treturn outcome(i, \"budget_refused\", \"unknown\", [], reason ?? \"operation_budget\");\n\t\treturn progress(exhausted);\n\t}\n\tfor (let i = 0; i < operations.length; i++) {\n\t\ttry {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tconst result = await recover(operations[i], i);\n\t\t\tsignal?.throwIfAborted();\n\t\t\tstringifyBoundedJson(result, Math.min(maxBytes, operations[i].maxBytes ?? maxBytes));\n\t\t\tresults[i] = result;\n\t\t\tstringifyNativeRecoveryResponse(assemble(scope, results), maxBytes);\n\t\t\tselectedItems += result.records.length;\n\t\t} catch (error) {\n\t\t\tconst budget =\n\t\t\t\terror instanceof NativeRecoveryBudgetRefusal ||\n\t\t\t\t(error instanceof Error && /budget|limit/i.test(error.message));\n\t\t\tresults[i] = outcome(\n\t\t\t\ti,\n\t\t\t\tbudget ? \"budget_refused\" : \"unavailable\",\n\t\t\t\t\"unknown\",\n\t\t\t\t[],\n\t\t\t\tbudget ? \"operation_budget\" : signal?.aborted ? \"aborted\" : \"canonical_source_unavailable\",\n\t\t\t);\n\t\t}\n\t}\n\tconst response = assemble(scope, results);\n\tstringifyNativeRecoveryResponse(response, maxBytes);\n\treturn response;\n}\n"]}
|