@bastani/atomic 0.9.5-alpha.6 → 0.9.5-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/builtin/cursor/package.json +2 -2
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/web-access/package.json +1 -1
  7. package/dist/builtin/workflows/package.json +1 -1
  8. package/dist/bun/split-loader.d.ts +2 -0
  9. package/dist/bun/split-loader.d.ts.map +1 -0
  10. package/dist/bun/split-loader.js +37 -0
  11. package/dist/bun/split-loader.js.map +1 -0
  12. package/dist/config.d.ts.map +1 -1
  13. package/dist/config.js +6 -4
  14. package/dist/config.js.map +1 -1
  15. package/dist/core/agent-session-auto-compaction.d.ts +5 -4
  16. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  17. package/dist/core/agent-session-auto-compaction.js +15 -9
  18. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  19. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  20. package/dist/core/agent-session-extension-bindings.js +1 -1
  21. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  22. package/dist/core/agent-session-methods.d.ts +1 -1
  23. package/dist/core/agent-session-methods.d.ts.map +1 -1
  24. package/dist/core/agent-session-methods.js.map +1 -1
  25. package/dist/core/builtin-packages.d.ts.map +1 -1
  26. package/dist/core/builtin-packages.js +8 -4
  27. package/dist/core/builtin-packages.js.map +1 -1
  28. package/dist/core/copilot-model-catalog.d.ts.map +1 -1
  29. package/dist/core/copilot-model-catalog.js +3 -2
  30. package/dist/core/copilot-model-catalog.js.map +1 -1
  31. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  32. package/dist/core/extensions/loader-virtual-modules.js +8 -3
  33. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  34. package/dist/core/openai-responses-payload-sanitizer.d.ts +6 -0
  35. package/dist/core/openai-responses-payload-sanitizer.d.ts.map +1 -0
  36. package/dist/core/openai-responses-payload-sanitizer.js +59 -0
  37. package/dist/core/openai-responses-payload-sanitizer.js.map +1 -0
  38. package/dist/core/package-manager-auto-resources.d.ts +2 -2
  39. package/dist/core/package-manager-auto-resources.d.ts.map +1 -1
  40. package/dist/core/package-manager-auto-resources.js +32 -52
  41. package/dist/core/package-manager-auto-resources.js.map +1 -1
  42. package/dist/core/package-manager-resolver.d.ts.map +1 -1
  43. package/dist/core/package-manager-resolver.js +23 -14
  44. package/dist/core/package-manager-resolver.js.map +1 -1
  45. package/dist/core/package-manager-resource-collector.d.ts +3 -3
  46. package/dist/core/package-manager-resource-collector.d.ts.map +1 -1
  47. package/dist/core/package-manager-resource-collector.js +76 -73
  48. package/dist/core/package-manager-resource-collector.js.map +1 -1
  49. package/dist/core/package-manager-resource-files.d.ts +9 -8
  50. package/dist/core/package-manager-resource-files.d.ts.map +1 -1
  51. package/dist/core/package-manager-resource-files.js +92 -81
  52. package/dist/core/package-manager-resource-files.js.map +1 -1
  53. package/dist/core/prompt-templates-async.d.ts +3 -0
  54. package/dist/core/prompt-templates-async.d.ts.map +1 -0
  55. package/dist/core/prompt-templates-async.js +118 -0
  56. package/dist/core/prompt-templates-async.js.map +1 -0
  57. package/dist/core/provider-context-usage.d.ts +11 -0
  58. package/dist/core/provider-context-usage.d.ts.map +1 -0
  59. package/dist/core/provider-context-usage.js +58 -0
  60. package/dist/core/provider-context-usage.js.map +1 -0
  61. package/dist/core/resource-loader-assets.d.ts +3 -3
  62. package/dist/core/resource-loader-assets.d.ts.map +1 -1
  63. package/dist/core/resource-loader-assets.js +66 -83
  64. package/dist/core/resource-loader-assets.js.map +1 -1
  65. package/dist/core/resource-loader-core.d.ts +1 -1
  66. package/dist/core/resource-loader-core.d.ts.map +1 -1
  67. package/dist/core/resource-loader-core.js +5 -5
  68. package/dist/core/resource-loader-core.js.map +1 -1
  69. package/dist/core/resource-loader-reload.d.ts.map +1 -1
  70. package/dist/core/resource-loader-reload.js +43 -7
  71. package/dist/core/resource-loader-reload.js.map +1 -1
  72. package/dist/core/resource-loader-types.d.ts +7 -1
  73. package/dist/core/resource-loader-types.d.ts.map +1 -1
  74. package/dist/core/resource-loader-types.js.map +1 -1
  75. package/dist/core/sdk.d.ts.map +1 -1
  76. package/dist/core/sdk.js +6 -4
  77. package/dist/core/sdk.js.map +1 -1
  78. package/dist/core/skills-async.d.ts +3 -0
  79. package/dist/core/skills-async.d.ts.map +1 -0
  80. package/dist/core/skills-async.js +269 -0
  81. package/dist/core/skills-async.js.map +1 -0
  82. package/dist/main-deferred-startup.d.ts +2 -0
  83. package/dist/main-deferred-startup.d.ts.map +1 -1
  84. package/dist/main-deferred-startup.js +2 -0
  85. package/dist/main-deferred-startup.js.map +1 -1
  86. package/dist/main.d.ts.map +1 -1
  87. package/dist/main.js +4 -4
  88. package/dist/main.js.map +1 -1
  89. package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
  90. package/dist/modes/interactive/interactive-agent-events.js +10 -1
  91. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  92. package/dist/modes/interactive/interactive-deferred-startup.d.ts +6 -0
  93. package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
  94. package/dist/modes/interactive/interactive-deferred-startup.js +27 -13
  95. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  96. package/dist/modes/interactive/interactive-editor-actions.d.ts.map +1 -1
  97. package/dist/modes/interactive/interactive-editor-actions.js +13 -13
  98. package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
  99. package/dist/modes/interactive/interactive-extension-runtime.d.ts.map +1 -1
  100. package/dist/modes/interactive/interactive-extension-runtime.js +16 -0
  101. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  102. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  103. package/dist/modes/interactive/interactive-input-handling.js +48 -0
  104. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  105. package/dist/modes/interactive/interactive-mode-base.d.ts +5 -0
  106. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  107. package/dist/modes/interactive/interactive-mode-base.js +5 -0
  108. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  109. package/dist/modes/interactive/interactive-mode-surface.d.ts +18 -6
  110. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  111. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  112. package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
  113. package/dist/modes/interactive/interactive-model-routing.js +3 -3
  114. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  115. package/dist/modes/interactive/interactive-onboarding.d.ts.map +1 -1
  116. package/dist/modes/interactive/interactive-onboarding.js +1 -0
  117. package/dist/modes/interactive/interactive-onboarding.js.map +1 -1
  118. package/dist/modes/interactive/interactive-process-lifecycle.d.ts.map +1 -1
  119. package/dist/modes/interactive/interactive-process-lifecycle.js +43 -6
  120. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  121. package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
  122. package/dist/modes/interactive/interactive-render-chat.js +57 -0
  123. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  124. package/dist/modes/interactive/interactive-resource-disclosure.d.ts.map +1 -1
  125. package/dist/modes/interactive/interactive-resource-disclosure.js +3 -2
  126. package/dist/modes/interactive/interactive-resource-disclosure.js.map +1 -1
  127. package/dist/modes/interactive/interactive-resource-rendering.d.ts.map +1 -1
  128. package/dist/modes/interactive/interactive-resource-rendering.js +10 -8
  129. package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
  130. package/dist/modes/interactive/interactive-session-runtime.d.ts.map +1 -1
  131. package/dist/modes/interactive/interactive-session-runtime.js +1 -1
  132. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  133. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  134. package/dist/modes/interactive/interactive-startup.js +59 -52
  135. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  136. package/dist/modes/interactive/theme/theme-loading.d.ts +1 -0
  137. package/dist/modes/interactive/theme/theme-loading.d.ts.map +1 -1
  138. package/dist/modes/interactive/theme/theme-loading.js +3 -0
  139. package/dist/modes/interactive/theme/theme-loading.js.map +1 -1
  140. package/dist/modes/interactive/theme/theme.d.ts +1 -1
  141. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  142. package/dist/modes/interactive/theme/theme.js +1 -1
  143. package/dist/modes/interactive/theme/theme.js.map +1 -1
  144. package/dist/utils/module-require.d.ts +11 -0
  145. package/dist/utils/module-require.d.ts.map +1 -1
  146. package/dist/utils/module-require.js +14 -1
  147. package/dist/utils/module-require.js.map +1 -1
  148. package/dist/utils/split-launcher.d.ts +38 -0
  149. package/dist/utils/split-launcher.d.ts.map +1 -0
  150. package/dist/utils/split-launcher.js +63 -0
  151. package/dist/utils/split-launcher.js.map +1 -0
  152. package/docs/compaction.md +3 -0
  153. package/docs/keybindings.md +2 -2
  154. package/docs/providers.md +1 -1
  155. package/docs/settings.md +2 -2
  156. package/docs/usage.md +1 -1
  157. package/npm-shrinkwrap.json +23 -23
  158. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AA2CA,OAAO,KAAK,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1F,YAAY,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAE1F,cAAc,kBAAkB,CAAC;AAuBjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,GAAE,yBAA8B,GACtC,OAAO,CAAC,wBAAwB,CAAC,CAgYnC","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/compat\";\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 { sanitizeCopilotGeminiPayload } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { restoreCopilotGeminiReasoningOpaque } from \"./copilot-gemini-reasoning.ts\";\nimport { normalizeCopilotGeminiReplayToolArguments } from \"./copilot-gemini-tool-arguments.ts\";\nimport { getModelDefaultContextWindow, getSupportedContextWindows, selectContextWindow } from \"./context-window.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveSavedModelReference } from \"./model-resolver.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 { defaultToolNames } from \"./tools/index.ts\";\n\nimport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\nexport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\n\nexport * from \"./sdk-exports.ts\";\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/compat';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\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. When a modelRegistry\n // is supplied (e.g. a workflow stage reusing one registry across model\n // fallback candidates), do NOT also build a fresh AuthStorage: its\n // constructor eagerly calls reload(), which acquires the auth.json file lock\n // and, under contention, can fail and leave an empty credential set. Reusing\n // the supplied registry's already-loaded auth avoids that race (issue #1431).\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const modelRegistry =\n options.modelRegistry ??\n ModelRegistry.create(options.authStorage ?? AuthStorage.create(authPath), 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 // Mark workflow-created sessions as internal so they are excluded from the\n // standard `/resume` history while remaining resumable via `/workflow resume`.\n // Only stamped when the orchestration context identifies a workflow stage;\n // reattaching to an already-marked session preserves its existing marker.\n if (options.orchestrationContext?.kind === \"workflow-stage\") {\n const ctx = options.orchestrationContext;\n sessionManager.markSessionInternal({\n runId: ctx.workflowRunId,\n stageId: ctx.workflowStageId,\n stageName: ctx.workflowStageName,\n });\n }\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 let finalPayload: unknown;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n finalPayload = replayGuardedPayload;\n } else {\n const extensionPayload = await runner.emitBeforeProviderRequest(\n replayGuardedPayload,\n );\n finalPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n : extensionPayload;\n }\n // GitHub Copilot Gemini models are served through CAPI, which translates\n // the OpenAI request into Google GenAI and rejects tool schemas whose\n // `anyOf`/`oneOf` wraps a complex object (HTTP 400 invalid request body).\n // Sanitize tool JSON Schemas into Gemini's supported subset. No-op for\n // every other provider/model, and runs last so it also covers tools\n // injected by `before_provider_request` extensions.\n const schemaSanitized = sanitizeCopilotGeminiPayload(finalPayload, model);\n // Reconstruct flattened tool-call arguments on replayed assistant\n // messages (for example `edits[0].newText` -> `edits: [{ newText }]`).\n // CAPI parses replayed arguments straight into Gemini's FunctionCall,\n // and a flattened/malformed prior call ends the next turn with\n // `finish_reason: \"error\"`. No-op for well-formed args / other models.\n const replayArgsNormalized = normalizeCopilotGeminiReplayToolArguments(schemaSanitized, model);\n // CAPI carries Gemini thought signatures in a `reasoning_opaque` field it\n // reads back off the assistant message on replay. Convert the\n // `reasoning_details` the client re-emits (captured inbound by the SSE\n // interceptor) into that field so multi-turn tool use keeps its thought\n // signature instead of dying on an empty completion. No-op otherwise.\n return restoreCopilotGeminiReasoningOpaque(replayArgsNormalized, model);\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 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.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AA6CA,OAAO,KAAK,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1F,YAAY,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAE1F,cAAc,kBAAkB,CAAC;AAuBjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,GAAE,yBAA8B,GACtC,OAAO,CAAC,wBAAwB,CAAC,CAiYnC","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/compat\";\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 { sanitizeCopilotGeminiPayload } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { restoreCopilotGeminiReasoningOpaque } from \"./copilot-gemini-reasoning.ts\";\nimport { normalizeCopilotGeminiReplayToolArguments } from \"./copilot-gemini-tool-arguments.ts\";\nimport { getModelDefaultContextWindow, getSupportedContextWindows, selectContextWindow } from \"./context-window.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveSavedModelReference } from \"./model-resolver.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 { sanitizeOpenAIResponsesPayload } from \"./openai-responses-payload-sanitizer.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\nimport { time } from \"./timings.ts\";\nimport { defaultToolNames } from \"./tools/index.ts\";\n\nimport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\nexport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\n\nexport * from \"./sdk-exports.ts\";\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/compat';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\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. When a modelRegistry\n // is supplied (e.g. a workflow stage reusing one registry across model\n // fallback candidates), do NOT also build a fresh AuthStorage: its\n // constructor eagerly calls reload(), which acquires the auth.json file lock\n // and, under contention, can fail and leave an empty credential set. Reusing\n // the supplied registry's already-loaded auth avoids that race (issue #1431).\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const modelRegistry =\n options.modelRegistry ??\n ModelRegistry.create(options.authStorage ?? AuthStorage.create(authPath), 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 // Mark workflow-created sessions as internal so they are excluded from the\n // standard `/resume` history while remaining resumable via `/workflow resume`.\n // Only stamped when the orchestration context identifies a workflow stage;\n // reattaching to an already-marked session preserves its existing marker.\n if (options.orchestrationContext?.kind === \"workflow-stage\") {\n const ctx = options.orchestrationContext;\n sessionManager.markSessionInternal({\n runId: ctx.workflowRunId,\n stageId: ctx.workflowStageId,\n stageName: ctx.workflowStageName,\n });\n }\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 let finalPayload: unknown;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n finalPayload = replayGuardedPayload;\n } else {\n const extensionPayload = await runner.emitBeforeProviderRequest(\n replayGuardedPayload,\n );\n finalPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n : extensionPayload;\n }\n // GitHub Copilot Gemini models are served through CAPI, which translates\n // the OpenAI request into Google GenAI and rejects tool schemas whose\n // `anyOf`/`oneOf` wraps a complex object (HTTP 400 invalid request body).\n // Sanitize tool JSON Schemas into Gemini's supported subset. No-op for\n // every other provider/model, and runs last so it also covers tools\n // injected by `before_provider_request` extensions.\n const schemaSanitized = sanitizeCopilotGeminiPayload(finalPayload, model);\n // Reconstruct flattened tool-call arguments on replayed assistant\n // messages (for example `edits[0].newText` -> `edits: [{ newText }]`).\n // CAPI parses replayed arguments straight into Gemini's FunctionCall,\n // and a flattened/malformed prior call ends the next turn with\n // `finish_reason: \"error\"`. No-op for well-formed args / other models.\n const replayArgsNormalized = normalizeCopilotGeminiReplayToolArguments(schemaSanitized, model);\n // CAPI carries Gemini thought signatures in a `reasoning_opaque` field it\n // reads back off the assistant message on replay. Convert the\n // `reasoning_details` the client re-emits (captured inbound by the SSE\n // interceptor) into that field so multi-turn tool use keeps its thought\n // signature instead of dying on an empty completion. No-op otherwise.\n const reasoningRestored = restoreCopilotGeminiReasoningOpaque(replayArgsNormalized, model);\n return sanitizeOpenAIResponsesPayload(reasoningRestored, model);\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 const transformed = runner ? await runner.emitContext(messages) : messages;\n return scrubPreCompactionAssistantUsage(transformed, sessionManager.getBranch());\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 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
