@bastani/atomic 0.9.20-alpha.6 → 0.9.20-alpha.7
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 +32 -0
- package/dist/builtin/intercom/package.json +2 -2
- package/dist/builtin/mcp/package.json +2 -2
- package/dist/builtin/subagents/CHANGELOG.md +6 -0
- package/dist/builtin/subagents/package.json +3 -3
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +18 -8
- package/dist/builtin/web-access/package.json +2 -2
- package/dist/builtin/workflows/CHANGELOG.md +21 -0
- package/dist/builtin/workflows/README.md +5 -19
- package/dist/builtin/workflows/builtin/{chunk-deq63d9p.js → chunk-7bzcersz.js} +30 -19
- package/dist/builtin/workflows/builtin/goal.js +1 -1
- package/dist/builtin/workflows/builtin/index.js +1 -1
- package/dist/builtin/workflows/package.json +2 -2
- package/dist/builtin/workflows/skills/prompt-engineer/SKILL.md +10 -9
- package/dist/builtin/workflows/skills/prompt-engineer/references/advanced_patterns.md +4 -4
- package/dist/builtin/workflows/skills/prompt-engineer/references/claude_fable_5.md +96 -23
- package/dist/builtin/workflows/skills/prompt-engineer/references/claude_fable_5_1.md +75 -27
- package/dist/builtin/workflows/skills/prompt-engineer/references/claude_opus_4_8.md +72 -26
- package/dist/builtin/workflows/skills/prompt-engineer/references/claude_opus_5.md +58 -22
- package/dist/builtin/workflows/skills/prompt-engineer/references/claude_opus_5_5.md +118 -0
- package/dist/builtin/workflows/skills/prompt-engineer/references/claude_sonnet_5.md +70 -29
- package/dist/builtin/workflows/skills/prompt-engineer/references/core_prompting.md +1 -1
- package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_5_5.md +95 -32
- package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_5_6.md +79 -30
- package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6.md +139 -0
- package/dist/builtin/workflows/skills/prompt-engineer/references/quality_improvement.md +4 -4
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +247 -603
- package/dist/builtin/workflows/src/index.js +17 -7
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js +3 -1
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +3 -0
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +4 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +6 -0
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-tasks.d.ts +9 -0
- package/dist/core/agent-session-tasks.d.ts.map +1 -1
- package/dist/core/agent-session-tasks.js +68 -16
- package/dist/core/agent-session-tasks.js.map +1 -1
- package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
- package/dist/core/agent-session-tool-registry.js +9 -21
- package/dist/core/agent-session-tool-registry.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +2 -0
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +3 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +5 -2
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/execution-model-router.d.ts +14 -0
- package/dist/core/execution-model-router.d.ts.map +1 -1
- package/dist/core/execution-model-router.js +67 -21
- package/dist/core/execution-model-router.js.map +1 -1
- package/dist/core/fast-model-variants.d.ts +16 -0
- package/dist/core/fast-model-variants.d.ts.map +1 -1
- package/dist/core/fast-model-variants.js +27 -0
- package/dist/core/fast-model-variants.js.map +1 -1
- package/dist/core/model-runtime.d.ts +13 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +16 -1
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/sdk-types.d.ts +5 -0
- package/dist/core/sdk-types.d.ts.map +1 -1
- package/dist/core/sdk-types.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +4 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-types.js.map +1 -1
- package/dist/core/structured-output/index.d.ts +1 -0
- package/dist/core/structured-output/index.d.ts.map +1 -1
- package/dist/core/structured-output/index.js +34 -26
- package/dist/core/structured-output/index.js.map +1 -1
- package/dist/core/structured-output/jev-client.d.ts +9 -0
- package/dist/core/structured-output/jev-client.d.ts.map +1 -1
- package/dist/core/structured-output/jev-client.js +57 -3
- package/dist/core/structured-output/jev-client.js.map +1 -1
- package/dist/core/structured-output/jev.d.ts.map +1 -1
- package/dist/core/structured-output/jev.js +35 -53
- package/dist/core/structured-output/jev.js.map +1 -1
- package/dist/core/structured-output/resolver.d.ts +32 -24
- package/dist/core/structured-output/resolver.d.ts.map +1 -1
- package/dist/core/structured-output/resolver.js +57 -9
- package/dist/core/structured-output/resolver.js.map +1 -1
- package/dist/core/structured-output/types.d.ts +8 -4
- package/dist/core/structured-output/types.d.ts.map +1 -1
- package/dist/core/structured-output/types.js.map +1 -1
- package/dist/core/tasks/child-command-owner.d.ts +34 -0
- package/dist/core/tasks/child-command-owner.d.ts.map +1 -0
- package/dist/core/tasks/child-command-owner.js +70 -0
- package/dist/core/tasks/child-command-owner.js.map +1 -0
- package/dist/core/tools/bash-pty-native.d.ts +5 -1
- package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
- package/dist/core/tools/bash-pty-native.js +15 -7
- package/dist/core/tools/bash-pty-native.js.map +1 -1
- package/dist/core/tools/kill.d.ts +2 -2
- package/dist/core/tools/kill.d.ts.map +1 -1
- package/dist/core/tools/kill.js +3 -4
- package/dist/core/tools/kill.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/interactive-auth-login.js +2 -4
- package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-auth.d.ts +16 -0
- package/dist/modes/interactive-engine/isolated-auth.d.ts.map +1 -1
- package/dist/modes/interactive-engine/isolated-auth.js +27 -0
- package/dist/modes/interactive-engine/isolated-auth.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.d.ts +4 -0
- package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.js +4 -1
- package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
- package/dist/modes/rpc/rpc-client-api.d.ts +2 -1
- package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-api.js +7 -2
- package/dist/modes/rpc/rpc-client-api.js.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.js +3 -1
- package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
- package/dist/modes/rpc/rpc-provider-auth.d.ts +2 -1
- package/dist/modes/rpc/rpc-provider-auth.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-provider-auth.js +2 -2
- package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +2 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/docs/background-tasks.md +11 -2
- package/docs/environment-variables.md +1 -1
- package/docs/getting-started/first-session.md +2 -2
- package/docs/llama-cpp.md +2 -2
- package/docs/models/evals.md +47 -43
- package/docs/models/reference.md +1 -1
- package/docs/providers.md +11 -4
- package/docs/reference/cli.md +2 -2
- package/docs/rpc/examples.md +2 -0
- package/docs/sdk/reference.md +1 -1
- package/docs/sdk/structured-decisions.md +20 -14
- package/docs/settings.md +8 -8
- package/docs/skills.md +5 -1
- package/docs/subagents/reference.md +2 -2
- package/docs/subagents.md +1 -1
- package/docs/workflows/api-reference.md +5 -34
- package/docs/workflows/builtins.md +1 -1
- package/docs/workflows/operations.md +11 -77
- package/docs/workflows/reliable-design.md +14 -29
- package/docs/workflows.md +8 -7
- package/examples/rpc-client.ts +38 -0
- package/examples/rpc-extension-ui.ts +19 -5
- package/examples/sdk/README.md +1 -1
- package/npm-shrinkwrap.json +65 -65
- package/package.json +7 -7
- package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_astra.md +0 -58
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,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAsC,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC7G,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,EAAE,KAAK,EAAqB,kBAAkB,EAAsB,MAAM,+BAA+B,CAAC;AACjH,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,0BAA0B,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC3F,OAAO,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EACN,mBAAmB,EAC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,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;YAC/E,CAAC,CAAC,CAAC;YACH,IAAI,OAAO;gBACV,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,wBAAwB,OAAO,CAAC,WAAW,KAAK,OAAO,CAAC,KAAK,EAAE,CAAC,EAAE;oBAC/F,IAAI,EAAE,oBAAoB;iBAC1B,CAAC,CAAC;QACL,CAAC;QACD,IAAI,CAAC,UAAU;YAAE,MAAM,OAAO,CAAC,cAAc,CAAC,OAAO,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC;QAC/E,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,CAAC;IACjF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,eAAe,CAAC,OAAO,CAAC,eAAe,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC5G,CAAC;AACF,CAAC","sourcesContent":["import { basename, join, relative, sep } from \"node:path\";\nimport { clampThinkingLevel, type Message, type ProviderHeaders, streamSimple } from \"@bastani/pi-ai/compat\";\nimport { getProviderEnvValue } from \"@bastani/pi-ai/utils/provider-env\";\nimport { Agent, type AgentMessage, setDefaultStreamFn, type ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { getAgentDir } from \"../config.js\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.js\";\nimport type { AgentSessionInternalSurface } from \"./agent-session-methods.ts\";\nimport { restoreAnthropicReplayThinkingBlocks } from \"./anthropic-thinking-guard.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { getBuiltinPackageLocations, getBuiltinPackagePaths } from \"./builtin-packages.ts\";\nimport { withBuiltinResourceLoader } from \"./builtin-resource-loader.ts\";\nimport { getDefaultCacheRetention } from \"./cache-retention.ts\";\nimport { CacheWarmer } from \"./cache-warmer.ts\";\nimport { inheritChildSessionOptions } from \"./child-session-options.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner } from \"./extensions/index.js\";\nimport {\n\tfactoryAcquisitions,\n\tfactoryRollbackError,\n\trollbackFactoryAcquisitions,\n} from \"./extensions/loader-rollback.ts\";\nimport { getModelFastRoute, streamWithFastRoute, withFastRouteStreamOptions } from \"./fast-model-routing.ts\";\nimport { markLifecycleTiming } from \"./lifecycle-timings.ts\";\nimport {\n\tisMandatoryResourceLoader,\n\tisolateMandatoryResourceLoader,\n\twithMandatoryResourceLoader,\n} from \"./mandatory-resource-loader.ts\";\nimport { convertToLlm, repairOrphanToolResults } from \"./messages.ts\";\nimport { findInitialModel, resolveRestoredModelReference } from \"./model-resolver.ts\";\nimport { ModelRuntime } from \"./model-runtime.js\";\nimport { type ModelRuntimeSimpleStreamOptions, mergeHeaders } from \"./model-runtime-streaming.ts\";\nimport { sanitizeOpenAIResponsesPayload } from \"./openai-responses-payload-sanitizer.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\nimport { canCloneDefaultResourceDiscovery, DefaultResourceLoader } from \"./resource-loader.ts\";\nimport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\nimport { sessionLifecycleCreation, sessionLifecycleScopes } from \"./session-lifecycle-scope.ts\";\nimport { sessionGenerationClosing, sessionLifetime, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { registerStartupRollback, rollbackStartup } from \"./session-startup-rollback.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { ownedSettingsManagers } from \"./settings-write-ownership.ts\";\nimport { time } from \"./timings.ts\";\nimport { allToolNames, getDefaultToolNames } from \"./tools/index.ts\";\n\nexport type { ModelFallbackReason } from \"./model-resolver-types.ts\";\nexport * from \"./sdk-exports.ts\";\nexport type { AtomicBuiltin, CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\n\n// Preserve the pre-0.81 fallback for extensions that construct Agent instances\n// or invoke low-level agent loops without supplying streamFn.\nsetDefaultStreamFn(streamSimple);\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\n/** Keep static model headers visible to hooks without promoting unchanged defaults to request overrides. */\nfunction removeUnownedModelHeaders(\n\theaders: ProviderHeaders | undefined,\n\tmodelHeaders: ProviderHeaders | undefined,\n\trequestHeaders: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!headers || !modelHeaders) return headers;\n\tconst requestOwned = new Set(Object.keys(requestHeaders ?? {}).map((name) => name.toLowerCase()));\n\tconst filtered = { ...headers };\n\tfor (const [modelName, modelValue] of Object.entries(modelHeaders)) {\n\t\tconst lowerName = modelName.toLowerCase();\n\t\tif (requestOwned.has(lowerName)) continue;\n\t\tfor (const [name, value] of Object.entries(filtered)) {\n\t\t\tif (name.toLowerCase() === lowerName && value === modelValue) delete filtered[name];\n\t\t}\n\t}\n\treturn Object.keys(filtered).length > 0 ? filtered : undefined;\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 '@bastani/pi-ai/compat';\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: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\treturn createScopedSession(options, false);\n}\n\n/** Internal CLI assembly seam. Not exported from the package entrypoint. */\nexport function createUnstartedAgentSession(options: CreateAgentSessionOptions): Promise<CreateAgentSessionResult> {\n\treturn createScopedSession(options, true);\n}\n\nfunction createScopedSession(\n\toptions: CreateAgentSessionOptions,\n\tdeferStart: boolean,\n): Promise<CreateAgentSessionResult> {\n\tconst inherited = sessionLifecycleCreation.getStore();\n\tconst context = inherited && !inherited.claimed ? inherited : { scope: {} };\n\treturn sessionLifecycleCreation.run({ ...context, claimed: true }, async () => {\n\t\tconst result = await factoryAcquisitions.run(\n\t\t\t{ pending: new Map(), replacement: context.replacement },\n\t\t\tasync () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await constructAgentSession(\n\t\t\t\t\t\t{ ...options, extensionBindings: options.extensionBindings ?? context.bindings },\n\t\t\t\t\t\tdeferStart,\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow factoryRollbackError(error, await rollbackFactoryAcquisitions());\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\tsessionLifecycleScopes.set(result.session, context.scope);\n\t\treturn result;\n\t});\n}\n\nasync function constructAgentSession(\n\toptions: CreateAgentSessionOptions,\n\tdeferStart: boolean,\n): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\t// The concrete default can rediscover into private storage (including deferred\n\t// CLI configuration). Custom discovery stays delegated; composition instantiates\n\t// its extensions independently without replacing overridden resource policy.\n\tif (canCloneDefaultResourceDiscovery(resourceLoader)) {\n\t\tresourceLoader = await resourceLoader.createSessionLoader(sessionLifecycleCreation.getStore()!.scope);\n\t}\n\tif (resourceLoader) resourceLoader = await isolateMandatoryResourceLoader(resourceLoader);\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst modelRuntime = options.modelRuntime ?? (await ModelRuntime.create({ authPath, modelsPath }));\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\t// Mark workflow-created sessions as internal so they are excluded from the\n\t// standard `/resume` history while remaining resumable via `/workflow resume`.\n\t// Only stamped when the orchestration context identifies a workflow stage;\n\t// reattaching to an already-marked session preserves its existing marker.\n\tif (options.orchestrationContext?.kind === \"workflow-stage\") {\n\t\tconst ctx = options.orchestrationContext;\n\t\tsessionManager.markSessionInternal({\n\t\t\trunId: ctx.workflowRunId,\n\t\t\tstageId: ctx.workflowStageId,\n\t\t\tstageName: ctx.workflowStageName,\n\t\t});\n\t}\n\n\tconst disableWorkflowExtension =\n\t\toptions.orchestrationContext?.kind === \"workflow-stage\" || options.subagentPolicy !== undefined;\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tsettingsManager,\n\t\t\tbuiltinPackagePaths: getBuiltinPackagePaths(options.builtins).map((source) =>\n\t\t\t\tdisableWorkflowExtension && basename(source) === \"workflows\" ? { source, extensions: [] } : source,\n\t\t\t),\n\t\t});\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\tif (\n\t\t(options.resourceLoader || options.builtins || disableWorkflowExtension) &&\n\t\t(!isMandatoryResourceLoader(resourceLoader) || options.builtins || disableWorkflowExtension)\n\t) {\n\t\tresourceLoader = await withBuiltinResourceLoader(\n\t\t\tresourceLoader,\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\toptions.builtins,\n\t\t\tdisableWorkflowExtension,\n\t\t);\n\t}\n\tif (options.builtins?.intercom !== false) {\n\t\tresourceLoader = await withMandatoryResourceLoader(resourceLoader, cwd);\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst repairedMessages = repairOrphanToolResults(existingSession.messages, { repairTrailing: true });\n\tconst existingMessages = options.initialContextTransform\n\t\t? options.initialContextTransform(repairedMessages)\n\t\t: repairedMessages;\n\tconst hasExistingSession = existingMessages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\tlet modelFallbackReason: import(\"./model-resolver-types.ts\").ModelFallbackReason | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tmodel = await resolveRestoredModelReference(\n\t\t\texistingSession.model.provider,\n\t\t\texistingSession.model.modelId,\n\t\t\tmodelRuntime,\n\t\t);\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t\tmodelFallbackReason = \"session-restore\";\n\t\t}\n\t}\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelThinkingLevels: settingsManager.getAllModelThinkingLevels(),\n\t\t\tmodelRuntime,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tif (result.fallbackReason === \"configured-provider-unsupported\") {\n\t\t\t\tmodelFallbackMessage = result.fallbackMessage;\n\t\t\t\tmodelFallbackReason = result.fallbackReason;\n\t\t\t} else if (!modelFallbackMessage) {\n\t\t\t\tmodelFallbackMessage = result.fallbackMessage ?? formatNoModelsAvailableMessage();\n\t\t\t\tmodelFallbackReason = result.fallbackReason ?? \"no-models-available\";\n\t\t\t}\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to per-model override, then global default\n\tif (thinkingLevel === undefined && model) {\n\t\tthinkingLevel = settingsManager.getModelThinkingLevel(model.provider, model.id);\n\t}\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\t// `defaultTools` narrows only the initial BUILT-IN selection. It must not\n\t// narrow `allowedToolNames`: a narrow allowlist would drop every extension\n\t// and SDK custom tool (workflow, subagent, intercom, mcp, web_search, ...)\n\t// for any user who configures it (upstream 4d9aa837 + companion fix 541045ae).\n\tconst configuredDefaultToolNames = settingsManager.getDefaultTools();\n\tconst allowedToolNames =\n\t\toptions.noTools === \"all\" ? [] : options.tools === undefined ? undefined : [...options.tools];\n\tconst initialActiveToolNames: string[] = allowedToolNames\n\t\t? [...allowedToolNames]\n\t\t: options.noTools\n\t\t\t? []\n\t\t\t: [...(configuredDefaultToolNames ?? getDefaultToolNames())];\n\tconst childBuiltins = { ...options.builtins };\n\tconst childExcludedTools = [\n\t\t...(options.excludedTools ?? []),\n\t\t...(allowedToolNames === undefined\n\t\t\t? [...allToolNames].filter((name) => !initialActiveToolNames.includes(name))\n\t\t\t: []),\n\t];\n\n\tlet agent: Agent;\n\n\tlet lastConvertedLlmMessages: Message[] | undefined;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\tlastConvertedLlmMessages = converted;\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\tconst filtered = converted.map((msg): Message => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\"\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\t\t\ttext: \"Image reading is disabled.\",\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\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\ti > 0 &&\n\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(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t// `user` and `toolResult` carry different content unions, and mapping them in one\n\t\t\t\t\t\t// branch widens both to their union. Only image blocks are rewritten here, so each\n\t\t\t\t\t\t// message keeps its own shape at runtime.\n\t\t\t\t\t\treturn { ...msg, content: filteredContent } as Message;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t\tlastConvertedLlmMessages = filtered;\n\t\treturn filtered;\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\tconst cacheWarmer = new CacheWarmer(\n\t\t{\n\t\t\tstreamSimple: (model, context, requestOptions) => {\n\t\t\t\tconst extension = modelRuntime.getRegisteredProviderConfig(model.provider);\n\t\t\t\treturn getModelFastRoute(model)?.serviceTier !== undefined &&\n\t\t\t\t\t!(extension?.streamSimple && extension.api === model.api)\n\t\t\t\t\t? streamWithFastRoute(model, context, requestOptions)\n\t\t\t\t\t: modelRuntime.streamSimple(model, context, requestOptions);\n\t\t\t},\n\t\t},\n\t\tsessionManager,\n\t\t() => settingsManager.getCacheWarmingMode(),\n\t\tasync (event) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) {\n\t\t\t\treturn event.action;\n\t\t\t}\n\t\t\treturn (await runner.emitCacheWarmingDecision(event)) ?? event.action;\n\t\t},\n\t\t(refresh) => trackSessionWork(session, refresh),\n\t);\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t\tmessages: existingMessages,\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, streamOptions) => {\n\t\t\tconst authResult = await modelRuntime.getRequestAuth(model, {\n\t\t\t\tapiKey: streamOptions?.apiKey,\n\t\t\t\tenv: streamOptions?.env,\n\t\t\t\tsignal: streamOptions?.signal,\n\t\t\t});\n\t\t\tconst compatibility = authResult ? undefined : modelRuntime.getCompatibilityRequestConfig(model);\n\t\t\tif (!authResult && compatibility?.authHeader) {\n\t\t\t\tthrow new Error(`No API key found for \"${model.provider}\"`);\n\t\t\t}\n\t\t\tconst auth = {\n\t\t\t\tapiKey: authResult?.auth.apiKey,\n\t\t\t\theaders: authResult?.auth.headers ?? compatibility?.headers,\n\t\t\t\tbaseUrl: authResult?.auth.baseUrl,\n\t\t\t\tenv: authResult?.env,\n\t\t\t};\n\t\t\tconst requestModel =\n\t\t\t\tauth.baseUrl !== undefined && auth.baseUrl !== model.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = streamOptions?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\tstreamOptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst streamDeadlineMs = streamOptions?.streamDeadlineMs ?? settingsManager.getStreamDeadlineMs();\n\t\t\tconst requestHeaders = mergeProviderAttributionHeaders(\n\t\t\t\tmodel,\n\t\t\t\tsettingsManager,\n\t\t\t\tstreamOptions?.sessionId,\n\t\t\t\tauth.headers,\n\t\t\t\tstreamOptions?.headers,\n\t\t\t);\n\t\t\tconst mergedHeaders = mergeHeaders(model.headers, requestHeaders);\n\t\t\tconst headerRunner = extensionRunnerRef.current;\n\t\t\tconst assembledHeaders = headerRunner?.hasHandlers(\"before_provider_headers\")\n\t\t\t\t? await headerRunner.emitBeforeProviderHeaders(mergedHeaders ?? {})\n\t\t\t\t: mergedHeaders;\n\t\t\tconst extensionProvider = modelRuntime.getRegisteredProviderConfig(requestModel.provider);\n\t\t\tconst usesExtensionStream =\n\t\t\t\textensionProvider?.streamSimple !== undefined && requestModel.api === extensionProvider.api;\n\t\t\tconst transportHeaders = usesExtensionStream\n\t\t\t\t? assembledHeaders\n\t\t\t\t: removeUnownedModelHeaders(assembledHeaders, model.headers, requestHeaders);\n\t\t\t// Fast-vs-normal is the selected model's own identity, so the canonical `-fast` model is what\n\t\t\t// dispatch, the recorded assistant message, session state, and usage all see. The provider\n\t\t\t// adapter reads `fastRoute.upstreamModelId` when it serializes the outbound request.\n\t\t\tconst fastRoute = getModelFastRoute(requestModel);\n\t\t\tif (fastRoute?.serviceTier !== undefined && !usesExtensionStream && !authResult) {\n\t\t\t\tthrow new Error(`No API key found for \"${model.provider}\"`);\n\t\t\t}\n\t\t\tconst env = auth.env || streamOptions?.env ? { ...auth.env, ...streamOptions?.env } : undefined;\n\t\t\tconst cacheRetentionEnv = getProviderEnvValue(\"PI_CACHE_RETENTION\", env);\n\t\t\t// Shared by main chat, workflow stages and subagents; provider capability gates still apply.\n\t\t\tconst cacheRetention =\n\t\t\t\tstreamOptions?.cacheRetention ??\n\t\t\t\t(cacheRetentionEnv === \"none\"\n\t\t\t\t\t? \"none\"\n\t\t\t\t\t: !cacheRetentionEnv\n\t\t\t\t\t\t? getDefaultCacheRetention(requestModel)\n\t\t\t\t\t\t: cacheRetentionEnv === \"long\"\n\t\t\t\t\t\t\t? \"long\"\n\t\t\t\t\t\t\t: \"short\");\n\t\t\tconst fastRouteStreamOptions = withFastRouteStreamOptions(fastRoute, {\n\t\t\t\t...streamOptions,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tenv,\n\t\t\t\tcacheRetention,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tstreamDeadlineMs,\n\t\t\t\tmaxRetries: streamOptions?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: streamOptions?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders: transportHeaders,\n\t\t\t});\n\t\t\tconst preparedStreamOptions: ModelRuntimeSimpleStreamOptions = {\n\t\t\t\t...fastRouteStreamOptions,\n\t\t\t\tpreparedRequestAuth: { resolution: authResult },\n\t\t\t};\n\t\t\tif (streamOptions?.sessionId === sessionManager.getSessionId()) {\n\t\t\t\tconst prefix = [...agent.state.messages];\n\t\t\t\tcacheWarmer.start({ model: requestModel, context, options: preparedStreamOptions }, () => {\n\t\t\t\t\tconst current = agent.state.model;\n\t\t\t\t\treturn (\n\t\t\t\t\t\t!sessionLifetime(session).aborted &&\n\t\t\t\t\t\t!sessionGenerationClosing.has(session) &&\n\t\t\t\t\t\t!(session as unknown as AgentSessionInternalSurface)._agentRunAbortRequested &&\n\t\t\t\t\t\tcurrent?.provider === model.provider &&\n\t\t\t\t\t\tcurrent.id === model.id &&\n\t\t\t\t\t\tprefix.every((message, index) => agent.state.messages[index] === message)\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (usesExtensionStream) {\n\t\t\t\treturn modelRuntime.streamSimple(requestModel, context, preparedStreamOptions);\n\t\t\t}\n\t\t\tif (fastRoute?.serviceTier !== undefined) {\n\t\t\t\treturn streamWithFastRoute(requestModel, context, fastRouteStreamOptions);\n\t\t\t}\n\t\t\t// The Codex routing identity is attached by ModelRuntimeStreaming, after auth headers are\n\t\t\t// merged. Applying it here would be inert: `mergeHeaders` copies the header object the\n\t\t\t// wrapper mutates.\n\t\t\treturn modelRuntime.streamSimple(requestModel, context, preparedStreamOptions);\n\t\t},\n\t\tonPayload: async (payload, model) => {\n\t\t\tconst sourceMessages = lastConvertedLlmMessages;\n\t\t\tconst replayGuardedPayload = sourceMessages\n\t\t\t\t? restoreAnthropicReplayThinkingBlocks(payload, sourceMessages, model)\n\t\t\t\t: payload;\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tlet finalPayload: unknown;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\tfinalPayload = replayGuardedPayload;\n\t\t\t} else {\n\t\t\t\tconst extensionPayload = await runner.emitBeforeProviderRequest(replayGuardedPayload);\n\t\t\t\tfinalPayload = sourceMessages\n\t\t\t\t\t? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n\t\t\t\t\t: extensionPayload;\n\t\t\t}\n\t\t\tconst sanitizedPayload = sanitizeOpenAIResponsesPayload(finalPayload, model);\n\t\t\tmarkLifecycleTiming(\"before-provider-request\");\n\t\t\treturn sanitizedPayload;\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tconst transformed = runner ? await runner.emitContext(messages) : messages;\n\t\t\treturn scrubPreCompactionAssistantUsage(transformed, sessionManager.getBranch());\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore missing settings metadata for older sessions.\n\tif (hasExistingSession) {\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst providerRollback = modelRuntime.createExtensionProviderTransaction();\n\tlet session: AgentSession;\n\ttry {\n\t\tsession = new AgentSession({\n\t\t\tagent,\n\t\t\tsessionManager,\n\t\t\tsettingsManager,\n\t\t\tcwd,\n\t\t\tchildSessionOptions: (child) =>\n\t\t\t\tinheritChildSessionOptions(\n\t\t\t\t\t{\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tagentDir,\n\t\t\t\t\t\tmodelRuntime,\n\t\t\t\t\t\tsettingsManager,\n\t\t\t\t\t\tmodel: session.model,\n\t\t\t\t\t\tthinkingLevel: session.thinkingLevel,\n\t\t\t\t\t\tfallbackModels: options.fallbackModels ?? settingsManager.getFallbackModels(),\n\t\t\t\t\t\tisFallbackModelAllowed: options.isFallbackModelAllowed,\n\t\t\t\t\t\tbuiltins: childBuiltins,\n\t\t\t\t\t\ttools: allowedToolNames,\n\t\t\t\t\t\tnoTools: options.noTools,\n\t\t\t\t\t\texcludedTools: childExcludedTools,\n\t\t\t\t\t\tcustomTools: options.customTools,\n\t\t\t\t\t\textensionBindings: session.extensionRunner.getChildHostBindings(),\n\t\t\t\t\t},\n\t\t\t\t\tchild,\n\t\t\t\t),\n\t\t\tscopedModels: options.scopedModels,\n\t\t\tfallbackModels: options.fallbackModels ?? settingsManager.getFallbackModels(),\n\t\t\tisFallbackModelAllowed: options.isFallbackModelAllowed,\n\t\t\tresourceLoader,\n\t\t\tcustomTools: options.customTools,\n\t\t\tmodelRuntime,\n\t\t\tcacheWarmer,\n\t\t\tinitialActiveToolNames,\n\t\t\tallowedToolNames,\n\t\t\texcludedToolNames: options.excludedTools,\n\t\t\textensionRunnerRef,\n\t\t\tsessionStartEvent: options.sessionStartEvent,\n\t\t\torchestrationContext: options.orchestrationContext,\n\t\t\tsubagentPolicy: options.subagentPolicy,\n\t\t\tsystemPromptTransform: options.systemPromptTransform,\n\t\t\tcontextProjectionTransform: options.initialContextTransform,\n\t\t});\n\t} catch (error) {\n\t\t// The constructor releases its own leases/subscriptions; restore borrowed provider state here.\n\t\tconst cleanup = await Promise.allSettled([providerRollback.commit(), settingsManager.flush()]);\n\t\tconst failures = cleanup.flatMap((result) => (result.status === \"rejected\" ? [result.reason] : []));\n\t\tif (failures.length)\n\t\t\tthrow new AggregateError([error, ...failures], \"Session construction failed and rollback reported errors\");\n\t\tthrow error;\n\t}\n\t// Only the selected factories transfer. Discovery may have acquired omitted factories.\n\tconst acquisitions = factoryAcquisitions.getStore();\n\tconst selected = resourceLoader.getExtensions();\n\tfor (const extension of selected.extensions) acquisitions?.pending?.delete(extension);\n\tif (!options.settingsManager) ownedSettingsManagers.set(settingsManager, session);\n\tconst rollbackReason = sessionLifecycleCreation.getStore()?.replacement ? \"new\" : \"quit\";\n\tregisterStartupRollback(session.extensionRunner, async (error) => {\n\t\tconst results = await Promise.allSettled([\n\t\t\t(session as unknown as AgentSessionInternalSurface)._close({\n\t\t\t\ttype: \"session_shutdown\",\n\t\t\t\treason: rollbackReason,\n\t\t\t}),\n\t\t\tproviderRollback.commit(),\n\t\t]);\n\t\tconst cleanupErrors = results.flatMap((result) => (result.status === \"rejected\" ? [result.reason] : []));\n\t\tif (cleanupErrors.length)\n\t\t\tthrow new AggregateError([error, ...cleanupErrors], \"Extension startup failed and rollback reported errors\");\n\t\tthrow error;\n\t});\n\ttry {\n\t\t// Omitted factories may share the selected runtime: release their acquisitions,\n\t\t// but leave that runtime and its selected subscriptions owned by the runner.\n\t\tconst failures = await rollbackFactoryAcquisitions(new Set([selected.runtime]));\n\t\tif (failures.length)\n\t\t\tthrow Object.assign(new AggregateError(failures, \"Unselected extension cleanup failed\"), {\n\t\t\t\tcode: \"ShutdownFailed\",\n\t\t\t});\n\t\tconst extensionsResult = resourceLoader.getExtensions();\n\t\tfor (const failure of extensionsResult.errors) {\n\t\t\tconst builtin = getBuiltinPackageLocations().find(({ packageDir }) => {\n\t\t\t\tconst path = relative(packageDir, failure.path);\n\t\t\t\treturn path !== \"..\" && !path.startsWith(`..${sep}`) && !path.startsWith(sep);\n\t\t\t});\n\t\t\tif (builtin)\n\t\t\t\tthrow Object.assign(new Error(`Builtin unavailable: ${builtin.packageName}: ${failure.error}`), {\n\t\t\t\t\tcode: \"BuiltinUnavailable\",\n\t\t\t\t});\n\t\t}\n\t\tif (!deferStart) await session.bindExtensions(options.extensionBindings ?? {});\n\t\treturn { session, extensionsResult, modelFallbackMessage, modelFallbackReason };\n\t} catch (error) {\n\t\treturn rollbackStartup(session.extensionRunner, error instanceof Error ? error : new Error(String(error)));\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAsC,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC7G,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,EAAE,KAAK,EAAqB,kBAAkB,EAAsB,MAAM,+BAA+B,CAAC;AACjH,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,0BAA0B,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC3F,OAAO,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO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AAI,EAAE,gBAAgB;aACtB,CAAC,CAAC;QACJ,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;QACxD,KAAK,MAAM,OAAO,IAAI,gBAAgB,CAAC,MAAM,EAAE,CAAC;YAC/C,MAAM,OAAO,GAAG,0BAA0B,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE;gBACpE,MAAM,IAAI,GAAG,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;gBAChD,OAAO,IAAI,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;YAC/E,CAAC,CAAC,CAAC;YACH,IAAI,OAAO;gBACV,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,wBAAwB,OAAO,CAAC,WAAW,KAAK,OAAO,CAAC,KAAK,EAAE,CAAC,EAAE;oBAC/F,IAAI,EAAE,oBAAoB;iBAC1B,CAAC,CAAC;QACL,CAAC;QACD,IAAI,CAAC,UAAU;YAAE,MAAM,OAAO,CAAC,cAAc,CAAC,OAAO,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC;QAC/E,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,CAAC;IACjF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,eAAe,CAAC,OAAO,CAAC,eAAe,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC5G,CAAC;AACF,CAAC","sourcesContent":["import { basename, join, relative, sep } from \"node:path\";\nimport { clampThinkingLevel, type Message, type ProviderHeaders, streamSimple } from \"@bastani/pi-ai/compat\";\nimport { getProviderEnvValue } from \"@bastani/pi-ai/utils/provider-env\";\nimport { Agent, type AgentMessage, setDefaultStreamFn, type ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { getAgentDir } from \"../config.js\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.js\";\nimport type { AgentSessionInternalSurface } from \"./agent-session-methods.ts\";\nimport { restoreAnthropicReplayThinkingBlocks } from \"./anthropic-thinking-guard.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { getBuiltinPackageLocations, getBuiltinPackagePaths } from \"./builtin-packages.ts\";\nimport { withBuiltinResourceLoader } from \"./builtin-resource-loader.ts\";\nimport { getDefaultCacheRetention } from \"./cache-retention.ts\";\nimport { CacheWarmer } from \"./cache-warmer.ts\";\nimport { inheritChildSessionOptions } from \"./child-session-options.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner } from \"./extensions/index.js\";\nimport {\n\tfactoryAcquisitions,\n\tfactoryRollbackError,\n\trollbackFactoryAcquisitions,\n} from \"./extensions/loader-rollback.ts\";\nimport { getModelFastRoute, streamWithFastRoute, withFastRouteStreamOptions } from \"./fast-model-routing.ts\";\nimport { markLifecycleTiming } from \"./lifecycle-timings.ts\";\nimport {\n\tisMandatoryResourceLoader,\n\tisolateMandatoryResourceLoader,\n\twithMandatoryResourceLoader,\n} from \"./mandatory-resource-loader.ts\";\nimport { convertToLlm, repairOrphanToolResults } from \"./messages.ts\";\nimport { findInitialModel, resolveRestoredModelReference } from \"./model-resolver.ts\";\nimport { ModelRuntime } from \"./model-runtime.js\";\nimport { type ModelRuntimeSimpleStreamOptions, mergeHeaders } from \"./model-runtime-streaming.ts\";\nimport { sanitizeOpenAIResponsesPayload } from \"./openai-responses-payload-sanitizer.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\nimport { canCloneDefaultResourceDiscovery, DefaultResourceLoader } from \"./resource-loader.ts\";\nimport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\nimport { sessionLifecycleCreation, sessionLifecycleScopes } from \"./session-lifecycle-scope.ts\";\nimport { sessionGenerationClosing, sessionLifetime, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { registerStartupRollback, rollbackStartup } from \"./session-startup-rollback.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { ownedSettingsManagers } from \"./settings-write-ownership.ts\";\nimport { createChildCommandTaskOwner } from \"./tasks/child-command-owner.js\";\nimport { time } from \"./timings.ts\";\nimport { allToolNames, getDefaultToolNames } from \"./tools/index.ts\";\n\nexport type { ModelFallbackReason } from \"./model-resolver-types.ts\";\nexport * from \"./sdk-exports.ts\";\nexport type { AtomicBuiltin, CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\n\n// Preserve the pre-0.81 fallback for extensions that construct Agent instances\n// or invoke low-level agent loops without supplying streamFn.\nsetDefaultStreamFn(streamSimple);\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\n/** Keep static model headers visible to hooks without promoting unchanged defaults to request overrides. */\nfunction removeUnownedModelHeaders(\n\theaders: ProviderHeaders | undefined,\n\tmodelHeaders: ProviderHeaders | undefined,\n\trequestHeaders: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!headers || !modelHeaders) return headers;\n\tconst requestOwned = new Set(Object.keys(requestHeaders ?? {}).map((name) => name.toLowerCase()));\n\tconst filtered = { ...headers };\n\tfor (const [modelName, modelValue] of Object.entries(modelHeaders)) {\n\t\tconst lowerName = modelName.toLowerCase();\n\t\tif (requestOwned.has(lowerName)) continue;\n\t\tfor (const [name, value] of Object.entries(filtered)) {\n\t\t\tif (name.toLowerCase() === lowerName && value === modelValue) delete filtered[name];\n\t\t}\n\t}\n\treturn Object.keys(filtered).length > 0 ? filtered : undefined;\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 '@bastani/pi-ai/compat';\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: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\treturn createScopedSession(options, false);\n}\n\n/** Internal CLI assembly seam. Not exported from the package entrypoint. */\nexport function createUnstartedAgentSession(options: CreateAgentSessionOptions): Promise<CreateAgentSessionResult> {\n\treturn createScopedSession(options, true);\n}\n\nfunction createScopedSession(\n\toptions: CreateAgentSessionOptions,\n\tdeferStart: boolean,\n): Promise<CreateAgentSessionResult> {\n\tconst inherited = sessionLifecycleCreation.getStore();\n\tconst context = inherited && !inherited.claimed ? inherited : { scope: {} };\n\treturn sessionLifecycleCreation.run({ ...context, claimed: true }, async () => {\n\t\tconst result = await factoryAcquisitions.run(\n\t\t\t{ pending: new Map(), replacement: context.replacement },\n\t\t\tasync () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await constructAgentSession(\n\t\t\t\t\t\t{ ...options, extensionBindings: options.extensionBindings ?? context.bindings },\n\t\t\t\t\t\tdeferStart,\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow factoryRollbackError(error, await rollbackFactoryAcquisitions());\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\tsessionLifecycleScopes.set(result.session, context.scope);\n\t\treturn result;\n\t});\n}\n\nasync function constructAgentSession(\n\toptions: CreateAgentSessionOptions,\n\tdeferStart: boolean,\n): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\t// The concrete default can rediscover into private storage (including deferred\n\t// CLI configuration). Custom discovery stays delegated; composition instantiates\n\t// its extensions independently without replacing overridden resource policy.\n\tif (canCloneDefaultResourceDiscovery(resourceLoader)) {\n\t\tresourceLoader = await resourceLoader.createSessionLoader(sessionLifecycleCreation.getStore()!.scope);\n\t}\n\tif (resourceLoader) resourceLoader = await isolateMandatoryResourceLoader(resourceLoader);\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst modelRuntime = options.modelRuntime ?? (await ModelRuntime.create({ authPath, modelsPath }));\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\t// Mark workflow-created sessions as internal so they are excluded from the\n\t// standard `/resume` history while remaining resumable via `/workflow resume`.\n\t// Only stamped when the orchestration context identifies a workflow stage;\n\t// reattaching to an already-marked session preserves its existing marker.\n\tif (options.orchestrationContext?.kind === \"workflow-stage\") {\n\t\tconst ctx = options.orchestrationContext;\n\t\tsessionManager.markSessionInternal({\n\t\t\trunId: ctx.workflowRunId,\n\t\t\tstageId: ctx.workflowStageId,\n\t\t\tstageName: ctx.workflowStageName,\n\t\t});\n\t}\n\n\tconst disableWorkflowExtension =\n\t\toptions.orchestrationContext?.kind === \"workflow-stage\" || options.subagentPolicy !== undefined;\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tsettingsManager,\n\t\t\tbuiltinPackagePaths: getBuiltinPackagePaths(options.builtins).map((source) =>\n\t\t\t\tdisableWorkflowExtension && basename(source) === \"workflows\" ? { source, extensions: [] } : source,\n\t\t\t),\n\t\t});\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\tif (\n\t\t(options.resourceLoader || options.builtins || disableWorkflowExtension) &&\n\t\t(!isMandatoryResourceLoader(resourceLoader) || options.builtins || disableWorkflowExtension)\n\t) {\n\t\tresourceLoader = await withBuiltinResourceLoader(\n\t\t\tresourceLoader,\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\toptions.builtins,\n\t\t\tdisableWorkflowExtension,\n\t\t);\n\t}\n\tif (options.builtins?.intercom !== false) {\n\t\tresourceLoader = await withMandatoryResourceLoader(resourceLoader, cwd);\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst repairedMessages = repairOrphanToolResults(existingSession.messages, { repairTrailing: true });\n\tconst existingMessages = options.initialContextTransform\n\t\t? options.initialContextTransform(repairedMessages)\n\t\t: repairedMessages;\n\tconst hasExistingSession = existingMessages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\tlet modelFallbackReason: import(\"./model-resolver-types.ts\").ModelFallbackReason | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tmodel = await resolveRestoredModelReference(\n\t\t\texistingSession.model.provider,\n\t\t\texistingSession.model.modelId,\n\t\t\tmodelRuntime,\n\t\t);\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t\tmodelFallbackReason = \"session-restore\";\n\t\t}\n\t}\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelThinkingLevels: settingsManager.getAllModelThinkingLevels(),\n\t\t\tmodelRuntime,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tif (result.fallbackReason === \"configured-provider-unsupported\") {\n\t\t\t\tmodelFallbackMessage = result.fallbackMessage;\n\t\t\t\tmodelFallbackReason = result.fallbackReason;\n\t\t\t} else if (!modelFallbackMessage) {\n\t\t\t\tmodelFallbackMessage = result.fallbackMessage ?? formatNoModelsAvailableMessage();\n\t\t\t\tmodelFallbackReason = result.fallbackReason ?? \"no-models-available\";\n\t\t\t}\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to per-model override, then global default\n\tif (thinkingLevel === undefined && model) {\n\t\tthinkingLevel = settingsManager.getModelThinkingLevel(model.provider, model.id);\n\t}\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\t// `defaultTools` narrows only the initial BUILT-IN selection. It must not\n\t// narrow `allowedToolNames`: a narrow allowlist would drop every extension\n\t// and SDK custom tool (workflow, subagent, intercom, mcp, web_search, ...)\n\t// for any user who configures it (upstream 4d9aa837 + companion fix 541045ae).\n\tconst configuredDefaultToolNames = settingsManager.getDefaultTools();\n\tconst allowedToolNames =\n\t\toptions.noTools === \"all\" ? [] : options.tools === undefined ? undefined : [...options.tools];\n\tconst initialActiveToolNames: string[] = allowedToolNames\n\t\t? [...allowedToolNames]\n\t\t: options.noTools\n\t\t\t? []\n\t\t\t: [...(configuredDefaultToolNames ?? getDefaultToolNames())];\n\tconst childBuiltins = { ...options.builtins };\n\tconst childExcludedTools = [\n\t\t...(options.excludedTools ?? []),\n\t\t...(allowedToolNames === undefined\n\t\t\t? [...allToolNames].filter((name) => !initialActiveToolNames.includes(name))\n\t\t\t: []),\n\t];\n\n\tlet agent: Agent;\n\n\tlet lastConvertedLlmMessages: Message[] | undefined;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\tlastConvertedLlmMessages = converted;\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\tconst filtered = converted.map((msg): Message => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\"\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\t\t\ttext: \"Image reading is disabled.\",\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\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\ti > 0 &&\n\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(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t// `user` and `toolResult` carry different content unions, and mapping them in one\n\t\t\t\t\t\t// branch widens both to their union. Only image blocks are rewritten here, so each\n\t\t\t\t\t\t// message keeps its own shape at runtime.\n\t\t\t\t\t\treturn { ...msg, content: filteredContent } as Message;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t\tlastConvertedLlmMessages = filtered;\n\t\treturn filtered;\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\tconst cacheWarmer = new CacheWarmer(\n\t\t{\n\t\t\tstreamSimple: (model, context, requestOptions) => {\n\t\t\t\tconst extension = modelRuntime.getRegisteredProviderConfig(model.provider);\n\t\t\t\treturn getModelFastRoute(model)?.serviceTier !== undefined &&\n\t\t\t\t\t!(extension?.streamSimple && extension.api === model.api)\n\t\t\t\t\t? streamWithFastRoute(model, context, requestOptions)\n\t\t\t\t\t: modelRuntime.streamSimple(model, context, requestOptions);\n\t\t\t},\n\t\t},\n\t\tsessionManager,\n\t\t() => settingsManager.getCacheWarmingMode(),\n\t\tasync (event) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) {\n\t\t\t\treturn event.action;\n\t\t\t}\n\t\t\treturn (await runner.emitCacheWarmingDecision(event)) ?? event.action;\n\t\t},\n\t\t(refresh) => trackSessionWork(session, refresh),\n\t);\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t\tmessages: existingMessages,\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, streamOptions) => {\n\t\t\tconst authResult = await modelRuntime.getRequestAuth(model, {\n\t\t\t\tapiKey: streamOptions?.apiKey,\n\t\t\t\tenv: streamOptions?.env,\n\t\t\t\tsignal: streamOptions?.signal,\n\t\t\t});\n\t\t\tconst compatibility = authResult ? undefined : modelRuntime.getCompatibilityRequestConfig(model);\n\t\t\tif (!authResult && compatibility?.authHeader) {\n\t\t\t\tthrow new Error(`No API key found for \"${model.provider}\"`);\n\t\t\t}\n\t\t\tconst auth = {\n\t\t\t\tapiKey: authResult?.auth.apiKey,\n\t\t\t\theaders: authResult?.auth.headers ?? compatibility?.headers,\n\t\t\t\tbaseUrl: authResult?.auth.baseUrl,\n\t\t\t\tenv: authResult?.env,\n\t\t\t};\n\t\t\tconst requestModel =\n\t\t\t\tauth.baseUrl !== undefined && auth.baseUrl !== model.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = streamOptions?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\tstreamOptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst streamDeadlineMs = streamOptions?.streamDeadlineMs ?? settingsManager.getStreamDeadlineMs();\n\t\t\tconst requestHeaders = mergeProviderAttributionHeaders(\n\t\t\t\tmodel,\n\t\t\t\tsettingsManager,\n\t\t\t\tstreamOptions?.sessionId,\n\t\t\t\tauth.headers,\n\t\t\t\tstreamOptions?.headers,\n\t\t\t);\n\t\t\tconst mergedHeaders = mergeHeaders(model.headers, requestHeaders);\n\t\t\tconst headerRunner = extensionRunnerRef.current;\n\t\t\tconst assembledHeaders = headerRunner?.hasHandlers(\"before_provider_headers\")\n\t\t\t\t? await headerRunner.emitBeforeProviderHeaders(mergedHeaders ?? {})\n\t\t\t\t: mergedHeaders;\n\t\t\tconst extensionProvider = modelRuntime.getRegisteredProviderConfig(requestModel.provider);\n\t\t\tconst usesExtensionStream =\n\t\t\t\textensionProvider?.streamSimple !== undefined && requestModel.api === extensionProvider.api;\n\t\t\tconst transportHeaders = usesExtensionStream\n\t\t\t\t? assembledHeaders\n\t\t\t\t: removeUnownedModelHeaders(assembledHeaders, model.headers, requestHeaders);\n\t\t\t// Fast-vs-normal is the selected model's own identity, so the canonical `-fast` model is what\n\t\t\t// dispatch, the recorded assistant message, session state, and usage all see. The provider\n\t\t\t// adapter reads `fastRoute.upstreamModelId` when it serializes the outbound request.\n\t\t\tconst fastRoute = getModelFastRoute(requestModel);\n\t\t\tif (fastRoute?.serviceTier !== undefined && !usesExtensionStream && !authResult) {\n\t\t\t\tthrow new Error(`No API key found for \"${model.provider}\"`);\n\t\t\t}\n\t\t\tconst env = auth.env || streamOptions?.env ? { ...auth.env, ...streamOptions?.env } : undefined;\n\t\t\tconst cacheRetentionEnv = getProviderEnvValue(\"PI_CACHE_RETENTION\", env);\n\t\t\t// Shared by main chat, workflow stages and subagents; provider capability gates still apply.\n\t\t\tconst cacheRetention =\n\t\t\t\tstreamOptions?.cacheRetention ??\n\t\t\t\t(cacheRetentionEnv === \"none\"\n\t\t\t\t\t? \"none\"\n\t\t\t\t\t: !cacheRetentionEnv\n\t\t\t\t\t\t? getDefaultCacheRetention(requestModel)\n\t\t\t\t\t\t: cacheRetentionEnv === \"long\"\n\t\t\t\t\t\t\t? \"long\"\n\t\t\t\t\t\t\t: \"short\");\n\t\t\tconst fastRouteStreamOptions = withFastRouteStreamOptions(fastRoute, {\n\t\t\t\t...streamOptions,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tenv,\n\t\t\t\tcacheRetention,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tstreamDeadlineMs,\n\t\t\t\tmaxRetries: streamOptions?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: streamOptions?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders: transportHeaders,\n\t\t\t});\n\t\t\tconst preparedStreamOptions: ModelRuntimeSimpleStreamOptions = {\n\t\t\t\t...fastRouteStreamOptions,\n\t\t\t\tpreparedRequestAuth: { resolution: authResult },\n\t\t\t};\n\t\t\tif (streamOptions?.sessionId === sessionManager.getSessionId()) {\n\t\t\t\tconst prefix = [...agent.state.messages];\n\t\t\t\tcacheWarmer.start({ model: requestModel, context, options: preparedStreamOptions }, () => {\n\t\t\t\t\tconst current = agent.state.model;\n\t\t\t\t\treturn (\n\t\t\t\t\t\t!sessionLifetime(session).aborted &&\n\t\t\t\t\t\t!sessionGenerationClosing.has(session) &&\n\t\t\t\t\t\t!(session as unknown as AgentSessionInternalSurface)._agentRunAbortRequested &&\n\t\t\t\t\t\tcurrent?.provider === model.provider &&\n\t\t\t\t\t\tcurrent.id === model.id &&\n\t\t\t\t\t\tprefix.every((message, index) => agent.state.messages[index] === message)\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (usesExtensionStream) {\n\t\t\t\treturn modelRuntime.streamSimple(requestModel, context, preparedStreamOptions);\n\t\t\t}\n\t\t\tif (fastRoute?.serviceTier !== undefined) {\n\t\t\t\treturn streamWithFastRoute(requestModel, context, fastRouteStreamOptions);\n\t\t\t}\n\t\t\t// The Codex routing identity is attached by ModelRuntimeStreaming, after auth headers are\n\t\t\t// merged. Applying it here would be inert: `mergeHeaders` copies the header object the\n\t\t\t// wrapper mutates.\n\t\t\treturn modelRuntime.streamSimple(requestModel, context, preparedStreamOptions);\n\t\t},\n\t\tonPayload: async (payload, model) => {\n\t\t\tconst sourceMessages = lastConvertedLlmMessages;\n\t\t\tconst replayGuardedPayload = sourceMessages\n\t\t\t\t? restoreAnthropicReplayThinkingBlocks(payload, sourceMessages, model)\n\t\t\t\t: payload;\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tlet finalPayload: unknown;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\tfinalPayload = replayGuardedPayload;\n\t\t\t} else {\n\t\t\t\tconst extensionPayload = await runner.emitBeforeProviderRequest(replayGuardedPayload);\n\t\t\t\tfinalPayload = sourceMessages\n\t\t\t\t\t? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n\t\t\t\t\t: extensionPayload;\n\t\t\t}\n\t\t\tconst sanitizedPayload = sanitizeOpenAIResponsesPayload(finalPayload, model);\n\t\t\tmarkLifecycleTiming(\"before-provider-request\");\n\t\t\treturn sanitizedPayload;\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tconst transformed = runner ? await runner.emitContext(messages) : messages;\n\t\t\treturn scrubPreCompactionAssistantUsage(transformed, sessionManager.getBranch());\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore missing settings metadata for older sessions.\n\tif (hasExistingSession) {\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst providerRollback = modelRuntime.createExtensionProviderTransaction();\n\tlet session: AgentSession;\n\tconst childCommandTaskOwner = createChildCommandTaskOwner(() => session.getAgentTaskHost());\n\ttry {\n\t\tsession = new AgentSession({\n\t\t\tagent,\n\t\t\tsessionManager,\n\t\t\tsettingsManager,\n\t\t\tcwd,\n\t\t\tchildSessionOptions: (child) =>\n\t\t\t\tinheritChildSessionOptions(\n\t\t\t\t\t{\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tagentDir,\n\t\t\t\t\t\tmodelRuntime,\n\t\t\t\t\t\tsettingsManager,\n\t\t\t\t\t\tmodel: session.model,\n\t\t\t\t\t\tthinkingLevel: session.thinkingLevel,\n\t\t\t\t\t\tfallbackModels: options.fallbackModels ?? settingsManager.getFallbackModels(),\n\t\t\t\t\t\tisFallbackModelAllowed: options.isFallbackModelAllowed,\n\t\t\t\t\t\tbuiltins: childBuiltins,\n\t\t\t\t\t\ttools: allowedToolNames,\n\t\t\t\t\t\tnoTools: options.noTools,\n\t\t\t\t\t\texcludedTools: childExcludedTools,\n\t\t\t\t\t\tcustomTools: options.customTools,\n\t\t\t\t\t\textensionBindings: session.extensionRunner.getChildHostBindings(),\n\t\t\t\t\t\tparentCommandTaskOwner: childCommandTaskOwner,\n\t\t\t\t\t},\n\t\t\t\t\tchild,\n\t\t\t\t),\n\t\t\tscopedModels: options.scopedModels,\n\t\t\tfallbackModels: options.fallbackModels ?? settingsManager.getFallbackModels(),\n\t\t\tisFallbackModelAllowed: options.isFallbackModelAllowed,\n\t\t\tresourceLoader,\n\t\t\tcustomTools: options.customTools,\n\t\t\tmodelRuntime,\n\t\t\tcacheWarmer,\n\t\t\tinitialActiveToolNames,\n\t\t\tallowedToolNames,\n\t\t\texcludedToolNames: options.excludedTools,\n\t\t\textensionRunnerRef,\n\t\t\tsessionStartEvent: options.sessionStartEvent,\n\t\t\torchestrationContext: options.orchestrationContext,\n\t\t\tsubagentPolicy: options.subagentPolicy,\n\t\t\tparentCommandTaskOwner: options.parentCommandTaskOwner,\n\t\t\tsystemPromptTransform: options.systemPromptTransform,\n\t\t\tcontextProjectionTransform: options.initialContextTransform,\n\t\t});\n\t} catch (error) {\n\t\t// The constructor releases its own leases/subscriptions; restore borrowed provider state here.\n\t\tconst cleanup = await Promise.allSettled([providerRollback.commit(), settingsManager.flush()]);\n\t\tconst failures = cleanup.flatMap((result) => (result.status === \"rejected\" ? [result.reason] : []));\n\t\tif (failures.length)\n\t\t\tthrow new AggregateError([error, ...failures], \"Session construction failed and rollback reported errors\");\n\t\tthrow error;\n\t}\n\t// Only the selected factories transfer. Discovery may have acquired omitted factories.\n\tconst acquisitions = factoryAcquisitions.getStore();\n\tconst selected = resourceLoader.getExtensions();\n\tfor (const extension of selected.extensions) acquisitions?.pending?.delete(extension);\n\tif (!options.settingsManager) ownedSettingsManagers.set(settingsManager, session);\n\tconst rollbackReason = sessionLifecycleCreation.getStore()?.replacement ? \"new\" : \"quit\";\n\tregisterStartupRollback(session.extensionRunner, async (error) => {\n\t\tconst results = await Promise.allSettled([\n\t\t\t(session as unknown as AgentSessionInternalSurface)._close({\n\t\t\t\ttype: \"session_shutdown\",\n\t\t\t\treason: rollbackReason,\n\t\t\t}),\n\t\t\tproviderRollback.commit(),\n\t\t]);\n\t\tconst cleanupErrors = results.flatMap((result) => (result.status === \"rejected\" ? [result.reason] : []));\n\t\tif (cleanupErrors.length)\n\t\t\tthrow new AggregateError([error, ...cleanupErrors], \"Extension startup failed and rollback reported errors\");\n\t\tthrow error;\n\t});\n\ttry {\n\t\t// Omitted factories may share the selected runtime: release their acquisitions,\n\t\t// but leave that runtime and its selected subscriptions owned by the runner.\n\t\tconst failures = await rollbackFactoryAcquisitions(new Set([selected.runtime]));\n\t\tif (failures.length)\n\t\t\tthrow Object.assign(new AggregateError(failures, \"Unselected extension cleanup failed\"), {\n\t\t\t\tcode: \"ShutdownFailed\",\n\t\t\t});\n\t\tconst extensionsResult = resourceLoader.getExtensions();\n\t\tfor (const failure of extensionsResult.errors) {\n\t\t\tconst builtin = getBuiltinPackageLocations().find(({ packageDir }) => {\n\t\t\t\tconst path = relative(packageDir, failure.path);\n\t\t\t\treturn path !== \"..\" && !path.startsWith(`..${sep}`) && !path.startsWith(sep);\n\t\t\t});\n\t\t\tif (builtin)\n\t\t\t\tthrow Object.assign(new Error(`Builtin unavailable: ${builtin.packageName}: ${failure.error}`), {\n\t\t\t\t\tcode: \"BuiltinUnavailable\",\n\t\t\t\t});\n\t\t}\n\t\tif (!deferStart) await session.bindExtensions(options.extensionBindings ?? {});\n\t\treturn { session, extensionsResult, modelFallbackMessage, modelFallbackReason };\n\t} catch (error) {\n\t\treturn rollbackStartup(session.extensionRunner, error instanceof Error ? error : new Error(String(error)));\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-types.js","sourceRoot":"","sources":["../../src/core/settings-types.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,CAAU,CAAC","sourcesContent":["export const CACHE_WARMING_MODES = [\"off\", \"streaming\", \"idle\"] as const;\nexport type CacheWarmingMode = (typeof CACHE_WARMING_MODES)[number];\n\nimport type { Transport } from \"@bastani/pi-ai/compat\";\nimport type { ScrollViewScrollbar } from \"@earendil-works/pi-tui\";\n\nexport interface CompactionModelOverride {\n\treserveTokens?: number;\n\tpreserve_recent?: number;\n}\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tcompression_ratio?: number; // default: 0.5 (fraction of compactable context to keep)\n\tpreserve_recent?: number; // default: 2 (recent context-eligible messages to keep)\n\tquery?: string; // default: auto-detected from session context\n\tmodelOverrides?: Record<string, CompactionModelOverride>; // exact \"provider/modelId\" keys\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface SessionSummarySettings {\n\tenabled?: boolean; // default: true - generate a one-line resume-picker summary once the agent goes idle\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tmaxAgentDelayMs?: number; // default: 60000\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n\thyperlinks?: boolean | \"auto\";\n\timages?: \"kitty\" | \"iterm2\" | \"auto\" | false;\n\ttrueColor?: boolean | \"auto\";\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface SearchSettings {\n\tcontextBefore?: number;\n\tcontextAfter?: number;\n}\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport type MermaidRenderingMode = \"off\" | \"final\" | \"streaming\";\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n\tmermaid?: MermaidRenderingMode; // default: \"streaming\"\n\tlatex?: boolean; // default: true\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\nexport type DefaultProjectTrust = \"ask\" | \"always\" | \"never\";\n\nexport type TransportSetting = Transport;\n\n/** What the terminal keeps when Atomic's fullscreen session exits. */\nexport type FullscreenExitOutput = \"transcript\" | \"resume-hint\";\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n * - autoload=false: start empty and apply only explicit resource patterns\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\tautoload?: boolean;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t\t\tworkflows?: string[];\n\t };\n\nexport interface BashInterceptorSettings {\n\tenabled?: boolean; // default: false\n}\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tfirstRunOnboardingStartedVersion?: string;\n\tonboardedVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\trouterModel?: string; // default: \"\"; prerequisite workflow/subagent router inference only, never \"auto\"\n\tdefaultThinkingLevel?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\tmodelThinkingLevels?: Record<string, \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\">;\n\tfallbackModels?: string[]; // Ordered main-chat fallback models, optionally suffixed with :thinkingLevel\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tenableAnalytics?: boolean; // storage only; no analytics transmission is performed\n\ttrackingId?: string; // stable UUID generated on first analytics opt-in\n\tshowCacheMissNotices?: boolean; // default: false - show cache costs and provider recovery diagnostics\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tsessionSummary?: SessionSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\texternalEditor?: string; // Command for Ctrl+G external editor; takes precedence over VISUAL/EDITOR\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)\n\tquietStartup?: boolean;\n\tdefaultProjectTrust?: DefaultProjectTrust; // default: \"ask\"; global setting only\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tbashInterceptor?: BashInterceptorSettings; // default: disabled; when enabled, user_bash handlers can intercept bash tool execution\n\tsearch?: SearchSettings; // Context lines for search results; defaults: before=1, after=3\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - version-adoption ping on first interactive launch with fresh settings or after an update with changelog entries\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths or directories\n\tskills?: string[]; // Array of local skill file paths or directories\n\tprompts?: string[]; // Array of local prompt template paths or directories\n\tthemes?: string[]; // Array of local theme file paths or directories\n\tworkflows?: string[]; // Array of local workflow file paths or directories\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tterminal?: TerminalSettings;\n\therdr?: { enabled?: boolean }; // default: true, only inside an interactive Herdr pane\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdefaultTools?: string[]; // Initial built-in tool selection; extension and SDK custom tools stay enabled\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\toutputPad?: 0 | 1; // Horizontal padding for chat message output (default: 1)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tfullscreenScrollbar?: ScrollViewScrollbar; // default: \"auto\"\n\tfullscreenExitOutput?: FullscreenExitOutput; // default: \"transcript\"\n\tfullscreenCopyOnSelect?: boolean; // default: true\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n\thttpProxy?: string; // Proxy URL applied as HTTP_PROXY and HTTPS_PROXY; global setting only\n\thttpIdleTimeoutMs?: number | string; // HTTP idle timeout; 0 or \"disabled\" disables it\n\tcacheWarming?: CacheWarmingMode; // Global only; each refresh costs money. Default: streaming.\n\twebsocketConnectTimeoutMs?: number | string; // WebSocket connect timeout; 0 or \"disabled\" disables it\n\tstreamDeadlineMs?: number | string; // Max idle gap between provider stream events; 0 or \"disabled\" disables it\n}\n\nexport type SettingsScope = \"global\" | \"project\";\n\nexport interface SettingsManagerCreateOptions {\n\tprojectTrusted?: boolean;\n}\n\nexport type SettingsFieldOrigin = \"primary\" | \"legacy\";\n\nexport interface SettingsStorage {\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;\n\t/**\n\t * Optional write-specific lock whose callback receives the current primary\n\t * document rather than a layered effective view. Storage implementations\n\t * without a distinct primary document can omit this method; layered storage\n\t * implementations must provide it to keep fallback fields out of the primary\n\t * document.\n\t */\n\twithPrimaryWriteLock?(scope: SettingsScope, fn: (currentPrimary: string | undefined) => string | undefined): void;\n\tgetFieldOrigin?(scope: SettingsScope, field: keyof Settings): SettingsFieldOrigin | undefined;\n}\n\nexport interface SettingsError {\n\tscope: SettingsScope;\n\tpath?: string;\n\terror: Error;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"settings-types.js","sourceRoot":"","sources":["../../src/core/settings-types.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,CAAU,CAAC","sourcesContent":["export const CACHE_WARMING_MODES = [\"off\", \"streaming\", \"idle\"] as const;\nexport type CacheWarmingMode = (typeof CACHE_WARMING_MODES)[number];\n\nimport type { Transport } from \"@bastani/pi-ai/compat\";\nimport type { ScrollViewScrollbar } from \"@earendil-works/pi-tui\";\n\nexport interface CompactionModelOverride {\n\treserveTokens?: number;\n\tpreserve_recent?: number;\n}\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tcompression_ratio?: number; // default: 0.5 (fraction of compactable context to keep)\n\tpreserve_recent?: number; // default: 2 (recent context-eligible messages to keep)\n\tquery?: string; // default: auto-detected from session context\n\tmodelOverrides?: Record<string, CompactionModelOverride>; // exact \"provider/modelId\" keys\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface SessionSummarySettings {\n\tenabled?: boolean; // default: true - generate a one-line resume-picker summary once the agent goes idle\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tmaxAgentDelayMs?: number; // default: 60000\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n\thyperlinks?: boolean | \"auto\";\n\timages?: \"kitty\" | \"iterm2\" | \"auto\" | false;\n\ttrueColor?: boolean | \"auto\";\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface SearchSettings {\n\tcontextBefore?: number;\n\tcontextAfter?: number;\n}\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport type MermaidRenderingMode = \"off\" | \"final\" | \"streaming\";\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n\tmermaid?: MermaidRenderingMode; // default: \"streaming\"\n\tlatex?: boolean; // default: true\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\nexport type DefaultProjectTrust = \"ask\" | \"always\" | \"never\";\n\nexport type TransportSetting = Transport;\n\n/** What the terminal keeps when Atomic's fullscreen session exits. */\nexport type FullscreenExitOutput = \"transcript\" | \"resume-hint\";\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n * - autoload=false: start empty and apply only explicit resource patterns\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\tautoload?: boolean;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t\t\tworkflows?: string[];\n\t };\n\nexport interface BashInterceptorSettings {\n\tenabled?: boolean; // default: false\n}\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tfirstRunOnboardingStartedVersion?: string;\n\tonboardedVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\trouterModel?: string; // default: \"\"; workflow-stage/subagent auto-model router inference only, never \"auto\"\n\tdefaultThinkingLevel?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\tmodelThinkingLevels?: Record<string, \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\">;\n\tfallbackModels?: string[]; // Ordered main-chat fallback models, optionally suffixed with :thinkingLevel\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tenableAnalytics?: boolean; // storage only; no analytics transmission is performed\n\ttrackingId?: string; // stable UUID generated on first analytics opt-in\n\tshowCacheMissNotices?: boolean; // default: false - show cache costs and provider recovery diagnostics\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tsessionSummary?: SessionSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\texternalEditor?: string; // Command for Ctrl+G external editor; takes precedence over VISUAL/EDITOR\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)\n\tquietStartup?: boolean;\n\tdefaultProjectTrust?: DefaultProjectTrust; // default: \"ask\"; global setting only\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tbashInterceptor?: BashInterceptorSettings; // default: disabled; when enabled, user_bash handlers can intercept bash tool execution\n\tsearch?: SearchSettings; // Context lines for search results; defaults: before=1, after=3\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - version-adoption ping on first interactive launch with fresh settings or after an update with changelog entries\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths or directories\n\tskills?: string[]; // Array of local skill file paths or directories\n\tprompts?: string[]; // Array of local prompt template paths or directories\n\tthemes?: string[]; // Array of local theme file paths or directories\n\tworkflows?: string[]; // Array of local workflow file paths or directories\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tterminal?: TerminalSettings;\n\therdr?: { enabled?: boolean }; // default: true, only inside an interactive Herdr pane\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdefaultTools?: string[]; // Initial built-in tool selection; extension and SDK custom tools stay enabled\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\toutputPad?: 0 | 1; // Horizontal padding for chat message output (default: 1)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tfullscreenScrollbar?: ScrollViewScrollbar; // default: \"auto\"\n\tfullscreenExitOutput?: FullscreenExitOutput; // default: \"transcript\"\n\tfullscreenCopyOnSelect?: boolean; // default: true\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n\thttpProxy?: string; // Proxy URL applied as HTTP_PROXY and HTTPS_PROXY; global setting only\n\thttpIdleTimeoutMs?: number | string; // HTTP idle timeout; 0 or \"disabled\" disables it\n\tcacheWarming?: CacheWarmingMode; // Global only; each refresh costs money. Default: streaming.\n\twebsocketConnectTimeoutMs?: number | string; // WebSocket connect timeout; 0 or \"disabled\" disables it\n\tstreamDeadlineMs?: number | string; // Max idle gap between provider stream events; 0 or \"disabled\" disables it\n}\n\nexport type SettingsScope = \"global\" | \"project\";\n\nexport interface SettingsManagerCreateOptions {\n\tprojectTrusted?: boolean;\n}\n\nexport type SettingsFieldOrigin = \"primary\" | \"legacy\";\n\nexport interface SettingsStorage {\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;\n\t/**\n\t * Optional write-specific lock whose callback receives the current primary\n\t * document rather than a layered effective view. Storage implementations\n\t * without a distinct primary document can omit this method; layered storage\n\t * implementations must provide it to keep fallback fields out of the primary\n\t * document.\n\t */\n\twithPrimaryWriteLock?(scope: SettingsScope, fn: (currentPrimary: string | undefined) => string | undefined): void;\n\tgetFieldOrigin?(scope: SettingsScope, field: keyof Settings): SettingsFieldOrigin | undefined;\n}\n\nexport interface SettingsError {\n\tscope: SettingsScope;\n\tpath?: string;\n\terror: Error;\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Static, TSchema } from "typebox";
|
|
2
2
|
import type { RouterDecisionRequest, StructuredOutputRequest, StructuredOutputResult } from "./types.js";
|
|
3
|
+
export type { JevStructuredOutputProvider } from "./resolver.js";
|
|
3
4
|
export { getStructuredOutputProviders, JEV_STRUCTURED_OUTPUT_PROVIDER, resolveRouterModel, } from "./resolver.js";
|
|
4
5
|
export type { RouterDecisionRequest, RouterModelSelectionOptions, StructuredChoiceQuestion, StructuredOutputModel, StructuredOutputRequest, StructuredOutputResult, } from "./types.js";
|
|
5
6
|
/** General structured inference remains one-shot. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/structured-output/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAY/C,OAAO,KAAK,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAEzG,OAAO,EACN,4BAA4B,EAC5B,8BAA8B,EAC9B,kBAAkB,GAClB,MAAM,eAAe,CAAC;AACvB,YAAY,EACX,qBAAqB,EACrB,2BAA2B,EAC3B,wBAAwB,EACxB,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/structured-output/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAY/C,OAAO,KAAK,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAEzG,YAAY,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EACN,4BAA4B,EAC5B,8BAA8B,EAC9B,kBAAkB,GAClB,MAAM,eAAe,CAAC;AACvB,YAAY,EACX,qBAAqB,EACrB,2BAA2B,EAC3B,wBAAwB,EACxB,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,YAAY,CAAC;AAkIpB,qDAAqD;AACrD,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,OAAO,EACtD,OAAO,EAAE,uBAAuB,CAAC,CAAC,CAAC,GACjC,OAAO,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAE5C;AAqID,6GAA6G;AAC7G,wBAAsB,mBAAmB,CAAC,CAAC,SAAS,OAAO,EAC1D,OAAO,EAAE,qBAAqB,CAAC,CAAC,CAAC;AACjC,iGAAiG;AACjG,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,OAAO,GAC9C,OAAO,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAc5C"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { retryAssistantCall } from "@bastani/pi-ai";
|
|
1
2
|
import { Check } from "typebox/value";
|
|
2
3
|
import { raceWithAbortSignal } from "../../utils/abort.js";
|
|
3
4
|
import { createStructuredOutputTool, STRUCTURED_OUTPUT_TOOL_NAME, } from "../tools/structured-output.js";
|
|
4
5
|
import { InvalidDecisionOutputError } from "./invalid-output.js";
|
|
5
6
|
import { inferJev, STRUCTURED_DECISION_POLICY } from "./jev.js";
|
|
6
|
-
import { JevRequestError } from "./jev-client.js";
|
|
7
|
-
import { resolveRouterModel } from "./resolver.js";
|
|
7
|
+
import { DEFAULT_DECISION_RETRY, JevRequestError } from "./jev-client.js";
|
|
8
|
+
import { isStructuredOutputProviderModel, resolveRouterModel } from "./resolver.js";
|
|
8
9
|
export { getStructuredOutputProviders, JEV_STRUCTURED_OUTPUT_PROVIDER, resolveRouterModel, } from "./resolver.js";
|
|
9
10
|
const DEFAULT_MAX_TOKENS = 4096;
|
|
10
11
|
function positiveInteger(value, name) {
|
|
@@ -48,7 +49,7 @@ async function inferChat(request, model, signal, assertActive) {
|
|
|
48
49
|
let response;
|
|
49
50
|
assertActive();
|
|
50
51
|
try {
|
|
51
|
-
response = await request.modelRegistry
|
|
52
|
+
response = await retryAssistantCall(() => request.modelRegistry
|
|
52
53
|
.streamSimple(decisionModel, {
|
|
53
54
|
systemPrompt: `${STRUCTURED_DECISION_POLICY}\n\n${request.instructions}\n\nCall ${STRUCTURED_OUTPUT_TOOL_NAME} exactly once with the decision. Do not use prose or other tools.`,
|
|
54
55
|
messages: [
|
|
@@ -73,12 +74,12 @@ async function inferChat(request, model, signal, assertActive) {
|
|
|
73
74
|
toolChoice: "auto",
|
|
74
75
|
maxTokens: request.maxTokens ?? DEFAULT_MAX_TOKENS,
|
|
75
76
|
})
|
|
76
|
-
.result();
|
|
77
|
+
.result(), request.retry ?? DEFAULT_DECISION_RETRY, signal);
|
|
77
78
|
}
|
|
78
79
|
catch {
|
|
79
80
|
signal.throwIfAborted();
|
|
80
81
|
// Provider exceptions can echo private state or credentials; do not retain their cause.
|
|
81
|
-
throw new Error("Structured output provider request failed. Check provider configuration and connectivity
|
|
82
|
+
throw new Error("Structured output provider request failed. Check provider configuration and connectivity.");
|
|
82
83
|
}
|
|
83
84
|
signal.throwIfAborted();
|
|
84
85
|
if (response.stopReason === "error" || response.stopReason === "aborted")
|
|
@@ -104,6 +105,12 @@ async function inferChat(request, model, signal, assertActive) {
|
|
|
104
105
|
usage: { inputTokens: response.usage.input, outputTokens: response.usage.output },
|
|
105
106
|
};
|
|
106
107
|
}
|
|
108
|
+
/** Credential failures get a static reason; their messages carry auth guidance. */
|
|
109
|
+
function jevFallbackReason(error) {
|
|
110
|
+
if (error instanceof JevRequestError && error.credential)
|
|
111
|
+
return "Jev credentials are missing or were rejected.";
|
|
112
|
+
return error instanceof Error ? error.message : "Jev routing failed.";
|
|
113
|
+
}
|
|
107
114
|
/** General structured inference remains one-shot. */
|
|
108
115
|
export function inferStructuredOutput(request) {
|
|
109
116
|
return inferDecision(request, 0);
|
|
@@ -186,31 +193,33 @@ async function inferDecision(request, repairs, validateDecision, fallbackModel)
|
|
|
186
193
|
}
|
|
187
194
|
catch (error) {
|
|
188
195
|
assertActive();
|
|
189
|
-
if (!(error instanceof InvalidDecisionOutputError) && !(error instanceof JevRequestError))
|
|
190
|
-
throw error;
|
|
191
|
-
if (error.usage) {
|
|
192
|
-
usage.inputTokens += error.usage.inputTokens;
|
|
193
|
-
usage.outputTokens += error.usage.outputTokens;
|
|
194
|
-
}
|
|
195
|
-
if (error instanceof InvalidDecisionOutputError && attempt < repairs) {
|
|
196
|
-
attempt++;
|
|
197
|
-
continue;
|
|
198
|
-
}
|
|
199
|
-
const failure = error instanceof InvalidDecisionOutputError
|
|
200
|
-
? new Error(`${error.message} ${repairs ? `${fallback ? "Chat fallback" : "Routing"} output repair exhausted after ${repairs + 1} attempts.` : "No repair request was made."}`)
|
|
201
|
-
: error;
|
|
202
196
|
if (selected.kind === "jev" && fallbackChat && !fallback) {
|
|
197
|
+
if ((error instanceof InvalidDecisionOutputError || error instanceof JevRequestError) && error.usage) {
|
|
198
|
+
usage.inputTokens += error.usage.inputTokens;
|
|
199
|
+
usage.outputTokens += error.usage.outputTokens;
|
|
200
|
+
}
|
|
203
201
|
fallback = {
|
|
204
202
|
from: selected.fullId,
|
|
205
203
|
to: `${fallbackChat.provider}/${fallbackChat.id}`,
|
|
206
|
-
reason:
|
|
204
|
+
reason: jevFallbackReason(error),
|
|
207
205
|
};
|
|
208
|
-
|
|
206
|
+
// Static text only: Jev errors can carry credential guidance.
|
|
207
|
+
console.warn(`Jev routing failed; falling back to current chat model ${fallback.to} for this routing decision.`);
|
|
209
208
|
selected = { kind: "chat", fullId: fallback.to, model: fallbackChat };
|
|
210
209
|
attempt = 0;
|
|
211
210
|
continue;
|
|
212
211
|
}
|
|
213
|
-
|
|
212
|
+
if (!(error instanceof InvalidDecisionOutputError))
|
|
213
|
+
throw error;
|
|
214
|
+
if (error.usage) {
|
|
215
|
+
usage.inputTokens += error.usage.inputTokens;
|
|
216
|
+
usage.outputTokens += error.usage.outputTokens;
|
|
217
|
+
}
|
|
218
|
+
if (attempt < repairs) {
|
|
219
|
+
attempt++;
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
throw new Error(`${error.message} ${repairs ? `${fallback ? "Chat fallback" : "Routing"} output repair exhausted after ${repairs + 1} attempts.` : "No repair request was made."}`);
|
|
214
223
|
}
|
|
215
224
|
}
|
|
216
225
|
}
|
|
@@ -225,15 +234,14 @@ validateDecision) {
|
|
|
225
234
|
request.signal?.throwIfAborted();
|
|
226
235
|
const { settings, currentModel, ...inference } = request;
|
|
227
236
|
const model = resolveRouterModel({ settings, currentModel, modelRegistry: request.modelRegistry });
|
|
228
|
-
//
|
|
237
|
+
// Any Jev failure, pinned or automatic, falls back to the current chat model.
|
|
229
238
|
const fallback = model.kind === "jev" &&
|
|
230
|
-
!settings.getRouterModel() &&
|
|
231
239
|
currentModel &&
|
|
232
240
|
currentModel.id !== "auto" &&
|
|
233
|
-
currentModel.provider
|
|
234
|
-
currentModel.id !== "~typesafe/jev-latest"
|
|
241
|
+
!isStructuredOutputProviderModel(currentModel.provider, currentModel.id)
|
|
235
242
|
? currentModel
|
|
236
243
|
: undefined;
|
|
237
|
-
|
|
244
|
+
const retry = inference.retry ?? settings.getRetrySettings?.() ?? DEFAULT_DECISION_RETRY;
|
|
245
|
+
return inferDecision({ ...inference, model, retry }, 3, validateDecision, fallback);
|
|
238
246
|
}
|
|
239
247
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/structured-output/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EACN,0BAA0B,EAE1B,2BAA2B,GAC3B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,0BAA0B,EAAE,MAAM,UAAU,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAGnD,OAAO,EACN,4BAA4B,EAC5B,8BAA8B,EAC9B,kBAAkB,GAClB,MAAM,eAAe,CAAC;AAUvB,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAEhC,SAAS,eAAe,CAAC,KAAa,EAAE,IAAY;IACnD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,C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port { Check } from \"typebox/value\";\nimport { raceWithAbortSignal } from \"../../utils/abort.js\";\nimport {\n\tcreateStructuredOutputTool,\n\ttype JsonObject,\n\tSTRUCTURED_OUTPUT_TOOL_NAME,\n} from \"../tools/structured-output.ts\";\nimport { InvalidDecisionOutputError } from \"./invalid-output.js\";\nimport { inferJev, STRUCTURED_DECISION_POLICY } from \"./jev.js\";\nimport { JevRequestError } from \"./jev-client.js\";\nimport { resolveRouterModel } from \"./resolver.js\";\nimport type { RouterDecisionRequest, StructuredOutputRequest, StructuredOutputResult } from \"./types.js\";\n\nexport {\n\tgetStructuredOutputProviders,\n\tJEV_STRUCTURED_OUTPUT_PROVIDER,\n\tresolveRouterModel,\n} from \"./resolver.js\";\nexport type {\n\tRouterDecisionRequest,\n\tRouterModelSelectionOptions,\n\tStructuredChoiceQuestion,\n\tStructuredOutputModel,\n\tStructuredOutputRequest,\n\tStructuredOutputResult,\n} from \"./types.js\";\n\nconst DEFAULT_MAX_TOKENS = 4096;\n\nfunction positiveInteger(value: number, name: string): void {\n\tif (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647) {\n\t\tthrow new Error(`Structured output ${name} must be a positive integer no greater than 2147483647.`);\n\t}\n}\n\n/** Reject lossy/non-JSON state rather than silently dropping context or exact numbers. */\nfunction jsonSnapshot<T>(value: T): T {\n\tconst seen = new Set<object>();\n\tconst visit = (item: unknown): void => {\n\t\tif (item === null || typeof item === \"string\" || typeof item === \"boolean\") return;\n\t\tif (typeof item === \"number\" && Number.isFinite(item)) return;\n\t\tif (typeof item !== \"object\" || item === null || seen.has(item))\n\t\t\tthrow new Error(\"Structured output inputs must be finite, acyclic JSON data.\");\n\t\tif (\n\t\t\t!Array.isArray(item) &&\n\t\t\tObject.getPrototypeOf(item) !== Object.prototype &&\n\t\t\tObject.getPrototypeOf(item) !== null\n\t\t)\n\t\t\tthrow new Error(\"Structured output inputs must be plain JSON objects.\");\n\t\tseen.add(item);\n\t\tfor (const child of Object.values(item)) visit(child);\n\t\tseen.delete(item);\n\t};\n\tvisit(value);\n\treturn JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction validateState(state: JsonObject): void {\n\tif (!state || typeof state !== \"object\" || Array.isArray(state) || Object.keys(state).length === 0) {\n\t\tthrow new Error(\n\t\t\t\"Structured output requires a nonempty named state object containing the task and relevant context text.\",\n\t\t);\n\t}\n}\n\nasync function inferChat<T extends TSchema>(\n\trequest: StructuredOutputRequest<T>,\n\tmodel: Model<Api>,\n\tsignal: AbortSignal,\n\tassertActive: () => void,\n): Promise<StructuredOutputResult<Static<T>>> {\n\t// Anthropic catalog configuration may opt into server-side fallback. A decision must not.\n\tconst decisionModel =\n\t\tmodel.api === \"anthropic-messages\"\n\t\t\t? { ...model, compat: { ...(model as Model<\"anthropic-messages\">).compat, allowedFallbackModels: [] } }\n\t\t\t: model;\n\tconst tool = createStructuredOutputTool({ schema: request.schema });\n\tlet response: AssistantMessage;\n\tassertActive();\n\ttry {\n\t\tresponse = await request.modelRegistry\n\t\t\t.streamSimple(\n\t\t\t\tdecisionModel,\n\t\t\t\t{\n\t\t\t\t\tsystemPrompt: `${STRUCTURED_DECISION_POLICY}\\n\\n${request.instructions}\\n\\nCall ${STRUCTURED_OUTPUT_TOOL_NAME} exactly once with the decision. Do not use prose or other tools.`,\n\t\t\t\t\tmessages: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\t\tcontent: JSON.stringify({ state: request.state, questions: request.jev.questions }),\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\ttools: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\t\tparameters: tool.parameters,\n\t\t\t\t\t\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsignal,\n\t\t\t\t\tmaxRetries: 0,\n\t\t\t\t\ttransport: \"sse\",\n\t\t\t\t\ttoolChoice: \"auto\",\n\t\t\t\t\tmaxTokens: request.maxTokens ?? DEFAULT_MAX_TOKENS,\n\t\t\t\t},\n\t\t\t)\n\t\t\t.result();\n\t} catch {\n\t\tsignal.throwIfAborted();\n\t\t// Provider exceptions can echo private state or credentials; do not retain their cause.\n\t\tthrow new Error(\n\t\t\t\"Structured output provider request failed. Check provider configuration and connectivity, then retry explicitly; no automatic retry was made.\",\n\t\t);\n\t}\n\tsignal.throwIfAborted();\n\tif (response.stopReason === \"error\" || response.stopReason === \"aborted\")\n\t\tthrow new Error(\n\t\t\t`Structured output inference ended with ${response.stopReason}; provider request failed; no decision was accepted.`,\n\t\t);\n\tif (response.content.some((part) => part.type === \"fallback\"))\n\t\tthrow new Error(\"Structured output requires exactly one structured_output call and no provider fallback.\");\n\tif (response.stopReason !== \"toolUse\") {\n\t\tconst error = new InvalidDecisionOutputError(\"Structured output requires one structured_output call.\");\n\t\terror.usage = { inputTokens: response.usage.input, outputTokens: response.usage.output };\n\t\tthrow error;\n\t}\n\tconst calls = response.content.filter((part) => part.type === \"toolCall\");\n\tif (calls.length !== 1 || calls[0].name !== STRUCTURED_OUTPUT_TOOL_NAME) {\n\t\tconst error = new InvalidDecisionOutputError(\n\t\t\t\"Structured output requires exactly one structured_output call and no provider fallback.\",\n\t\t);\n\t\terror.usage = { inputTokens: response.usage.input, outputTokens: response.usage.output };\n\t\tthrow error;\n\t}\n\t// These are result arguments, never executable tool calls. Strict validation happens below.\n\treturn {\n\t\tvalue: calls[0].arguments as Static<T>,\n\t\tmodel: `${model.provider}/${model.id}`,\n\t\tresponseModel: response.model,\n\t\tusage: { inputTokens: response.usage.input, outputTokens: response.usage.output },\n\t};\n}\n\n/** General structured inference remains one-shot. */\nexport function inferStructuredOutput<T extends TSchema>(\n\trequest: StructuredOutputRequest<T>,\n): Promise<StructuredOutputResult<Static<T>>> {\n\treturn inferDecision(request, 0);\n}\n\nasync function inferDecision<T extends TSchema>(\n\trequest: StructuredOutputRequest<T>,\n\trepairs: number,\n\tvalidateDecision?: (value: Static<T>) => boolean,\n\tfallbackModel?: Model<Api>,\n): Promise<StructuredOutputResult<Static<T>>> {\n\trequest.signal?.throwIfAborted();\n\tpositiveInteger(request.maxTokens ?? DEFAULT_MAX_TOKENS, \"maxTokens\");\n\tvalidateState(request.state);\n\tif (!request.instructions?.trim()) throw new Error(\"Structured output requires complete judgment instructions.\");\n\tconst questions = jsonSnapshot(request.jev.questions);\n\tif (Object.keys(questions).length === 0) throw new Error(\"Structured output requires at least one Choice question.\");\n\tfor (const [id, question] of Object.entries(questions)) {\n\t\tif (\n\t\t\t!id.trim() ||\n\t\t\t!question.instructions?.trim() ||\n\t\t\t!question.criteria ||\n\t\t\tObject.keys(question.criteria).length === 0 ||\n\t\t\tObject.entries(question.criteria).some(\n\t\t\t\t([key, text]) => !key.trim() || typeof text !== \"string\" || !text.trim(),\n\t\t\t)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Structured output questions require nonempty IDs, full instructions and described Choice candidates.\",\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tquestion.retainForFinal !== undefined &&\n\t\t\t(typeof question.retainForFinal !== \"string\" || !Object.hasOwn(question.criteria, question.retainForFinal))\n\t\t) {\n\t\t\tthrow new Error(\"Structured output retainForFinal must name an original Choice option.\");\n\t\t}\n\t}\n\t// Own immutable input data across awaits, including schema and candidates. The mapper is trusted code.\n\tlet selected = request.model ? structuredClone(request.model) : request.model;\n\tconst snapshot = {\n\t\t...request,\n\t\tmodel: selected,\n\t\tstate: jsonSnapshot(request.state),\n\t\tschema: jsonSnapshot(request.schema),\n\t\tjev: { questions, decode: request.jev.decode },\n\t};\n\tif (!selected || (selected.kind !== \"chat\" && selected.kind !== \"jev\")) {\n\t\tthrow new Error(\"Structured output requires an explicit concrete inference model.\");\n\t}\n\tif (\n\t\tselected.kind === \"chat\" &&\n\t\t(!selected.model || selected.model.id === \"auto\" || selected.model.provider === \"typesafe-ai\")\n\t) {\n\t\tthrow new Error(\"Structured output requires a concrete chat model or the decision-only Jev adapter.\");\n\t}\n\tconst fallbackChat = fallbackModel ? structuredClone(fallbackModel) : undefined;\n\tlet fallback: StructuredOutputResult<Static<T>>[\"fallback\"];\n\tconst controller = new AbortController();\n\tconst abort = () => controller.abort(new Error(\"Structured output cancelled; no decision was accepted.\"));\n\trequest.signal?.addEventListener(\"abort\", abort, { once: true });\n\tconst assertActive = () => controller.signal.throwIfAborted();\n\ttry {\n\t\tif (request.signal?.aborted) abort();\n\t\tconst usage = { inputTokens: 0, outputTokens: 0 };\n\t\tfor (let attempt = 0; ; ) {\n\t\t\tassertActive();\n\t\t\tconst current = {\n\t\t\t\t...snapshot,\n\t\t\t\tmodel: selected,\n\t\t\t\tinstructions:\n\t\t\t\t\tattempt === 0\n\t\t\t\t\t\t? snapshot.instructions\n\t\t\t\t\t\t: `${snapshot.instructions}\\n\\nThe previous response failed output validation. Return a complete valid decision satisfying the original schema, candidates and constraints. Do not change the task or invent values.`,\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tconst result = await raceWithAbortSignal(\n\t\t\t\t\tselected.kind === \"jev\"\n\t\t\t\t\t\t? inferJev(current, controller.signal, assertActive)\n\t\t\t\t\t\t: inferChat(current, selected.model, controller.signal, assertActive),\n\t\t\t\t\tcontroller.signal,\n\t\t\t\t);\n\t\t\t\tassertActive();\n\t\t\t\tusage.inputTokens += result.usage.inputTokens;\n\t\t\t\tusage.outputTokens += result.usage.outputTokens;\n\t\t\t\tlet value: Static<T>;\n\t\t\t\ttry {\n\t\t\t\t\tvalue = jsonSnapshot(result.value);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new InvalidDecisionOutputError(\"Invalid structured output: non-JSON decision.\");\n\t\t\t\t}\n\t\t\t\tif (!Check(snapshot.schema, value) || (validateDecision && !validateDecision(value)))\n\t\t\t\t\tthrow new InvalidDecisionOutputError(\n\t\t\t\t\t\t\"Invalid structured output: response does not match the decision schema.\",\n\t\t\t\t\t);\n\t\t\t\tassertActive();\n\t\t\t\treturn { ...result, value, usage, ...(fallback ? { fallback } : {}) };\n\t\t\t} catch (error) {\n\t\t\t\tassertActive();\n\t\t\t\tif (!(error instanceof InvalidDecisionOutputError) && !(error instanceof JevRequestError)) throw error;\n\t\t\t\tif (error.usage) {\n\t\t\t\t\tusage.inputTokens += error.usage.inputTokens;\n\t\t\t\t\tusage.outputTokens += error.usage.outputTokens;\n\t\t\t\t}\n\t\t\t\tif (error instanceof InvalidDecisionOutputError && attempt < repairs) {\n\t\t\t\t\tattempt++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst failure =\n\t\t\t\t\terror instanceof InvalidDecisionOutputError\n\t\t\t\t\t\t? new Error(\n\t\t\t\t\t\t\t\t`${error.message} ${repairs ? `${fallback ? \"Chat fallback\" : \"Routing\"} output repair exhausted after ${repairs + 1} attempts.` : \"No repair request was made.\"}`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: error;\n\t\t\t\tif (selected.kind === \"jev\" && fallbackChat && !fallback) {\n\t\t\t\t\tfallback = {\n\t\t\t\t\t\tfrom: selected.fullId,\n\t\t\t\t\t\tto: `${fallbackChat.provider}/${fallbackChat.id}`,\n\t\t\t\t\t\treason: failure.message,\n\t\t\t\t\t};\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`${failure.message} Falling back to current chat model ${fallback.to} for this routing decision.`,\n\t\t\t\t\t);\n\t\t\t\t\tselected = { kind: \"chat\", fullId: fallback.to, model: fallbackChat };\n\t\t\t\t\tattempt = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow failure;\n\t\t\t}\n\t\t}\n\t} finally {\n\t\trequest.signal?.removeEventListener(\"abort\", abort);\n\t}\n}\n\n/** Resolve only prerequisite routing inference. Does not execute the selected action or alter chat/tools. */\nexport async function inferRouterDecision<T extends TSchema>(\n\trequest: RouterDecisionRequest<T>,\n\t/** Pure correlated-field validation against original candidates, never live admission checks. */\n\tvalidateDecision?: (value: Static<T>) => boolean,\n): Promise<StructuredOutputResult<Static<T>>> {\n\trequest.signal?.throwIfAborted();\n\tconst { settings, currentModel, ...inference } = request;\n\tconst model = resolveRouterModel({ settings, currentModel, modelRegistry: request.modelRegistry });\n\t// A concrete routerModel is a provider pin. Only default, automatically selected Jev may switch.\n\tconst fallback =\n\t\tmodel.kind === \"jev\" &&\n\t\t!settings.getRouterModel() &&\n\t\tcurrentModel &&\n\t\tcurrentModel.id !== \"auto\" &&\n\t\tcurrentModel.provider !== \"typesafe-ai\" &&\n\t\tcurrentModel.id !== \"~typesafe/jev-latest\"\n\t\t\t? currentModel\n\t\t\t: undefined;\n\treturn inferDecision({ ...inference, model }, 3, validateDecision, fallback);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/structured-output/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+C,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEjG,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EACN,0BAA0B,EAE1B,2BAA2B,GAC3B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,0BAA0B,EAAE,MAAM,UAAU,CAAC;AAChE,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,+BAA+B,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAIpF,OAAO,EACN,4BAA4B,EAC5B,8BAA8B,EAC9B,kBAAkB,GAClB,MAAM,eAAe,CAAC;AAUvB,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAEhC,SAAS,eAAe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Aa,EAAE,CAAC,CAAC;IACnG,8EAA8E;IAC9E,MAAM,QAAQ,GACb,KAAK,CAAC,IAAI,KAAK,KAAK;QACpB,YAAY;QACZ,YAAY,CAAC,EAAE,KAAK,MAAM;QAC1B,CAAC,+BAA+B,CAAC,YAAY,CAAC,QAAQ,EAAE,YAAY,CAAC,EAAE,CAAC;QACvE,CAAC,CAAC,YAAY;QACd,CAAC,CAAC,SAAS,CAAC;IACd,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,IAAI,QAAQ,CAAC,gBAAgB,EAAE,EAAE,IAAI,sBAAsB,CAAC;IACzF,OAAO,aAAa,CAAC,EAAE,GAAG,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,EAAE,gBAAgB,EAAE,QAAQ,CAAC,CAAC;AACrF,CAAC","sourcesContent":["import { type Api, type AssistantMessage, type Model, retryAssistantCall } from \"@bastani/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\nimport { Check } from \"typebox/value\";\nimport { raceWithAbortSignal } from \"../../utils/abort.js\";\nimport {\n\tcreateStructuredOutputTool,\n\ttype JsonObject,\n\tSTRUCTURED_OUTPUT_TOOL_NAME,\n} from \"../tools/structured-output.ts\";\nimport { InvalidDecisionOutputError } from \"./invalid-output.js\";\nimport { inferJev, STRUCTURED_DECISION_POLICY } from \"./jev.js\";\nimport { DEFAULT_DECISION_RETRY, JevRequestError } from \"./jev-client.js\";\nimport { isStructuredOutputProviderModel, resolveRouterModel } from \"./resolver.js\";\nimport type { RouterDecisionRequest, StructuredOutputRequest, StructuredOutputResult } from \"./types.js\";\n\nexport type { JevStructuredOutputProvider } from \"./resolver.js\";\nexport {\n\tgetStructuredOutputProviders,\n\tJEV_STRUCTURED_OUTPUT_PROVIDER,\n\tresolveRouterModel,\n} from \"./resolver.js\";\nexport type {\n\tRouterDecisionRequest,\n\tRouterModelSelectionOptions,\n\tStructuredChoiceQuestion,\n\tStructuredOutputModel,\n\tStructuredOutputRequest,\n\tStructuredOutputResult,\n} from \"./types.js\";\n\nconst DEFAULT_MAX_TOKENS = 4096;\n\nfunction positiveInteger(value: number, name: string): void {\n\tif (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647) {\n\t\tthrow new Error(`Structured output ${name} must be a positive integer no greater than 2147483647.`);\n\t}\n}\n\n/** Reject lossy/non-JSON state rather than silently dropping context or exact numbers. */\nfunction jsonSnapshot<T>(value: T): T {\n\tconst seen = new Set<object>();\n\tconst visit = (item: unknown): void => {\n\t\tif (item === null || typeof item === \"string\" || typeof item === \"boolean\") return;\n\t\tif (typeof item === \"number\" && Number.isFinite(item)) return;\n\t\tif (typeof item !== \"object\" || item === null || seen.has(item))\n\t\t\tthrow new Error(\"Structured output inputs must be finite, acyclic JSON data.\");\n\t\tif (\n\t\t\t!Array.isArray(item) &&\n\t\t\tObject.getPrototypeOf(item) !== Object.prototype &&\n\t\t\tObject.getPrototypeOf(item) !== null\n\t\t)\n\t\t\tthrow new Error(\"Structured output inputs must be plain JSON objects.\");\n\t\tseen.add(item);\n\t\tfor (const child of Object.values(item)) visit(child);\n\t\tseen.delete(item);\n\t};\n\tvisit(value);\n\treturn JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction validateState(state: JsonObject): void {\n\tif (!state || typeof state !== \"object\" || Array.isArray(state) || Object.keys(state).length === 0) {\n\t\tthrow new Error(\n\t\t\t\"Structured output requires a nonempty named state object containing the task and relevant context text.\",\n\t\t);\n\t}\n}\n\nasync function inferChat<T extends TSchema>(\n\trequest: StructuredOutputRequest<T>,\n\tmodel: Model<Api>,\n\tsignal: AbortSignal,\n\tassertActive: () => void,\n): Promise<StructuredOutputResult<Static<T>>> {\n\t// Anthropic catalog configuration may opt into server-side fallback. A decision must not.\n\tconst decisionModel =\n\t\tmodel.api === \"anthropic-messages\"\n\t\t\t? { ...model, compat: { ...(model as Model<\"anthropic-messages\">).compat, allowedFallbackModels: [] } }\n\t\t\t: model;\n\tconst tool = createStructuredOutputTool({ schema: request.schema });\n\tlet response: AssistantMessage;\n\tassertActive();\n\ttry {\n\t\tresponse = await retryAssistantCall(\n\t\t\t() =>\n\t\t\t\trequest.modelRegistry\n\t\t\t\t\t.streamSimple(\n\t\t\t\t\t\tdecisionModel,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsystemPrompt: `${STRUCTURED_DECISION_POLICY}\\n\\n${request.instructions}\\n\\nCall ${STRUCTURED_OUTPUT_TOOL_NAME} exactly once with the decision. Do not use prose or other tools.`,\n\t\t\t\t\t\t\tmessages: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\t\t\t\tcontent: JSON.stringify({ state: request.state, questions: request.jev.questions }),\n\t\t\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttools: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\t\t\t\tparameters: tool.parameters,\n\t\t\t\t\t\t\t\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tmaxRetries: 0,\n\t\t\t\t\t\t\ttransport: \"sse\",\n\t\t\t\t\t\t\ttoolChoice: \"auto\",\n\t\t\t\t\t\t\tmaxTokens: request.maxTokens ?? DEFAULT_MAX_TOKENS,\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t\t.result(),\n\t\t\trequest.retry ?? DEFAULT_DECISION_RETRY,\n\t\t\tsignal,\n\t\t);\n\t} catch {\n\t\tsignal.throwIfAborted();\n\t\t// Provider exceptions can echo private state or credentials; do not retain their cause.\n\t\tthrow new Error(\"Structured output provider request failed. Check provider configuration and connectivity.\");\n\t}\n\tsignal.throwIfAborted();\n\tif (response.stopReason === \"error\" || response.stopReason === \"aborted\")\n\t\tthrow new Error(\n\t\t\t`Structured output inference ended with ${response.stopReason}; provider request failed; no decision was accepted.`,\n\t\t);\n\tif (response.content.some((part) => part.type === \"fallback\"))\n\t\tthrow new Error(\"Structured output requires exactly one structured_output call and no provider fallback.\");\n\tif (response.stopReason !== \"toolUse\") {\n\t\tconst error = new InvalidDecisionOutputError(\"Structured output requires one structured_output call.\");\n\t\terror.usage = { inputTokens: response.usage.input, outputTokens: response.usage.output };\n\t\tthrow error;\n\t}\n\tconst calls = response.content.filter((part) => part.type === \"toolCall\");\n\tif (calls.length !== 1 || calls[0].name !== STRUCTURED_OUTPUT_TOOL_NAME) {\n\t\tconst error = new InvalidDecisionOutputError(\n\t\t\t\"Structured output requires exactly one structured_output call and no provider fallback.\",\n\t\t);\n\t\terror.usage = { inputTokens: response.usage.input, outputTokens: response.usage.output };\n\t\tthrow error;\n\t}\n\t// These are result arguments, never executable tool calls. Strict validation happens below.\n\treturn {\n\t\tvalue: calls[0].arguments as Static<T>,\n\t\tmodel: `${model.provider}/${model.id}`,\n\t\tresponseModel: response.model,\n\t\tusage: { inputTokens: response.usage.input, outputTokens: response.usage.output },\n\t};\n}\n\n/** Credential failures get a static reason; their messages carry auth guidance. */\nfunction jevFallbackReason(error: unknown): string {\n\tif (error instanceof JevRequestError && error.credential) return \"Jev credentials are missing or were rejected.\";\n\treturn error instanceof Error ? error.message : \"Jev routing failed.\";\n}\n\n/** General structured inference remains one-shot. */\nexport function inferStructuredOutput<T extends TSchema>(\n\trequest: StructuredOutputRequest<T>,\n): Promise<StructuredOutputResult<Static<T>>> {\n\treturn inferDecision(request, 0);\n}\n\nasync function inferDecision<T extends TSchema>(\n\trequest: StructuredOutputRequest<T>,\n\trepairs: number,\n\tvalidateDecision?: (value: Static<T>) => boolean,\n\tfallbackModel?: Model<Api>,\n): Promise<StructuredOutputResult<Static<T>>> {\n\trequest.signal?.throwIfAborted();\n\tpositiveInteger(request.maxTokens ?? DEFAULT_MAX_TOKENS, \"maxTokens\");\n\tvalidateState(request.state);\n\tif (!request.instructions?.trim()) throw new Error(\"Structured output requires complete judgment instructions.\");\n\tconst questions = jsonSnapshot(request.jev.questions);\n\tif (Object.keys(questions).length === 0) throw new Error(\"Structured output requires at least one Choice question.\");\n\tfor (const [id, question] of Object.entries(questions)) {\n\t\tif (\n\t\t\t!id.trim() ||\n\t\t\t!question.instructions?.trim() ||\n\t\t\t!question.criteria ||\n\t\t\tObject.keys(question.criteria).length === 0 ||\n\t\t\tObject.entries(question.criteria).some(\n\t\t\t\t([key, text]) => !key.trim() || typeof text !== \"string\" || !text.trim(),\n\t\t\t)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Structured output questions require nonempty IDs, full instructions and described Choice candidates.\",\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tquestion.retainForFinal !== undefined &&\n\t\t\t(typeof question.retainForFinal !== \"string\" || !Object.hasOwn(question.criteria, question.retainForFinal))\n\t\t) {\n\t\t\tthrow new Error(\"Structured output retainForFinal must name an original Choice option.\");\n\t\t}\n\t}\n\t// Own immutable input data across awaits, including schema and candidates. The mapper is trusted code.\n\tlet selected = request.model ? structuredClone(request.model) : request.model;\n\tconst snapshot = {\n\t\t...request,\n\t\tmodel: selected,\n\t\tstate: jsonSnapshot(request.state),\n\t\tschema: jsonSnapshot(request.schema),\n\t\tjev: { questions, decode: request.jev.decode },\n\t};\n\tif (!selected || (selected.kind !== \"chat\" && selected.kind !== \"jev\")) {\n\t\tthrow new Error(\"Structured output requires an explicit concrete inference model.\");\n\t}\n\tif (\n\t\tselected.kind === \"chat\" &&\n\t\t(!selected.model || selected.model.id === \"auto\" || selected.model.provider === \"typesafe-ai\")\n\t) {\n\t\tthrow new Error(\"Structured output requires a concrete chat model or the decision-only Jev adapter.\");\n\t}\n\tconst fallbackChat = fallbackModel ? structuredClone(fallbackModel) : undefined;\n\tlet fallback: StructuredOutputResult<Static<T>>[\"fallback\"];\n\tconst controller = new AbortController();\n\tconst abort = () => controller.abort(new Error(\"Structured output cancelled; no decision was accepted.\"));\n\trequest.signal?.addEventListener(\"abort\", abort, { once: true });\n\tconst assertActive = () => controller.signal.throwIfAborted();\n\ttry {\n\t\tif (request.signal?.aborted) abort();\n\t\tconst usage = { inputTokens: 0, outputTokens: 0 };\n\t\tfor (let attempt = 0; ; ) {\n\t\t\tassertActive();\n\t\t\tconst current = {\n\t\t\t\t...snapshot,\n\t\t\t\tmodel: selected,\n\t\t\t\tinstructions:\n\t\t\t\t\tattempt === 0\n\t\t\t\t\t\t? snapshot.instructions\n\t\t\t\t\t\t: `${snapshot.instructions}\\n\\nThe previous response failed output validation. Return a complete valid decision satisfying the original schema, candidates and constraints. Do not change the task or invent values.`,\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tconst result = await raceWithAbortSignal(\n\t\t\t\t\tselected.kind === \"jev\"\n\t\t\t\t\t\t? inferJev(current, controller.signal, assertActive)\n\t\t\t\t\t\t: inferChat(current, selected.model, controller.signal, assertActive),\n\t\t\t\t\tcontroller.signal,\n\t\t\t\t);\n\t\t\t\tassertActive();\n\t\t\t\tusage.inputTokens += result.usage.inputTokens;\n\t\t\t\tusage.outputTokens += result.usage.outputTokens;\n\t\t\t\tlet value: Static<T>;\n\t\t\t\ttry {\n\t\t\t\t\tvalue = jsonSnapshot(result.value);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new InvalidDecisionOutputError(\"Invalid structured output: non-JSON decision.\");\n\t\t\t\t}\n\t\t\t\tif (!Check(snapshot.schema, value) || (validateDecision && !validateDecision(value)))\n\t\t\t\t\tthrow new InvalidDecisionOutputError(\n\t\t\t\t\t\t\"Invalid structured output: response does not match the decision schema.\",\n\t\t\t\t\t);\n\t\t\t\tassertActive();\n\t\t\t\treturn { ...result, value, usage, ...(fallback ? { fallback } : {}) };\n\t\t\t} catch (error) {\n\t\t\t\tassertActive();\n\t\t\t\tif (selected.kind === \"jev\" && fallbackChat && !fallback) {\n\t\t\t\t\tif ((error instanceof InvalidDecisionOutputError || error instanceof JevRequestError) && error.usage) {\n\t\t\t\t\t\tusage.inputTokens += error.usage.inputTokens;\n\t\t\t\t\t\tusage.outputTokens += error.usage.outputTokens;\n\t\t\t\t\t}\n\t\t\t\t\tfallback = {\n\t\t\t\t\t\tfrom: selected.fullId,\n\t\t\t\t\t\tto: `${fallbackChat.provider}/${fallbackChat.id}`,\n\t\t\t\t\t\treason: jevFallbackReason(error),\n\t\t\t\t\t};\n\t\t\t\t\t// Static text only: Jev errors can carry credential guidance.\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`Jev routing failed; falling back to current chat model ${fallback.to} for this routing decision.`,\n\t\t\t\t\t);\n\t\t\t\t\tselected = { kind: \"chat\", fullId: fallback.to, model: fallbackChat };\n\t\t\t\t\tattempt = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!(error instanceof InvalidDecisionOutputError)) throw error;\n\t\t\t\tif (error.usage) {\n\t\t\t\t\tusage.inputTokens += error.usage.inputTokens;\n\t\t\t\t\tusage.outputTokens += error.usage.outputTokens;\n\t\t\t\t}\n\t\t\t\tif (attempt < repairs) {\n\t\t\t\t\tattempt++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${error.message} ${repairs ? `${fallback ? \"Chat fallback\" : \"Routing\"} output repair exhausted after ${repairs + 1} attempts.` : \"No repair request was made.\"}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t} finally {\n\t\trequest.signal?.removeEventListener(\"abort\", abort);\n\t}\n}\n\n/** Resolve only prerequisite routing inference. Does not execute the selected action or alter chat/tools. */\nexport async function inferRouterDecision<T extends TSchema>(\n\trequest: RouterDecisionRequest<T>,\n\t/** Pure correlated-field validation against original candidates, never live admission checks. */\n\tvalidateDecision?: (value: Static<T>) => boolean,\n): Promise<StructuredOutputResult<Static<T>>> {\n\trequest.signal?.throwIfAborted();\n\tconst { settings, currentModel, ...inference } = request;\n\tconst model = resolveRouterModel({ settings, currentModel, modelRegistry: request.modelRegistry });\n\t// Any Jev failure, pinned or automatic, falls back to the current chat model.\n\tconst fallback =\n\t\tmodel.kind === \"jev\" &&\n\t\tcurrentModel &&\n\t\tcurrentModel.id !== \"auto\" &&\n\t\t!isStructuredOutputProviderModel(currentModel.provider, currentModel.id)\n\t\t\t? currentModel\n\t\t\t: undefined;\n\tconst retry = inference.retry ?? settings.getRetrySettings?.() ?? DEFAULT_DECISION_RETRY;\n\treturn inferDecision({ ...inference, model, retry }, 3, validateDecision, fallback);\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type RetryPolicy } from "@bastani/pi-ai";
|
|
1
2
|
import { type JsonValue, type SystemOneRequest } from "@typesafe-ai/sdk";
|
|
2
3
|
/** Safe diagnostics only. Never retain SDK errors, headers, bodies, or causes. */
|
|
3
4
|
export declare class JevRequestError extends Error {
|
|
@@ -5,12 +6,20 @@ export declare class JevRequestError extends Error {
|
|
|
5
6
|
inputTokens: number;
|
|
6
7
|
outputTokens: number;
|
|
7
8
|
};
|
|
9
|
+
transient: boolean;
|
|
10
|
+
/** Missing, unresolvable, or rejected credentials; the message carries auth guidance. */
|
|
11
|
+
credential: boolean;
|
|
8
12
|
}
|
|
13
|
+
export declare function jevCredentialError(message: string): JevRequestError;
|
|
14
|
+
/** Matches the `settings.retry` defaults used by ordinary chat providers. */
|
|
15
|
+
export declare const DEFAULT_DECISION_RETRY: RetryPolicy;
|
|
16
|
+
/** Retry transient transport, 408, 429 and 5xx failures with the provider retry policy. */
|
|
9
17
|
export declare function requestJev(options: {
|
|
10
18
|
apiKey: string;
|
|
11
19
|
endpoint: string;
|
|
12
20
|
request: SystemOneRequest;
|
|
13
21
|
signal: AbortSignal;
|
|
14
22
|
authGuidance: string;
|
|
23
|
+
retry: RetryPolicy;
|
|
15
24
|
}): Promise<JsonValue>;
|
|
16
25
|
//# sourceMappingURL=jev-client.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jev-client.d.ts","sourceRoot":"","sources":["../../../src/core/structured-output/jev-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,KAAK,SAAS,EAId,KAAK,gBAAgB,EAErB,MAAM,kBAAkB,CAAC;AAE1B,kFAAkF;AAClF,qBAAa,eAAgB,SAAQ,KAAK;IACzC,KAAK,CAAC,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"jev-client.d.ts","sourceRoot":"","sources":["../../../src/core/structured-output/jev-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAAgB,MAAM,gBAAgB,CAAC;AAChE,OAAO,EAKN,KAAK,SAAS,EAId,KAAK,gBAAgB,EAErB,MAAM,kBAAkB,CAAC;AAE1B,kFAAkF;AAClF,qBAAa,eAAgB,SAAQ,KAAK;IACzC,KAAK,CAAC,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC;IACtD,SAAS,UAAS;IAClB,yFAAyF;IACzF,UAAU,UAAS;CACnB;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,eAAe,CAInE;AAED,6EAA6E;AAC7E,eAAO,MAAM,sBAAsB,EAAE,WAAgF,CAAC;AA4GtH,2FAA2F;AAC3F,wBAAsB,UAAU,CAAC,OAAO,EAAE;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,gBAAgB,CAAC;IAC1B,MAAM,EAAE,WAAW,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,WAAW,CAAC;CACnB,GAAG,OAAO,CAAC,SAAS,CAAC,CAWrB"}
|