@bastani/atomic 0.8.31-alpha.1 → 0.8.31-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/CHANGELOG.md +14 -3
  2. package/README.md +12 -10
  3. package/dist/builtin/cursor/CHANGELOG.md +1 -1
  4. package/dist/builtin/cursor/package.json +2 -2
  5. package/dist/builtin/intercom/CHANGELOG.md +1 -1
  6. package/dist/builtin/intercom/package.json +2 -2
  7. package/dist/builtin/mcp/CHANGELOG.md +1 -1
  8. package/dist/builtin/mcp/package.json +3 -3
  9. package/dist/builtin/subagents/CHANGELOG.md +10 -1
  10. package/dist/builtin/subagents/agents/codebase-online-researcher.md +8 -8
  11. package/dist/builtin/subagents/agents/debugger.md +6 -6
  12. package/dist/builtin/subagents/package.json +4 -4
  13. package/dist/builtin/subagents/skills/effective-liteparse/SKILL.md +118 -0
  14. package/dist/builtin/subagents/skills/effective-liteparse/scripts/search.py +128 -0
  15. package/dist/builtin/subagents/skills/playwright-cli/SKILL.md +404 -0
  16. package/dist/builtin/subagents/skills/playwright-cli/references/element-attributes.md +23 -0
  17. package/dist/builtin/subagents/skills/playwright-cli/references/playwright-tests.md +39 -0
  18. package/dist/builtin/subagents/skills/playwright-cli/references/request-mocking.md +87 -0
  19. package/dist/builtin/subagents/skills/playwright-cli/references/running-code.md +241 -0
  20. package/dist/builtin/subagents/skills/playwright-cli/references/session-management.md +225 -0
  21. package/dist/builtin/subagents/skills/playwright-cli/references/spec-driven-testing.md +305 -0
  22. package/dist/builtin/subagents/skills/playwright-cli/references/storage-state.md +275 -0
  23. package/dist/builtin/subagents/skills/playwright-cli/references/test-generation.md +134 -0
  24. package/dist/builtin/subagents/skills/playwright-cli/references/tracing.md +139 -0
  25. package/dist/builtin/subagents/skills/playwright-cli/references/video-recording.md +143 -0
  26. package/dist/builtin/web-access/CHANGELOG.md +1 -1
  27. package/dist/builtin/web-access/package.json +2 -2
  28. package/dist/builtin/workflows/CHANGELOG.md +7 -1
  29. package/dist/builtin/workflows/README.md +4 -4
  30. package/dist/builtin/workflows/builtin/open-claude-design.ts +59 -56
  31. package/dist/builtin/workflows/builtin/ralph.ts +56 -3
  32. package/dist/builtin/workflows/builtin/shared-prompts.ts +1 -1
  33. package/dist/builtin/workflows/package.json +2 -2
  34. package/dist/builtin/workflows/skills/research-codebase/SKILL.md +1 -1
  35. package/dist/cli/args.d.ts.map +1 -1
  36. package/dist/cli/args.js +1 -1
  37. package/dist/cli/args.js.map +1 -1
  38. package/dist/core/agent-session.d.ts +1 -0
  39. package/dist/core/agent-session.d.ts.map +1 -1
  40. package/dist/core/agent-session.js +38 -18
  41. package/dist/core/agent-session.js.map +1 -1
  42. package/dist/core/context-window.d.ts +11 -1
  43. package/dist/core/context-window.d.ts.map +1 -1
  44. package/dist/core/context-window.js +19 -6
  45. package/dist/core/context-window.js.map +1 -1
  46. package/dist/core/copilot-model-catalog.d.ts +19 -16
  47. package/dist/core/copilot-model-catalog.d.ts.map +1 -1
  48. package/dist/core/copilot-model-catalog.js +14 -11
  49. package/dist/core/copilot-model-catalog.js.map +1 -1
  50. package/dist/core/project-trust.d.ts.map +1 -1
  51. package/dist/core/project-trust.js +2 -1
  52. package/dist/core/project-trust.js.map +1 -1
  53. package/dist/core/sdk.d.ts.map +1 -1
  54. package/dist/core/sdk.js +18 -7
  55. package/dist/core/sdk.js.map +1 -1
  56. package/dist/core/settings-manager.d.ts +11 -2
  57. package/dist/core/settings-manager.d.ts.map +1 -1
  58. package/dist/core/settings-manager.js +62 -8
  59. package/dist/core/settings-manager.js.map +1 -1
  60. package/dist/core/system-prompt.d.ts.map +1 -1
  61. package/dist/core/system-prompt.js +1 -0
  62. package/dist/core/system-prompt.js.map +1 -1
  63. package/dist/core/tools/edit-diff.d.ts +1 -2
  64. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  65. package/dist/core/tools/edit-diff.js +1 -2
  66. package/dist/core/tools/edit-diff.js.map +1 -1
  67. package/dist/index.d.ts +2 -1
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +1 -0
  70. package/dist/index.js.map +1 -1
  71. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  72. package/dist/modes/interactive/components/config-selector.js +5 -7
  73. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  74. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  75. package/dist/modes/interactive/components/model-selector.js +2 -1
  76. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  77. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  78. package/dist/modes/interactive/components/scoped-models-selector.js +4 -1
  79. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  80. package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  81. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  82. package/dist/modes/interactive/components/settings-selector.js +165 -15
  83. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  84. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  85. package/dist/modes/interactive/components/tree-selector.js +44 -4
  86. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  87. package/dist/modes/interactive/interactive-mode.d.ts +1 -1
  88. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  89. package/dist/modes/interactive/interactive-mode.js +24 -54
  90. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  91. package/dist/modes/interactive/model-search.d.ts +7 -0
  92. package/dist/modes/interactive/model-search.d.ts.map +1 -0
  93. package/dist/modes/interactive/model-search.js +6 -0
  94. package/dist/modes/interactive/model-search.js.map +1 -0
  95. package/dist/modes/interactive/theme/theme-controller.d.ts +30 -0
  96. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -0
  97. package/dist/modes/interactive/theme/theme-controller.js +108 -0
  98. package/dist/modes/interactive/theme/theme-controller.js.map +1 -0
  99. package/dist/modes/interactive/theme/theme-schema.json +2 -1
  100. package/dist/modes/interactive/theme/theme.d.ts +5 -0
  101. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  102. package/dist/modes/interactive/theme/theme.js +70 -29
  103. package/dist/modes/interactive/theme/theme.js.map +1 -1
  104. package/dist/modes/rpc/rpc-client.d.ts +1 -1
  105. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  106. package/dist/modes/rpc/rpc-client.js +1 -1
  107. package/dist/modes/rpc/rpc-client.js.map +1 -1
  108. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  109. package/dist/modes/rpc/rpc-mode.js +1 -1
  110. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  111. package/dist/package-manager-cli.d.ts.map +1 -1
  112. package/dist/package-manager-cli.js +39 -9
  113. package/dist/package-manager-cli.js.map +1 -1
  114. package/docs/extensions.md +21 -0
  115. package/docs/models.md +3 -3
  116. package/docs/packages.md +13 -9
  117. package/docs/providers.md +2 -2
  118. package/docs/quickstart.md +14 -0
  119. package/docs/rpc.md +3 -3
  120. package/docs/sdk.md +15 -11
  121. package/docs/session-format.md +1 -1
  122. package/docs/settings.md +8 -3
  123. package/docs/themes.md +3 -1
  124. package/docs/tui.md +1 -1
  125. package/docs/usage.md +12 -9
  126. package/docs/workflows.md +9 -7
  127. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  128. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  129. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  130. package/examples/extensions/gondolin/package-lock.json +2 -2
  131. package/examples/extensions/gondolin/package.json +1 -1
  132. package/examples/extensions/preset.ts +10 -4
  133. package/examples/extensions/provider-payload.ts +5 -5
  134. package/examples/extensions/sandbox/index.ts +2 -2
  135. package/examples/extensions/sandbox/package-lock.json +3 -3
  136. package/examples/extensions/sandbox/package.json +2 -2
  137. package/examples/extensions/subagent/agents.ts +2 -2
  138. package/examples/extensions/subagent/index.ts +4 -2
  139. package/examples/extensions/with-deps/package-lock.json +2 -2
  140. package/examples/extensions/with-deps/package.json +1 -1
  141. package/package.json +5 -5
  142. package/dist/builtin/subagents/skills/browser/EXAMPLES.md +0 -151
  143. package/dist/builtin/subagents/skills/browser/LICENSE.txt +0 -21
  144. package/dist/builtin/subagents/skills/browser/REFERENCE.md +0 -451
  145. package/dist/builtin/subagents/skills/browser/SKILL.md +0 -170
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,KAAK,aAAa,EACnB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEL,KAAK,GAAG,EAER,KAAK,KAAK,EAEX,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAUhD,OAAO,KAAK,EAEV,oBAAoB,EACpB,oBAAoB,EACpB,iBAAiB,EACjB,cAAc,EACf,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EAAwB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,2BAA2B,EAC3B,6BAA6B,EAC7B,0BAA0B,EAC1B,eAAe,EAEf,qBAAqB,EACrB,KAAK,iBAAiB,EACvB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,yBAAyB;IACxC,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,wDAAwD;IACxD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,oFAAoF;IACpF,WAAW,CAAC,EAAE,WAAW,C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C,EAAE,MAAM,CAAC;IAC9B,2EAA2E;IAC3E,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAID,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACV,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACf,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EACV,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,EACjB,yBAAyB,EACzB,0BAA0B,EAC1B,0BAA0B,EAC1B,eAAe,EACf,kBAAkB,EAClB,wBAAwB,EACxB,UAAU,EACV,aAAa,EACb,SAAS,EACT,uBAAuB,EACvB,2BAA2B,EAC3B,2BAA2B,EAC3B,IAAI,GACL,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,qBAAqB,EACrB,2BAA2B,EAE3B,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,EACZ,6BAA6B,EAC7B,0BAA0B,GAC3B,CAAC;AAmBF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,GAAE,yBAA8B,GACtC,OAAO,CAAC,wBAAwB,CAAC,CA0UnC","sourcesContent":["import { join } from \"node:path\";\nimport {\n Agent,\n type AgentMessage,\n type ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport {\n clampThinkingLevel,\n type Api,\n type Message,\n type Model,\n streamSimple,\n} from \"@earendil-works/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport {\n shouldApplyCodexFastMode,\n streamWithCodexFastMode,\n withCodexFastModePayload,\n withCodexFastModeStreamOptions,\n} from \"./codex-fast-mode.ts\";\nimport { restoreAnthropicReplayThinkingBlocks } from \"./anthropic-thinking-guard.ts\";\nimport { getModelDefaultContextWindow, getSupportedContextWindows, selectContextWindow } from \"./context-window.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n LoadExtensionsResult,\n OrchestrationContext,\n SessionStartEvent,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveSavedModelReference } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n createBashTool,\n createCodingTools,\n createEditTool,\n createFindTool,\n createGrepTool,\n createLsTool,\n createReadOnlyTools,\n createReadTool,\n STRUCTURED_OUTPUT_TOOL_NAME,\n createStructuredOutputCapture,\n createStructuredOutputTool,\n createWriteTool,\n defaultToolNames,\n withFileMutationQueue,\n type BashCommandPolicy,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n /** Working directory for project-local discovery. Default: process.cwd() */\n cwd?: string;\n /** Global config directory. Default: ~/.atomic/agent */\n agentDir?: string;\n\n /** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n authStorage?: AuthStorage;\n /** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n modelRegistry?: ModelRegistry;\n\n /** Model to use. Default: from settings, else first available */\n model?: Model<Api>;\n /** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n thinkingLevel?: ThinkingLevel;\n /** Context window token count. Default: model scalar contextWindow, or settings/session override when supported. */\n contextWindow?: number;\n /** Treat unsupported contextWindow as an error instead of a warning/fallback. */\n contextWindowStrict?: boolean;\n /** Models available for cycling (Ctrl+P in interactive mode) */\n scopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\n /**\n * Optional default tool suppression mode when no explicit allowlist is provided.\n *\n * - \"all\": start with no tools enabled\n * - \"builtin\": disable the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) but keep extension/custom tools enabled\n */\n noTools?: \"all\" | \"builtin\";\n /**\n * Optional allowlist of tool names.\n *\n * When omitted, pi enables the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) and leaves extension/custom tools enabled unless\n * `noTools` changes that default.\n * When provided, only the listed tool names are enabled, minus any names in\n * `excludedTools`.\n */\n tools?: string[];\n /**\n * Optional blocklist of tool names.\n *\n * Matching built-in, extension, and SDK custom tools are omitted from the\n * final session tool registry and active tool set. Unknown names are ignored.\n */\n excludedTools?: string[];\n /** Custom tools to register (in addition to built-in tools). */\n customTools?: ToolDefinition[];\n /** Optional command-level policy for the built-in bash tool. Does not expose bash by itself. */\n bashPolicy?: BashCommandPolicy;\n\n /** Resource loader. When omitted, DefaultResourceLoader is used. */\n resourceLoader?: ResourceLoader;\n\n /** Session manager. Default: SessionManager.create(cwd) */\n sessionManager?: SessionManager;\n\n /** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n settingsManager?: SettingsManager;\n /** Session start event metadata for extension runtime startup. */\n sessionStartEvent?: SessionStartEvent;\n /** Session-scoped orchestration policy exposed to extension/tool handlers. */\n orchestrationContext?: OrchestrationContext;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n /** The created session */\n session: AgentSession;\n /** Extensions result (for UI context setup in interactive mode) */\n extensionsResult: LoadExtensionsResult;\n /** Warning if session was restored with a different model than saved */\n modelFallbackMessage?: string;\n /** Warning if a saved/default context window could not be applied to the selected model. */\n contextWindowWarning?: string;\n /** Error if an explicit strict context-window selection is unsupported. */\n contextWindowError?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n ExtensionAPI,\n ExtensionCommandContext,\n ExtensionContext,\n ExtensionFactory,\n SlashCommandInfo,\n SlashCommandSource,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type {\n BashCommandParseError,\n BashCommandParseResult,\n BashCommandPolicy,\n BashCommandPolicyDecision,\n BashCommandPolicyMatchMode,\n BashCommandPolicyRejection,\n BashCommandRule,\n BashCommandSegment,\n BashCommandSegmentSource,\n JsonObject,\n JsonPrimitive,\n JsonValue,\n StructuredOutputCapture,\n StructuredOutputFileCapture,\n StructuredOutputToolOptions,\n Tool,\n} from \"./tools/index.ts\";\n\nexport {\n withFileMutationQueue,\n STRUCTURED_OUTPUT_TOOL_NAME,\n // Tool factories (for custom cwd)\n createCodingTools,\n createReadOnlyTools,\n createReadTool,\n createBashTool,\n createEditTool,\n createWriteTool,\n createGrepTool,\n createFindTool,\n createLsTool,\n createStructuredOutputCapture,\n createStructuredOutputTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n return getAgentDir();\n}\n\nfunction getAlreadyAppliedContextWindow(model: Model<Api>): number | undefined {\n const defaultContextWindow = getModelDefaultContextWindow(model);\n if (model.contextWindow === defaultContextWindow) {\n return undefined;\n }\n\n return getSupportedContextWindows(model).includes(model.contextWindow)\n ? model.contextWindow\n : 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 '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\n options: CreateAgentSessionOptions = {},\n): Promise<CreateAgentSessionResult> {\n const cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n const agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n let resourceLoader = options.resourceLoader;\n\n // Use provided or create AuthStorage and ModelRegistry\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const authStorage = options.authStorage ?? AuthStorage.create(authPath);\n const modelRegistry =\n options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n const settingsManager =\n options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n const sessionManager =\n options.sessionManager ??\n SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n if (!resourceLoader) {\n resourceLoader = new DefaultResourceLoader({\n cwd,\n agentDir,\n settingsManager,\n });\n await resourceLoader.reload();\n time(\"resourceLoader.reload\");\n }\n\n // Check if session has existing data to restore\n const existingSession = sessionManager.buildSessionContext();\n const hasExistingSession = existingSession.messages.length > 0;\n const hasThinkingEntry = sessionManager\n .getBranch()\n .some((entry) => entry.type === \"thinking_level_change\");\n\n let model = options.model;\n let modelFallbackMessage: string | undefined;\n\n // If session has data, try to restore model from it\n if (!model && hasExistingSession && existingSession.model) {\n const restoredModel = await resolveSavedModelReference(\n existingSession.model.provider,\n existingSession.model.modelId,\n modelRegistry,\n );\n if (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n model = restoredModel;\n }\n if (!model) {\n modelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n }\n }\n\n // If still no model, use findInitialModel (checks settings default, then provider defaults)\n if (!model) {\n const result = await findInitialModel({\n scopedModels: [],\n isContinuing: hasExistingSession,\n defaultProvider: settingsManager.getDefaultProvider(),\n defaultModelId: settingsManager.getDefaultModel(),\n defaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n modelRegistry,\n });\n model = result.model;\n if (!model) {\n modelFallbackMessage = formatNoModelsAvailableMessage();\n } else if (modelFallbackMessage) {\n modelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n }\n }\n\n let thinkingLevel = options.thinkingLevel;\n\n // If session has data, restore thinking level from it\n if (thinkingLevel === undefined && hasExistingSession) {\n thinkingLevel = hasThinkingEntry\n ? (existingSession.thinkingLevel as ThinkingLevel)\n : (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n }\n\n // Fall back to settings default\n if (thinkingLevel === undefined) {\n thinkingLevel =\n settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n }\n\n // Clamp to model capabilities\n if (!model) {\n thinkingLevel = \"off\";\n } else {\n thinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n }\n\n let selectedContextWindow: number | undefined;\n let contextWindowWarning: string | undefined;\n let contextWindowError: string | undefined;\n const explicitContextWindowSelection = options.contextWindow !== undefined;\n const incomingModelContextWindow =\n model && options.model ? getAlreadyAppliedContextWindow(model) : undefined;\n const requestedContextWindow =\n options.contextWindow ??\n incomingModelContextWindow ??\n (hasExistingSession ? existingSession.contextWindow : undefined) ??\n settingsManager.getDefaultContextWindow();\n if (model && requestedContextWindow !== undefined) {\n const selected = selectContextWindow(model, requestedContextWindow);\n if (\"error\" in selected) {\n if (options.contextWindowStrict) {\n contextWindowError = selected.error;\n } else {\n contextWindowWarning = selected.error;\n }\n } else {\n model = selected.model;\n selectedContextWindow = selected.contextWindow;\n }\n }\n\n const allowedToolNames =\n options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n const initialActiveToolNames: string[] = options.tools\n ? [...options.tools]\n : options.noTools\n ? []\n : [...defaultToolNames];\n\n let agent: Agent;\n\n let lastConvertedLlmMessages: Message[] | undefined;\n\n // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n const convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n const converted = convertToLlm(messages);\n // Check setting dynamically so mid-session changes take effect\n if (!settingsManager.getBlockImages()) {\n lastConvertedLlmMessages = converted;\n return converted;\n }\n // Filter out ImageContent from all messages, replacing with text placeholder\n const filtered = converted.map((msg) => {\n if (msg.role === \"user\" || msg.role === \"toolResult\") {\n const content = msg.content;\n if (Array.isArray(content)) {\n const hasImages = content.some((c) => c.type === \"image\");\n if (hasImages) {\n const filteredContent = content\n .map((c) =>\n c.type === \"image\"\n ? {\n type: \"text\" as const,\n text: \"Image reading is disabled.\",\n }\n : c,\n )\n .filter(\n (c, i, arr) =>\n // Dedupe consecutive \"Image reading is disabled.\" texts\n !(\n c.type === \"text\" &&\n c.text === \"Image reading is disabled.\" &&\n i > 0 &&\n arr[i - 1].type === \"text\" &&\n (arr[i - 1] as { type: \"text\"; text: string }).text ===\n \"Image reading is disabled.\"\n ),\n );\n return { ...msg, content: filteredContent };\n }\n }\n }\n return msg;\n });\n lastConvertedLlmMessages = filtered;\n return filtered;\n };\n\n const extensionRunnerRef: { current?: ExtensionRunner } = {};\n const isCodexFastModeEnabled = (requestModel: Model<Api>): boolean =>\n shouldApplyCodexFastMode(\n requestModel,\n settingsManager.getCodexFastModeSettings(),\n options.orchestrationContext,\n );\n\n agent = new Agent({\n initialState: {\n systemPrompt: \"\",\n model,\n thinkingLevel,\n tools: [],\n },\n convertToLlm: convertToLlmWithBlockImages,\n streamFn: async (model, context, streamOptions) => {\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n const providerRetrySettings = settingsManager.getProviderRetrySettings();\n const httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n // SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n // Use max int32 to effectively disable the timeout.\n const effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n const timeoutMs = streamOptions?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n const websocketConnectTimeoutMs =\n streamOptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n const attributionHeaders = mergeProviderAttributionHeaders(\n model,\n settingsManager,\n streamOptions?.sessionId,\n auth.headers,\n streamOptions?.headers,\n );\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const codexFastModeStreamOptions = withCodexFastModeStreamOptions(\n {\n ...streamOptions,\n apiKey: auth.apiKey,\n timeoutMs,\n websocketConnectTimeoutMs,\n maxRetries: streamOptions?.maxRetries ?? providerRetrySettings.maxRetries,\n maxRetryDelayMs:\n streamOptions?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n headers: attributionHeaders,\n },\n fastModeEnabled,\n );\n if (modelRegistry.hasRegisteredStreamSimpleForApi(model.api)) {\n return streamSimple(model, context, codexFastModeStreamOptions);\n }\n return streamWithCodexFastMode(model, context, codexFastModeStreamOptions);\n },\n onPayload: async (payload, model) => {\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const guardedPayload = withCodexFastModePayload(payload, fastModeEnabled);\n const sourceMessages = lastConvertedLlmMessages;\n const replayGuardedPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(guardedPayload, sourceMessages, model)\n : guardedPayload;\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n return replayGuardedPayload;\n }\n const extensionPayload = await runner.emitBeforeProviderRequest(\n replayGuardedPayload,\n );\n return sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n : extensionPayload;\n },\n onResponse: async (response, _model) => {\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"after_provider_response\")) {\n return;\n }\n await runner.emit({\n type: \"after_provider_response\",\n status: response.status,\n headers: response.headers,\n });\n },\n sessionId: sessionManager.getSessionId(),\n transformContext: async (messages) => {\n const runner = extensionRunnerRef.current;\n if (!runner) return messages;\n return runner.emitContext(messages);\n },\n steeringMode: settingsManager.getSteeringMode(),\n followUpMode: settingsManager.getFollowUpMode(),\n transport: settingsManager.getTransport(),\n thinkingBudgets: settingsManager.getThinkingBudgets(),\n maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n });\n\n // Restore messages if session has existing data\n if (hasExistingSession) {\n agent.state.messages = existingSession.messages;\n const transcriptContextWindow = model\n ? (existingSession.contextWindow ?? getModelDefaultContextWindow(model))\n : undefined;\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== transcriptContextWindow)\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n if (!hasThinkingEntry) {\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n } else {\n // Save initial model and thinking level for new sessions so they can be restored on resume\n if (model) {\n sessionManager.appendModelChange(model.provider, model.id);\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== getModelDefaultContextWindow(model))\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n }\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd,\n scopedModels: options.scopedModels,\n resourceLoader,\n customTools: options.customTools,\n bashPolicy: options.bashPolicy,\n modelRegistry,\n initialActiveToolNames,\n allowedToolNames,\n excludedToolNames: options.excludedTools,\n extensionRunnerRef,\n sessionStartEvent: options.sessionStartEvent,\n orchestrationContext: options.orchestrationContext,\n });\n const extensionsResult = resourceLoader.getExtensions();\n\n return {\n session,\n extensionsResult,\n modelFallbackMessage,\n contextWindowW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gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACf,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EACV,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,EACjB,yBAAyB,EACzB,0BAA0B,EAC1B,0BAA0B,EAC1B,eAAe,EACf,kBAAkB,EAClB,wBAAwB,EACxB,UAAU,EACV,aAAa,EACb,SAAS,EACT,uBAAuB,EACvB,2BAA2B,EAC3B,2BAA2B,EAC3B,IAAI,GACL,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,qBAAqB,EACrB,2BAA2B,EAE3B,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,EACZ,6BAA6B,EAC7B,0BAA0B,GAC3B,CAAC;AAuBF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,GAAE,yBAA8B,GACtC,OAAO,CAAC,wBAAwB,CAAC,CA0VnC","sourcesContent":["import { join } from \"node:path\";\nimport {\n Agent,\n type AgentMessage,\n type ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport {\n clampThinkingLevel,\n type Api,\n type Message,\n type Model,\n streamSimple,\n} from \"@earendil-works/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport {\n shouldApplyCodexFastMode,\n streamWithCodexFastMode,\n withCodexFastModePayload,\n withCodexFastModeStreamOptions,\n} from \"./codex-fast-mode.ts\";\nimport { restoreAnthropicReplayThinkingBlocks } from \"./anthropic-thinking-guard.ts\";\nimport { getModelDefaultContextWindow, getSupportedContextWindows, selectContextWindow } from \"./context-window.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n LoadExtensionsResult,\n OrchestrationContext,\n SessionStartEvent,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveSavedModelReference } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n createBashTool,\n createCodingTools,\n createEditTool,\n createFindTool,\n createGrepTool,\n createLsTool,\n createReadOnlyTools,\n createReadTool,\n STRUCTURED_OUTPUT_TOOL_NAME,\n createStructuredOutputCapture,\n createStructuredOutputTool,\n createWriteTool,\n defaultToolNames,\n withFileMutationQueue,\n type BashCommandPolicy,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n /** Working directory for project-local discovery. Default: process.cwd() */\n cwd?: string;\n /** Global config directory. Default: ~/.atomic/agent */\n agentDir?: string;\n\n /** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n authStorage?: AuthStorage;\n /** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n modelRegistry?: ModelRegistry;\n\n /** Model to use. Default: from settings, else first available */\n model?: Model<Api>;\n /** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n thinkingLevel?: ThinkingLevel;\n /** Context window token count. Default: model scalar contextWindow, or settings/session override when supported. */\n contextWindow?: number;\n /** Treat unsupported contextWindow as an error instead of a warning/fallback. */\n contextWindowStrict?: boolean;\n /** Models available for cycling (Ctrl+P in interactive mode) */\n scopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\n /**\n * Optional default tool suppression mode when no explicit allowlist is provided.\n *\n * - \"all\": start with no tools enabled\n * - \"builtin\": disable the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) but keep extension/custom tools enabled\n */\n noTools?: \"all\" | \"builtin\";\n /**\n * Optional allowlist of tool names.\n *\n * When omitted, pi enables the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) and leaves extension/custom tools enabled unless\n * `noTools` changes that default.\n * When provided, only the listed tool names are enabled, minus any names in\n * `excludedTools`.\n */\n tools?: string[];\n /**\n * Optional blocklist of tool names.\n *\n * Matching built-in, extension, and SDK custom tools are omitted from the\n * final session tool registry and active tool set. Unknown names are ignored.\n */\n excludedTools?: string[];\n /** Custom tools to register (in addition to built-in tools). */\n customTools?: ToolDefinition[];\n /** Optional command-level policy for the built-in bash tool. Does not expose bash by itself. */\n bashPolicy?: BashCommandPolicy;\n\n /** Resource loader. When omitted, DefaultResourceLoader is used. */\n resourceLoader?: ResourceLoader;\n\n /** Session manager. Default: SessionManager.create(cwd) */\n sessionManager?: SessionManager;\n\n /** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n settingsManager?: SettingsManager;\n /** Session start event metadata for extension runtime startup. */\n sessionStartEvent?: SessionStartEvent;\n /** Session-scoped orchestration policy exposed to extension/tool handlers. */\n orchestrationContext?: OrchestrationContext;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n /** The created session */\n session: AgentSession;\n /** Extensions result (for UI context setup in interactive mode) */\n extensionsResult: LoadExtensionsResult;\n /** Warning if session was restored with a different model than saved */\n modelFallbackMessage?: string;\n /** Warning if a saved/default context window could not be applied to the selected model. */\n contextWindowWarning?: string;\n /** Error if an explicit strict context-window selection is unsupported. */\n contextWindowError?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n ExtensionAPI,\n ExtensionCommandContext,\n ExtensionContext,\n ExtensionFactory,\n SlashCommandInfo,\n SlashCommandSource,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type {\n BashCommandParseError,\n BashCommandParseResult,\n BashCommandPolicy,\n BashCommandPolicyDecision,\n BashCommandPolicyMatchMode,\n BashCommandPolicyRejection,\n BashCommandRule,\n BashCommandSegment,\n BashCommandSegmentSource,\n JsonObject,\n JsonPrimitive,\n JsonValue,\n StructuredOutputCapture,\n StructuredOutputFileCapture,\n StructuredOutputToolOptions,\n Tool,\n} from \"./tools/index.ts\";\n\nexport {\n withFileMutationQueue,\n STRUCTURED_OUTPUT_TOOL_NAME,\n // Tool factories (for custom cwd)\n createCodingTools,\n createReadOnlyTools,\n createReadTool,\n createBashTool,\n createEditTool,\n createWriteTool,\n createGrepTool,\n createFindTool,\n createLsTool,\n createStructuredOutputCapture,\n createStructuredOutputTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n return getAgentDir();\n}\n\ntype ContextWindowRequestSource = \"explicit\" | \"incoming-model\" | \"session\" | \"model-settings\" | \"global-settings\";\n\nconst COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS = { allowCopilotLongContextFallback: true } as const;\n\nfunction getAlreadyAppliedContextWindow(model: Model<Api>): number | undefined {\n const defaultContextWindow = getModelDefaultContextWindow(model);\n if (model.contextWindow === defaultContextWindow) {\n return undefined;\n }\n\n return getSupportedContextWindows(model).includes(model.contextWindow)\n ? model.contextWindow\n : 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 '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\n options: CreateAgentSessionOptions = {},\n): Promise<CreateAgentSessionResult> {\n const cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n const agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n let resourceLoader = options.resourceLoader;\n\n // Use provided or create AuthStorage and ModelRegistry\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const authStorage = options.authStorage ?? AuthStorage.create(authPath);\n const modelRegistry =\n options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n const settingsManager =\n options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n const sessionManager =\n options.sessionManager ??\n SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n if (!resourceLoader) {\n resourceLoader = new DefaultResourceLoader({\n cwd,\n agentDir,\n settingsManager,\n });\n await resourceLoader.reload();\n time(\"resourceLoader.reload\");\n }\n\n // Check if session has existing data to restore\n const existingSession = sessionManager.buildSessionContext();\n const hasExistingSession = existingSession.messages.length > 0;\n const hasThinkingEntry = sessionManager\n .getBranch()\n .some((entry) => entry.type === \"thinking_level_change\");\n\n let model = options.model;\n let modelFallbackMessage: string | undefined;\n\n // If session has data, try to restore model from it\n if (!model && hasExistingSession && existingSession.model) {\n const restoredModel = await resolveSavedModelReference(\n existingSession.model.provider,\n existingSession.model.modelId,\n modelRegistry,\n );\n if (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n model = restoredModel;\n }\n if (!model) {\n modelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n }\n }\n\n // If still no model, use findInitialModel (checks settings default, then provider defaults)\n if (!model) {\n const result = await findInitialModel({\n scopedModels: [],\n isContinuing: hasExistingSession,\n defaultProvider: settingsManager.getDefaultProvider(),\n defaultModelId: settingsManager.getDefaultModel(),\n defaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n modelRegistry,\n });\n model = result.model;\n if (!model) {\n modelFallbackMessage = formatNoModelsAvailableMessage();\n } else if (modelFallbackMessage) {\n modelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n }\n }\n\n let thinkingLevel = options.thinkingLevel;\n\n // If session has data, restore thinking level from it\n if (thinkingLevel === undefined && hasExistingSession) {\n thinkingLevel = hasThinkingEntry\n ? (existingSession.thinkingLevel as ThinkingLevel)\n : (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n }\n\n // Fall back to settings default\n if (thinkingLevel === undefined) {\n thinkingLevel =\n settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n }\n\n // Clamp to model capabilities\n if (!model) {\n thinkingLevel = \"off\";\n } else {\n thinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n }\n\n let selectedContextWindow: number | undefined;\n let contextWindowWarning: string | undefined;\n let contextWindowError: string | undefined;\n const explicitContextWindowSelection = options.contextWindow !== undefined;\n const incomingModelContextWindow =\n model && options.model ? getAlreadyAppliedContextWindow(model) : undefined;\n const sessionContextWindow = hasExistingSession ? existingSession.contextWindow : undefined;\n const modelSettingsContextWindow = model ? settingsManager.getDefaultContextWindowForModel(model.provider, model.id) : undefined;\n const globalSettingsContextWindow = settingsManager.getDefaultContextWindow();\n const contextWindowRequest:\n | { contextWindow: number; source: ContextWindowRequestSource }\n | undefined =\n options.contextWindow !== undefined\n ? { contextWindow: options.contextWindow, source: \"explicit\" }\n : incomingModelContextWindow !== undefined\n ? { contextWindow: incomingModelContextWindow, source: \"incoming-model\" }\n : sessionContextWindow !== undefined\n ? { contextWindow: sessionContextWindow, source: \"session\" }\n : modelSettingsContextWindow !== undefined\n ? { contextWindow: modelSettingsContextWindow, source: \"model-settings\" }\n : globalSettingsContextWindow !== undefined\n ? { contextWindow: globalSettingsContextWindow, source: \"global-settings\" }\n : undefined;\n if (model && contextWindowRequest !== undefined) {\n const selected = selectContextWindow(\n model,\n contextWindowRequest.contextWindow,\n COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS,\n );\n if (\"error\" in selected) {\n if (options.contextWindowStrict) {\n contextWindowError = selected.error;\n } else if (contextWindowRequest.source !== \"global-settings\") {\n contextWindowWarning = selected.error;\n }\n } else {\n model = selected.model;\n selectedContextWindow = selected.contextWindow;\n }\n }\n\n const allowedToolNames =\n options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n const initialActiveToolNames: string[] = options.tools\n ? [...options.tools]\n : options.noTools\n ? []\n : [...defaultToolNames];\n\n let agent: Agent;\n\n let lastConvertedLlmMessages: Message[] | undefined;\n\n // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n const convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n const converted = convertToLlm(messages);\n // Check setting dynamically so mid-session changes take effect\n if (!settingsManager.getBlockImages()) {\n lastConvertedLlmMessages = converted;\n return converted;\n }\n // Filter out ImageContent from all messages, replacing with text placeholder\n const filtered = converted.map((msg) => {\n if (msg.role === \"user\" || msg.role === \"toolResult\") {\n const content = msg.content;\n if (Array.isArray(content)) {\n const hasImages = content.some((c) => c.type === \"image\");\n if (hasImages) {\n const filteredContent = content\n .map((c) =>\n c.type === \"image\"\n ? {\n type: \"text\" as const,\n text: \"Image reading is disabled.\",\n }\n : c,\n )\n .filter(\n (c, i, arr) =>\n // Dedupe consecutive \"Image reading is disabled.\" texts\n !(\n c.type === \"text\" &&\n c.text === \"Image reading is disabled.\" &&\n i > 0 &&\n arr[i - 1].type === \"text\" &&\n (arr[i - 1] as { type: \"text\"; text: string }).text ===\n \"Image reading is disabled.\"\n ),\n );\n return { ...msg, content: filteredContent };\n }\n }\n }\n return msg;\n });\n lastConvertedLlmMessages = filtered;\n return filtered;\n };\n\n const extensionRunnerRef: { current?: ExtensionRunner } = {};\n const isCodexFastModeEnabled = (requestModel: Model<Api>): boolean =>\n shouldApplyCodexFastMode(\n requestModel,\n settingsManager.getCodexFastModeSettings(),\n options.orchestrationContext,\n );\n\n agent = new Agent({\n initialState: {\n systemPrompt: \"\",\n model,\n thinkingLevel,\n tools: [],\n },\n convertToLlm: convertToLlmWithBlockImages,\n streamFn: async (model, context, streamOptions) => {\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n const providerRetrySettings = settingsManager.getProviderRetrySettings();\n const httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n // SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n // Use max int32 to effectively disable the timeout.\n const effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n const timeoutMs = streamOptions?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n const websocketConnectTimeoutMs =\n streamOptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n const attributionHeaders = mergeProviderAttributionHeaders(\n model,\n settingsManager,\n streamOptions?.sessionId,\n auth.headers,\n streamOptions?.headers,\n );\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const codexFastModeStreamOptions = withCodexFastModeStreamOptions(\n {\n ...streamOptions,\n apiKey: auth.apiKey,\n timeoutMs,\n websocketConnectTimeoutMs,\n maxRetries: streamOptions?.maxRetries ?? providerRetrySettings.maxRetries,\n maxRetryDelayMs:\n streamOptions?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n headers: attributionHeaders,\n },\n fastModeEnabled,\n );\n if (modelRegistry.hasRegisteredStreamSimpleForApi(model.api)) {\n return streamSimple(model, context, codexFastModeStreamOptions);\n }\n return streamWithCodexFastMode(model, context, codexFastModeStreamOptions);\n },\n onPayload: async (payload, model) => {\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const guardedPayload = withCodexFastModePayload(payload, fastModeEnabled);\n const sourceMessages = lastConvertedLlmMessages;\n const replayGuardedPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(guardedPayload, sourceMessages, model)\n : guardedPayload;\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n return replayGuardedPayload;\n }\n const extensionPayload = await runner.emitBeforeProviderRequest(\n replayGuardedPayload,\n );\n return sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n : extensionPayload;\n },\n onResponse: async (response, _model) => {\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"after_provider_response\")) {\n return;\n }\n await runner.emit({\n type: \"after_provider_response\",\n status: response.status,\n headers: response.headers,\n });\n },\n sessionId: sessionManager.getSessionId(),\n transformContext: async (messages) => {\n const runner = extensionRunnerRef.current;\n if (!runner) return messages;\n return runner.emitContext(messages);\n },\n steeringMode: settingsManager.getSteeringMode(),\n followUpMode: settingsManager.getFollowUpMode(),\n transport: settingsManager.getTransport(),\n thinkingBudgets: settingsManager.getThinkingBudgets(),\n maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n });\n\n // Restore messages if session has existing data\n if (hasExistingSession) {\n agent.state.messages = existingSession.messages;\n const transcriptContextWindow = model\n ? (existingSession.contextWindow ?? getModelDefaultContextWindow(model))\n : undefined;\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== transcriptContextWindow)\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n if (!hasThinkingEntry) {\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n } else {\n // Save initial model and thinking level for new sessions so they can be restored on resume\n if (model) {\n sessionManager.appendModelChange(model.provider, model.id);\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== getModelDefaultContextWindow(model))\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n }\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd,\n scopedModels: options.scopedModels,\n resourceLoader,\n customTools: options.customTools,\n bashPolicy: options.bashPolicy,\n modelRegistry,\n initialActiveToolNames,\n allowedToolNames,\n excludedToolNames: options.excludedTools,\n extensionRunnerRef,\n sessionStartEvent: options.sessionStartEvent,\n orchestrationContext: options.orchestrationContext,\n });\n const extensionsResult = resourceLoader.getExtensions();\n\n return {\n session,\n extensionsResult,\n modelFallbackMessage,\n contextWindowWarning,\n contextWindowError,\n };\n}\n"]}
package/dist/core/sdk.js CHANGED
@@ -28,6 +28,7 @@ createCodingTools, createReadOnlyTools, createReadTool, createBashTool, createEd
28
28
  function getDefaultAgentDir() {
29
29
  return getAgentDir();
30
30
  }
