@leanandmean/coding-agent 0.74.1-scramjet.70 → 0.74.1-scramjet.71

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 (37) hide show
  1. package/README.md +14 -0
  2. package/dist/cli/args.d.ts +2 -0
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +44 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/core/agent-session-services.d.ts +1 -0
  7. package/dist/core/agent-session-services.d.ts.map +1 -1
  8. package/dist/core/agent-session-services.js +1 -0
  9. package/dist/core/agent-session-services.js.map +1 -1
  10. package/dist/core/agent-session.d.ts +6 -2
  11. package/dist/core/agent-session.d.ts.map +1 -1
  12. package/dist/core/agent-session.js +23 -6
  13. package/dist/core/agent-session.js.map +1 -1
  14. package/dist/core/model-registry.d.ts +99 -0
  15. package/dist/core/model-registry.d.ts.map +1 -1
  16. package/dist/core/model-registry.js +93 -0
  17. package/dist/core/model-registry.js.map +1 -1
  18. package/dist/core/sdk.d.ts +2 -0
  19. package/dist/core/sdk.d.ts.map +1 -1
  20. package/dist/core/sdk.js +9 -1
  21. package/dist/core/sdk.js.map +1 -1
  22. package/dist/main.d.ts +105 -2
  23. package/dist/main.d.ts.map +1 -1
  24. package/dist/main.js +77 -3
  25. package/dist/main.js.map +1 -1
  26. package/dist/modes/interactive/components/model-selector.d.ts +1 -3
  27. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  28. package/dist/modes/interactive/components/model-selector.js +2 -5
  29. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  30. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  31. package/dist/modes/interactive/interactive-mode.js +1 -1
  32. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  33. package/docs/json.md +6 -0
  34. package/docs/models.md +69 -2
  35. package/docs/rpc.md +8 -0
  36. package/docs/sdk.md +17 -0
  37. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":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AAK;QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,2BAA2B;QAC3B,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,aAAa;QACb,sBAAsB;QACtB,gBAAgB;QAChB,kBAAkB;QAClB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,MAAM,OAAO,CAAC,8BAA8B,EAAE,CAAC;IAC/C,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type ThinkingLevel } from \"@leanandmean/agent\";\nimport {\n\ttype CacheRetention,\n\tclampThinkingLevel,\n\tinspectProviderRequestToolInventory,\n\ttype Message,\n\ttype Model,\n\tstreamSimple,\n\tvalidateModelContextLimits,\n} from \"@leanandmean/ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { getRequestMaxTokens } from \"./compaction/compaction.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { getDefaultSessionDir, getLatestCompactionEntry, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.scramjet/agent */\n\tagentDir?: string;\n\t/** Output-throughput history path resolved by runtime services. */\n\toutputThroughputHistoryPath?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\t/**\n\t * Prompt-cache retention for provider requests.\n\t *\n\t * Precedence: this option, then the PI_CACHE_RETENTION environment variable,\n\t * then \"long\". Pass \"short\" for short-lived sessions such as subagents.\n\t */\n\tcacheRetention?: CacheRetention;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction isCacheRetention(value: string): value is CacheRetention {\n\treturn value === \"none\" || value === \"short\" || value === \"long\";\n}\n\n// resolveCacheRetention runs on every createAgentSession call (including /new),\n// so warn about a bad env var only once per process to keep it out of the TUI.\n//\n// Defaults to \"long\" (1h tier). NOTE: the Anthropic adapter has a same-named\n// resolveCacheRetention (packages/ai/src/providers/anthropic.ts) that defaults\n// to \"short\" for backward compatibility. The divergence is intentional: this\n// SDK resolver runs first and passes a concrete value down, so the adapter's\n// \"short\" default is effectively shadowed in the coding-agent path. Keep both\n// in mind when changing either default.\nlet warnedInvalidCacheRetention = false;\n\nfunction resolveCacheRetention(option: CacheRetention | undefined): CacheRetention {\n\tif (option) {\n\t\treturn option;\n\t}\n\t// SCRAMJET-DIVERGENCE: prefer SCRAMJET_CACHE_RETENTION, fall back to PI_CACHE_RETENTION.\n\tconst env = process.env.SCRAMJET_CACHE_RETENTION || process.env.PI_CACHE_RETENTION;\n\tif (env) {\n\t\tif (isCacheRetention(env)) {\n\t\t\treturn env;\n\t\t}\n\t\tif (!warnedInvalidCacheRetention) {\n\t\t\twarnedInvalidCacheRetention = true;\n\t\t\tconsole.warn(`Invalid SCRAMJET_CACHE_RETENTION \"${env}\". Valid values: none, short, long. Using \"long\".`);\n\t\t}\n\t}\n\treturn \"long\";\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n): Record<string, string> | undefined {\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\t// SCRAMJET-DIVERGENCE: Identify as Scramjet to OpenRouter\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://github.com/LeanAndMean/scramjet\",\n\t\t\t\"X-OpenRouter-Title\": \"scramjet\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\t// SCRAMJET-DIVERGENCE: Identify as Scramjet to Cloudflare\n\t\treturn {\n\t\t\t\"User-Agent\": \"scramjet-coding-agent\",\n\t\t};\n\t}\n\n\treturn 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 '@leanandmean/ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tif (options.model) validateModelContextLimits(options.model);\n\tfor (const { model } of options.scopedModels ?? []) validateModelContextLimits(model);\n\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tconst outputThroughputHistoryPath =\n\t\toptions.outputThroughputHistoryPath ?? join(agentDir, \"output-throughput-history.json\");\n\tconst cacheRetention = resolveCacheRetention(options.cacheRetention);\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\t// SCRAMJET-DIVERGENCE: Carry configured-default warnings without replacing restoration diagnostics.\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = [modelFallbackMessage, result.fallbackMessage, formatNoModelsAvailableMessage()]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(\" \");\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += result.fallbackMessage\n\t\t\t\t? `. ${result.fallbackMessage}`\n\t\t\t\t: `. Using ${model.provider}/${model.id}`;\n\t\t} else {\n\t\t\tmodelFallbackMessage = result.fallbackMessage;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst initialActiveToolNames: string[] = options.tools\n\t\t? [...options.tools]\n\t\t: options.noTools\n\t\t\t? []\n\t\t\t: defaultActiveToolNames;\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\t// SCRAMJET-DIVERGENCE: per-session runner handoff from beforeProviderCall to streamFn (#524).\n\t// Precondition: this is per-session closure state (not shared across sessions), and requests\n\t// are serialized by runWithLifecycle, so beforeProviderCall runs immediately before streamFn\n\t// for the same request and sets a fresh binding that streamFn consumes synchronously at entry.\n\t// Capturing the runner at beforeProviderCall time (not extensionRunnerRef.current at streamFn\n\t// entry) is deliberate: if a reload swaps the runner across the intervening convertToLlm await,\n\t// onPayload's requestRunner !== extensionRunnerRef.current check suppresses the observation\n\t// rather than emitting it onto the replacement runner. The object wrapper (not the runner\n\t// directly) encodes \"beforeProviderCall ran\", distinguishing a captured undefined runner from\n\t// \"no capture\" (streamFn then falls back to the current runner).\n\tlet requestRunnerBinding: { runner?: ExtensionRunner } | undefined;\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst routedModelIdentity = { provider: model.provider, id: model.id, api: model.api } as const;\n\t\t\tconst requestContextToolNames = (context.tools ?? []).map((tool) => tool.name);\n\t\t\tconst binding = requestRunnerBinding;\n\t\t\trequestRunnerBinding = undefined;\n\t\t\tconst requestRunner = binding ? binding.runner : extensionRunnerRef.current;\n\t\t\tconst incomingOnPayload = options?.onPayload;\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager);\n\t\t\tconst compaction = getLatestCompactionEntry(sessionManager.getBranch());\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tmaxTokens: getRequestMaxTokens(\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions?.maxTokens,\n\t\t\t\t\tcompaction ? new Date(compaction.timestamp).getTime() : undefined,\n\t\t\t\t),\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tcacheRetention: options?.cacheRetention ?? cacheRetention,\n\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\t// SCRAMJET-DIVERGENCE: compose the public callback, payload hooks, and observation on one runner (#524).\n\t\t\t\tonPayload: async (payload, payloadModel) => {\n\t\t\t\t\tconst callbackResult = await incomingOnPayload?.(payload, payloadModel);\n\t\t\t\t\tconst callbackPayload = callbackResult === undefined ? payload : callbackResult;\n\t\t\t\t\tif (requestRunner !== extensionRunnerRef.current) return callbackPayload;\n\t\t\t\t\tconst finalPayload = requestRunner?.hasHandlers(\"before_provider_request\")\n\t\t\t\t\t\t? await requestRunner.emitBeforeProviderRequest(callbackPayload, payloadModel)\n\t\t\t\t\t\t: callbackPayload;\n\t\t\t\t\tif (\n\t\t\t\t\t\trequestRunner === extensionRunnerRef.current &&\n\t\t\t\t\t\trequestRunner?.hasHandlers(\"provider_request_tool_inventory\")\n\t\t\t\t\t) {\n\t\t\t\t\t\tawait requestRunner.emitProviderRequestToolInventory(\n\t\t\t\t\t\t\troutedModelIdentity,\n\t\t\t\t\t\t\trequestContextToolNames,\n\t\t\t\t\t\t\tinspectProviderRequestToolInventory(routedModelIdentity.api, finalPayload),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn finalPayload;\n\t\t\t\t},\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tbeforeProviderCall: async (context, model) => {\n\t\t\tconst binding = { runner: extensionRunnerRef.current };\n\t\t\trequestRunnerBinding = binding;\n\t\t\tconst runner = binding.runner;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_call\")) return context;\n\t\t\treturn runner.emitBeforeProviderCall(context, model);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\toutputThroughputHistoryPath,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\textensionRunnerRef,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tawait session.refreshOutputThroughputHistory();\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