@@ -20,6 +20,8 @@ import { DefaultResourceLoader } from "./resource-loader.js";
20
20
  import { getDefaultSessionDir, SessionManager } from "./session-manager.js";
21
21
  import { SettingsManager } from "./settings-manager.js";
22
22
  import { mergeProviderAttributionHeaders } from "./provider-attribution.js";
23
+ import { sanitizeOpenAIResponsesPayload } from "./openai-responses-payload-sanitizer.js";
24
+ import { scrubPreCompactionAssistantUsage } from "./provider-context-usage.js";
23
25
  import { time } from "./timings.js";
24
26
  import { defaultToolNames } from "./tools/index.js";
25
27
  export * from "./sdk-exports.js";
@@ -322,7 +324,8 @@ export async function createAgentSession(options = {}) {
322
324
  // `reasoning_details` the client re-emits (captured inbound by the SSE
323
325
  // interceptor) into that field so multi-turn tool use keeps its thought
324
326
  // signature instead of dying on an empty completion. No-op otherwise.
325
- return restoreCopilotGeminiReasoningOpaque(replayArgsNormalized, model);
327
+ const reasoningRestored = restoreCopilotGeminiReasoningOpaque(replayArgsNormalized, model);
328
+ return sanitizeOpenAIResponsesPayload(reasoningRestored, model);
326
329
  },