31
+ const COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS = { allowCopilotLongContextFallback: true };
31
32
  function getAlreadyAppliedContextWindow(model) {
32
33
  const defaultContextWindow = getModelDefaultContextWindow(model);
33
34
  if (model.contextWindow === defaultContextWindow) {
@@ -155,17 +156,27 @@ export async function createAgentSession(options = {}) {
155
156
  let contextWindowError;
156
157
  const explicitContextWindowSelection = options.contextWindow !== undefined;
157
158
  const incomingModelContextWindow = model && options.model ? getAlreadyAppliedContextWindow(model) : undefined;
158
- const requestedContextWindow = options.contextWindow ??
159
- incomingModelContextWindow ??
160
- (hasExistingSession ? existingSession.contextWindow : undefined) ??
161
- settingsManager.getDefaultContextWindow();
162
- if (model && requestedContextWindow !== undefined) {
163
- const selected = selectContextWindow(model, requestedContextWindow);
159
+ const sessionContextWindow = hasExistingSession ? existingSession.contextWindow : undefined;
160
+ const modelSettingsContextWindow = model ? settingsManager.getDefaultContextWindowForModel(model.provider, model.id) : undefined;
161
+ const globalSettingsContextWindow = settingsManager.getDefaultContextWindow();
162
+ const contextWindowRequest = options.contextWindow !== undefined
163
+ ? { contextWindow: options.contextWindow, source: "explicit" }
164
+ : incomingModelContextWindow !== undefined
165
+ ? { contextWindow: incomingModelContextWindow, source: "incoming-model" }
166
+ : sessionContextWindow !== undefined
167
+ ? { contextWindow: sessionContextWindow, source: "session" }
168
+ : modelSettingsContextWindow !== undefined
169
+ ? { contextWindow: modelSettingsContextWindow, source: "model-settings" }
170
+ : globalSettingsContextWindow !== undefined
171
+ ? { contextWindow: globalSettingsContextWindow, source: "global-settings" }
172
+ : undefined;
173
+ if (model && contextWindowRequest !== undefined) {
174
+ const selected = selectContextWindow(model, contextWindowRequest.contextWindow, COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS);
164
175
  if ("error" in selected) {
165
176
  if (options.contextWindowStrict) {
166
177
  contextWindowError = selected.error;
167
178
  }
168
- else {
179
+ else if (contextWindowRequest.source !== "global-settings") {
169
180
  contextWindowWarning = selected.error;
170
181
  }
171
182
  }
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACL,KAAK,GAGN,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,kBAAkB,EAIlB,YAAY,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,o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a;QACb,sBAAsB;QACtB,gBAAgB;QAChB,iBAAiB,EAAE,OAAO,CAAC,aAAa;QACxC,kBAAkB;QAClB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;QAC5C,oBAAoB,EAAE,OAAO,CAAC,oBAAoB;KACnD,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACL,OAAO;QACP,gBAAgB;QAChB,oBAAoB;QACpB,oBAAoB;QACpB,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport {\n Agent,\n type AgentMessage,\n type ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport {\n clampThinkingLevel,\n type Api,\n type Message,\n type Model,\n streamSimple,\n} from \"@earendil-works/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport {\n shouldApplyCodexFastMode,\n streamWithCodexFastMode,\n withCodexFastModePayload,\n withCodexFastModeStreamOptions,\n} from \"./codex-fast-mode.ts\";\nimport { restoreAnthropicReplayThinkingBlocks } from \"./anthropic-thinking-guard.ts\";\nimport { getModelDefaultContextWindow, getSupportedContextWindows, selectContextWindow } from \"./context-window.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n LoadExtensionsResult,\n OrchestrationContext,\n SessionStartEvent,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveSavedModelReference } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n createBashTool,\n createCodingTools,\n createEditTool,\n createFindTool,\n createGrepTool,\n createLsTool,\n createReadOnlyTools,\n createReadTool,\n STRUCTURED_OUTPUT_TOOL_NAME,\n createStructuredOutputCapture,\n createStructuredOutputTool,\n createWriteTool,\n defaultToolNames,\n withFileMutationQueue,\n type BashCommandPolicy,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n /** Working directory for project-local discovery. Default: process.cwd() */\n cwd?: string;\n /** Global config directory. Default: ~/.atomic/agent */\n agentDir?: string;\n\n /** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n authStorage?: AuthStorage;\n /** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n modelRegistry?: ModelRegistry;\n\n /** Model to use. Default: from settings, else first available */\n model?: Model<Api>;\n /** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n thinkingLevel?: ThinkingLevel;\n /** Context window token count. Default: model scalar contextWindow, or settings/session override when supported. */\n contextWindow?: number;\n /** Treat unsupported contextWindow as an error instead of a warning/fallback. */\n contextWindowStrict?: boolean;\n /** Models available for cycling (Ctrl+P in interactive mode) */\n scopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\n /**\n * Optional default tool suppression mode when no explicit allowlist is provided.\n *\n * - \"all\": start with no tools enabled\n * - \"builtin\": disable the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) but keep extension/custom tools enabled\n */\n noTools?: \"all\" | \"builtin\";\n /**\n * Optional allowlist of tool names.\n *\n * When omitted, pi enables the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) and leaves extension/custom tools enabled unless\n * `noTools` changes that default.\n * When provided, only the listed tool names are enabled, minus any names in\n * `excludedTools`.\n */\n tools?: string[];\n /**\n * Optional blocklist of tool names.\n *\n * Matching built-in, extension, and SDK custom tools are omitted from the\n * final session tool registry and active tool set. Unknown names are ignored.\n */\n excludedTools?: string[];\n /** Custom tools to register (in addition to built-in tools). */\n customTools?: ToolDefinition[];\n /** Optional command-level policy for the built-in bash tool. Does not expose bash by itself. */\n bashPolicy?: BashCommandPolicy;\n\n /** Resource loader. When omitted, DefaultResourceLoader is used. */\n resourceLoader?: ResourceLoader;\n\n /** Session manager. Default: SessionManager.create(cwd) */\n sessionManager?: SessionManager;\n\n /** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n settingsManager?: SettingsManager;\n /** Session start event metadata for extension runtime startup. */\n sessionStartEvent?: SessionStartEvent;\n /** Session-scoped orchestration policy exposed to extension/tool handlers. */\n orchestrationContext?: OrchestrationContext;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n /** The created session */\n session: AgentSession;\n /** Extensions result (for UI context setup in interactive mode) */\n extensionsResult: LoadExtensionsResult;\n /** Warning if session was restored with a different model than saved */\n modelFallbackMessage?: string;\n /** Warning if a saved/default context window could not be applied to the selected model. */\n contextWindowWarning?: string;\n /** Error if an explicit strict context-window selection is unsupported. */\n contextWindowError?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n ExtensionAPI,\n ExtensionCommandContext,\n ExtensionContext,\n ExtensionFactory,\n SlashCommandInfo,\n SlashCommandSource,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type {\n BashCommandParseError,\n BashCommandParseResult,\n BashCommandPolicy,\n BashCommandPolicyDecision,\n BashCommandPolicyMatchMode,\n BashCommandPolicyRejection,\n BashCommandRule,\n BashCommandSegment,\n BashCommandSegmentSource,\n JsonObject,\n JsonPrimitive,\n JsonValue,\n StructuredOutputCapture,\n StructuredOutputFileCapture,\n StructuredOutputToolOptions,\n Tool,\n} from \"./tools/index.ts\";\n\nexport {\n withFileMutationQueue,\n STRUCTURED_OUTPUT_TOOL_NAME,\n // Tool factories (for custom cwd)\n createCodingTools,\n createReadOnlyTools,\n createReadTool,\n createBashTool,\n createEditTool,\n createWriteTool,\n createGrepTool,\n createFindTool,\n createLsTool,\n createStructuredOutputCapture,\n createStructuredOutputTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n return getAgentDir();\n}\n\nfunction getAlreadyAppliedContextWindow(model: Model<Api>): number | undefined {\n const defaultContextWindow = getModelDefaultContextWindow(model);\n if (model.contextWindow === defaultContextWindow) {\n return undefined;\n }\n\n return getSupportedContextWindows(model).includes(model.contextWindow)\n ? model.contextWindow\n : 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 '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\n options: CreateAgentSessionOptions = {},\n): Promise<CreateAgentSessionResult> {\n const cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n const agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n let resourceLoader = options.resourceLoader;\n\n // Use provided or create AuthStorage and ModelRegistry\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const authStorage = options.authStorage ?? AuthStorage.create(authPath);\n const modelRegistry =\n options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n const settingsManager =\n options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n const sessionManager =\n options.sessionManager ??\n SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n if (!resourceLoader) {\n resourceLoader = new DefaultResourceLoader({\n cwd,\n agentDir,\n settingsManager,\n });\n await resourceLoader.reload();\n time(\"resourceLoader.reload\");\n }\n\n // Check if session has existing data to restore\n const existingSession = sessionManager.buildSessionContext();\n const hasExistingSession = existingSession.messages.length > 0;\n const hasThinkingEntry = sessionManager\n .getBranch()\n .some((entry) => entry.type === \"thinking_level_change\");\n\n let model = options.model;\n let modelFallbackMessage: string | undefined;\n\n // If session has data, try to restore model from it\n if (!model && hasExistingSession && existingSession.model) {\n const restoredModel = await resolveSavedModelReference(\n existingSession.model.provider,\n existingSession.model.modelId,\n modelRegistry,\n );\n if (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n model = restoredModel;\n }\n if (!model) {\n modelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n }\n }\n\n // If still no model, use findInitialModel (checks settings default, then provider defaults)\n if (!model) {\n const result = await findInitialModel({\n scopedModels: [],\n isContinuing: hasExistingSession,\n defaultProvider: settingsManager.getDefaultProvider(),\n defaultModelId: settingsManager.getDefaultModel(),\n defaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n modelRegistry,\n });\n model = result.model;\n if (!model) {\n modelFallbackMessage = formatNoModelsAvailableMessage();\n } else if (modelFallbackMessage) {\n modelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n }\n }\n\n let thinkingLevel = options.thinkingLevel;\n\n // If session has data, restore thinking level from it\n if (thinkingLevel === undefined && hasExistingSession) {\n thinkingLevel = hasThinkingEntry\n ? (existingSession.thinkingLevel as ThinkingLevel)\n : (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n }\n\n // Fall back to settings default\n if (thinkingLevel === undefined) {\n thinkingLevel =\n settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n }\n\n // Clamp to model capabilities\n if (!model) {\n thinkingLevel = \"off\";\n } else {\n thinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n }\n\n let selectedContextWindow: number | undefined;\n let contextWindowWarning: string | undefined;\n let contextWindowError: string | undefined;\n const explicitContextWindowSelection = options.contextWindow !== undefined;\n const incomingModelContextWindow =\n model && options.model ? getAlreadyAppliedContextWindow(model) : undefined;\n const requestedContextWindow =\n options.contextWindow ??\n incomingModelContextWindow ??\n (hasExistingSession ? existingSession.contextWindow : undefined) ??\n settingsManager.getDefaultContextWindow();\n if (model && requestedContextWindow !== undefined) {\n const selected = selectContextWindow(model, requestedContextWindow);\n if (\"error\" in selected) {\n if (options.contextWindowStrict) {\n contextWindowError = selected.error;\n } else {\n contextWindowWarning = selected.error;\n }\n } else {\n model = selected.model;\n selectedContextWindow = selected.contextWindow;\n }\n }\n\n const allowedToolNames =\n options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n const initialActiveToolNames: string[] = options.tools\n ? [...options.tools]\n : options.noTools\n ? []\n : [...defaultToolNames];\n\n let agent: Agent;\n\n let lastConvertedLlmMessages: Message[] | undefined;\n\n // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n const convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n const converted = convertToLlm(messages);\n // Check setting dynamically so mid-session changes take effect\n if (!settingsManager.getBlockImages()) {\n lastConvertedLlmMessages = converted;\n return converted;\n }\n // Filter out ImageContent from all messages, replacing with text placeholder\n const filtered = converted.map((msg) => {\n if (msg.role === \"user\" || msg.role === \"toolResult\") {\n const content = msg.content;\n if (Array.isArray(content)) {\n const hasImages = content.some((c) => c.type === \"image\");\n if (hasImages) {\n const filteredContent = content\n .map((c) =>\n c.type === \"image\"\n ? {\n type: \"text\" as const,\n text: \"Image reading is disabled.\",\n }\n : c,\n )\n .filter(\n (c, i, arr) =>\n // Dedupe consecutive \"Image reading is disabled.\" texts\n !(\n c.type === \"text\" &&\n c.text === \"Image reading is disabled.\" &&\n i > 0 &&\n arr[i - 1].type === \"text\" &&\n (arr[i - 1] as { type: \"text\"; text: string }).text ===\n \"Image reading is disabled.\"\n ),\n );\n return { ...msg, content: filteredContent };\n }\n }\n }\n return msg;\n });\n lastConvertedLlmMessages = filtered;\n return filtered;\n };\n\n const extensionRunnerRef: { current?: ExtensionRunner } = {};\n const isCodexFastModeEnabled = (requestModel: Model<Api>): boolean =>\n shouldApplyCodexFastMode(\n requestModel,\n settingsManager.getCodexFastModeSettings(),\n options.orchestrationContext,\n );\n\n agent = new Agent({\n initialState: {\n systemPrompt: \"\",\n model,\n thinkingLevel,\n tools: [],\n },\n convertToLlm: convertToLlmWithBlockImages,\n streamFn: async (model, context, streamOptions) => {\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n const providerRetrySettings = settingsManager.getProviderRetrySettings();\n const httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n // SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n // Use max int32 to effectively disable the timeout.\n const effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n const timeoutMs = streamOptions?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n const websocketConnectTimeoutMs =\n streamOptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n const attributionHeaders = mergeProviderAttributionHeaders(\n model,\n settingsManager,\n streamOptions?.sessionId,\n auth.headers,\n streamOptions?.headers,\n );\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const codexFastModeStreamOptions = withCodexFastModeStreamOptions(\n {\n ...streamOptions,\n apiKey: auth.apiKey,\n timeoutMs,\n websocketConnectTimeoutMs,\n maxRetries: streamOptions?.maxRetries ?? providerRetrySettings.maxRetries,\n maxRetryDelayMs:\n streamOptions?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n headers: attributionHeaders,\n },\n fastModeEnabled,\n );\n if (modelRegistry.hasRegisteredStreamSimpleForApi(model.api)) {\n return streamSimple(model, context, codexFastModeStreamOptions);\n }\n return streamWithCodexFastMode(model, context, codexFastModeStreamOptions);\n },\n onPayload: async (payload, model) => {\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const guardedPayload = withCodexFastModePayload(payload, fastModeEnabled);\n const sourceMessages = lastConvertedLlmMessages;\n const replayGuardedPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(guardedPayload, sourceMessages, model)\n : guardedPayload;\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n return replayGuardedPayload;\n }\n const extensionPayload = await runner.emitBeforeProviderRequest(\n replayGuardedPayload,\n );\n return sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n : extensionPayload;\n },\n onResponse: async (response, _model) => {\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"after_provider_response\")) {\n return;\n }\n await runner.emit({\n type: \"after_provider_response\",\n status: response.status,\n headers: response.headers,\n });\n },\n sessionId: sessionManager.getSessionId(),\n transformContext: async (messages) => {\n const runner = extensionRunnerRef.current;\n if (!runner) return messages;\n return runner.emitContext(messages);\n },\n steeringMode: settingsManager.getSteeringMode(),\n followUpMode: settingsManager.getFollowUpMode(),\n transport: settingsManager.getTransport(),\n thinkingBudgets: settingsManager.getThinkingBudgets(),\n maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n });\n\n // Restore messages if session has existing data\n if (hasExistingSession) {\n agent.state.messages = existingSession.messages;\n const transcriptContextWindow = model\n ? (existingSession.contextWindow ?? getModelDefaultContextWindow(model))\n : undefined;\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== transcriptContextWindow)\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n if (!hasThinkingEntry) {\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n } else {\n // Save initial model and thinking level for new sessions so they can be restored on resume\n if (model) {\n sessionManager.appendModelChange(model.provider, model.id);\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== getModelDefaultContextWindow(model))\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n }\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd,\n scopedModels: options.scopedModels,\n resourceLoader,\n customTools: options.customTools,\n bashPolicy: options.bashPolicy,\n modelRegistry,\n initialActiveToolNames,\n allowedToolNames,\n excludedToolNames: options.excludedTools,\n extensionRunnerRef,\n sessionStartEvent: options.sessionStartEvent,\n orchestrationContext: options.orchestrationContext,\n });\n const extensionsResult = resourceLoader.getExtensions();\n\n return {\n session,\n extensionsResult,\n modelFallbackMessage,\n contextWindowWarning,\n contextWindowError,\n };\n}\n"]}
1
+ {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACL,KAAK,GAGN,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,kBAAkB,EAIlB,YAAY,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EACxB,8BAA8B,GAC/B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AChB,oBAAoB;QACpB,oBAAoB;QACpB,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport {\n Agent,\n type AgentMessage,\n type ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport {\n clampThinkingLevel,\n type Api,\n type Message,\n type Model,\n streamSimple,\n} from \"@earendil-works/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport {\n shouldApplyCodexFastMode,\n streamWithCodexFastMode,\n withCodexFastModePayload,\n withCodexFastModeStreamOptions,\n} from \"./codex-fast-mode.ts\";\nimport { restoreAnthropicReplayThinkingBlocks } from \"./anthropic-thinking-guard.ts\";\nimport { getModelDefaultContextWindow, getSupportedContextWindows, selectContextWindow } from \"./context-window.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n LoadExtensionsResult,\n OrchestrationContext,\n SessionStartEvent,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveSavedModelReference } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n createBashTool,\n createCodingTools,\n createEditTool,\n createFindTool,\n createGrepTool,\n createLsTool,\n createReadOnlyTools,\n createReadTool,\n STRUCTURED_OUTPUT_TOOL_NAME,\n createStructuredOutputCapture,\n createStructuredOutputTool,\n createWriteTool,\n defaultToolNames,\n withFileMutationQueue,\n type BashCommandPolicy,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n /** Working directory for project-local discovery. Default: process.cwd() */\n cwd?: string;\n /** Global config directory. Default: ~/.atomic/agent */\n agentDir?: string;\n\n /** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n authStorage?: AuthStorage;\n /** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n modelRegistry?: ModelRegistry;\n\n /** Model to use. Default: from settings, else first available */\n model?: Model<Api>;\n /** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n thinkingLevel?: ThinkingLevel;\n /** Context window token count. Default: model scalar contextWindow, or settings/session override when supported. */\n contextWindow?: number;\n /** Treat unsupported contextWindow as an error instead of a warning/fallback. */\n contextWindowStrict?: boolean;\n /** Models available for cycling (Ctrl+P in interactive mode) */\n scopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\n /**\n * Optional default tool suppression mode when no explicit allowlist is provided.\n *\n * - \"all\": start with no tools enabled\n * - \"builtin\": disable the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) but keep extension/custom tools enabled\n */\n noTools?: \"all\" | \"builtin\";\n /**\n * Optional allowlist of tool names.\n *\n * When omitted, pi enables the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) and leaves extension/custom tools enabled unless\n * `noTools` changes that default.\n * When provided, only the listed tool names are enabled, minus any names in\n * `excludedTools`.\n */\n tools?: string[];\n /**\n * Optional blocklist of tool names.\n *\n * Matching built-in, extension, and SDK custom tools are omitted from the\n * final session tool registry and active tool set. Unknown names are ignored.\n */\n excludedTools?: string[];\n /** Custom tools to register (in addition to built-in tools). */\n customTools?: ToolDefinition[];\n /** Optional command-level policy for the built-in bash tool. Does not expose bash by itself. */\n bashPolicy?: BashCommandPolicy;\n\n /** Resource loader. When omitted, DefaultResourceLoader is used. */\n resourceLoader?: ResourceLoader;\n\n /** Session manager. Default: SessionManager.create(cwd) */\n sessionManager?: SessionManager;\n\n /** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n settingsManager?: SettingsManager;\n /** Session start event metadata for extension runtime startup. */\n sessionStartEvent?: SessionStartEvent;\n /** Session-scoped orchestration policy exposed to extension/tool handlers. */\n orchestrationContext?: OrchestrationContext;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n /** The created session */\n session: AgentSession;\n /** Extensions result (for UI context setup in interactive mode) */\n extensionsResult: LoadExtensionsResult;\n /** Warning if session was restored with a different model than saved */\n modelFallbackMessage?: string;\n /** Warning if a saved/default context window could not be applied to the selected model. */\n contextWindowWarning?: string;\n /** Error if an explicit strict context-window selection is unsupported. */\n contextWindowError?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n ExtensionAPI,\n ExtensionCommandContext,\n ExtensionContext,\n ExtensionFactory,\n SlashCommandInfo,\n SlashCommandSource,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type {\n BashCommandParseError,\n BashCommandParseResult,\n BashCommandPolicy,\n BashCommandPolicyDecision,\n BashCommandPolicyMatchMode,\n BashCommandPolicyRejection,\n BashCommandRule,\n BashCommandSegment,\n BashCommandSegmentSource,\n JsonObject,\n JsonPrimitive,\n JsonValue,\n StructuredOutputCapture,\n StructuredOutputFileCapture,\n StructuredOutputToolOptions,\n Tool,\n} from \"./tools/index.ts\";\n\nexport {\n withFileMutationQueue,\n STRUCTURED_OUTPUT_TOOL_NAME,\n // Tool factories (for custom cwd)\n createCodingTools,\n createReadOnlyTools,\n createReadTool,\n createBashTool,\n createEditTool,\n createWriteTool,\n createGrepTool,\n createFindTool,\n createLsTool,\n createStructuredOutputCapture,\n createStructuredOutputTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n return getAgentDir();\n}\n\ntype ContextWindowRequestSource = \"explicit\" | \"incoming-model\" | \"session\" | \"model-settings\" | \"global-settings\";\n\nconst COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS = { allowCopilotLongContextFallback: true } as const;\n\nfunction getAlreadyAppliedContextWindow(model: Model<Api>): number | undefined {\n const defaultContextWindow = getModelDefaultContextWindow(model);\n if (model.contextWindow === defaultContextWindow) {\n return undefined;\n }\n\n return getSupportedContextWindows(model).includes(model.contextWindow)\n ? model.contextWindow\n : 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 '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\n options: CreateAgentSessionOptions = {},\n): Promise<CreateAgentSessionResult> {\n const cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n const agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n let resourceLoader = options.resourceLoader;\n\n // Use provided or create AuthStorage and ModelRegistry\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const authStorage = options.authStorage ?? AuthStorage.create(authPath);\n const modelRegistry =\n options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n const settingsManager =\n options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n const sessionManager =\n options.sessionManager ??\n SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n if (!resourceLoader) {\n resourceLoader = new DefaultResourceLoader({\n cwd,\n agentDir,\n settingsManager,\n });\n await resourceLoader.reload();\n time(\"resourceLoader.reload\");\n }\n\n // Check if session has existing data to restore\n const existingSession = sessionManager.buildSessionContext();\n const hasExistingSession = existingSession.messages.length > 0;\n const hasThinkingEntry = sessionManager\n .getBranch()\n .some((entry) => entry.type === \"thinking_level_change\");\n\n let model = options.model;\n let modelFallbackMessage: string | undefined;\n\n // If session has data, try to restore model from it\n if (!model && hasExistingSession && existingSession.model) {\n const restoredModel = await resolveSavedModelReference(\n existingSession.model.provider,\n existingSession.model.modelId,\n modelRegistry,\n );\n if (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n model = restoredModel;\n }\n if (!model) {\n modelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n }\n }\n\n // If still no model, use findInitialModel (checks settings default, then provider defaults)\n if (!model) {\n const result = await findInitialModel({\n scopedModels: [],\n isContinuing: hasExistingSession,\n defaultProvider: settingsManager.getDefaultProvider(),\n defaultModelId: settingsManager.getDefaultModel(),\n defaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n modelRegistry,\n });\n model = result.model;\n if (!model) {\n modelFallbackMessage = formatNoModelsAvailableMessage();\n } else if (modelFallbackMessage) {\n modelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n }\n }\n\n let thinkingLevel = options.thinkingLevel;\n\n // If session has data, restore thinking level from it\n if (thinkingLevel === undefined && hasExistingSession) {\n thinkingLevel = hasThinkingEntry\n ? (existingSession.thinkingLevel as ThinkingLevel)\n : (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n }\n\n // Fall back to settings default\n if (thinkingLevel === undefined) {\n thinkingLevel =\n settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n }\n\n // Clamp to model capabilities\n if (!model) {\n thinkingLevel = \"off\";\n } else {\n thinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n }\n\n let selectedContextWindow: number | undefined;\n let contextWindowWarning: string | undefined;\n let contextWindowError: string | undefined;\n const explicitContextWindowSelection = options.contextWindow !== undefined;\n const incomingModelContextWindow =\n model && options.model ? getAlreadyAppliedContextWindow(model) : undefined;\n const sessionContextWindow = hasExistingSession ? existingSession.contextWindow : undefined;\n const modelSettingsContextWindow = model ? settingsManager.getDefaultContextWindowForModel(model.provider, model.id) : undefined;\n const globalSettingsContextWindow = settingsManager.getDefaultContextWindow();\n const contextWindowRequest:\n | { contextWindow: number; source: ContextWindowRequestSource }\n | undefined =\n options.contextWindow !== undefined\n ? { contextWindow: options.contextWindow, source: \"explicit\" }\n : incomingModelContextWindow !== undefined\n ? { contextWindow: incomingModelContextWindow, source: \"incoming-model\" }\n : sessionContextWindow !== undefined\n ? { contextWindow: sessionContextWindow, source: \"session\" }\n : modelSettingsContextWindow !== undefined\n ? { contextWindow: modelSettingsContextWindow, source: \"model-settings\" }\n : globalSettingsContextWindow !== undefined\n ? { contextWindow: globalSettingsContextWindow, source: \"global-settings\" }\n : undefined;\n if (model && contextWindowRequest !== undefined) {\n const selected = selectContextWindow(\n model,\n contextWindowRequest.contextWindow,\n COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS,\n );\n if (\"error\" in selected) {\n if (options.contextWindowStrict) {\n contextWindowError = selected.error;\n } else if (contextWindowRequest.source !== \"global-settings\") {\n contextWindowWarning = selected.error;\n }\n } else {\n model = selected.model;\n selectedContextWindow = selected.contextWindow;\n }\n }\n\n const allowedToolNames =\n options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n const initialActiveToolNames: string[] = options.tools\n ? [...options.tools]\n : options.noTools\n ? []\n : [...defaultToolNames];\n\n let agent: Agent;\n\n let lastConvertedLlmMessages: Message[] | undefined;\n\n // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n const convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n const converted = convertToLlm(messages);\n // Check setting dynamically so mid-session changes take effect\n if (!settingsManager.getBlockImages()) {\n lastConvertedLlmMessages = converted;\n return converted;\n }\n // Filter out ImageContent from all messages, replacing with text placeholder\n const filtered = converted.map((msg) => {\n if (msg.role === \"user\" || msg.role === \"toolResult\") {\n const content = msg.content;\n if (Array.isArray(content)) {\n const hasImages = content.some((c) => c.type === \"image\");\n if (hasImages) {\n const filteredContent = content\n .map((c) =>\n c.type === \"image\"\n ? {\n type: \"text\" as const,\n text: \"Image reading is disabled.\",\n }\n : c,\n )\n .filter(\n (c, i, arr) =>\n // Dedupe consecutive \"Image reading is disabled.\" texts\n !(\n c.type === \"text\" &&\n c.text === \"Image reading is disabled.\" &&\n i > 0 &&\n arr[i - 1].type === \"text\" &&\n (arr[i - 1] as { type: \"text\"; text: string }).text ===\n \"Image reading is disabled.\"\n ),\n );\n return { ...msg, content: filteredContent };\n }\n }\n }\n return msg;\n });\n lastConvertedLlmMessages = filtered;\n return filtered;\n };\n\n const extensionRunnerRef: { current?: ExtensionRunner } = {};\n const isCodexFastModeEnabled = (requestModel: Model<Api>): boolean =>\n shouldApplyCodexFastMode(\n requestModel,\n settingsManager.getCodexFastModeSettings(),\n options.orchestrationContext,\n );\n\n agent = new Agent({\n initialState: {\n systemPrompt: \"\",\n model,\n thinkingLevel,\n tools: [],\n },\n convertToLlm: convertToLlmWithBlockImages,\n streamFn: async (model, context, streamOptions) => {\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n const providerRetrySettings = settingsManager.getProviderRetrySettings();\n const httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n // SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n // Use max int32 to effectively disable the timeout.\n const effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n const timeoutMs = streamOptions?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n const websocketConnectTimeoutMs =\n streamOptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n const attributionHeaders = mergeProviderAttributionHeaders(\n model,\n settingsManager,\n streamOptions?.sessionId,\n auth.headers,\n streamOptions?.headers,\n );\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const codexFastModeStreamOptions = withCodexFastModeStreamOptions(\n {\n ...streamOptions,\n apiKey: auth.apiKey,\n timeoutMs,\n websocketConnectTimeoutMs,\n maxRetries: streamOptions?.maxRetries ?? providerRetrySettings.maxRetries,\n maxRetryDelayMs:\n streamOptions?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n headers: attributionHeaders,\n },\n fastModeEnabled,\n );\n if (modelRegistry.hasRegisteredStreamSimpleForApi(model.api)) {\n return streamSimple(model, context, codexFastModeStreamOptions);\n }\n return streamWithCodexFastMode(model, context, codexFastModeStreamOptions);\n },\n onPayload: async (payload, model) => {\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const guardedPayload = withCodexFastModePayload(payload, fastModeEnabled);\n const sourceMessages = lastConvertedLlmMessages;\n const replayGuardedPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(guardedPayload, sourceMessages, model)\n : guardedPayload;\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n return replayGuardedPayload;\n }\n const extensionPayload = await runner.emitBeforeProviderRequest(\n replayGuardedPayload,\n );\n return sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n : extensionPayload;\n },\n onResponse: async (response, _model) => {\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"after_provider_response\")) {\n return;\n }\n await runner.emit({\n type: \"after_provider_response\",\n status: response.status,\n headers: response.headers,\n });\n },\n sessionId: sessionManager.getSessionId(),\n transformContext: async (messages) => {\n const runner = extensionRunnerRef.current;\n if (!runner) return messages;\n return runner.emitContext(messages);\n },\n steeringMode: settingsManager.getSteeringMode(),\n followUpMode: settingsManager.getFollowUpMode(),\n transport: settingsManager.getTransport(),\n thinkingBudgets: settingsManager.getThinkingBudgets(),\n maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n });\n\n // Restore messages if session has existing data\n if (hasExistingSession) {\n agent.state.messages = existingSession.messages;\n const transcriptContextWindow = model\n ? (existingSession.contextWindow ?? getModelDefaultContextWindow(model))\n : undefined;\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== transcriptContextWindow)\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n if (!hasThinkingEntry) {\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n } else {\n // Save initial model and thinking level for new sessions so they can be restored on resume\n if (model) {\n sessionManager.appendModelChange(model.provider, model.id);\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== getModelDefaultContextWindow(model))\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n }\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd,\n scopedModels: options.scopedModels,\n resourceLoader,\n customTools: options.customTools,\n bashPolicy: options.bashPolicy,\n modelRegistry,\n initialActiveToolNames,\n allowedToolNames,\n excludedToolNames: options.excludedTools,\n extensionRunnerRef,\n sessionStartEvent: options.sessionStartEvent,\n orchestrationContext: options.orchestrationContext,\n });\n const extensionsResult = resourceLoader.getExtensions();\n\n return {\n session,\n extensionsResult,\n modelFallbackMessage,\n contextWindowWarning,\n contextWindowError,\n };\n}\n"]}
@@ -49,6 +49,8 @@ export interface CodexFastModeSettings {
49
49
  }
50
50
  export type DefaultProjectTrust = "ask" | "always" | "never";
51
51
  export type TransportSetting = Transport;
52
+ export type ContextWindowSetting = number | string;
53
+ export type ModelContextWindowSettings = Record<string, ContextWindowSetting>;
52
54
  /**
53
55
  * Package source for npm/git packages.
54
56
  * - String form: load all resources from the package
@@ -67,7 +69,8 @@ export interface Settings {
67
69
  defaultProvider?: string;
68
70
  defaultModel?: string;
69
71
  defaultThinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
70
- defaultContextWindow?: number | string;
72
+ defaultContextWindow?: ContextWindowSetting;
73
+ defaultContextWindows?: ModelContextWindowSettings;
71
74
  transport?: TransportSetting;
72
75
  steeringMode?: "all" | "one-at-a-time";
73
76
  followUpMode?: "all" | "one-at-a-time";
@@ -162,7 +165,8 @@ export declare class SettingsManager {
162
165
  private static loadFromStorage;
163
166
  private static tryLoadFromStorage;
164
167
  private static validateLoadedSettings;
165
- private static validateDefaultContextWindowSetting;
168
+ private static isPlainRecord;
169
+ private static validateContextWindowSettingValue;
166
170
  private static formatSettingValue;
167
171
  /** Migrate old settings format to new format */
168
172
  private static migrateSettings;
@@ -199,12 +203,17 @@ export declare class SettingsManager {
199
203
  setSteeringMode(mode: "all" | "one-at-a-time"): void;
200
204
  getFollowUpMode(): "all" | "one-at-a-time";
201
205
  setFollowUpMode(mode: "all" | "one-at-a-time"): void;
206
+ getThemeSetting(): string | undefined;
202
207
  getTheme(): string | undefined;
203
208
  setTheme(theme: string): void;
204
209
  getDefaultThinkingLevel(): "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | undefined;
205
210
  setDefaultThinkingLevel(level: "off" | "minimal" | "low" | "medium" | "high" | "xhigh"): void;
211
+ private static defaultContextWindowModelKey;
212
+ private static parseContextWindowSetting;
206
213
  getDefaultContextWindow(): number | undefined;
214
+ getDefaultContextWindowForModel(provider: string, modelId: string): number | undefined;
207
215
  setDefaultContextWindow(contextWindow: number | undefined): void;
216
+ setDefaultContextWindowForModel(provider: string, modelId: string, contextWindow: number | undefined): void;
208
217
  getTransport(): TransportSetting;
209
218
  setTransport(transport: TransportSetting): void;
210
219
  getCompactionEnabled(): boolean;