1
+ {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAyC,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAEN,kBAAkB,EAClB,mCAAmC,EAGnC,YAAY,EACZ,0BAA0B,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,sBAAsB,EAAE,MAA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W,EAAE,OAAO,CAAC,WAAW;QAChC,aAAa;QACb,sBAAsB;QACtB,gBAAgB;QAChB,kBAAkB;QAClB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,MAAM,OAAO,CAAC,8BAA8B,EAAE,CAAC;IAC/C,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type ThinkingLevel } from \"@leanandmean/agent\";\nimport {\n\ttype CacheRetention,\n\tclampThinkingLevel,\n\tinspectProviderRequestToolInventory,\n\ttype Message,\n\ttype Model,\n\tstreamSimple,\n\tvalidateModelContextLimits,\n} from \"@leanandmean/ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { getRequestMaxTokens } from \"./compaction/compaction.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { getDefaultSessionDir, getLatestCompactionEntry, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.scramjet/agent */\n\tagentDir?: string;\n\t/** Output-throughput history path resolved by runtime services. */\n\toutputThroughputHistoryPath?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Save model/thinking changes as global defaults. Default: true. */\n\tpersistModelPreferences?: boolean;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\t/**\n\t * Prompt-cache retention for provider requests.\n\t *\n\t * Precedence: this option, then the PI_CACHE_RETENTION environment variable,\n\t * then \"long\". Pass \"short\" for short-lived sessions such as subagents.\n\t */\n\tcacheRetention?: CacheRetention;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction isCacheRetention(value: string): value is CacheRetention {\n\treturn value === \"none\" || value === \"short\" || value === \"long\";\n}\n\n// resolveCacheRetention runs on every createAgentSession call (including /new),\n// so warn about a bad env var only once per process to keep it out of the TUI.\n//\n// Defaults to \"long\" (1h tier). NOTE: the Anthropic adapter has a same-named\n// resolveCacheRetention (packages/ai/src/providers/anthropic.ts) that defaults\n// to \"short\" for backward compatibility. The divergence is intentional: this\n// SDK resolver runs first and passes a concrete value down, so the adapter's\n// \"short\" default is effectively shadowed in the coding-agent path. Keep both\n// in mind when changing either default.\nlet warnedInvalidCacheRetention = false;\n\nfunction resolveCacheRetention(option: CacheRetention | undefined): CacheRetention {\n\tif (option) {\n\t\treturn option;\n\t}\n\t// SCRAMJET-DIVERGENCE: prefer SCRAMJET_CACHE_RETENTION, fall back to PI_CACHE_RETENTION.\n\tconst env = process.env.SCRAMJET_CACHE_RETENTION || process.env.PI_CACHE_RETENTION;\n\tif (env) {\n\t\tif (isCacheRetention(env)) {\n\t\t\treturn env;\n\t\t}\n\t\tif (!warnedInvalidCacheRetention) {\n\t\t\twarnedInvalidCacheRetention = true;\n\t\t\tconsole.warn(`Invalid SCRAMJET_CACHE_RETENTION \"${env}\". Valid values: none, short, long. Using \"long\".`);\n\t\t}\n\t}\n\treturn \"long\";\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n): Record<string, string> | undefined {\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\t// SCRAMJET-DIVERGENCE: Identify as Scramjet to OpenRouter\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://github.com/LeanAndMean/scramjet\",\n\t\t\t\"X-OpenRouter-Title\": \"scramjet\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\t// SCRAMJET-DIVERGENCE: Identify as Scramjet to Cloudflare\n\t\treturn {\n\t\t\t\"User-Agent\": \"scramjet-coding-agent\",\n\t\t};\n\t}\n\n\treturn 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 '@leanandmean/ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tif (options.model) validateModelContextLimits(options.model);\n\tfor (const { model } of options.scopedModels ?? []) validateModelContextLimits(model);\n\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tconst outputThroughputHistoryPath =\n\t\toptions.outputThroughputHistoryPath ?? join(agentDir, \"output-throughput-history.json\");\n\tconst cacheRetention = resolveCacheRetention(options.cacheRetention);\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\t// SCRAMJET-DIVERGENCE: Carry configured-default warnings without replacing restoration diagnostics.\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = [modelFallbackMessage, result.fallbackMessage, formatNoModelsAvailableMessage()]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(\" \");\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += result.fallbackMessage\n\t\t\t\t? `. ${result.fallbackMessage}`\n\t\t\t\t: `. Using ${model.provider}/${model.id}`;\n\t\t} else {\n\t\t\tmodelFallbackMessage = result.fallbackMessage;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst initialActiveToolNames: string[] = options.tools\n\t\t? [...options.tools]\n\t\t: options.noTools\n\t\t\t? []\n\t\t\t: defaultActiveToolNames;\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\t// SCRAMJET-DIVERGENCE: per-session runner handoff from beforeProviderCall to streamFn (#524).\n\t// Precondition: this is per-session closure state (not shared across sessions), and requests\n\t// are serialized by runWithLifecycle, so beforeProviderCall runs immediately before streamFn\n\t// for the same request and sets a fresh binding that streamFn consumes synchronously at entry.\n\t// Capturing the runner at beforeProviderCall time (not extensionRunnerRef.current at streamFn\n\t// entry) is deliberate: if a reload swaps the runner across the intervening convertToLlm await,\n\t// onPayload's requestRunner !== extensionRunnerRef.current check suppresses the observation\n\t// rather than emitting it onto the replacement runner. The object wrapper (not the runner\n\t// directly) encodes \"beforeProviderCall ran\", distinguishing a captured undefined runner from\n\t// \"no capture\" (streamFn then falls back to the current runner).\n\tlet requestRunnerBinding: { runner?: ExtensionRunner } | undefined;\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst routedModelIdentity = { provider: model.provider, id: model.id, api: model.api } as const;\n\t\t\tconst requestContextToolNames = (context.tools ?? []).map((tool) => tool.name);\n\t\t\tconst binding = requestRunnerBinding;\n\t\t\trequestRunnerBinding = undefined;\n\t\t\tconst requestRunner = binding ? binding.runner : extensionRunnerRef.current;\n\t\t\tconst incomingOnPayload = options?.onPayload;\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager);\n\t\t\tconst compaction = getLatestCompactionEntry(sessionManager.getBranch());\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tmaxTokens: getRequestMaxTokens(\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions?.maxTokens,\n\t\t\t\t\tcompaction ? new Date(compaction.timestamp).getTime() : undefined,\n\t\t\t\t),\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tcacheRetention: options?.cacheRetention ?? cacheRetention,\n\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\t// SCRAMJET-DIVERGENCE: compose the public callback, payload hooks, and observation on one runner (#524).\n\t\t\t\tonPayload: async (payload, payloadModel) => {\n\t\t\t\t\tconst callbackResult = await incomingOnPayload?.(payload, payloadModel);\n\t\t\t\t\tconst callbackPayload = callbackResult === undefined ? payload : callbackResult;\n\t\t\t\t\tif (requestRunner !== extensionRunnerRef.current) return callbackPayload;\n\t\t\t\t\tconst finalPayload = requestRunner?.hasHandlers(\"before_provider_request\")\n\t\t\t\t\t\t? await requestRunner.emitBeforeProviderRequest(callbackPayload, payloadModel)\n\t\t\t\t\t\t: callbackPayload;\n\t\t\t\t\tif (\n\t\t\t\t\t\trequestRunner === extensionRunnerRef.current &&\n\t\t\t\t\t\trequestRunner?.hasHandlers(\"provider_request_tool_inventory\")\n\t\t\t\t\t) {\n\t\t\t\t\t\tawait requestRunner.emitProviderRequestToolInventory(\n\t\t\t\t\t\t\troutedModelIdentity,\n\t\t\t\t\t\t\trequestContextToolNames,\n\t\t\t\t\t\t\tinspectProviderRequestToolInventory(routedModelIdentity.api, finalPayload),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn finalPayload;\n\t\t\t\t},\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tbeforeProviderCall: async (context, model) => {\n\t\t\tconst binding = { runner: extensionRunnerRef.current };\n\t\t\trequestRunnerBinding = binding;\n\t\t\tconst runner = binding.runner;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_call\")) return context;\n\t\t\treturn runner.emitBeforeProviderCall(context, model);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\t// SCRAMJET-DIVERGENCE: Explicit ephemeral selection must remain accurate in branch-local history.\n\t\tif (\n\t\t\toptions.persistModelPreferences === false &&\n\t\t\tmodel &&\n\t\t\t(existingSession.model?.provider !== model.provider || existingSession.model?.modelId !== model.id)\n\t\t) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tif (\n\t\t\t!hasThinkingEntry ||\n\t\t\t(options.persistModelPreferences === false && existingSession.thinkingLevel !== thinkingLevel)\n\t\t) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\toutputThroughputHistoryPath,\n\t\tscopedModels: options.scopedModels,\n\t\tpersistModelPreferences: options.persistModelPreferences,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\textensionRunnerRef,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tawait session.refreshOutputThroughputHistory();\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
package/dist/main.d.ts CHANGED
@@ -8,15 +8,118 @@ import type { ThinkingLevel } from "@leanandmean/agent";
8
8
  import { type Model } from "@leanandmean/ai";
9
9
  import { type Args } from "./cli/args.js";
10
10
  import { type AgentSessionRuntimeDiagnostic } from "./core/agent-session-services.js";
11
+ import { AuthStorage } from "./core/auth-storage.js";
11
12
  import type { ExtensionAPI, ExtensionFactory } from "./core/extensions/types.js";
12
- import type { ModelRegistry } from "./core/model-registry.js";
13
+ import { type ModelRegistry } from "./core/model-registry.js";
13
14
  import { type ScopedModel } from "./core/model-resolver.js";
14
15
  import type { CreateAgentSessionOptions } from "./core/sdk.js";
15
16
  import { SettingsManager } from "./core/settings-manager.js";