327
330
  onResponse: async (response, _model) => {
328
331
  const runner = extensionRunnerRef.current;
@@ -338,9 +341,8 @@ export async function createAgentSession(options = {}) {
338
341
  sessionId: sessionManager.getSessionId(),
339
342
  transformContext: async (messages) => {
340
343
  const runner = extensionRunnerRef.current;
341
- if (!runner)
342
- return messages;
343
- return runner.emitContext(messages);
344
+ const transformed = runner ? await runner.emitContext(messages) : messages;
345
+ return scrubPreCompactionAssistantUsage(transformed, sessionManager.getBranch());
344
346
  },
345
347
  steeringMode: settingsManager.getSteeringMode(),
346
348
  followUpMode: settingsManager.getFollowUpMode(),
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CA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B,IAAI,qBAAqB,KAAK,uBAAuB,CAAC,EACrF,CAAC;YACD,cAAc,CAAC,yBAAyB,CAAC,qBAAqB,CAAC,CAAC;QAClE,CAAC;QACD,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtB,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;QAC1D,CAAC;IACH,CAAC;SAAM,CAAC;QACN,2FAA2F;QAC3F,IAAI,KAAK,EAAE,CAAC;YACV,cAAc,CAAC,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;YAC3D,IACE,qBAAqB,KAAK,SAAS;gBACnC,CAAC,8BAA8B,IAAI,qBAAqB,KAAK,4BAA4B,CAAC,KAAK,CAAC,CAAC,EACjG,CAAC;gBACD,cAAc,CAAC,yBAAyB,CAAC,qBAAqB,CAAC,CAAC;YAClE,CAAC;QACH,CAAC;QACD,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC;QAC/B,KAAK;QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,aAAa;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/compat\";\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 { sanitizeCopilotGeminiPayload } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { restoreCopilotGeminiReasoningOpaque } from \"./copilot-gemini-reasoning.ts\";\nimport { normalizeCopilotGeminiReplayToolArguments } from \"./copilot-gemini-tool-arguments.ts\";\nimport { getModelDefaultContextWindow, getSupportedContextWindows, selectContextWindow } from \"./context-window.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveSavedModelReference } from \"./model-resolver.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 { defaultToolNames } from \"./tools/index.ts\";\n\nimport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\nexport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\n\nexport * from \"./sdk-exports.ts\";\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/compat';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\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. When a modelRegistry\n // is supplied (e.g. a workflow stage reusing one registry across model\n // fallback candidates), do NOT also build a fresh AuthStorage: its\n // constructor eagerly calls reload(), which acquires the auth.json file lock\n // and, under contention, can fail and leave an empty credential set. Reusing\n // the supplied registry's already-loaded auth avoids that race (issue #1431).\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const modelRegistry =\n options.modelRegistry ??\n ModelRegistry.create(options.authStorage ?? AuthStorage.create(authPath), 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 // Mark workflow-created sessions as internal so they are excluded from the\n // standard `/resume` history while remaining resumable via `/workflow resume`.\n // Only stamped when the orchestration context identifies a workflow stage;\n // reattaching to an already-marked session preserves its existing marker.\n if (options.orchestrationContext?.kind === \"workflow-stage\") {\n const ctx = options.orchestrationContext;\n sessionManager.markSessionInternal({\n runId: ctx.workflowRunId,\n stageId: ctx.workflowStageId,\n stageName: ctx.workflowStageName,\n });\n }\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 let finalPayload: unknown;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n finalPayload = replayGuardedPayload;\n } else {\n const extensionPayload = await runner.emitBeforeProviderRequest(\n replayGuardedPayload,\n );\n finalPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n : extensionPayload;\n }\n // GitHub Copilot Gemini models are served through CAPI, which translates\n // the OpenAI request into Google GenAI and rejects tool schemas whose\n // `anyOf`/`oneOf` wraps a complex object (HTTP 400 invalid request body).\n // Sanitize tool JSON Schemas into Gemini's supported subset. No-op for\n // every other provider/model, and runs last so it also covers tools\n // injected by `before_provider_request` extensions.\n const schemaSanitized = sanitizeCopilotGeminiPayload(finalPayload, model);\n // Reconstruct flattened tool-call arguments on replayed assistant\n // messages (for example `edits[0].newText` -> `edits: [{ newText }]`).\n // CAPI parses replayed arguments straight into Gemini's FunctionCall,\n // and a flattened/malformed prior call ends the next turn with\n // `finish_reason: \"error\"`. No-op for well-formed args / other models.\n const replayArgsNormalized = normalizeCopilotGeminiReplayToolArguments(schemaSanitized, model);\n // CAPI carries Gemini thought signatures in a `reasoning_opaque` field it\n // reads back off the assistant message on replay. Convert the\n // `reasoning_details` the client re-emits (captured inbound by the SSE\n // interceptor) into that field so multi-turn tool use keeps its thought\n // signature instead of dying on an empty completion. No-op otherwise.\n return restoreCopilotGeminiReasoningOpaque(replayArgsNormalized, model);\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 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,8BAA8B,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,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\"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/compat\";\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 { sanitizeCopilotGeminiPayload } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { restoreCopilotGeminiReasoningOpaque } from \"./copilot-gemini-reasoning.ts\";\nimport { normalizeCopilotGeminiReplayToolArguments } from \"./copilot-gemini-tool-arguments.ts\";\nimport { getModelDefaultContextWindow, getSupportedContextWindows, selectContextWindow } from \"./context-window.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveSavedModelReference } from \"./model-resolver.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 { sanitizeOpenAIResponsesPayload } from \"./openai-responses-payload-sanitizer.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\nimport { time } from \"./timings.ts\";\nimport { defaultToolNames } from \"./tools/index.ts\";\n\nimport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\nexport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\n\nexport * from \"./sdk-exports.ts\";\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/compat';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\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. When a modelRegistry\n // is supplied (e.g. a workflow stage reusing one registry across model\n // fallback candidates), do NOT also build a fresh AuthStorage: its\n // constructor eagerly calls reload(), which acquires the auth.json file lock\n // and, under contention, can fail and leave an empty credential set. Reusing\n // the supplied registry's already-loaded auth avoids that race (issue #1431).\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const modelRegistry =\n options.modelRegistry ??\n ModelRegistry.create(options.authStorage ?? AuthStorage.create(authPath), 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 // Mark workflow-created sessions as internal so they are excluded from the\n // standard `/resume` history while remaining resumable via `/workflow resume`.\n // Only stamped when the orchestration context identifies a workflow stage;\n // reattaching to an already-marked session preserves its existing marker.\n if (options.orchestrationContext?.kind === \"workflow-stage\") {\n const ctx = options.orchestrationContext;\n sessionManager.markSessionInternal({\n runId: ctx.workflowRunId,\n stageId: ctx.workflowStageId,\n stageName: ctx.workflowStageName,\n });\n }\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 let finalPayload: unknown;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n finalPayload = replayGuardedPayload;\n } else {\n const extensionPayload = await runner.emitBeforeProviderRequest(\n replayGuardedPayload,\n );\n finalPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n : extensionPayload;\n }\n // GitHub Copilot Gemini models are served through CAPI, which translates\n // the OpenAI request into Google GenAI and rejects tool schemas whose\n // `anyOf`/`oneOf` wraps a complex object (HTTP 400 invalid request body).\n // Sanitize tool JSON Schemas into Gemini's supported subset. No-op for\n // every other provider/model, and runs last so it also covers tools\n // injected by `before_provider_request` extensions.\n const schemaSanitized = sanitizeCopilotGeminiPayload(finalPayload, model);\n // Reconstruct flattened tool-call arguments on replayed assistant\n // messages (for example `edits[0].newText` -> `edits: [{ newText }]`).\n // CAPI parses replayed arguments straight into Gemini's FunctionCall,\n // and a flattened/malformed prior call ends the next turn with\n // `finish_reason: \"error\"`. No-op for well-formed args / other models.\n const replayArgsNormalized = normalizeCopilotGeminiReplayToolArguments(schemaSanitized, model);\n // CAPI carries Gemini thought signatures in a `reasoning_opaque` field it\n // reads back off the assistant message on replay. Convert the\n // `reasoning_details` the client re-emits (captured inbound by the SSE\n // interceptor) into that field so multi-turn tool use keeps its thought\n // signature instead of dying on an empty completion. No-op otherwise.\n const reasoningRestored = restoreCopilotGeminiReasoningOpaque(replayArgsNormalized, model);\n return sanitizeOpenAIResponsesPayload(reasoningRestored, model);\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 const transformed = runner ? await runner.emitContext(messages) : messages;\n return scrubPreCompactionAssistantUsage(transformed, sessionManager.getBranch());\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 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"]}
@@ -0,0 +1,3 @@
1
+ import type { LoadSkillsOptions, LoadSkillsResult } from "./skills.ts";
2
+ export declare function loadSkillsAsync(options: LoadSkillsOptions): Promise<LoadSkillsResult>;
3
+ //# sourceMappingURL=skills-async.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"skills-async.d.ts","sourceRoot":"","sources":["../../src/core/skills-async.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAA2B,MAAM,aAAa,CAAC;AAkKhG,wBAAsB,eAAe,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAsE3F","sourcesContent":["import { access, readdir, readFile, stat } from \"node:fs/promises\";\nimport ignore from \"ignore\";\nimport { basename, dirname, join, relative, resolve, sep } from \"node:path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { parseFrontmatter } from \"../utils/frontmatter.ts\";\nimport { yieldToEventLoopIfSlow } from \"../utils/event-loop.ts\";\nimport { canonicalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type { ResourceDiagnostic } from \"./diagnostics.ts\";\nimport { createSyntheticSourceInfo, type SourceInfo } from \"./source-info.ts\";\nimport type { LoadSkillsOptions, LoadSkillsResult, Skill, SkillFrontmatter } from \"./skills.ts\";\n\nconst MAX_NAME_LENGTH = 64;\nconst MAX_DESCRIPTION_LENGTH = 1024;\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\nconst YIELD_AFTER_MS = 8;\ntype IgnoreMatcher = ReturnType<typeof ignore>;\n\nasync function exists(path: string): Promise<boolean> {\n\ttry { await access(path); return true; } catch { return false; }\n}\n\nfunction toPosixPath(path: string): string {\n\treturn path.split(sep).join(\"/\");\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed || (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\"))) return null;\n\tlet pattern = line;\n\tlet negated = false;\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\tif (pattern.startsWith(\"/\")) pattern = pattern.slice(1);\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nasync function addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): Promise<void> {\n\tconst relativeDir = relative(rootDir, dir);\n\tconst prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : \"\";\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = join(dir, filename);\n\t\ttry {\n\t\t\tconst content = await readFile(ignorePath, \"utf-8\");\n\t\t\tconst patterns = content\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t\t.filter((line): line is string => Boolean(line));\n\t\t\tif (patterns.length > 0) ig.add(patterns);\n\t\t} catch {}\n\t}\n}\n\nfunction createSkillSourceInfo(filePath: string, baseDir: string, source: string): SourceInfo {\n\tswitch (source) {\n\t\tcase \"user\": return createSyntheticSourceInfo(filePath, { source: \"local\", scope: \"user\", baseDir });\n\t\tcase \"project\": return createSyntheticSourceInfo(filePath, { source: \"local\", scope: \"project\", baseDir });\n\t\tcase \"path\": return createSyntheticSourceInfo(filePath, { source: \"local\", baseDir });\n\t\tdefault: return createSyntheticSourceInfo(filePath, { source, baseDir });\n\t}\n}\n\nfunction validateName(name: string): string[] {\n\tconst errors: string[] = [];\n\tif (name.length > MAX_NAME_LENGTH) errors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\tif (!/^[a-z0-9-]+$/.test(name)) errors.push(\"name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)\");\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) errors.push(\"name must not start or end with a hyphen\");\n\tif (name.includes(\"--\")) errors.push(\"name must not contain consecutive hyphens\");\n\treturn errors;\n}\n\nfunction validateDescription(description: string | undefined): string[] {\n\tif (!description || description.trim() === \"\") return [\"description is required\"];\n\tif (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\treturn [`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`];\n\t}\n\treturn [];\n}\n\nasync function loadSkillFromFile(filePath: string, source: string): Promise<{ skill: Skill | null; diagnostics: ResourceDiagnostic[] }> {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\ttry {\n\t\tconst rawContent = await readFile(filePath, \"utf-8\");\n\t\tconst { frontmatter } = parseFrontmatter<SkillFrontmatter>(rawContent);\n\t\tconst skillDir = dirname(filePath);\n\t\tfor (const error of validateDescription(frontmatter.description)) diagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\tconst name = frontmatter.name || basename(skillDir);\n\t\tfor (const error of validateName(name)) diagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\tif (!frontmatter.description || frontmatter.description.trim() === \"\") return { skill: null, diagnostics };\n\t\treturn {\n\t\t\tskill: {\n\t\t\t\tname,\n\t\t\t\tdescription: frontmatter.description,\n\t\t\t\tfilePath,\n\t\t\t\tbaseDir: skillDir,\n\t\t\t\tsourceInfo: createSkillSourceInfo(filePath, skillDir, source),\n\t\t\t\tdisableModelInvocation: frontmatter[\"disable-model-invocation\"] === true,\n\t\t\t},\n\t\t\tdiagnostics,\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to parse skill file\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n}\n\nasync function loadSkillsFromDirInternal(\n\tdir: string,\n\tsource: string,\n\tincludeRootFiles: boolean,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): Promise<LoadSkillsResult> {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\tif (!(await exists(dir))) return { skills, diagnostics };\n\tconst startedAt = Date.now();\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\tawait addIgnoreRules(ig, dir, root);\n\ttry {\n\t\tconst entries = await readdir(dir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name !== \"SKILL.md\") continue;\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry { isFile = (await stat(fullPath)).isFile(); } catch { continue; }\n\t\t\t}\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tif (!isFile || ig.ignores(relPath)) continue;\n\t\t\tconst result = await loadSkillFromFile(fullPath, source);\n\t\t\tif (result.skill) skills.push(result.skill);\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t\treturn { skills, diagnostics };\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tawait yieldToEventLoopIfSlow(startedAt, YIELD_AFTER_MS);\n\t\t\tif (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDirectory = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = await stat(fullPath);\n\t\t\t\t\tisDirectory = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch { continue; }\n\t\t\t}\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tif (ig.ignores(isDirectory ? `${relPath}/` : relPath)) continue;\n\t\t\tif (isDirectory) {\n\t\t\t\tconst subResult = await loadSkillsFromDirInternal(fullPath, source, false, ig, root);\n\t\t\t\tskills.push(...subResult.skills);\n\t\t\t\tdiagnostics.push(...subResult.diagnostics);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isFile || !includeRootFiles || !entry.name.endsWith(\".md\")) continue;\n\t\t\tconst result = await loadSkillFromFile(fullPath, source);\n\t\t\tif (result.skill) skills.push(result.skill);\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t}\n\t} catch {}\n\treturn { skills, diagnostics };\n}\n\nexport async function loadSkillsAsync(options: LoadSkillsOptions): Promise<LoadSkillsResult> {\n\tconst { agentDir, skillPaths, includeDefaults } = options;\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir ?? getAgentDir());\n\tconst skillMap = new Map<string, Skill>();\n\tconst realPathSet = new Set<string>();\n\tconst allDiagnostics: ResourceDiagnostic[] = [];\n\tconst collisionDiagnostics: ResourceDiagnostic[] = [];\n\tconst userSkillsDir = join(resolvedAgentDir, \"skills\");\n\tconst projectSkillsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\");\n\tconst addSkills = (result: LoadSkillsResult) => {\n\t\tallDiagnostics.push(...result.diagnostics);\n\t\tfor (const skill of result.skills) {\n\t\t\tconst realPath = canonicalizePath(skill.filePath);\n\t\t\tif (realPathSet.has(realPath)) continue;\n\t\t\tconst existing = skillMap.get(skill.name);\n\t\t\tif (existing) {\n\t\t\t\tcollisionDiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"${skill.name}\" collision`,\n\t\t\t\t\tpath: skill.filePath,\n\t\t\t\t\tcollision: { resourceType: \"skill\", name: skill.name, winnerPath: existing.filePath, loserPath: skill.filePath },\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tskillMap.set(skill.name, skill);\n\t\t\t\trealPathSet.add(realPath);\n\t\t\t}\n\t\t}\n\t};\n\tif (includeDefaults) {\n\t\taddSkills(await loadSkillsFromDirInternal(userSkillsDir, \"user\", true));\n\t\taddSkills(await loadSkillsFromDirInternal(projectSkillsDir, \"project\", true));\n\t}\n\tconst isUnderPath = (target: string, root: string): boolean => {\n\t\tconst normalizedRoot = resolve(root);\n\t\treturn target === normalizedRoot || target.startsWith(normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`);\n\t};\n\tconst getSource = (resolvedPath: string): \"user\" | \"project\" | \"path\" => {\n\t\tif (!includeDefaults) {\n\t\t\tif (isUnderPath(resolvedPath, userSkillsDir)) return \"user\";\n\t\t\tif (isUnderPath(resolvedPath, projectSkillsDir)) return \"project\";\n\t\t}\n\t\treturn \"path\";\n\t};\n\tconst startedAt = Date.now();\n\tfor (const rawPath of skillPaths) {\n\t\tawait yieldToEventLoopIfSlow(startedAt, YIELD_AFTER_MS);\n\t\tconst resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true });\n\t\tif (!(await exists(resolvedPath))) {\n\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path does not exist\", path: resolvedPath });\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst stats = await stat(resolvedPath);\n\t\t\tconst source = getSource(resolvedPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\taddSkills(await loadSkillsFromDirInternal(resolvedPath, source, true));\n\t\t\t} else if (stats.isFile() && resolvedPath.endsWith(\".md\")) {\n\t\t\t\tconst result = await loadSkillFromFile(resolvedPath, source);\n\t\t\t\tif (result.skill) addSkills({ skills: [result.skill], diagnostics: result.diagnostics });\n\t\t\t\telse allDiagnostics.push(...result.diagnostics);\n\t\t\t} else {\n\t\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path is not a markdown file\", path: resolvedPath });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read skill path\";\n\t\t\tallDiagnostics.push({ type: \"warning\", message, path: resolvedPath });\n\t\t}\n\t}\n\treturn { skills: Array.from(skillMap.values()), diagnostics: [...allDiagnostics, ...collisionDiagnostics] };\n}\n"]}
@@ -0,0 +1,269 @@
1
+ import { access, readdir, readFile, stat } from "node:fs/promises";
2
+ import ignore from "ignore";
3
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
+ import { CONFIG_DIR_NAME, getAgentDir } from "../config.js";
5
+ import { parseFrontmatter } from "../utils/frontmatter.js";
6
+ import { yieldToEventLoopIfSlow } from "../utils/event-loop.js";
7
+ import { canonicalizePath, resolvePath } from "../utils/paths.js";
8
+ import { createSyntheticSourceInfo } from "./source-info.js";
9
+ const MAX_NAME_LENGTH = 64;
10
+ const MAX_DESCRIPTION_LENGTH = 1024;
11
+ const IGNORE_FILE_NAMES = [".gitignore", ".ignore", ".fdignore"];
12
+ const YIELD_AFTER_MS = 8;
13
+ async function exists(path) {
14
+ try {
15
+ await access(path);
16
+ return true;
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ function toPosixPath(path) {
23
+ return path.split(sep).join("/");
24
+ }
25
+ function prefixIgnorePattern(line, prefix) {
26
+ const trimmed = line.trim();
27
+ if (!trimmed || (trimmed.startsWith("#") && !trimmed.startsWith("\\#")))
28
+ return null;
29
+ let pattern = line;
30
+ let negated = false;
31
+ if (pattern.startsWith("!")) {
32
+ negated = true;
33
+ pattern = pattern.slice(1);
34
+ }
35
+ else if (pattern.startsWith("\\!")) {
36
+ pattern = pattern.slice(1);
37
+ }
38
+ if (pattern.startsWith("/"))
39
+ pattern = pattern.slice(1);
40
+ const prefixed = prefix ? `${prefix}${pattern}` : pattern;
41
+ return negated ? `!${prefixed}` : prefixed;
42
+ }
43
+ async function addIgnoreRules(ig, dir, rootDir) {
44
+ const relativeDir = relative(rootDir, dir);
45
+ const prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : "";
46
+ for (const filename of IGNORE_FILE_NAMES) {
47
+ const ignorePath = join(dir, filename);
48
+ try {
49
+ const content = await readFile(ignorePath, "utf-8");
50
+ const patterns = content
51
+ .split(/\r?\n/)
52
+ .map((line) => prefixIgnorePattern(line, prefix))
53
+ .filter((line) => Boolean(line));
54
+ if (patterns.length > 0)
55
+ ig.add(patterns);
56
+ }
57
+ catch { }
58
+ }
59
+ }
60
+ function createSkillSourceInfo(filePath, baseDir, source) {
61
+ switch (source) {
62
+ case "user": return createSyntheticSourceInfo(filePath, { source: "local", scope: "user", baseDir });
63
+ case "project": return createSyntheticSourceInfo(filePath, { source: "local", scope: "project", baseDir });
64
+ case "path": return createSyntheticSourceInfo(filePath, { source: "local", baseDir });
65
+ default: return createSyntheticSourceInfo(filePath, { source, baseDir });
66
+ }
67
+ }
68
+ function validateName(name) {
69
+ const errors = [];
70
+ if (name.length > MAX_NAME_LENGTH)
71
+ errors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);
72
+ if (!/^[a-z0-9-]+$/.test(name))
73
+ errors.push("name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)");
74
+ if (name.startsWith("-") || name.endsWith("-"))
75
+ errors.push("name must not start or end with a hyphen");
76
+ if (name.includes("--"))
77
+ errors.push("name must not contain consecutive hyphens");
78
+ return errors;
79
+ }
80
+ function validateDescription(description) {
81
+ if (!description || description.trim() === "")
82
+ return ["description is required"];
83
+ if (description.length > MAX_DESCRIPTION_LENGTH) {
84
+ return [`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`];
85
+ }
86
+ return [];
87
+ }
88
+ async function loadSkillFromFile(filePath, source) {
89
+ const diagnostics = [];
90
+ try {
91
+ const rawContent = await readFile(filePath, "utf-8");
92
+ const { frontmatter } = parseFrontmatter(rawContent);
93
+ const skillDir = dirname(filePath);
94
+ for (const error of validateDescription(frontmatter.description))
95
+ diagnostics.push({ type: "warning", message: error, path: filePath });
96
+ const name = frontmatter.name || basename(skillDir);
97
+ for (const error of validateName(name))
98
+ diagnostics.push({ type: "warning", message: error, path: filePath });
99
+ if (!frontmatter.description || frontmatter.description.trim() === "")
100
+ return { skill: null, diagnostics };
101
+ return {
102
+ skill: {
103
+ name,
104
+ description: frontmatter.description,
105
+ filePath,
106
+ baseDir: skillDir,
107
+ sourceInfo: createSkillSourceInfo(filePath, skillDir, source),
108
+ disableModelInvocation: frontmatter["disable-model-invocation"] === true,
109
+ },
110
+ diagnostics,
111
+ };
112
+ }
113
+ catch (error) {
114
+ const message = error instanceof Error ? error.message : "failed to parse skill file";
115
+ diagnostics.push({ type: "warning", message, path: filePath });
116
+ return { skill: null, diagnostics };
117
+ }
118
+ }
119
+ async function loadSkillsFromDirInternal(dir, source, includeRootFiles, ignoreMatcher, rootDir) {
120
+ const skills = [];
121
+ const diagnostics = [];
122
+ if (!(await exists(dir)))
123
+ return { skills, diagnostics };
124
+ const startedAt = Date.now();
125
+ const root = rootDir ?? dir;
126
+ const ig = ignoreMatcher ?? ignore();
127
+ await addIgnoreRules(ig, dir, root);
128
+ try {
129
+ const entries = await readdir(dir, { withFileTypes: true });
130
+ for (const entry of entries) {
131
+ if (entry.name !== "SKILL.md")
132
+ continue;
133
+ const fullPath = join(dir, entry.name);
134
+ let isFile = entry.isFile();
135
+ if (entry.isSymbolicLink()) {
136
+ try {
137
+ isFile = (await stat(fullPath)).isFile();
138
+ }
139
+ catch {
140
+ continue;
141
+ }
142
+ }
143
+ const relPath = toPosixPath(relative(root, fullPath));
144
+ if (!isFile || ig.ignores(relPath))
145
+ continue;
146
+ const result = await loadSkillFromFile(fullPath, source);
147
+ if (result.skill)
148
+ skills.push(result.skill);
149
+ diagnostics.push(...result.diagnostics);
150
+ return { skills, diagnostics };
151
+ }
152
+ for (const entry of entries) {
153
+ await yieldToEventLoopIfSlow(startedAt, YIELD_AFTER_MS);
154
+ if (entry.name.startsWith(".") || entry.name === "node_modules")
155
+ continue;
156
+ const fullPath = join(dir, entry.name);
157
+ let isDirectory = entry.isDirectory();
158
+ let isFile = entry.isFile();
159
+ if (entry.isSymbolicLink()) {
160
+ try {
161
+ const stats = await stat(fullPath);
162
+ isDirectory = stats.isDirectory();
163
+ isFile = stats.isFile();
164
+ }
165
+ catch {
166
+ continue;
167
+ }
168
+ }
169
+ const relPath = toPosixPath(relative(root, fullPath));
170
+ if (ig.ignores(isDirectory ? `${relPath}/` : relPath))
171
+ continue;
172
+ if (isDirectory) {
173
+ const subResult = await loadSkillsFromDirInternal(fullPath, source, false, ig, root);
174
+ skills.push(...subResult.skills);
175
+ diagnostics.push(...subResult.diagnostics);
176
+ continue;
177
+ }
178
+ if (!isFile || !includeRootFiles || !entry.name.endsWith(".md"))
179
+ continue;
180
+ const result = await loadSkillFromFile(fullPath, source);
181
+ if (result.skill)
182
+ skills.push(result.skill);
183
+ diagnostics.push(...result.diagnostics);
184
+ }
185
+ }
186
+ catch { }
187
+ return { skills, diagnostics };
188
+ }
189
+ export async function loadSkillsAsync(options) {
190
+ const { agentDir, skillPaths, includeDefaults } = options;
191
+ const resolvedCwd = resolvePath(options.cwd);
192
+ const resolvedAgentDir = resolvePath(agentDir ?? getAgentDir());
193
+ const skillMap = new Map();
194
+ const realPathSet = new Set();
195
+ const allDiagnostics = [];
196
+ const collisionDiagnostics = [];
197
+ const userSkillsDir = join(resolvedAgentDir, "skills");
198
+ const projectSkillsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, "skills");
199
+ const addSkills = (result) => {
200
+ allDiagnostics.push(...result.diagnostics);
201
+ for (const skill of result.skills) {
202
+ const realPath = canonicalizePath(skill.filePath);
203
+ if (realPathSet.has(realPath))
204
+ continue;
205
+ const existing = skillMap.get(skill.name);
206
+ if (existing) {
207
+ collisionDiagnostics.push({
208
+ type: "collision",
209
+ message: `name "${skill.name}" collision`,
210
+ path: skill.filePath,
211
+ collision: { resourceType: "skill", name: skill.name, winnerPath: existing.filePath, loserPath: skill.filePath },
212
+ });
213
+ }
214
+ else {
215
+ skillMap.set(skill.name, skill);
216
+ realPathSet.add(realPath);
217
+ }
218
+ }
219
+ };
220
+ if (includeDefaults) {
221
+ addSkills(await loadSkillsFromDirInternal(userSkillsDir, "user", true));
222
+ addSkills(await loadSkillsFromDirInternal(projectSkillsDir, "project", true));
223
+ }
224
+ const isUnderPath = (target, root) => {
225
+ const normalizedRoot = resolve(root);
226
+ return target === normalizedRoot || target.startsWith(normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`);
227
+ };
228
+ const getSource = (resolvedPath) => {
229
+ if (!includeDefaults) {
230
+ if (isUnderPath(resolvedPath, userSkillsDir))
231
+ return "user";
232
+ if (isUnderPath(resolvedPath, projectSkillsDir))
233
+ return "project";
234
+ }
235
+ return "path";
236
+ };
237
+ const startedAt = Date.now();
238
+ for (const rawPath of skillPaths) {
239
+ await yieldToEventLoopIfSlow(startedAt, YIELD_AFTER_MS);
240
+ const resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true });
241
+ if (!(await exists(resolvedPath))) {
242
+ allDiagnostics.push({ type: "warning", message: "skill path does not exist", path: resolvedPath });
243
+ continue;
244
+ }
245
+ try {
246
+ const stats = await stat(resolvedPath);
247
+ const source = getSource(resolvedPath);
248
+ if (stats.isDirectory()) {
249
+ addSkills(await loadSkillsFromDirInternal(resolvedPath, source, true));
250
+ }
251
+ else if (stats.isFile() && resolvedPath.endsWith(".md")) {
252
+ const result = await loadSkillFromFile(resolvedPath, source);
253
+ if (result.skill)
254
+ addSkills({ skills: [result.skill], diagnostics: result.diagnostics });
255
+ else
256
+ allDiagnostics.push(...result.diagnostics);
257
+ }
258
+ else {
259
+ allDiagnostics.push({ type: "warning", message: "skill path is not a markdown file", path: resolvedPath });
260
+ }
261
+ }
262
+ catch (error) {
263
+ const message = error instanceof Error ? error.message : "failed to read skill path";
264
+ allDiagnostics.push({ type: "warning", message, path: resolvedPath });
265
+ }
266
+ }
267
+ return { skills: Array.from(skillMap.values()), diagnostics: [...allDiagnostics, ...collisionDiagnostics] };
268
+ }
269
+ //# sourceMappingURL=skills-async.js.map