17
+ export declare function resolveInvocationModelDefinition(parsed: Args, stdinIsTTY: boolean, env?: NodeJS.ProcessEnv): {
18
+ definition: {
19
+ api: "anthropic-messages" | "google-generative-ai" | "openai-completions" | "openai-responses";
20
+ baseUrl: string;
21
+ apiKeyEnv: string;
22
+ contextWindow: number;
23
+ maxTokens: number;
24
+ name: string;
25
+ reasoning: boolean;
26
+ input: ("image" | "text")[];
27
+ cost: {
28
+ input: number;
29
+ output: number;
30
+ cacheRead: number;
31
+ cacheWrite: number;
32
+ };
33
+ compat?: {
34
+ supportsStore?: boolean | undefined;
35
+ supportsDeveloperRole?: boolean | undefined;
36
+ supportsReasoningEffort?: boolean | undefined;
37
+ supportsUsageInStreaming?: boolean | undefined;
38
+ maxTokensField?: "max_completion_tokens" | "max_tokens" | undefined;
39
+ requiresToolResultName?: boolean | undefined;
40
+ requiresAssistantAfterToolResult?: boolean | undefined;
41
+ requiresThinkingAsText?: boolean | undefined;
42
+ requiresReasoningContentOnAssistantMessages?: boolean | undefined;
43
+ thinkingFormat?: "deepseek" | "openai" | "openrouter" | "qwen" | "qwen-chat-template" | "together" | "zai" | undefined;
44
+ cacheControlFormat?: "anthropic" | undefined;
45
+ openRouterRouting?: {
46
+ allow_fallbacks?: boolean | undefined;
47
+ require_parameters?: boolean | undefined;
48
+ data_collection?: "allow" | "deny" | undefined;
49
+ zdr?: boolean | undefined;
50
+ enforce_distillable_text?: boolean | undefined;
51
+ order?: string[] | undefined;
52
+ only?: string[] | undefined;
53
+ ignore?: string[] | undefined;
54
+ quantizations?: string[] | undefined;
55
+ sort?: string | {
56
+ by?: string | undefined;
57
+ partition?: string | null | undefined;
58
+ } | undefined;
59
+ max_price?: {
60
+ prompt?: string | number | undefined;
61
+ completion?: string | number | undefined;
62
+ image?: string | number | undefined;
63
+ audio?: string | number | undefined;
64
+ request?: string | number | undefined;
65
+ } | undefined;
66
+ preferred_min_throughput?: number | {
67
+ p50?: number | undefined;
68
+ p75?: number | undefined;
69
+ p90?: number | undefined;
70
+ p99?: number | undefined;
71
+ } | undefined;
72
+ preferred_max_latency?: number | {
73
+ p50?: number | undefined;
74
+ p75?: number | undefined;
75
+ p90?: number | undefined;
76
+ p99?: number | undefined;
77
+ } | undefined;
78
+ } | undefined;
79
+ vercelGatewayRouting?: {
80
+ only?: string[] | undefined;
81
+ order?: string[] | undefined;
82
+ } | undefined;
83
+ zaiToolStream?: boolean | undefined;
84
+ supportsStrictMode?: boolean | undefined;
85
+ sendSessionAffinityHeaders?: boolean | undefined;
86
+ supportsLongCacheRetention?: boolean | undefined;
87
+ } | {
88
+ sendSessionIdHeader?: boolean | undefined;
89
+ supportsLongCacheRetention?: boolean | undefined;
90
+ } | {
91
+ supportsEagerToolInputStreaming?: boolean | undefined;
92
+ supportsLongCacheRetention?: boolean | undefined;
93
+ sendSessionAffinityHeaders?: boolean | undefined;
94
+ supportsCacheControlOnTools?: boolean | undefined;
95
+ supportsTemperature?: boolean | undefined;
96
+ forceAdaptiveThinking?: boolean | undefined;
97
+ } | undefined;
98
+ id: string;
99
+ maxInputTokens?: number | undefined;
100
+ requestLimits?: {
101
+ maxTotalTokens: number;
102
+ maxInputTokens?: number | undefined;
103
+ maxOutputTokens?: number | undefined;
104
+ supportsTools: boolean;
105
+ }[] | undefined;
106
+ thinkingLevelMap?: {
107
+ off?: string | null | undefined;
108
+ minimal?: string | null | undefined;
109
+ low?: string | null | undefined;
110
+ medium?: string | null | undefined;
111
+ high?: string | null | undefined;
112
+ xhigh?: string | null | undefined;
113
+ max?: string | null | undefined;
114
+ } | undefined;
115
+ };
116
+ apiKey: string | undefined;
117
+ } | undefined;
118
+ export declare function registerInvocationModel(invocation: NonNullable<ReturnType<typeof resolveInvocationModelDefinition>>, provider: string, modelRegistry: ModelRegistry, authStorage: AuthStorage): Model<any>;
16
119
  export declare function buildSessionOptions(parsed: Args, scopedModels: ScopedModel[], hasExistingSession: boolean, modelRegistry: ModelRegistry, settingsManager: SettingsManager, inherited?: {
17
120
  model: Model<any>;
18
121
  thinkingLevel: ThinkingLevel;
19
- }): {
122
+ }, invocationModel?: Model<any>): {
20
123
  options: CreateAgentSessionOptions;
21
124
  cliThinkingFromModel: boolean;
22
125
  diagnostics: AgentSessionRuntimeDiagnostic[];
@@ -1 +1 @@
1
- {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAqB,KAAK,KAAK,EAAkB,MAAM,iBAAiB,CAAC;AAGhF,OAAO,EAAE,KAAK,IAAI,EAAmC,MAAM,eAAe,CAAC;AAO3E,OAAO,EACN,KAAK,6BAA6B,EAGlC,MAAM,kCAAkC,CAAC;AAI1C,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAEjF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAsC,KAAK,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAGhG,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAQ/D,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAuP7D,wBAAgB,mBAAmB,CAClC,MAAM,EAAE,IAAI,EACZ,YAAY,EAAE,WAAW,EAAE,EAC3B,kBAAkB,EAAE,OAAO,EAC3B,aAAa,EAAE,aAAa,EAC5B,eAAe,EAAE,eAAe,EAChC,SAAS,CAAC,EAAE;IAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAAC,aAAa,EAAE,aAAa,CAAA;CAAE,GAC7D;IACF,OAAO,EAAE,yBAAyB,CAAC;IACnC,oBAAoB,EAAE,OAAO,CAAC;IAC9B,WAAW,EAAE,6BAA6B,EAAE,CAAC;CAC7C,CA+FA;AAyCD,MAAM,WAAW,WAAW;IAC3B,kBAAkB,CAAC,EAAE,gBAAgB,EAAE,CAAC;IACxC,WAAW,CAAC,EAAE,CAAC,EAAE,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACzD;AAED,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,WAAW,iBAgU/D","sourcesContent":["/**\n * Main entry point for the coding agent CLI.\n *\n * This file handles CLI argument parsing and translates them into\n * createAgentSession() options. The SDK does the heavy lifting.\n */\n\nimport { resolve } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { ThinkingLevel } from \"@leanandmean/agent\";\nimport { type ImageContent, type Model, modelsAreEqual } from \"@leanandmean/ai\";\nimport { ProcessTerminal, setKeybindings, TUI } from \"@leanandmean/tui\";\nimport chalk from \"chalk\";\nimport { type Args, type Mode, parseArgs, printHelp } from \"./cli/args.js\";\nimport { processFileArguments } from \"./cli/file-processor.js\";\nimport { buildInitialMessage, normalizePipedStdinContent } from \"./cli/initial-message.js\";\nimport { listModels } from \"./cli/list-models.js\";\nimport { selectSession } from \"./cli/session-picker.js\";\nimport { ENV_SESSION_DIR, expandTildePath, getAgentDir, VERSION } from \"./config.js\";\nimport { type CreateAgentSessionRuntimeFactory, createAgentSessionRuntime } from \"./core/agent-session-runtime.js\";\nimport {\n\ttype AgentSessionRuntimeDiagnostic,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./core/agent-session-services.js\";\nimport { formatNoModelsAvailableMessage } from \"./core/auth-guidance.js\";\nimport { AuthStorage } from \"./core/auth-storage.js\";\nimport { exportFromFile } from \"./core/export-html/index.js\";\nimport type { ExtensionAPI, ExtensionFactory } from \"./core/extensions/types.js\";\nimport { KeybindingsManager } from \"./core/keybindings.js\";\nimport type { ModelRegistry } from \"./core/model-registry.js\";\nimport { resolveCliModel, resolveModelScope, type ScopedModel } from \"./core/model-resolver.js\";\nimport { restoreStdout, takeOverStdout } from \"./core/output-guard.js\";\nimport { isRequiredBuiltinInitError, renderRequiredBuiltinInitCause } from \"./core/resource-loader.js\";\nimport type { CreateAgentSessionOptions } from \"./core/sdk.js\";\nimport {\n\tformatMissingSessionCwdPrompt,\n\tgetMissingSessionCwdIssue,\n\tMissingSessionCwdError,\n\ttype SessionCwdIssue,\n} from \"./core/session-cwd.js\";\nimport { SessionManager } from \"./core/session-manager.js\";\nimport { SettingsManager } from \"./core/settings-manager.js\";\nimport { printTimings, resetTimings, time } from \"./core/timings.js\";\nimport { runMigrations, showDeprecationWarnings } from \"./migrations.js\";\nimport { InteractiveMode, runPrintMode, runRpcMode } from \"./modes/index.js\";\nimport { ExtensionSelectorComponent } from \"./modes/interactive/components/extension-selector.js\";\nimport { initTheme, stopThemeWatcher } from \"./modes/interactive/theme/theme.js\";\nimport { handleConfigCommand, handlePackageCommand } from \"./package-manager-cli.js\";\nimport { isLocalPath } from \"./utils/paths.js\";\n\n/**\n * Read all content from piped stdin.\n * Returns undefined if stdin is a TTY (interactive terminal).\n */\nasync function readPipedStdin(): Promise<string | undefined> {\n\t// If stdin is a TTY, we're running interactively - don't read stdin\n\tif (process.stdin.isTTY) {\n\t\treturn undefined;\n\t}\n\n\treturn new Promise((resolve) => {\n\t\tlet data = \"\";\n\t\tprocess.stdin.setEncoding(\"utf8\");\n\t\tprocess.stdin.on(\"data\", (chunk) => {\n\t\t\tdata += chunk;\n\t\t});\n\t\tprocess.stdin.on(\"end\", () => {\n\t\t\tresolve(normalizePipedStdinContent(data));\n\t\t});\n\t\tprocess.stdin.resume();\n\t});\n}\n\nfunction collectSettingsDiagnostics(\n\tsettingsManager: SettingsManager,\n\tcontext: string,\n): AgentSessionRuntimeDiagnostic[] {\n\treturn settingsManager.drainErrors().map(({ scope, error }) => ({\n\t\ttype: \"warning\",\n\t\tmessage: `(${context}, ${scope} settings) ${error.message}`,\n\t}));\n}\n\nfunction reportDiagnostics(diagnostics: readonly AgentSessionRuntimeDiagnostic[]): void {\n\tfor (const diagnostic of diagnostics) {\n\t\tconst color = diagnostic.type === \"error\" ? chalk.red : diagnostic.type === \"warning\" ? chalk.yellow : chalk.dim;\n\t\tconst prefix = diagnostic.type === \"error\" ? \"Error: \" : diagnostic.type === \"warning\" ? \"Warning: \" : \"\";\n\t\tconsole.error(color(`${prefix}${diagnostic.message}`));\n\t}\n}\n\nfunction isTruthyEnvFlag(value: string | undefined): boolean {\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ntype AppMode = \"interactive\" | \"print\" | \"json\" | \"rpc\";\n\nfunction resolveAppMode(parsed: Args, stdinIsTTY: boolean): AppMode {\n\tif (parsed.mode === \"rpc\") {\n\t\treturn \"rpc\";\n\t}\n\tif (parsed.mode === \"json\") {\n\t\treturn \"json\";\n\t}\n\tif (parsed.print || !stdinIsTTY) {\n\t\treturn \"print\";\n\t}\n\treturn \"interactive\";\n}\n\nfunction toPrintOutputMode(appMode: AppMode): Exclude<Mode, \"rpc\"> {\n\treturn appMode === \"json\" ? \"json\" : \"text\";\n}\n\nasync function prepareInitialMessage(\n\tparsed: Args,\n\tautoResizeImages: boolean,\n\tstdinContent?: string,\n): Promise<{\n\tinitialMessage?: string;\n\tinitialImages?: ImageContent[];\n}> {\n\tif (parsed.fileArgs.length === 0) {\n\t\treturn buildInitialMessage({ parsed, stdinContent });\n\t}\n\n\tconst { text, images } = await processFileArguments(parsed.fileArgs, { autoResizeImages });\n\treturn buildInitialMessage({\n\t\tparsed,\n\t\tfileText: text,\n\t\tfileImages: images,\n\t\tstdinContent,\n\t});\n}\n\n/** Result from resolving a session argument */\ntype ResolvedSession =\n\t| { type: \"path\"; path: string } // Direct file path\n\t| { type: \"local\"; path: string } // Found in current project\n\t| { type: \"global\"; path: string; cwd: string } // Found in different project\n\t| { type: \"not_found\"; arg: string }; // Not found anywhere\n\n/**\n * Resolve a session argument to a file path.\n * If it looks like a path, use as-is. Otherwise try to match as session ID prefix.\n */\nasync function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?: string): Promise<ResolvedSession> {\n\t// If it looks like a file path, use as-is\n\tif (sessionArg.includes(\"/\") || sessionArg.includes(\"\\\\\") || sessionArg.endsWith(\".jsonl\")) {\n\t\treturn { type: \"path\", path: sessionArg };\n\t}\n\n\t// Try to match as session ID in current project first\n\tconst localSessions = await SessionManager.list(cwd, sessionDir);\n\tconst localMatches = localSessions.filter((s) => s.id.startsWith(sessionArg));\n\n\tif (localMatches.length >= 1) {\n\t\treturn { type: \"local\", path: localMatches[0].path };\n\t}\n\n\t// Try global search across all projects\n\tconst allSessions = await SessionManager.listAll();\n\tconst globalMatches = allSessions.filter((s) => s.id.startsWith(sessionArg));\n\n\tif (globalMatches.length >= 1) {\n\t\tconst match = globalMatches[0];\n\t\treturn { type: \"global\", path: match.path, cwd: match.cwd };\n\t}\n\n\t// Not found anywhere\n\treturn { type: \"not_found\", arg: sessionArg };\n}\n\n/** Prompt user for yes/no confirmation */\nasync function promptConfirm(message: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t});\n\t\trl.question(`${message} [y/N] `, (answer) => {\n\t\t\trl.close();\n\t\t\tresolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n\t\t});\n\t});\n}\n\nfunction validateForkFlags(parsed: Args): void {\n\tif (!parsed.fork) return;\n\n\tconst conflictingFlags = [\n\t\tparsed.session ? \"--session\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t\tparsed.noSession ? \"--no-session\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\n\tif (conflictingFlags.length > 0) {\n\t\tconsole.error(chalk.red(`Error: --fork cannot be combined with ${conflictingFlags.join(\", \")}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nfunction forkSessionOrExit(sourcePath: string, cwd: string, sessionDir?: string): SessionManager {\n\ttry {\n\t\treturn SessionManager.forkFrom(sourcePath, cwd, sessionDir);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nasync function createSessionManager(\n\tparsed: Args,\n\tcwd: string,\n\tsessionDir: string | undefined,\n\tsettingsManager: SettingsManager,\n): Promise<SessionManager> {\n\tif (parsed.noSession) {\n\t\treturn SessionManager.inMemory();\n\t}\n\n\tif (parsed.fork) {\n\t\tconst resolved = await resolveSessionPath(parsed.fork, cwd, sessionDir);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"path\":\n\t\t\tcase \"local\":\n\t\t\tcase \"global\":\n\t\t\t\treturn forkSessionOrExit(resolved.path, cwd, sessionDir);\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.session) {\n\t\tconst resolved = await resolveSessionPath(parsed.session, cwd, sessionDir);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"path\":\n\t\t\tcase \"local\":\n\t\t\t\treturn SessionManager.open(resolved.path, sessionDir);\n\n\t\t\tcase \"global\": {\n\t\t\t\tconsole.log(chalk.yellow(`Session found in different project: ${resolved.cwd}`));\n\t\t\t\tconst shouldFork = await promptConfirm(\"Fork this session into current directory?\");\n\t\t\t\tif (!shouldFork) {\n\t\t\t\t\tconsole.log(chalk.dim(\"Aborted.\"));\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t\treturn forkSessionOrExit(resolved.path, cwd, sessionDir);\n\t\t\t}\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.resume) {\n\t\tinitTheme(settingsManager.getTheme(), true);\n\t\ttry {\n\t\t\tconst selectedPath = await selectSession(\n\t\t\t\t(onProgress) => SessionManager.list(cwd, sessionDir, onProgress),\n\t\t\t\tSessionManager.listAll,\n\t\t\t);\n\t\t\tif (!selectedPath) {\n\t\t\t\tconsole.log(chalk.dim(\"No session selected\"));\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\treturn SessionManager.open(selectedPath, sessionDir);\n\t\t} finally {\n\t\t\tstopThemeWatcher();\n\t\t}\n\t}\n\n\tif (parsed.continue) {\n\t\treturn SessionManager.continueRecent(cwd, sessionDir);\n\t}\n\n\treturn SessionManager.create(cwd, sessionDir);\n}\n\n// SCRAMJET-DIVERGENCE: exported for direct unit testing (issue 186).\nexport function buildSessionOptions(\n\tparsed: Args,\n\tscopedModels: ScopedModel[],\n\thasExistingSession: boolean,\n\tmodelRegistry: ModelRegistry,\n\tsettingsManager: SettingsManager,\n\tinherited?: { model: Model<any>; thinkingLevel: ThinkingLevel },\n): {\n\toptions: CreateAgentSessionOptions;\n\tcliThinkingFromModel: boolean;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n} {\n\tconst options: CreateAgentSessionOptions = {};\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tlet cliThinkingFromModel = false;\n\n\t// SCRAMJET-DIVERGENCE: inherited model/thinkingLevel from the previous session takes highest\n\t// precedence, above CLI --model and scoped models. See issue 186.\n\tif (inherited) {\n\t\toptions.model = inherited.model;\n\t\toptions.thinkingLevel = inherited.thinkingLevel;\n\t}\n\n\t// Model from CLI\n\t// - supports --provider <name> --model <pattern>\n\t// - supports --model <provider>/<pattern>\n\tif (!options.model && parsed.model) {\n\t\tconst resolved = resolveCliModel({\n\t\t\tcliProvider: parsed.provider,\n\t\t\tcliModel: parsed.model,\n\t\t\tmodelRegistry,\n\t\t});\n\t\tif (resolved.warning) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: resolved.warning });\n\t\t}\n\t\tif (resolved.error) {\n\t\t\tdiagnostics.push({ type: \"error\", message: resolved.error });\n\t\t}\n\t\tif (resolved.model) {\n\t\t\toptions.model = resolved.model;\n\t\t\t// Allow \"--model <pattern>:<thinking>\" as a shorthand.\n\t\t\t// Explicit --thinking still takes precedence (applied later).\n\t\t\tif (!parsed.thinking && resolved.thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = resolved.thinkingLevel;\n\t\t\t\tcliThinkingFromModel = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!options.model && scopedModels.length > 0 && !hasExistingSession) {\n\t\t// Check if saved default is in scoped models - use it if so, otherwise first scoped model\n\t\tconst savedProvider = settingsManager.getDefaultProvider();\n\t\tconst savedModelId = settingsManager.getDefaultModel();\n\t\tconst savedModel = savedProvider && savedModelId ? modelRegistry.find(savedProvider, savedModelId) : undefined;\n\t\tconst savedInScope = savedModel ? scopedModels.find((sm) => modelsAreEqual(sm.model, savedModel)) : undefined;\n\n\t\tif (savedInScope) {\n\t\t\toptions.model = savedInScope.model;\n\t\t\t// Use thinking level from scoped model config if explicitly set\n\t\t\tif (!parsed.thinking && savedInScope.thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = savedInScope.thinkingLevel;\n\t\t\t}\n\t\t} else {\n\t\t\toptions.model = scopedModels[0].model;\n\t\t\t// Use thinking level from first scoped model if explicitly set\n\t\t\tif (!parsed.thinking && scopedModels[0].thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = scopedModels[0].thinkingLevel;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Thinking level from CLI (takes precedence over scoped model thinking levels set above,\n\t// but NOT over inherited thinking level — SCRAMJET-DIVERGENCE: issue 186)\n\tif (options.thinkingLevel === undefined && parsed.thinking) {\n\t\toptions.thinkingLevel = parsed.thinking;\n\t}\n\n\t// Cache retention from CLI (PI_CACHE_RETENTION and the default are resolved by the SDK)\n\tif (parsed.cacheRetention) {\n\t\toptions.cacheRetention = parsed.cacheRetention;\n\t}\n\n\t// Scoped models for Ctrl+P cycling\n\t// Keep thinking level undefined when not explicitly set in the model pattern.\n\t// Undefined means \"inherit current session thinking level\" during cycling.\n\tif (scopedModels.length > 0) {\n\t\toptions.scopedModels = scopedModels.map((sm) => ({\n\t\t\tmodel: sm.model,\n\t\t\tthinkingLevel: sm.thinkingLevel,\n\t\t}));\n\t}\n\n\t// API key from CLI - set in authStorage\n\t// (handled by caller before createAgentSession)\n\n\t// Tools\n\tif (parsed.noTools) {\n\t\toptions.noTools = \"all\";\n\t} else if (parsed.noBuiltinTools) {\n\t\toptions.noTools = \"builtin\";\n\t}\n\tif (parsed.tools) {\n\t\toptions.tools = [...parsed.tools];\n\t}\n\n\treturn { options, cliThinkingFromModel, diagnostics };\n}\n\nfunction resolveCliPaths(cwd: string, paths: string[] | undefined): string[] | undefined {\n\treturn paths?.map((value) => (isLocalPath(value) ? resolve(cwd, value) : value));\n}\n\nasync function promptForMissingSessionCwd(\n\tissue: SessionCwdIssue,\n\tsettingsManager: SettingsManager,\n): Promise<string | undefined> {\n\tinitTheme(settingsManager.getTheme());\n\tsetKeybindings(KeybindingsManager.create());\n\n\treturn new Promise((resolve) => {\n\t\t// SCRAMJET-DIVERGENCE: shrink recovery is mandatory renderer behavior; no legacy toggle is applied (#389).\n\t\tconst ui = new TUI(new ProcessTerminal(), settingsManager.getShowHardwareCursor());\n\n\t\tlet settled = false;\n\t\tconst finish = (result: string | undefined) => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tui.stop();\n\t\t\tresolve(result);\n\t\t};\n\n\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\tformatMissingSessionCwdPrompt(issue),\n\t\t\t[\"Continue\", \"Cancel\"],\n\t\t\t(option) => finish(option === \"Continue\" ? issue.fallbackCwd : undefined),\n\t\t\t() => finish(undefined),\n\t\t\t{ tui: ui },\n\t\t);\n\t\tui.addChild(selector);\n\t\tui.setFocus(selector);\n\t\tui.start();\n\t});\n}\n\n// SCRAMJET-DIVERGENCE: added builtinInit for direct product wiring without extension discovery.\nexport interface MainOptions {\n\textensionFactories?: ExtensionFactory[];\n\tbuiltinInit?: (pi: ExtensionAPI) => void | Promise<void>;\n}\n\nexport async function main(args: string[], options?: MainOptions) {\n\tresetTimings();\n\t// SCRAMJET-DIVERGENCE: prefer SCRAMJET_OFFLINE, fall back to PI_OFFLINE.\n\tconst offlineMode =\n\t\targs.includes(\"--offline\") ||\n\t\tisTruthyEnvFlag(process.env.SCRAMJET_OFFLINE) ||\n\t\tisTruthyEnvFlag(process.env.PI_OFFLINE);\n\tif (offlineMode) {\n\t\tprocess.env.SCRAMJET_OFFLINE = \"1\";\n\t\tprocess.env.PI_OFFLINE = \"1\";\n\t\tprocess.env.PI_SKIP_VERSION_CHECK = \"1\";\n\t}\n\n\tif (await handlePackageCommand(args)) {\n\t\treturn;\n\t}\n\n\tif (await handleConfigCommand(args)) {\n\t\treturn;\n\t}\n\n\tconst parsed = parseArgs(args);\n\tif (parsed.diagnostics.length > 0) {\n\t\tfor (const d of parsed.diagnostics) {\n\t\t\tconst color = d.type === \"error\" ? chalk.red : chalk.yellow;\n\t\t\tconsole.error(color(`${d.type === \"error\" ? \"Error\" : \"Warning\"}: ${d.message}`));\n\t\t}\n\t\tif (parsed.diagnostics.some((d) => d.type === \"error\")) {\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\ttime(\"parseArgs\");\n\tlet appMode = resolveAppMode(parsed, process.stdin.isTTY);\n\tconst shouldTakeOverStdout = appMode !== \"interactive\";\n\tif (shouldTakeOverStdout) {\n\t\ttakeOverStdout();\n\t}\n\n\tif (parsed.version) {\n\t\tconsole.log(VERSION);\n\t\tprocess.exit(0);\n\t}\n\n\tif (parsed.export) {\n\t\tlet result: string;\n\t\ttry {\n\t\t\tconst outputPath = parsed.messages.length > 0 ? parsed.messages[0] : undefined;\n\t\t\tresult = await exportFromFile(parsed.export, outputPath);\n\t\t} catch (error: unknown) {\n\t\t\tconst message = error instanceof Error ? error.message : \"Failed to export session\";\n\t\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tconsole.log(`Exported to: ${result}`);\n\t\tprocess.exit(0);\n\t}\n\n\tif (parsed.mode === \"rpc\" && parsed.fileArgs.length > 0) {\n\t\tconsole.error(chalk.red(\"Error: @file arguments are not supported in RPC mode\"));\n\t\tprocess.exit(1);\n\t}\n\n\tvalidateForkFlags(parsed);\n\n\t// Run migrations (pass cwd for project-local migrations)\n\tconst { migratedAuthProviders: migratedProviders, deprecationWarnings } = runMigrations(process.cwd());\n\ttime(\"runMigrations\");\n\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst startupSettingsManager = SettingsManager.create(cwd, agentDir);\n\treportDiagnostics(collectSettingsDiagnostics(startupSettingsManager, \"startup session lookup\"));\n\n\t// Decide the final runtime cwd before creating cwd-bound runtime services.\n\t// --session and --resume may select a session from another project, so project-local\n\t// settings, resources, provider registrations, and models must be resolved only after\n\t// the target session cwd is known. The startup-cwd settings manager is used only for\n\t// sessionDir lookup during session selection.\n\tconst envSessionDir = process.env[ENV_SESSION_DIR];\n\tconst sessionDir =\n\t\tparsed.sessionDir ??\n\t\t(envSessionDir ? expandTildePath(envSessionDir) : undefined) ??\n\t\tstartupSettingsManager.getSessionDir();\n\tlet sessionManager = await createSessionManager(parsed, cwd, sessionDir, startupSettingsManager);\n\tconst missingSessionCwdIssue = getMissingSessionCwdIssue(sessionManager, cwd);\n\tif (missingSessionCwdIssue) {\n\t\tif (appMode === \"interactive\") {\n\t\t\tconst selectedCwd = await promptForMissingSessionCwd(missingSessionCwdIssue, startupSettingsManager);\n\t\t\tif (!selectedCwd) {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\tsessionManager = SessionManager.open(missingSessionCwdIssue.sessionFile!, sessionDir, selectedCwd);\n\t\t} else {\n\t\t\tconsole.error(chalk.red(new MissingSessionCwdError(missingSessionCwdIssue).message));\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\ttime(\"createSessionManager\");\n\n\tconst resolvedExtensionPaths = resolveCliPaths(cwd, parsed.extensions);\n\tconst resolvedSkillPaths = resolveCliPaths(cwd, parsed.skills);\n\tconst resolvedPromptTemplatePaths = resolveCliPaths(cwd, parsed.promptTemplates);\n\tconst resolvedThemePaths = resolveCliPaths(cwd, parsed.themes);\n\tconst authStorage = AuthStorage.create();\n\tconst createRuntime: CreateAgentSessionRuntimeFactory = async ({\n\t\tcwd,\n\t\tagentDir,\n\t\tsessionManager,\n\t\tsessionStartEvent,\n\t\tinherited, // SCRAMJET-DIVERGENCE: forward inherited model/thinkingLevel (issue 186)\n\t}) => {\n\t\tconst services = await createAgentSessionServices({\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tauthStorage,\n\t\t\textensionFlagValues: parsed.unknownFlags,\n\t\t\tresourceLoaderOptions: {\n\t\t\t\tadditionalExtensionPaths: resolvedExtensionPaths,\n\t\t\t\tadditionalSkillPaths: resolvedSkillPaths,\n\t\t\t\tadditionalPromptTemplatePaths: resolvedPromptTemplatePaths,\n\t\t\t\tadditionalThemePaths: resolvedThemePaths,\n\t\t\t\tnoExtensions: parsed.noExtensions,\n\t\t\t\tnoSkills: parsed.noSkills,\n\t\t\t\tnoPromptTemplates: parsed.noPromptTemplates,\n\t\t\t\tnoThemes: parsed.noThemes,\n\t\t\t\tnoContextFiles: parsed.noContextFiles,\n\t\t\t\tsystemPrompt: parsed.systemPrompt,\n\t\t\t\tappendSystemPrompt: parsed.appendSystemPrompt,\n\t\t\t\textensionFactories: options?.extensionFactories,\n\t\t\t\tbuiltinInit: options?.builtinInit,\n\t\t\t},\n\t\t});\n\t\tconst { settingsManager, modelRegistry, resourceLoader } = services;\n\t\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [\n\t\t\t...services.diagnostics,\n\t\t\t...collectSettingsDiagnostics(settingsManager, \"runtime creation\"),\n\t\t\t...resourceLoader.getExtensions().errors.map(({ path, error }) => ({\n\t\t\t\ttype: \"error\" as const,\n\t\t\t\tmessage: `Failed to load extension \"${path}\": ${error}`,\n\t\t\t})),\n\t\t];\n\n\t\tconst modelPatterns = parsed.models ?? settingsManager.getEnabledModels();\n\t\tconst scopedModels =\n\t\t\tmodelPatterns && modelPatterns.length > 0 ? await resolveModelScope(modelPatterns, modelRegistry) : [];\n\t\tconst {\n\t\t\toptions: sessionOptions,\n\t\t\tcliThinkingFromModel,\n\t\t\tdiagnostics: sessionOptionDiagnostics,\n\t\t} = buildSessionOptions(\n\t\t\tparsed,\n\t\t\tscopedModels,\n\t\t\tsessionManager.buildSessionContext().messages.length > 0,\n\t\t\tmodelRegistry,\n\t\t\tsettingsManager,\n\t\t\tinherited, // SCRAMJET-DIVERGENCE: pass inherited model/thinkingLevel (issue 186)\n\t\t);\n\t\tdiagnostics.push(...sessionOptionDiagnostics);\n\n\t\tif (parsed.apiKey) {\n\t\t\tif (!sessionOptions.model) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: \"--api-key requires a model to be specified via --model, --provider/--model, or --models\",\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tauthStorage.setRuntimeApiKey(sessionOptions.model.provider, parsed.apiKey);\n\t\t\t}\n\t\t}\n\n\t\tconst created = await createAgentSessionFromServices({\n\t\t\tservices,\n\t\t\tsessionManager,\n\t\t\tsessionStartEvent,\n\t\t\tmodel: sessionOptions.model,\n\t\t\tthinkingLevel: sessionOptions.thinkingLevel,\n\t\t\tscopedModels: sessionOptions.scopedModels,\n\t\t\tcacheRetention: sessionOptions.cacheRetention,\n\t\t\ttools: sessionOptions.tools,\n\t\t\tnoTools: sessionOptions.noTools,\n\t\t\tcustomTools: sessionOptions.customTools,\n\t\t});\n\t\tconst cliThinkingOverride = parsed.thinking !== undefined || cliThinkingFromModel;\n\t\tif (created.session.model && cliThinkingOverride) {\n\t\t\tcreated.session.setThinkingLevel(created.session.thinkingLevel);\n\t\t}\n\n\t\treturn {\n\t\t\t...created,\n\t\t\tservices,\n\t\t\tdiagnostics,\n\t\t};\n\t};\n\ttime(\"createRuntime\");\n\tconst runtime = await createAgentSessionRuntime(createRuntime, {\n\t\tcwd: sessionManager.getCwd(),\n\t\tagentDir,\n\t\tsessionManager,\n\t}).catch((error: unknown) => {\n\t\t// SCRAMJET-DIVERGENCE: a required Scramjet builtin failure during candidate preparation aborts startup\n\t\t// before any productless AgentSession or session_start. Surface it as a fatal, product-attributed error\n\t\t// (retaining the original cause) with a non-zero exit, never an anonymous crash or the optional-extension\n\t\t// diagnostic path.\n\t\tif (isRequiredBuiltinInitError(error)) {\n\t\t\tconsole.error(chalk.red(`Error: ${error.message}`));\n\t\t\tconst detail = renderRequiredBuiltinInitCause(error);\n\t\t\tif (detail !== undefined) {\n\t\t\t\tconsole.error(chalk.dim(detail));\n\t\t\t}\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tthrow error;\n\t});\n\tconst { services, session, modelFallbackMessage } = runtime;\n\tconst { settingsManager, modelRegistry, resourceLoader } = services;\n\n\tif (parsed.help) {\n\t\tconst extensionFlags = resourceLoader\n\t\t\t.getExtensions()\n\t\t\t.extensions.flatMap((extension) => Array.from(extension.flags.values()));\n\t\tprintHelp(extensionFlags);\n\t\tprocess.exit(0);\n\t}\n\n\tif (parsed.listModels !== undefined) {\n\t\tconst searchPattern = typeof parsed.listModels === \"string\" ? parsed.listModels : undefined;\n\t\tawait listModels(modelRegistry, searchPattern);\n\t\tprocess.exit(0);\n\t}\n\n\t// Read piped stdin content (if any) - skip for RPC mode which uses stdin for JSON-RPC\n\tlet stdinContent: string | undefined;\n\tif (appMode !== \"rpc\") {\n\t\tstdinContent = await readPipedStdin();\n\t\tif (stdinContent !== undefined && appMode === \"interactive\") {\n\t\t\tappMode = \"print\";\n\t\t}\n\t}\n\ttime(\"readPipedStdin\");\n\n\tconst { initialMessage, initialImages } = await prepareInitialMessage(\n\t\tparsed,\n\t\tsettingsManager.getImageAutoResize(),\n\t\tstdinContent,\n\t);\n\ttime(\"prepareInitialMessage\");\n\tinitTheme(settingsManager.getTheme(), appMode === \"interactive\");\n\ttime(\"initTheme\");\n\n\t// Show deprecation warnings in interactive mode\n\tif (appMode === \"interactive\" && deprecationWarnings.length > 0) {\n\t\tawait showDeprecationWarnings(deprecationWarnings);\n\t}\n\n\ttime(\"resolveModelScope\");\n\treportDiagnostics(runtime.diagnostics);\n\tif (runtime.diagnostics.some((diagnostic) => diagnostic.type === \"error\")) {\n\t\tprocess.exit(1);\n\t}\n\ttime(\"createAgentSession\");\n\n\t// SCRAMJET-DIVERGENCE: Headless fallback warnings go to stderr, never JSON/RPC stdout.\n\tif (appMode !== \"interactive\" && !session.model) {\n\t\tconsole.error(chalk.red(modelFallbackMessage ?? formatNoModelsAvailableMessage()));\n\t\tprocess.exit(1);\n\t}\n\tif (appMode !== \"interactive\" && modelFallbackMessage) {\n\t\tconsole.error(chalk.yellow(`Warning: ${modelFallbackMessage}`));\n\t}\n\n\tconst startupBenchmark = isTruthyEnvFlag(process.env.PI_STARTUP_BENCHMARK);\n\tif (startupBenchmark && appMode !== \"interactive\") {\n\t\tconsole.error(chalk.red(\"Error: PI_STARTUP_BENCHMARK only supports interactive mode\"));\n\t\tprocess.exit(1);\n\t}\n\n\tif (appMode === \"rpc\") {\n\t\tprintTimings();\n\t\tawait runRpcMode(runtime);\n\t} else if (appMode === \"interactive\") {\n\t\tconst interactiveMode = new InteractiveMode(runtime, {\n\t\t\tmigratedProviders,\n\t\t\tmodelFallbackMessage,\n\t\t\tinitialMessage,\n\t\t\tinitialImages,\n\t\t\tinitialMessages: parsed.messages,\n\t\t\tverbose: parsed.verbose,\n\t\t});\n\t\tif (startupBenchmark) {\n\t\t\tawait interactiveMode.init();\n\t\t\ttime(\"interactiveMode.init\");\n\t\t\tprintTimings();\n\t\t\tinteractiveMode.stop();\n\t\t\tstopThemeWatcher();\n\t\t\tif (process.stdout.writableLength > 0) {\n\t\t\t\tawait new Promise<void>((resolve) => process.stdout.once(\"drain\", resolve));\n\t\t\t}\n\t\t\tif (process.stderr.writableLength > 0) {\n\t\t\t\tawait new Promise<void>((resolve) => process.stderr.once(\"drain\", resolve));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tprintTimings();\n\t\tawait interactiveMode.run();\n\t} else {\n\t\tprintTimings();\n\t\tconst exitCode = await runPrintMode(runtime, {\n\t\t\tmode: toPrintOutputMode(appMode),\n\t\t\tmessages: parsed.messages,\n\t\t\tinitialMessage,\n\t\t\tinitialImages,\n\t\t});\n\t\tstopThemeWatcher();\n\t\trestoreStdout();\n\t\tif (exitCode !== 0) {\n\t\t\tprocess.exitCode = exitCode;\n\t\t}\n\t\treturn;\n\t}\n}\n"]}
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAqB,KAAK,KAAK,EAAkB,MAAM,iBAAiB,CAAC;AAGhF,OAAO,EAAE,KAAK,IAAI,EAAmC,MAAM,eAAe,CAAC;AAO3E,OAAO,EACN,KAAK,6BAA6B,EAGlC,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAErD,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAEjF,OAAO,EAAE,KAAK,aAAa,EAAqC,MAAM,0BAA0B,CAAC;AACjG,OAAO,EAAsC,KAAK,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAGhG,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAQ/D,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AA0D7D,wBAAgB,gCAAgC,CAC/C,MAAM,EAAE,IAAI,EACZ,UAAU,EAAE,OAAO,EACnB,GAAG,GAAE,MAAM,CAAC,UAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqCpC;AAGD,wBAAgB,uBAAuB,CACtC,UAAU,EAAE,WAAW,CAAC,UAAU,CAAC,OAAO,gCAAgC,CAAC,CAAC,EAC5E,QAAQ,EAAE,MAAM,EAChB,aAAa,EAAE,aAAa,EAC5B,WAAW,EAAE,WAAW,GACtB,KAAK,CAAC,GAAG,CAAC,CAUZ;AAgMD,wBAAgB,mBAAmB,CAClC,MAAM,EAAE,IAAI,EACZ,YAAY,EAAE,WAAW,EAAE,EAC3B,kBAAkB,EAAE,OAAO,EAC3B,aAAa,EAAE,aAAa,EAC5B,eAAe,EAAE,eAAe,EAChC,SAAS,CAAC,EAAE;IAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAAC,aAAa,EAAE,aAAa,CAAA;CAAE,EAC/D,eAAe,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,GAC1B;IACF,OAAO,EAAE,yBAAyB,CAAC;IACnC,oBAAoB,EAAE,OAAO,CAAC;IAC9B,WAAW,EAAE,6BAA6B,EAAE,CAAC;CAC7C,CAqGA;AAyCD,MAAM,WAAW,WAAW;IAC3B,kBAAkB,CAAC,EAAE,gBAAgB,EAAE,CAAC;IACxC,WAAW,CAAC,EAAE,CAAC,EAAE,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACzD;AAED,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,WAAW,iBA8U/D","sourcesContent":["/**\n * Main entry point for the coding agent CLI.\n *\n * This file handles CLI argument parsing and translates them into\n * createAgentSession() options. The SDK does the heavy lifting.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { resolve } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { ThinkingLevel } from \"@leanandmean/agent\";\nimport { type ImageContent, type Model, modelsAreEqual } from \"@leanandmean/ai\";\nimport { ProcessTerminal, setKeybindings, TUI } from \"@leanandmean/tui\";\nimport chalk from \"chalk\";\nimport { type Args, type Mode, parseArgs, printHelp } from \"./cli/args.js\";\nimport { processFileArguments } from \"./cli/file-processor.js\";\nimport { buildInitialMessage, normalizePipedStdinContent } from \"./cli/initial-message.js\";\nimport { listModels } from \"./cli/list-models.js\";\nimport { selectSession } from \"./cli/session-picker.js\";\nimport { ENV_SESSION_DIR, expandTildePath, getAgentDir, VERSION } from \"./config.js\";\nimport { type CreateAgentSessionRuntimeFactory, createAgentSessionRuntime } from \"./core/agent-session-runtime.js\";\nimport {\n\ttype AgentSessionRuntimeDiagnostic,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./core/agent-session-services.js\";\nimport { formatNoModelsAvailableMessage } from \"./core/auth-guidance.js\";\nimport { AuthStorage } from \"./core/auth-storage.js\";\nimport { exportFromFile } from \"./core/export-html/index.js\";\nimport type { ExtensionAPI, ExtensionFactory } from \"./core/extensions/types.js\";\nimport { KeybindingsManager } from \"./core/keybindings.js\";\nimport { type ModelRegistry, validateInvocationModelDefinition } from \"./core/model-registry.js\";\nimport { resolveCliModel, resolveModelScope, type ScopedModel } from \"./core/model-resolver.js\";\nimport { restoreStdout, takeOverStdout } from \"./core/output-guard.js\";\nimport { isRequiredBuiltinInitError, renderRequiredBuiltinInitCause } from \"./core/resource-loader.js\";\nimport type { CreateAgentSessionOptions } from \"./core/sdk.js\";\nimport {\n\tformatMissingSessionCwdPrompt,\n\tgetMissingSessionCwdIssue,\n\tMissingSessionCwdError,\n\ttype SessionCwdIssue,\n} from \"./core/session-cwd.js\";\nimport { SessionManager } from \"./core/session-manager.js\";\nimport { SettingsManager } from \"./core/settings-manager.js\";\nimport { printTimings, resetTimings, time } from \"./core/timings.js\";\nimport { runMigrations, showDeprecationWarnings } from \"./migrations.js\";\nimport { InteractiveMode, runPrintMode, runRpcMode } from \"./modes/index.js\";\nimport { ExtensionSelectorComponent } from \"./modes/interactive/components/extension-selector.js\";\nimport { initTheme, stopThemeWatcher } from \"./modes/interactive/theme/theme.js\";\nimport { handleConfigCommand, handlePackageCommand } from \"./package-manager-cli.js\";\nimport { isLocalPath } from \"./utils/paths.js\";\n\n/**\n * Read all content from piped stdin.\n * Returns undefined if stdin is a TTY (interactive terminal).\n */\nasync function readPipedStdin(): Promise<string | undefined> {\n\t// If stdin is a TTY, we're running interactively - don't read stdin\n\tif (process.stdin.isTTY) {\n\t\treturn undefined;\n\t}\n\n\treturn new Promise((resolve) => {\n\t\tlet data = \"\";\n\t\tprocess.stdin.setEncoding(\"utf8\");\n\t\tprocess.stdin.on(\"data\", (chunk) => {\n\t\t\tdata += chunk;\n\t\t});\n\t\tprocess.stdin.on(\"end\", () => {\n\t\t\tresolve(normalizePipedStdinContent(data));\n\t\t});\n\t\tprocess.stdin.resume();\n\t});\n}\n\nfunction collectSettingsDiagnostics(\n\tsettingsManager: SettingsManager,\n\tcontext: string,\n): AgentSessionRuntimeDiagnostic[] {\n\treturn settingsManager.drainErrors().map(({ scope, error }) => ({\n\t\ttype: \"warning\",\n\t\tmessage: `(${context}, ${scope} settings) ${error.message}`,\n\t}));\n}\n\nfunction reportDiagnostics(diagnostics: readonly AgentSessionRuntimeDiagnostic[]): void {\n\tfor (const diagnostic of diagnostics) {\n\t\tconst color = diagnostic.type === \"error\" ? chalk.red : diagnostic.type === \"warning\" ? chalk.yellow : chalk.dim;\n\t\tconst prefix = diagnostic.type === \"error\" ? \"Error: \" : diagnostic.type === \"warning\" ? \"Warning: \" : \"\";\n\t\tconsole.error(color(`${prefix}${diagnostic.message}`));\n\t}\n}\n\nfunction isTruthyEnvFlag(value: string | undefined): boolean {\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ntype AppMode = \"interactive\" | \"print\" | \"json\" | \"rpc\";\n\n// SCRAMJET-DIVERGENCE: Resolve strict invocation inputs before runtime construction, without secret-bearing errors.\nexport function resolveInvocationModelDefinition(\n\tparsed: Args,\n\tstdinIsTTY: boolean,\n\tenv: NodeJS.ProcessEnv = process.env,\n) {\n\tif (parsed.help || parsed.version) return undefined;\n\tif (parsed.diagnostics.some((diagnostic) => diagnostic.type === \"error\")) {\n\t\tthrow new Error(\"--model-definition/--model-definition-env: correct the selector diagnostics before continuing.\");\n\t}\n\tif (parsed.modelDefinition === undefined && parsed.modelDefinitionEnv === undefined) return undefined;\n\tif (parsed.listModels === undefined && resolveAppMode(parsed, stdinIsTTY) === \"interactive\") {\n\t\tthrow new Error(\n\t\t\t\"--model-definition/--model-definition-env requires headless execution; use --print, --mode json, --mode rpc or redirected stdin.\",\n\t\t);\n\t}\n\tfunction readEnvironment(name: string, field: string): string {\n\t\tif (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n\t\t\tthrow new Error(`${field}: supply a valid environment variable identifier.`);\n\t\t}\n\t\tconst value = env[name];\n\t\tif (!value?.trim()) throw new Error(`${field}: set the named environment variable to a nonblank value.`);\n\t\treturn value;\n\t}\n\tconst json = parsed.modelDefinition ?? readEnvironment(parsed.modelDefinitionEnv!, \"--model-definition-env\");\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(json);\n\t} catch {\n\t\tthrow new Error(\n\t\t\t\"--model-definition/--model-definition-env: supply strict JSON without comments or trailing commas.\",\n\t\t);\n\t}\n\tlet definition: ReturnType<typeof validateInvocationModelDefinition>;\n\ttry {\n\t\tdefinition = validateInvocationModelDefinition(value);\n\t} catch (error) {\n\t\tthrow new Error(`--model-definition/--model-definition-env: ${(error as Error).message}`);\n\t}\n\tconst apiKey = parsed.listModels === undefined ? readEnvironment(definition.apiKeyEnv, \"apiKeyEnv\") : undefined;\n\treturn { definition, apiKey };\n}\n\n// SCRAMJET-DIVERGENCE: Install captured invocation routes after extension registrations, without storing secrets in models.\nexport function registerInvocationModel(\n\tinvocation: NonNullable<ReturnType<typeof resolveInvocationModelDefinition>>,\n\tprovider: string,\n\tmodelRegistry: ModelRegistry,\n\tauthStorage: AuthStorage,\n): Model<any> {\n\tif (modelRegistry.getAll().some((model) => model.provider === provider)) {\n\t\tthrow new Error(\"--model-definition: generated provider identity collided; retry the invocation.\");\n\t}\n\tconst { api, baseUrl, apiKeyEnv, ...model } = invocation.definition;\n\tmodelRegistry.registerProvider(provider, { api, baseUrl, apiKey: apiKeyEnv, models: [model] });\n\tif (invocation.apiKey !== undefined) authStorage.setRuntimeApiKey(provider, invocation.apiKey);\n\tconst registered = modelRegistry.find(provider, model.id);\n\tif (!registered) throw new Error(\"--model-definition: registration failed; correct the definition before retrying.\");\n\treturn registered;\n}\n\nfunction resolveAppMode(parsed: Args, stdinIsTTY: boolean): AppMode {\n\tif (parsed.mode === \"rpc\") {\n\t\treturn \"rpc\";\n\t}\n\tif (parsed.mode === \"json\") {\n\t\treturn \"json\";\n\t}\n\tif (parsed.print || !stdinIsTTY) {\n\t\treturn \"print\";\n\t}\n\treturn \"interactive\";\n}\n\nfunction toPrintOutputMode(appMode: AppMode): Exclude<Mode, \"rpc\"> {\n\treturn appMode === \"json\" ? \"json\" : \"text\";\n}\n\nasync function prepareInitialMessage(\n\tparsed: Args,\n\tautoResizeImages: boolean,\n\tstdinContent?: string,\n): Promise<{\n\tinitialMessage?: string;\n\tinitialImages?: ImageContent[];\n}> {\n\tif (parsed.fileArgs.length === 0) {\n\t\treturn buildInitialMessage({ parsed, stdinContent });\n\t}\n\n\tconst { text, images } = await processFileArguments(parsed.fileArgs, { autoResizeImages });\n\treturn buildInitialMessage({\n\t\tparsed,\n\t\tfileText: text,\n\t\tfileImages: images,\n\t\tstdinContent,\n\t});\n}\n\n/** Result from resolving a session argument */\ntype ResolvedSession =\n\t| { type: \"path\"; path: string } // Direct file path\n\t| { type: \"local\"; path: string } // Found in current project\n\t| { type: \"global\"; path: string; cwd: string } // Found in different project\n\t| { type: \"not_found\"; arg: string }; // Not found anywhere\n\n/**\n * Resolve a session argument to a file path.\n * If it looks like a path, use as-is. Otherwise try to match as session ID prefix.\n */\nasync function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?: string): Promise<ResolvedSession> {\n\t// If it looks like a file path, use as-is\n\tif (sessionArg.includes(\"/\") || sessionArg.includes(\"\\\\\") || sessionArg.endsWith(\".jsonl\")) {\n\t\treturn { type: \"path\", path: sessionArg };\n\t}\n\n\t// Try to match as session ID in current project first\n\tconst localSessions = await SessionManager.list(cwd, sessionDir);\n\tconst localMatches = localSessions.filter((s) => s.id.startsWith(sessionArg));\n\n\tif (localMatches.length >= 1) {\n\t\treturn { type: \"local\", path: localMatches[0].path };\n\t}\n\n\t// Try global search across all projects\n\tconst allSessions = await SessionManager.listAll();\n\tconst globalMatches = allSessions.filter((s) => s.id.startsWith(sessionArg));\n\n\tif (globalMatches.length >= 1) {\n\t\tconst match = globalMatches[0];\n\t\treturn { type: \"global\", path: match.path, cwd: match.cwd };\n\t}\n\n\t// Not found anywhere\n\treturn { type: \"not_found\", arg: sessionArg };\n}\n\n/** Prompt user for yes/no confirmation */\nasync function promptConfirm(message: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t});\n\t\trl.question(`${message} [y/N] `, (answer) => {\n\t\t\trl.close();\n\t\t\tresolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n\t\t});\n\t});\n}\n\nfunction validateForkFlags(parsed: Args): void {\n\tif (!parsed.fork) return;\n\n\tconst conflictingFlags = [\n\t\tparsed.session ? \"--session\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t\tparsed.noSession ? \"--no-session\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\n\tif (conflictingFlags.length > 0) {\n\t\tconsole.error(chalk.red(`Error: --fork cannot be combined with ${conflictingFlags.join(\", \")}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nfunction forkSessionOrExit(sourcePath: string, cwd: string, sessionDir?: string): SessionManager {\n\ttry {\n\t\treturn SessionManager.forkFrom(sourcePath, cwd, sessionDir);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nasync function createSessionManager(\n\tparsed: Args,\n\tcwd: string,\n\tsessionDir: string | undefined,\n\tsettingsManager: SettingsManager,\n): Promise<SessionManager> {\n\tif (parsed.noSession) {\n\t\treturn SessionManager.inMemory();\n\t}\n\n\tif (parsed.fork) {\n\t\tconst resolved = await resolveSessionPath(parsed.fork, cwd, sessionDir);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"path\":\n\t\t\tcase \"local\":\n\t\t\tcase \"global\":\n\t\t\t\treturn forkSessionOrExit(resolved.path, cwd, sessionDir);\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.session) {\n\t\tconst resolved = await resolveSessionPath(parsed.session, cwd, sessionDir);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"path\":\n\t\t\tcase \"local\":\n\t\t\t\treturn SessionManager.open(resolved.path, sessionDir);\n\n\t\t\tcase \"global\": {\n\t\t\t\tconsole.log(chalk.yellow(`Session found in different project: ${resolved.cwd}`));\n\t\t\t\tconst shouldFork = await promptConfirm(\"Fork this session into current directory?\");\n\t\t\t\tif (!shouldFork) {\n\t\t\t\t\tconsole.log(chalk.dim(\"Aborted.\"));\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t\treturn forkSessionOrExit(resolved.path, cwd, sessionDir);\n\t\t\t}\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.resume) {\n\t\tinitTheme(settingsManager.getTheme(), true);\n\t\ttry {\n\t\t\tconst selectedPath = await selectSession(\n\t\t\t\t(onProgress) => SessionManager.list(cwd, sessionDir, onProgress),\n\t\t\t\tSessionManager.listAll,\n\t\t\t);\n\t\t\tif (!selectedPath) {\n\t\t\t\tconsole.log(chalk.dim(\"No session selected\"));\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\treturn SessionManager.open(selectedPath, sessionDir);\n\t\t} finally {\n\t\t\tstopThemeWatcher();\n\t\t}\n\t}\n\n\tif (parsed.continue) {\n\t\treturn SessionManager.continueRecent(cwd, sessionDir);\n\t}\n\n\treturn SessionManager.create(cwd, sessionDir);\n}\n\n// SCRAMJET-DIVERGENCE: exported for direct unit testing (issue 186).\nexport function buildSessionOptions(\n\tparsed: Args,\n\tscopedModels: ScopedModel[],\n\thasExistingSession: boolean,\n\tmodelRegistry: ModelRegistry,\n\tsettingsManager: SettingsManager,\n\tinherited?: { model: Model<any>; thinkingLevel: ThinkingLevel },\n\tinvocationModel?: Model<any>,\n): {\n\toptions: CreateAgentSessionOptions;\n\tcliThinkingFromModel: boolean;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n} {\n\tconst options: CreateAgentSessionOptions = {};\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tlet cliThinkingFromModel = false;\n\n\t// SCRAMJET-DIVERGENCE: inherited model/thinkingLevel from the previous session takes highest\n\t// precedence, above CLI --model and scoped models. See issue 186.\n\tif (inherited) {\n\t\toptions.model = inherited.model;\n\t\toptions.thinkingLevel = inherited.thinkingLevel;\n\t}\n\n\t// SCRAMJET-DIVERGENCE: Invocation selection bypasses ordinary resolution and saved startup scopes.\n\tif (invocationModel) {\n\t\toptions.model ??= invocationModel;\n\t\toptions.persistModelPreferences = false;\n\t}\n\n\t// Model from CLI\n\t// - supports --provider <name> --model <pattern>\n\t// - supports --model <provider>/<pattern>\n\tif (!options.model && parsed.model) {\n\t\tconst resolved = resolveCliModel({\n\t\t\tcliProvider: parsed.provider,\n\t\t\tcliModel: parsed.model,\n\t\t\tmodelRegistry,\n\t\t});\n\t\tif (resolved.warning) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: resolved.warning });\n\t\t}\n\t\tif (resolved.error) {\n\t\t\tdiagnostics.push({ type: \"error\", message: resolved.error });\n\t\t}\n\t\tif (resolved.model) {\n\t\t\toptions.model = resolved.model;\n\t\t\t// Allow \"--model <pattern>:<thinking>\" as a shorthand.\n\t\t\t// Explicit --thinking still takes precedence (applied later).\n\t\t\tif (!parsed.thinking && resolved.thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = resolved.thinkingLevel;\n\t\t\t\tcliThinkingFromModel = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!options.model && scopedModels.length > 0 && !hasExistingSession) {\n\t\t// Check if saved default is in scoped models - use it if so, otherwise first scoped model\n\t\tconst savedProvider = settingsManager.getDefaultProvider();\n\t\tconst savedModelId = settingsManager.getDefaultModel();\n\t\tconst savedModel = savedProvider && savedModelId ? modelRegistry.find(savedProvider, savedModelId) : undefined;\n\t\tconst savedInScope = savedModel ? scopedModels.find((sm) => modelsAreEqual(sm.model, savedModel)) : undefined;\n\n\t\tif (savedInScope) {\n\t\t\toptions.model = savedInScope.model;\n\t\t\t// Use thinking level from scoped model config if explicitly set\n\t\t\tif (!parsed.thinking && savedInScope.thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = savedInScope.thinkingLevel;\n\t\t\t}\n\t\t} else {\n\t\t\toptions.model = scopedModels[0].model;\n\t\t\t// Use thinking level from first scoped model if explicitly set\n\t\t\tif (!parsed.thinking && scopedModels[0].thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = scopedModels[0].thinkingLevel;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Thinking level from CLI (takes precedence over scoped model thinking levels set above,\n\t// but NOT over inherited thinking level — SCRAMJET-DIVERGENCE: issue 186)\n\tif (options.thinkingLevel === undefined && parsed.thinking) {\n\t\toptions.thinkingLevel = parsed.thinking;\n\t}\n\n\t// Cache retention from CLI (PI_CACHE_RETENTION and the default are resolved by the SDK)\n\tif (parsed.cacheRetention) {\n\t\toptions.cacheRetention = parsed.cacheRetention;\n\t}\n\n\t// Scoped models for Ctrl+P cycling\n\t// Keep thinking level undefined when not explicitly set in the model pattern.\n\t// Undefined means \"inherit current session thinking level\" during cycling.\n\tif (scopedModels.length > 0) {\n\t\toptions.scopedModels = scopedModels.map((sm) => ({\n\t\t\tmodel: sm.model,\n\t\t\tthinkingLevel: sm.thinkingLevel,\n\t\t}));\n\t}\n\n\t// API key from CLI - set in authStorage\n\t// (handled by caller before createAgentSession)\n\n\t// Tools\n\tif (parsed.noTools) {\n\t\toptions.noTools = \"all\";\n\t} else if (parsed.noBuiltinTools) {\n\t\toptions.noTools = \"builtin\";\n\t}\n\tif (parsed.tools) {\n\t\toptions.tools = [...parsed.tools];\n\t}\n\n\treturn { options, cliThinkingFromModel, diagnostics };\n}\n\nfunction resolveCliPaths(cwd: string, paths: string[] | undefined): string[] | undefined {\n\treturn paths?.map((value) => (isLocalPath(value) ? resolve(cwd, value) : value));\n}\n\nasync function promptForMissingSessionCwd(\n\tissue: SessionCwdIssue,\n\tsettingsManager: SettingsManager,\n): Promise<string | undefined> {\n\tinitTheme(settingsManager.getTheme());\n\tsetKeybindings(KeybindingsManager.create());\n\n\treturn new Promise((resolve) => {\n\t\t// SCRAMJET-DIVERGENCE: shrink recovery is mandatory renderer behavior; no legacy toggle is applied (#389).\n\t\tconst ui = new TUI(new ProcessTerminal(), settingsManager.getShowHardwareCursor());\n\n\t\tlet settled = false;\n\t\tconst finish = (result: string | undefined) => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tui.stop();\n\t\t\tresolve(result);\n\t\t};\n\n\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\tformatMissingSessionCwdPrompt(issue),\n\t\t\t[\"Continue\", \"Cancel\"],\n\t\t\t(option) => finish(option === \"Continue\" ? issue.fallbackCwd : undefined),\n\t\t\t() => finish(undefined),\n\t\t\t{ tui: ui },\n\t\t);\n\t\tui.addChild(selector);\n\t\tui.setFocus(selector);\n\t\tui.start();\n\t});\n}\n\n// SCRAMJET-DIVERGENCE: added builtinInit for direct product wiring without extension discovery.\nexport interface MainOptions {\n\textensionFactories?: ExtensionFactory[];\n\tbuiltinInit?: (pi: ExtensionAPI) => void | Promise<void>;\n}\n\nexport async function main(args: string[], options?: MainOptions) {\n\tresetTimings();\n\t// SCRAMJET-DIVERGENCE: prefer SCRAMJET_OFFLINE, fall back to PI_OFFLINE.\n\tconst offlineMode =\n\t\targs.includes(\"--offline\") ||\n\t\tisTruthyEnvFlag(process.env.SCRAMJET_OFFLINE) ||\n\t\tisTruthyEnvFlag(process.env.PI_OFFLINE);\n\tif (offlineMode) {\n\t\tprocess.env.SCRAMJET_OFFLINE = \"1\";\n\t\tprocess.env.PI_OFFLINE = \"1\";\n\t\tprocess.env.PI_SKIP_VERSION_CHECK = \"1\";\n\t}\n\n\tif (await handlePackageCommand(args)) {\n\t\treturn;\n\t}\n\n\tif (await handleConfigCommand(args)) {\n\t\treturn;\n\t}\n\n\tconst parsed = parseArgs(args);\n\tif (parsed.diagnostics.length > 0) {\n\t\tfor (const d of parsed.diagnostics) {\n\t\t\tconst color = d.type === \"error\" ? chalk.red : chalk.yellow;\n\t\t\tconsole.error(color(`${d.type === \"error\" ? \"Error\" : \"Warning\"}: ${d.message}`));\n\t\t}\n\t\tif (parsed.diagnostics.some((d) => d.type === \"error\")) {\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\ttime(\"parseArgs\");\n\tlet appMode = resolveAppMode(parsed, process.stdin.isTTY);\n\tconst shouldTakeOverStdout = appMode !== \"interactive\";\n\tif (shouldTakeOverStdout) {\n\t\ttakeOverStdout();\n\t}\n\n\tif (parsed.version) {\n\t\tconsole.log(VERSION);\n\t\tprocess.exit(0);\n\t}\n\n\tlet invocation: ReturnType<typeof resolveInvocationModelDefinition>;\n\ttry {\n\t\tinvocation = resolveInvocationModelDefinition(parsed, process.stdin.isTTY);\n\t} catch (error) {\n\t\tconsole.error(chalk.red(`Error: ${(error as Error).message}`));\n\t\tprocess.exit(1);\n\t}\n\n\tif (parsed.export) {\n\t\tlet result: string;\n\t\ttry {\n\t\t\tconst outputPath = parsed.messages.length > 0 ? parsed.messages[0] : undefined;\n\t\t\tresult = await exportFromFile(parsed.export, outputPath);\n\t\t} catch (error: unknown) {\n\t\t\tconst message = error instanceof Error ? error.message : \"Failed to export session\";\n\t\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tconsole.log(`Exported to: ${result}`);\n\t\tprocess.exit(0);\n\t}\n\n\tif (parsed.mode === \"rpc\" && parsed.fileArgs.length > 0) {\n\t\tconsole.error(chalk.red(\"Error: @file arguments are not supported in RPC mode\"));\n\t\tprocess.exit(1);\n\t}\n\n\tvalidateForkFlags(parsed);\n\n\t// Run migrations (pass cwd for project-local migrations)\n\tconst { migratedAuthProviders: migratedProviders, deprecationWarnings } = runMigrations(process.cwd());\n\ttime(\"runMigrations\");\n\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst startupSettingsManager = SettingsManager.create(cwd, agentDir);\n\treportDiagnostics(collectSettingsDiagnostics(startupSettingsManager, \"startup session lookup\"));\n\n\t// Decide the final runtime cwd before creating cwd-bound runtime services.\n\t// --session and --resume may select a session from another project, so project-local\n\t// settings, resources, provider registrations, and models must be resolved only after\n\t// the target session cwd is known. The startup-cwd settings manager is used only for\n\t// sessionDir lookup during session selection.\n\tconst envSessionDir = process.env[ENV_SESSION_DIR];\n\tconst sessionDir =\n\t\tparsed.sessionDir ??\n\t\t(envSessionDir ? expandTildePath(envSessionDir) : undefined) ??\n\t\tstartupSettingsManager.getSessionDir();\n\tlet sessionManager = await createSessionManager(parsed, cwd, sessionDir, startupSettingsManager);\n\tconst missingSessionCwdIssue = getMissingSessionCwdIssue(sessionManager, cwd);\n\tif (missingSessionCwdIssue) {\n\t\tif (appMode === \"interactive\") {\n\t\t\tconst selectedCwd = await promptForMissingSessionCwd(missingSessionCwdIssue, startupSettingsManager);\n\t\t\tif (!selectedCwd) {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\tsessionManager = SessionManager.open(missingSessionCwdIssue.sessionFile!, sessionDir, selectedCwd);\n\t\t} else {\n\t\t\tconsole.error(chalk.red(new MissingSessionCwdError(missingSessionCwdIssue).message));\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\ttime(\"createSessionManager\");\n\n\tconst resolvedExtensionPaths = resolveCliPaths(cwd, parsed.extensions);\n\tconst resolvedSkillPaths = resolveCliPaths(cwd, parsed.skills);\n\tconst resolvedPromptTemplatePaths = resolveCliPaths(cwd, parsed.promptTemplates);\n\tconst resolvedThemePaths = resolveCliPaths(cwd, parsed.themes);\n\tconst authStorage = AuthStorage.create();\n\tconst invocationProvider = invocation ? `invocation-${randomUUID()}` : undefined;\n\tconst createRuntime: CreateAgentSessionRuntimeFactory = async ({\n\t\tcwd,\n\t\tagentDir,\n\t\tsessionManager,\n\t\tsessionStartEvent,\n\t\tinherited, // SCRAMJET-DIVERGENCE: forward inherited model/thinkingLevel (issue 186)\n\t}) => {\n\t\tconst services = await createAgentSessionServices({\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tauthStorage,\n\t\t\textensionFlagValues: parsed.unknownFlags,\n\t\t\tresourceLoaderOptions: {\n\t\t\t\tadditionalExtensionPaths: resolvedExtensionPaths,\n\t\t\t\tadditionalSkillPaths: resolvedSkillPaths,\n\t\t\t\tadditionalPromptTemplatePaths: resolvedPromptTemplatePaths,\n\t\t\t\tadditionalThemePaths: resolvedThemePaths,\n\t\t\t\tnoExtensions: parsed.noExtensions,\n\t\t\t\tnoSkills: parsed.noSkills,\n\t\t\t\tnoPromptTemplates: parsed.noPromptTemplates,\n\t\t\t\tnoThemes: parsed.noThemes,\n\t\t\t\tnoContextFiles: parsed.noContextFiles,\n\t\t\t\tsystemPrompt: parsed.systemPrompt,\n\t\t\t\tappendSystemPrompt: parsed.appendSystemPrompt,\n\t\t\t\textensionFactories: options?.extensionFactories,\n\t\t\t\tbuiltinInit: options?.builtinInit,\n\t\t\t},\n\t\t});\n\t\tconst { settingsManager, modelRegistry, resourceLoader } = services;\n\t\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [\n\t\t\t...services.diagnostics,\n\t\t\t...collectSettingsDiagnostics(settingsManager, \"runtime creation\"),\n\t\t\t...resourceLoader.getExtensions().errors.map(({ path, error }) => ({\n\t\t\t\ttype: \"error\" as const,\n\t\t\t\tmessage: `Failed to load extension \"${path}\": ${error}`,\n\t\t\t})),\n\t\t];\n\n\t\tconst invocationModel = invocation\n\t\t\t? registerInvocationModel(invocation, invocationProvider!, modelRegistry, authStorage)\n\t\t\t: undefined;\n\t\tconst modelPatterns = invocation ? undefined : (parsed.models ?? settingsManager.getEnabledModels());\n\t\tconst scopedModels =\n\t\t\tmodelPatterns && modelPatterns.length > 0 ? await resolveModelScope(modelPatterns, modelRegistry) : [];\n\t\tconst {\n\t\t\toptions: sessionOptions,\n\t\t\tcliThinkingFromModel,\n\t\t\tdiagnostics: sessionOptionDiagnostics,\n\t\t} = buildSessionOptions(\n\t\t\tparsed,\n\t\t\tscopedModels,\n\t\t\tsessionManager.buildSessionContext().messages.length > 0,\n\t\t\tmodelRegistry,\n\t\t\tsettingsManager,\n\t\t\tinherited, // SCRAMJET-DIVERGENCE: pass inherited model/thinkingLevel (issue 186)\n\t\t\tinvocationModel,\n\t\t);\n\t\tdiagnostics.push(...sessionOptionDiagnostics);\n\n\t\tif (parsed.apiKey) {\n\t\t\tif (!sessionOptions.model) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: \"--api-key requires a model to be specified via --model, --provider/--model, or --models\",\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tauthStorage.setRuntimeApiKey(sessionOptions.model.provider, parsed.apiKey);\n\t\t\t}\n\t\t}\n\n\t\tconst created = await createAgentSessionFromServices({\n\t\t\tservices,\n\t\t\tsessionManager,\n\t\t\tsessionStartEvent,\n\t\t\tmodel: sessionOptions.model,\n\t\t\tpersistModelPreferences: sessionOptions.persistModelPreferences,\n\t\t\tthinkingLevel: sessionOptions.thinkingLevel,\n\t\t\tscopedModels: sessionOptions.scopedModels,\n\t\t\tcacheRetention: sessionOptions.cacheRetention,\n\t\t\ttools: sessionOptions.tools,\n\t\t\tnoTools: sessionOptions.noTools,\n\t\t\tcustomTools: sessionOptions.customTools,\n\t\t});\n\t\tconst cliThinkingOverride = parsed.thinking !== undefined || cliThinkingFromModel;\n\t\tif (created.session.model && cliThinkingOverride) {\n\t\t\tcreated.session.setThinkingLevel(created.session.thinkingLevel);\n\t\t}\n\n\t\treturn {\n\t\t\t...created,\n\t\t\tservices,\n\t\t\tdiagnostics,\n\t\t};\n\t};\n\ttime(\"createRuntime\");\n\tconst runtime = await createAgentSessionRuntime(createRuntime, {\n\t\tcwd: sessionManager.getCwd(),\n\t\tagentDir,\n\t\tsessionManager,\n\t}).catch((error: unknown) => {\n\t\t// SCRAMJET-DIVERGENCE: a required Scramjet builtin failure during candidate preparation aborts startup\n\t\t// before any productless AgentSession or session_start. Surface it as a fatal, product-attributed error\n\t\t// (retaining the original cause) with a non-zero exit, never an anonymous crash or the optional-extension\n\t\t// diagnostic path.\n\t\tif (isRequiredBuiltinInitError(error)) {\n\t\t\tconsole.error(chalk.red(`Error: ${error.message}`));\n\t\t\tconst detail = renderRequiredBuiltinInitCause(error);\n\t\t\tif (detail !== undefined) {\n\t\t\t\tconsole.error(chalk.dim(detail));\n\t\t\t}\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tthrow error;\n\t});\n\tconst { services, session, modelFallbackMessage } = runtime;\n\tconst { settingsManager, modelRegistry, resourceLoader } = services;\n\n\tif (parsed.help) {\n\t\tconst extensionFlags = resourceLoader\n\t\t\t.getExtensions()\n\t\t\t.extensions.flatMap((extension) => Array.from(extension.flags.values()));\n\t\tprintHelp(extensionFlags);\n\t\tprocess.exit(0);\n\t}\n\n\tif (parsed.listModels !== undefined) {\n\t\tconst searchPattern = typeof parsed.listModels === \"string\" ? parsed.listModels : undefined;\n\t\tawait listModels(modelRegistry, searchPattern);\n\t\tprocess.exit(0);\n\t}\n\n\t// Read piped stdin content (if any) - skip for RPC mode which uses stdin for JSON-RPC\n\tlet stdinContent: string | undefined;\n\tif (appMode !== \"rpc\") {\n\t\tstdinContent = await readPipedStdin();\n\t\tif (stdinContent !== undefined && appMode === \"interactive\") {\n\t\t\tappMode = \"print\";\n\t\t}\n\t}\n\ttime(\"readPipedStdin\");\n\n\tconst { initialMessage, initialImages } = await prepareInitialMessage(\n\t\tparsed,\n\t\tsettingsManager.getImageAutoResize(),\n\t\tstdinContent,\n\t);\n\ttime(\"prepareInitialMessage\");\n\tinitTheme(settingsManager.getTheme(), appMode === \"interactive\");\n\ttime(\"initTheme\");\n\n\t// Show deprecation warnings in interactive mode\n\tif (appMode === \"interactive\" && deprecationWarnings.length > 0) {\n\t\tawait showDeprecationWarnings(deprecationWarnings);\n\t}\n\n\ttime(\"resolveModelScope\");\n\treportDiagnostics(runtime.diagnostics);\n\tif (runtime.diagnostics.some((diagnostic) => diagnostic.type === \"error\")) {\n\t\tprocess.exit(1);\n\t}\n\ttime(\"createAgentSession\");\n\n\t// SCRAMJET-DIVERGENCE: Headless fallback warnings go to stderr, never JSON/RPC stdout.\n\tif (appMode !== \"interactive\" && !session.model) {\n\t\tconsole.error(chalk.red(modelFallbackMessage ?? formatNoModelsAvailableMessage()));\n\t\tprocess.exit(1);\n\t}\n\tif (appMode !== \"interactive\" && modelFallbackMessage) {\n\t\tconsole.error(chalk.yellow(`Warning: ${modelFallbackMessage}`));\n\t}\n\n\tconst startupBenchmark = isTruthyEnvFlag(process.env.PI_STARTUP_BENCHMARK);\n\tif (startupBenchmark && appMode !== \"interactive\") {\n\t\tconsole.error(chalk.red(\"Error: PI_STARTUP_BENCHMARK only supports interactive mode\"));\n\t\tprocess.exit(1);\n\t}\n\n\tif (appMode === \"rpc\") {\n\t\tprintTimings();\n\t\tawait runRpcMode(runtime);\n\t} else if (appMode === \"interactive\") {\n\t\tconst interactiveMode = new InteractiveMode(runtime, {\n\t\t\tmigratedProviders,\n\t\t\tmodelFallbackMessage,\n\t\t\tinitialMessage,\n\t\t\tinitialImages,\n\t\t\tinitialMessages: parsed.messages,\n\t\t\tverbose: parsed.verbose,\n\t\t});\n\t\tif (startupBenchmark) {\n\t\t\tawait interactiveMode.init();\n\t\t\ttime(\"interactiveMode.init\");\n\t\t\tprintTimings();\n\t\t\tinteractiveMode.stop();\n\t\t\tstopThemeWatcher();\n\t\t\tif (process.stdout.writableLength > 0) {\n\t\t\t\tawait new Promise<void>((resolve) => process.stdout.once(\"drain\", resolve));\n\t\t\t}\n\t\t\tif (process.stderr.writableLength > 0) {\n\t\t\t\tawait new Promise<void>((resolve) => process.stderr.once(\"drain\", resolve));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tprintTimings();\n\t\tawait interactiveMode.run();\n\t} else {\n\t\tprintTimings();\n\t\tconst exitCode = await runPrintMode(runtime, {\n\t\t\tmode: toPrintOutputMode(appMode),\n\t\t\tmessages: parsed.messages,\n\t\t\tinitialMessage,\n\t\t\tinitialImages,\n\t\t});\n\t\tstopThemeWatcher();\n\t\trestoreStdout();\n\t\tif (exitCode !== 0) {\n\t\t\tprocess.exitCode = exitCode;\n\t\t}\n\t\treturn;\n\t}\n}\n"]}
package/dist/main.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * This file handles CLI argument parsing and translates them into
5
5
  * createAgentSession() options. The SDK does the heavy lifting.
6
6
  */
7
+ import { randomUUID } from "node:crypto";
7
8
  import { resolve } from "node:path";
8
9
  import { createInterface } from "node:readline";
9
10
  import { modelsAreEqual } from "@leanandmean/ai";
@@ -21,6 +22,7 @@ import { formatNoModelsAvailableMessage } from "./core/auth-guidance.js";
21
22
  import { AuthStorage } from "./core/auth-storage.js";
22
23
  import { exportFromFile } from "./core/export-html/index.js";
23
24
  import { KeybindingsManager } from "./core/keybindings.js";
25
+ import { validateInvocationModelDefinition } from "./core/model-registry.js";
24
26
  import { resolveCliModel, resolveModelScope } from "./core/model-resolver.js";
25
27
  import { restoreStdout, takeOverStdout } from "./core/output-guard.js";
26
28
  import { isRequiredBuiltinInitError, renderRequiredBuiltinInitCause } from "./core/resource-loader.js";
@@ -73,6 +75,59 @@ function isTruthyEnvFlag(value) {
73
75
  return false;
74
76
  return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes";
75
77
  }
78
+ // SCRAMJET-DIVERGENCE: Resolve strict invocation inputs before runtime construction, without secret-bearing errors.
79
+ export function resolveInvocationModelDefinition(parsed, stdinIsTTY, env = process.env) {
80
+ if (parsed.help || parsed.version)
81
+ return undefined;
82
+ if (parsed.diagnostics.some((diagnostic) => diagnostic.type === "error")) {
83
+ throw new Error("--model-definition/--model-definition-env: correct the selector diagnostics before continuing.");
84
+ }
85
+ if (parsed.modelDefinition === undefined && parsed.modelDefinitionEnv === undefined)
86
+ return undefined;
87
+ if (parsed.listModels === undefined && resolveAppMode(parsed, stdinIsTTY) === "interactive") {
88
+ throw new Error("--model-definition/--model-definition-env requires headless execution; use --print, --mode json, --mode rpc or redirected stdin.");
89
+ }
90
+ function readEnvironment(name, field) {
91
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
92
+ throw new Error(`${field}: supply a valid environment variable identifier.`);
93
+ }
94
+ const value = env[name];
95
+ if (!value?.trim())
96
+ throw new Error(`${field}: set the named environment variable to a nonblank value.`);
97
+ return value;
98
+ }
99
+ const json = parsed.modelDefinition ?? readEnvironment(parsed.modelDefinitionEnv, "--model-definition-env");
100
+ let value;
101
+ try {
102
+ value = JSON.parse(json);
103
+ }
104
+ catch {
105
+ throw new Error("--model-definition/--model-definition-env: supply strict JSON without comments or trailing commas.");
106
+ }
107
+ let definition;
108
+ try {
109
+ definition = validateInvocationModelDefinition(value);
110
+ }
111
+ catch (error) {
112
+ throw new Error(`--model-definition/--model-definition-env: ${error.message}`);
113
+ }
114
+ const apiKey = parsed.listModels === undefined ? readEnvironment(definition.apiKeyEnv, "apiKeyEnv") : undefined;
115
+ return { definition, apiKey };
116
+ }
117
+ // SCRAMJET-DIVERGENCE: Install captured invocation routes after extension registrations, without storing secrets in models.
118
+ export function registerInvocationModel(invocation, provider, modelRegistry, authStorage) {
119
+ if (modelRegistry.getAll().some((model) => model.provider === provider)) {
120
+ throw new Error("--model-definition: generated provider identity collided; retry the invocation.");
121
+ }
122
+ const { api, baseUrl, apiKeyEnv, ...model } = invocation.definition;
123
+ modelRegistry.registerProvider(provider, { api, baseUrl, apiKey: apiKeyEnv, models: [model] });
124
+ if (invocation.apiKey !== undefined)
125
+ authStorage.setRuntimeApiKey(provider, invocation.apiKey);
126
+ const registered = modelRegistry.find(provider, model.id);
127
+ if (!registered)
128
+ throw new Error("--model-definition: registration failed; correct the definition before retrying.");
129
+ return registered;
130
+ }
76
131
  function resolveAppMode(parsed, stdinIsTTY) {
77
132
  if (parsed.mode === "rpc") {
78
133
  return "rpc";
@@ -218,7 +273,7 @@ async function createSessionManager(parsed, cwd, sessionDir, settingsManager) {
218
273
  return SessionManager.create(cwd, sessionDir);
219
274
  }
220
275
  // SCRAMJET-DIVERGENCE: exported for direct unit testing (issue 186).
221
- export function buildSessionOptions(parsed, scopedModels, hasExistingSession, modelRegistry, settingsManager, inherited) {
276
+ export function buildSessionOptions(parsed, scopedModels, hasExistingSession, modelRegistry, settingsManager, inherited, invocationModel) {
222
277
  const options = {};
223
278
  const diagnostics = [];
224
279
  let cliThinkingFromModel = false;
@@ -228,6 +283,11 @@ export function buildSessionOptions(parsed, scopedModels, hasExistingSession, mo
228
283
  options.model = inherited.model;
229
284
  options.thinkingLevel = inherited.thinkingLevel;
230
285
  }
286
+ // SCRAMJET-DIVERGENCE: Invocation selection bypasses ordinary resolution and saved startup scopes.
287
+ if (invocationModel) {
288
+ options.model ??= invocationModel;
289
+ options.persistModelPreferences = false;
290
+ }
231
291
  // Model from CLI
232
292
  // - supports --provider <name> --model <pattern>
233
293
  // - supports --model <provider>/<pattern>
@@ -367,6 +427,14 @@ export async function main(args, options) {
367
427
  console.log(VERSION);
368
428
  process.exit(0);
369
429
  }
430
+ let invocation;
431
+ try {
432
+ invocation = resolveInvocationModelDefinition(parsed, process.stdin.isTTY);
433
+ }
434
+ catch (error) {
435
+ console.error(chalk.red(`Error: ${error.message}`));
436
+ process.exit(1);
437
+ }
370
438
  if (parsed.export) {
371
439
  let result;
372
440
  try {
@@ -423,6 +491,7 @@ export async function main(args, options) {
423
491
  const resolvedPromptTemplatePaths = resolveCliPaths(cwd, parsed.promptTemplates);
424
492
  const resolvedThemePaths = resolveCliPaths(cwd, parsed.themes);
425
493
  const authStorage = AuthStorage.create();
494
+ const invocationProvider = invocation ? `invocation-${randomUUID()}` : undefined;
426
495
  const createRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent, inherited, // SCRAMJET-DIVERGENCE: forward inherited model/thinkingLevel (issue 186)
427
496
  }) => {
428
497
  const services = await createAgentSessionServices({
@@ -455,9 +524,13 @@ export async function main(args, options) {
455
524
  message: `Failed to load extension "${path}": ${error}`,
456
525
  })),
457
526
  ];
458
- const modelPatterns = parsed.models ?? settingsManager.getEnabledModels();
527
+ const invocationModel = invocation
528
+ ? registerInvocationModel(invocation, invocationProvider, modelRegistry, authStorage)
529
+ : undefined;
530
+ const modelPatterns = invocation ? undefined : (parsed.models ?? settingsManager.getEnabledModels());
459
531
  const scopedModels = modelPatterns && modelPatterns.length > 0 ? await resolveModelScope(modelPatterns, modelRegistry) : [];
460
- const { options: sessionOptions, cliThinkingFromModel, diagnostics: sessionOptionDiagnostics, } = buildSessionOptions(parsed, scopedModels, sessionManager.buildSessionContext().messages.length > 0, modelRegistry, settingsManager, inherited);
532
+ const { options: sessionOptions, cliThinkingFromModel, diagnostics: sessionOptionDiagnostics, } = buildSessionOptions(parsed, scopedModels, sessionManager.buildSessionContext().messages.length > 0, modelRegistry, settingsManager, inherited, // SCRAMJET-DIVERGENCE: pass inherited model/thinkingLevel (issue 186)
533
+ invocationModel);
461
534
  diagnostics.push(...sessionOptionDiagnostics);
462
535
  if (parsed.apiKey) {
463
536
  if (!sessionOptions.model) {
@@ -475,6 +548,7 @@ export async function main(args, options) {
475
548
  sessionManager,
476
549
  sessionStartEvent,
477
550
  model: sessionOptions.model,
551
+ persistModelPreferences: sessionOptions.persistModelPreferences,
478
552
  thinkingLevel: sessionOptions.thinkingLevel,
479
553
  scopedModels: sessionOptions.scopedModels,
480
554
  cacheRetention: sessionOptions.cacheRetention,