@superatomai/sdk-node 0.0.90-dsp → 0.0.92-dsp

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -5734,8 +5734,22 @@ interface CodexSessionOptions extends CodingAgentSessionOptions {
5734
5734
  * drops the rest without a word; composed instructions run past that, losing their closing rules.
5735
5735
  */
5736
5736
  declare const CODEX_DOC_MAX_BYTES: number;
5737
+ /** The env var codex reads the OpenRouter key from: the driver passes only CODEX_* and OPENAI_* through. */
5738
+ declare const CODEX_OPENROUTER_KEY_ENV = "CODEX_OPENROUTER_API_KEY";
5739
+ interface CodexProvider {
5740
+ config: Record<string, unknown>;
5741
+ env: Record<string, string>;
5742
+ }
5743
+ /**
5744
+ * OpenRouter by default, on the deployment's OPENROUTER_API_KEY and through the Superatom proxy when
5745
+ * set, so no VM needs its own codex config or login. A provider chosen in config.toml, or
5746
+ * CODEX_MODEL_PROVIDER naming another (e.g. `chatgpt` for a `codex login`), is left alone.
5747
+ */
5748
+ declare function codexDefaultProvider(env?: NodeJS.ProcessEnv, configToml?: string): CodexProvider | null;
5749
+ /** OpenRouter names models by vendor: `gpt-6-luna` there is `openai/gpt-6-luna`. */
5750
+ declare function codexModelFor(model: string | undefined, provider: CodexProvider | null): string | undefined;
5737
5751
  /** The `--config` overrides for one run: per run, so no host's config.toml decides them. */
5738
- declare function codexRunConfig(opts: Pick<CodexSessionOptions, 'mcpServers' | 'instructionsFile' | 'extraConfig'>): Record<string, unknown>;
5752
+ declare function codexRunConfig(opts: Pick<CodexSessionOptions, 'mcpServers' | 'instructionsFile' | 'extraConfig'>, provider?: CodexProvider | null): Record<string, unknown>;
5739
5753
  declare function createCodexSession(opts: CodexSessionOptions): CodingAgentSession;
5740
5754
 
5741
5755
  /**
@@ -6840,4 +6854,4 @@ declare class SuperatomSDK {
6840
6854
  getConversationSimilarityThreshold(): number;
6841
6855
  }
6842
6856
 
6843
- export { ALL_COLUMN_KEYS, ANSWER_COMPONENT_NAMES, type AgentConfig, type AgentEvent, type AgentResponse, type AgentRunContext, type AgentRunHandlers, type AgentRunRecord, type AgentRunResult, type AgentTrigger, type AgentUsage, type AnalyticsEventType, type AnalyticsStatus, type AnswerProvider, type AnswerProviderContext, type ApplySummary, BM25L, type BM25LOptions, type BaseLLMConfig, type BuildTriggerInput, CATEGORY_KEYS, CODEX_DOC_MAX_BYTES, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CodexSessionOptions, type CodingAgentCollectionConfig, type CodingAgentDefinition, type CodingAgentSession, type CodingAgentSessionOptions, type CodingAgentsConfig, type ColInfo, type ColType, type CollectionHandler, type CollectionOperation, type Component, type ConstraintFilter, type ConstraintOp, type ConstraintPolicy, type DBUIBlock, DEFAULT_AGENT_CONFIG, DEFAULT_FMT_CONFIG, type DashboardAgentCollectionConfig, type DatabaseType, type FindingCode, type Fmt, type FmtConfig, type GeneratedFile, type GraphVersion, type Harness, type HybridSearchOptions, INSTRUCTIONS_FILE, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type McpServerSpec, type Message, MissingRequestContextError, type ModelStrategy, NUMERIC_KEYS, type NarrationUpdate, type OutputContract, type OutputField, type OutputValidator, type PiSessionListener, type PiSessionState, type PiTranscriptEntry, type PolicyException, type PolicyExceptionTable, type Principal, type PromptAttachment, type PromptContext, type RequestContext, type RerankedResult, type ResolvedAccess, type RowFilter, type RunAgentOptions, STORAGE_CONFIG, type ScriptComponentSpec, ScriptMatcher, type ScriptParameter, type ScriptRecipe, type ScriptRecipeMetaRow, type ScriptRecipeStore, type ScriptResult, ScriptStore, type ScriptStoreOptions, type SelectedWorkflow, type ShimDef, type ShimSummary, type ShimTarget, type SourcePolicy, type SpecToValidate, SuperatomSDK, type SuperatomSDKConfig, type T_RESPONSE, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, type TriggerEvent, type TriggerFireInfo, UIBlock, UILogCollector, type User, UserManager, type UsersData, type ValidationContext, type ValidationFinding, type WorkflowDescriptor, type Workspace, accessFromConfig, analyticsClient, answerCatalogForBinding, answerComponents, anthropicLLM, assertReadOnlySql, bindContext, bridgePreamble, captureContext, clearContextTokens, codexRunConfig, constraintPoliciesFromConfig, contextTokenCount, createCodexSession, createCodingAgentSession, dashboardConversationHistory, dataFingerprint, describeContext, describeTriggers, emitAgentEvent, extractNamedExport, formatFindingsForAgent, geminiLLM, getCodingAgent, getCodingAgentsConfig, getPiSessionState, getRequestContext, groqLLM, hybridRerank, inferColumns, isUserContext, listCodingAgents, llmUsageLogger, logger, makeFmt, mintContextToken, normalizeScriptBody, onAgentRun, onPiSessionUpdate, openaiLLM, policiesFromConfig, projectForDatasetBinding, promptLoader, queryCache, registerCodingAgentCollection, registerCodingAgents, registerDashboardAgentCollection, requireRequestContext, rerankChromaResults, rerankConversationResults, resolveContextToken, resolveScriptRecipeStore, revokeContextToken, runAsSystem, runAsUser, runCodingAgent, runScript, runWithContext, runWithMessageIdentity, startAgentTriggers, stopAgentTriggers, userPromptErrorLogger, validateComponentSpec, withCapturedContext, writeBridgeShims, writeShims };
6857
+ export { ALL_COLUMN_KEYS, ANSWER_COMPONENT_NAMES, type AgentConfig, type AgentEvent, type AgentResponse, type AgentRunContext, type AgentRunHandlers, type AgentRunRecord, type AgentRunResult, type AgentTrigger, type AgentUsage, type AnalyticsEventType, type AnalyticsStatus, type AnswerProvider, type AnswerProviderContext, type ApplySummary, BM25L, type BM25LOptions, type BaseLLMConfig, type BuildTriggerInput, CATEGORY_KEYS, CODEX_DOC_MAX_BYTES, CODEX_OPENROUTER_KEY_ENV, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CodexProvider, type CodexSessionOptions, type CodingAgentCollectionConfig, type CodingAgentDefinition, type CodingAgentSession, type CodingAgentSessionOptions, type CodingAgentsConfig, type ColInfo, type ColType, type CollectionHandler, type CollectionOperation, type Component, type ConstraintFilter, type ConstraintOp, type ConstraintPolicy, type DBUIBlock, DEFAULT_AGENT_CONFIG, DEFAULT_FMT_CONFIG, type DashboardAgentCollectionConfig, type DatabaseType, type FindingCode, type Fmt, type FmtConfig, type GeneratedFile, type GraphVersion, type Harness, type HybridSearchOptions, INSTRUCTIONS_FILE, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type McpServerSpec, type Message, MissingRequestContextError, type ModelStrategy, NUMERIC_KEYS, type NarrationUpdate, type OutputContract, type OutputField, type OutputValidator, type PiSessionListener, type PiSessionState, type PiTranscriptEntry, type PolicyException, type PolicyExceptionTable, type Principal, type PromptAttachment, type PromptContext, type RequestContext, type RerankedResult, type ResolvedAccess, type RowFilter, type RunAgentOptions, STORAGE_CONFIG, type ScriptComponentSpec, ScriptMatcher, type ScriptParameter, type ScriptRecipe, type ScriptRecipeMetaRow, type ScriptRecipeStore, type ScriptResult, ScriptStore, type ScriptStoreOptions, type SelectedWorkflow, type ShimDef, type ShimSummary, type ShimTarget, type SourcePolicy, type SpecToValidate, SuperatomSDK, type SuperatomSDKConfig, type T_RESPONSE, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, type TriggerEvent, type TriggerFireInfo, UIBlock, UILogCollector, type User, UserManager, type UsersData, type ValidationContext, type ValidationFinding, type WorkflowDescriptor, type Workspace, accessFromConfig, analyticsClient, answerCatalogForBinding, answerComponents, anthropicLLM, assertReadOnlySql, bindContext, bridgePreamble, captureContext, clearContextTokens, codexDefaultProvider, codexModelFor, codexRunConfig, constraintPoliciesFromConfig, contextTokenCount, createCodexSession, createCodingAgentSession, dashboardConversationHistory, dataFingerprint, describeContext, describeTriggers, emitAgentEvent, extractNamedExport, formatFindingsForAgent, geminiLLM, getCodingAgent, getCodingAgentsConfig, getPiSessionState, getRequestContext, groqLLM, hybridRerank, inferColumns, isUserContext, listCodingAgents, llmUsageLogger, logger, makeFmt, mintContextToken, normalizeScriptBody, onAgentRun, onPiSessionUpdate, openaiLLM, policiesFromConfig, projectForDatasetBinding, promptLoader, queryCache, registerCodingAgentCollection, registerCodingAgents, registerDashboardAgentCollection, requireRequestContext, rerankChromaResults, rerankConversationResults, resolveContextToken, resolveScriptRecipeStore, revokeContextToken, runAsSystem, runAsUser, runCodingAgent, runScript, runWithContext, runWithMessageIdentity, startAgentTriggers, stopAgentTriggers, userPromptErrorLogger, validateComponentSpec, withCapturedContext, writeBridgeShims, writeShims };
package/dist/index.d.ts CHANGED
@@ -5734,8 +5734,22 @@ interface CodexSessionOptions extends CodingAgentSessionOptions {
5734
5734
  * drops the rest without a word; composed instructions run past that, losing their closing rules.
5735
5735
  */
5736
5736
  declare const CODEX_DOC_MAX_BYTES: number;
5737
+ /** The env var codex reads the OpenRouter key from: the driver passes only CODEX_* and OPENAI_* through. */
5738
+ declare const CODEX_OPENROUTER_KEY_ENV = "CODEX_OPENROUTER_API_KEY";
5739
+ interface CodexProvider {
5740
+ config: Record<string, unknown>;
5741
+ env: Record<string, string>;
5742
+ }
5743
+ /**
5744
+ * OpenRouter by default, on the deployment's OPENROUTER_API_KEY and through the Superatom proxy when
5745
+ * set, so no VM needs its own codex config or login. A provider chosen in config.toml, or
5746
+ * CODEX_MODEL_PROVIDER naming another (e.g. `chatgpt` for a `codex login`), is left alone.
5747
+ */
5748
+ declare function codexDefaultProvider(env?: NodeJS.ProcessEnv, configToml?: string): CodexProvider | null;
5749
+ /** OpenRouter names models by vendor: `gpt-6-luna` there is `openai/gpt-6-luna`. */
5750
+ declare function codexModelFor(model: string | undefined, provider: CodexProvider | null): string | undefined;
5737
5751
  /** The `--config` overrides for one run: per run, so no host's config.toml decides them. */
5738
- declare function codexRunConfig(opts: Pick<CodexSessionOptions, 'mcpServers' | 'instructionsFile' | 'extraConfig'>): Record<string, unknown>;
5752
+ declare function codexRunConfig(opts: Pick<CodexSessionOptions, 'mcpServers' | 'instructionsFile' | 'extraConfig'>, provider?: CodexProvider | null): Record<string, unknown>;
5739
5753
  declare function createCodexSession(opts: CodexSessionOptions): CodingAgentSession;
5740
5754
 
5741
5755
  /**
@@ -6840,4 +6854,4 @@ declare class SuperatomSDK {
6840
6854
  getConversationSimilarityThreshold(): number;
6841
6855
  }
6842
6856
 
6843
- export { ALL_COLUMN_KEYS, ANSWER_COMPONENT_NAMES, type AgentConfig, type AgentEvent, type AgentResponse, type AgentRunContext, type AgentRunHandlers, type AgentRunRecord, type AgentRunResult, type AgentTrigger, type AgentUsage, type AnalyticsEventType, type AnalyticsStatus, type AnswerProvider, type AnswerProviderContext, type ApplySummary, BM25L, type BM25LOptions, type BaseLLMConfig, type BuildTriggerInput, CATEGORY_KEYS, CODEX_DOC_MAX_BYTES, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CodexSessionOptions, type CodingAgentCollectionConfig, type CodingAgentDefinition, type CodingAgentSession, type CodingAgentSessionOptions, type CodingAgentsConfig, type ColInfo, type ColType, type CollectionHandler, type CollectionOperation, type Component, type ConstraintFilter, type ConstraintOp, type ConstraintPolicy, type DBUIBlock, DEFAULT_AGENT_CONFIG, DEFAULT_FMT_CONFIG, type DashboardAgentCollectionConfig, type DatabaseType, type FindingCode, type Fmt, type FmtConfig, type GeneratedFile, type GraphVersion, type Harness, type HybridSearchOptions, INSTRUCTIONS_FILE, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type McpServerSpec, type Message, MissingRequestContextError, type ModelStrategy, NUMERIC_KEYS, type NarrationUpdate, type OutputContract, type OutputField, type OutputValidator, type PiSessionListener, type PiSessionState, type PiTranscriptEntry, type PolicyException, type PolicyExceptionTable, type Principal, type PromptAttachment, type PromptContext, type RequestContext, type RerankedResult, type ResolvedAccess, type RowFilter, type RunAgentOptions, STORAGE_CONFIG, type ScriptComponentSpec, ScriptMatcher, type ScriptParameter, type ScriptRecipe, type ScriptRecipeMetaRow, type ScriptRecipeStore, type ScriptResult, ScriptStore, type ScriptStoreOptions, type SelectedWorkflow, type ShimDef, type ShimSummary, type ShimTarget, type SourcePolicy, type SpecToValidate, SuperatomSDK, type SuperatomSDKConfig, type T_RESPONSE, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, type TriggerEvent, type TriggerFireInfo, UIBlock, UILogCollector, type User, UserManager, type UsersData, type ValidationContext, type ValidationFinding, type WorkflowDescriptor, type Workspace, accessFromConfig, analyticsClient, answerCatalogForBinding, answerComponents, anthropicLLM, assertReadOnlySql, bindContext, bridgePreamble, captureContext, clearContextTokens, codexRunConfig, constraintPoliciesFromConfig, contextTokenCount, createCodexSession, createCodingAgentSession, dashboardConversationHistory, dataFingerprint, describeContext, describeTriggers, emitAgentEvent, extractNamedExport, formatFindingsForAgent, geminiLLM, getCodingAgent, getCodingAgentsConfig, getPiSessionState, getRequestContext, groqLLM, hybridRerank, inferColumns, isUserContext, listCodingAgents, llmUsageLogger, logger, makeFmt, mintContextToken, normalizeScriptBody, onAgentRun, onPiSessionUpdate, openaiLLM, policiesFromConfig, projectForDatasetBinding, promptLoader, queryCache, registerCodingAgentCollection, registerCodingAgents, registerDashboardAgentCollection, requireRequestContext, rerankChromaResults, rerankConversationResults, resolveContextToken, resolveScriptRecipeStore, revokeContextToken, runAsSystem, runAsUser, runCodingAgent, runScript, runWithContext, runWithMessageIdentity, startAgentTriggers, stopAgentTriggers, userPromptErrorLogger, validateComponentSpec, withCapturedContext, writeBridgeShims, writeShims };
6857
+ export { ALL_COLUMN_KEYS, ANSWER_COMPONENT_NAMES, type AgentConfig, type AgentEvent, type AgentResponse, type AgentRunContext, type AgentRunHandlers, type AgentRunRecord, type AgentRunResult, type AgentTrigger, type AgentUsage, type AnalyticsEventType, type AnalyticsStatus, type AnswerProvider, type AnswerProviderContext, type ApplySummary, BM25L, type BM25LOptions, type BaseLLMConfig, type BuildTriggerInput, CATEGORY_KEYS, CODEX_DOC_MAX_BYTES, CODEX_OPENROUTER_KEY_ENV, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CodexProvider, type CodexSessionOptions, type CodingAgentCollectionConfig, type CodingAgentDefinition, type CodingAgentSession, type CodingAgentSessionOptions, type CodingAgentsConfig, type ColInfo, type ColType, type CollectionHandler, type CollectionOperation, type Component, type ConstraintFilter, type ConstraintOp, type ConstraintPolicy, type DBUIBlock, DEFAULT_AGENT_CONFIG, DEFAULT_FMT_CONFIG, type DashboardAgentCollectionConfig, type DatabaseType, type FindingCode, type Fmt, type FmtConfig, type GeneratedFile, type GraphVersion, type Harness, type HybridSearchOptions, INSTRUCTIONS_FILE, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type McpServerSpec, type Message, MissingRequestContextError, type ModelStrategy, NUMERIC_KEYS, type NarrationUpdate, type OutputContract, type OutputField, type OutputValidator, type PiSessionListener, type PiSessionState, type PiTranscriptEntry, type PolicyException, type PolicyExceptionTable, type Principal, type PromptAttachment, type PromptContext, type RequestContext, type RerankedResult, type ResolvedAccess, type RowFilter, type RunAgentOptions, STORAGE_CONFIG, type ScriptComponentSpec, ScriptMatcher, type ScriptParameter, type ScriptRecipe, type ScriptRecipeMetaRow, type ScriptRecipeStore, type ScriptResult, ScriptStore, type ScriptStoreOptions, type SelectedWorkflow, type ShimDef, type ShimSummary, type ShimTarget, type SourcePolicy, type SpecToValidate, SuperatomSDK, type SuperatomSDKConfig, type T_RESPONSE, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, type TriggerEvent, type TriggerFireInfo, UIBlock, UILogCollector, type User, UserManager, type UsersData, type ValidationContext, type ValidationFinding, type WorkflowDescriptor, type Workspace, accessFromConfig, analyticsClient, answerCatalogForBinding, answerComponents, anthropicLLM, assertReadOnlySql, bindContext, bridgePreamble, captureContext, clearContextTokens, codexDefaultProvider, codexModelFor, codexRunConfig, constraintPoliciesFromConfig, contextTokenCount, createCodexSession, createCodingAgentSession, dashboardConversationHistory, dataFingerprint, describeContext, describeTriggers, emitAgentEvent, extractNamedExport, formatFindingsForAgent, geminiLLM, getCodingAgent, getCodingAgentsConfig, getPiSessionState, getRequestContext, groqLLM, hybridRerank, inferColumns, isUserContext, listCodingAgents, llmUsageLogger, logger, makeFmt, mintContextToken, normalizeScriptBody, onAgentRun, onPiSessionUpdate, openaiLLM, policiesFromConfig, projectForDatasetBinding, promptLoader, queryCache, registerCodingAgentCollection, registerCodingAgents, registerDashboardAgentCollection, requireRequestContext, rerankChromaResults, rerankConversationResults, resolveContextToken, resolveScriptRecipeStore, revokeContextToken, runAsSystem, runAsUser, runCodingAgent, runScript, runWithContext, runWithMessageIdentity, startAgentTriggers, stopAgentTriggers, userPromptErrorLogger, validateComponentSpec, withCapturedContext, writeBridgeShims, writeShims };
package/dist/index.js CHANGED
@@ -35,6 +35,7 @@ __export(index_exports, {
35
35
  BM25L: () => BM25L,
36
36
  CATEGORY_KEYS: () => CATEGORY_KEYS,
37
37
  CODEX_DOC_MAX_BYTES: () => CODEX_DOC_MAX_BYTES,
38
+ CODEX_OPENROUTER_KEY_ENV: () => CODEX_OPENROUTER_KEY_ENV,
38
39
  CONTEXT_CONFIG: () => CONTEXT_CONFIG,
39
40
  CleanupService: () => CleanupService,
40
41
  DEFAULT_AGENT_CONFIG: () => DEFAULT_AGENT_CONFIG,
@@ -63,6 +64,8 @@ __export(index_exports, {
63
64
  bridgePreamble: () => bridgePreamble,
64
65
  captureContext: () => captureContext,
65
66
  clearContextTokens: () => clearContextTokens,
67
+ codexDefaultProvider: () => codexDefaultProvider,
68
+ codexModelFor: () => codexModelFor,
66
69
  codexRunConfig: () => codexRunConfig,
67
70
  constraintPoliciesFromConfig: () => constraintPoliciesFromConfig,
68
71
  contextTokenCount: () => contextTokenCount,
@@ -24706,6 +24709,9 @@ async function handleDashboardAgentRequest(data, collections, sendMessage) {
24706
24709
  }
24707
24710
 
24708
24711
  // src/codingAgent/drivers/codex.ts
24712
+ var fs8 = __toESM(require("fs"));
24713
+ var os2 = __toESM(require("os"));
24714
+ var path9 = __toESM(require("path"));
24709
24715
  var dynamicImport = new Function("specifier", "return import(specifier)");
24710
24716
  var codexModulePromise = null;
24711
24717
  function loadCodex() {
@@ -24803,17 +24809,51 @@ function markerFor(event) {
24803
24809
  return null;
24804
24810
  }
24805
24811
  }
24806
- function buildEnv(opts) {
24807
- if (opts.inheritEnv) return opts.env ? { ...process.env, ...opts.env } : void 0;
24812
+ function buildEnv(opts, provider = null) {
24813
+ const extra = { ...provider?.env ?? {}, ...opts.env ?? {} };
24814
+ if (opts.inheritEnv) return Object.keys(extra).length ? { ...process.env, ...extra } : void 0;
24808
24815
  const env = {};
24809
24816
  for (const [k, v] of Object.entries(process.env)) {
24810
24817
  if (v === void 0) continue;
24811
24818
  if (envAllowed(k)) env[k] = v;
24812
24819
  }
24813
- return { ...env, ...opts.env ?? {} };
24820
+ return { ...env, ...extra };
24814
24821
  }
24815
24822
  var CODEX_DOC_MAX_BYTES = 256 * 1024;
24816
- function codexRunConfig(opts) {
24823
+ var CODEX_OPENROUTER_KEY_ENV = "CODEX_OPENROUTER_API_KEY";
24824
+ function tomlTopLevel(toml) {
24825
+ const i = toml.search(/^\s*\[/m);
24826
+ return i < 0 ? toml : toml.slice(0, i);
24827
+ }
24828
+ function readCodexConfig(env) {
24829
+ try {
24830
+ return fs8.readFileSync(path9.join(env.CODEX_HOME || path9.join(os2.homedir(), ".codex"), "config.toml"), "utf-8");
24831
+ } catch {
24832
+ return "";
24833
+ }
24834
+ }
24835
+ function codexDefaultProvider(env = process.env, configToml) {
24836
+ const choice = env.CODEX_MODEL_PROVIDER?.trim();
24837
+ if (choice && choice !== "openrouter") return null;
24838
+ if (!choice && /^\s*model_provider\s*=/m.test(tomlTopLevel(configToml ?? readCodexConfig(env)))) return null;
24839
+ const key = env.OPENROUTER_API_KEY?.trim();
24840
+ if (!key) return null;
24841
+ const root = env.SUPERATOM_LLM_PROXY_URL?.trim();
24842
+ const baseUrl = env.OPENROUTER_BASE_URL?.trim() || (root ? `${root.replace(/\/+$/, "")}/openrouter` : "https://openrouter.ai/api/v1");
24843
+ return {
24844
+ config: {
24845
+ model_provider: "openrouter",
24846
+ model_providers: { openrouter: { name: "OpenRouter", base_url: baseUrl, env_key: CODEX_OPENROUTER_KEY_ENV, wire_api: "responses" } },
24847
+ // codex's default compacts at ~112k tokens, well short of the model's window.
24848
+ model_auto_compact_token_limit: 23e4
24849
+ },
24850
+ env: { [CODEX_OPENROUTER_KEY_ENV]: key }
24851
+ };
24852
+ }
24853
+ function codexModelFor(model, provider) {
24854
+ return provider && model && !model.includes("/") ? `openai/${model}` : model;
24855
+ }
24856
+ function codexRunConfig(opts, provider = null) {
24817
24857
  return {
24818
24858
  // Tools reach codex as MCP servers; each server's name shows up on
24819
24859
  // every tool event, so the runner can tell ours from codex's own.
@@ -24822,12 +24862,16 @@ function codexRunConfig(opts) {
24822
24862
  // the agent with no instructions at all. AGENTS.md still wins if present.
24823
24863
  ...opts.instructionsFile && opts.instructionsFile !== "AGENTS.md" ? { project_doc_fallback_filenames: [opts.instructionsFile] } : {},
24824
24864
  project_doc_max_bytes: CODEX_DOC_MAX_BYTES,
24865
+ // Without it reasoning items arrive empty, so a run shows no thinking.
24866
+ model_reasoning_summary: "detailed",
24867
+ ...provider?.config ?? {},
24825
24868
  // Last: a deployment's own value wins.
24826
24869
  ...opts.extraConfig ?? {}
24827
24870
  };
24828
24871
  }
24829
24872
  function createCodexSession(opts) {
24830
- const model = opts.model ?? process.env.CODEX_AGENT_MODEL;
24873
+ const provider = opts.apiKey || opts.baseUrl ? null : codexDefaultProvider();
24874
+ const model = codexModelFor(opts.model ?? process.env.CODEX_AGENT_MODEL, provider);
24831
24875
  let thread = null;
24832
24876
  let resumeId = opts.resumeId;
24833
24877
  let threadId = opts.resumeId;
@@ -24848,11 +24892,11 @@ function createCodexSession(opts) {
24848
24892
  async function ensureThread() {
24849
24893
  if (thread) return thread;
24850
24894
  const { Codex } = await loadCodex();
24851
- const config2 = codexRunConfig(opts);
24895
+ const config2 = codexRunConfig(opts, provider);
24852
24896
  const codex = new Codex({
24853
24897
  ...opts.apiKey ? { apiKey: opts.apiKey } : {},
24854
24898
  ...opts.baseUrl ? { baseUrl: opts.baseUrl } : {},
24855
- env: buildEnv(opts),
24899
+ env: buildEnv(opts, provider),
24856
24900
  config: config2
24857
24901
  });
24858
24902
  thread = resumeId ? codex.resumeThread(resumeId, threadOptions()) : codex.startThread(threadOptions());
@@ -25015,8 +25059,8 @@ ${marker}
25015
25059
 
25016
25060
  // src/codingAgent/drivers/pi.ts
25017
25061
  var crypto3 = __toESM(require("crypto"));
25018
- var fs8 = __toESM(require("fs"));
25019
- var path9 = __toESM(require("path"));
25062
+ var fs9 = __toESM(require("fs"));
25063
+ var path10 = __toESM(require("path"));
25020
25064
  var dynamicImport2 = new Function("specifier", "return import(specifier)");
25021
25065
  var piModulePromise = null;
25022
25066
  function loadPi() {
@@ -25183,9 +25227,9 @@ function startSweeper() {
25183
25227
  }
25184
25228
  function readInstructions(opts) {
25185
25229
  if (!opts.instructionsFile) return void 0;
25186
- const file = path9.resolve(opts.cwd, opts.instructionsFile);
25230
+ const file = path10.resolve(opts.cwd, opts.instructionsFile);
25187
25231
  try {
25188
- return { file, content: fs8.readFileSync(file, "utf-8") };
25232
+ return { file, content: fs9.readFileSync(file, "utf-8") };
25189
25233
  } catch {
25190
25234
  return void 0;
25191
25235
  }
@@ -25208,7 +25252,7 @@ function createPiSession(opts) {
25208
25252
  agentsFilesOverride: (base) => instructions ? { agentsFiles: [{ path: instructions.file, content: instructions.content }] } : base
25209
25253
  });
25210
25254
  await resourceLoader.reload();
25211
- const sessionManager = resumeFile && fs8.existsSync(resumeFile) ? pi.SessionManager.open(resumeFile) : pi.SessionManager.create(opts.cwd);
25255
+ const sessionManager = resumeFile && fs9.existsSync(resumeFile) ? pi.SessionManager.open(resumeFile) : pi.SessionManager.create(opts.cwd);
25212
25256
  const live = {
25213
25257
  running: false,
25214
25258
  transcript: [],
@@ -25427,11 +25471,11 @@ function createCodingAgentSession(harness, opts) {
25427
25471
  }
25428
25472
 
25429
25473
  // src/codingAgent/registry.ts
25430
- var path10 = __toESM(require("path"));
25474
+ var path11 = __toESM(require("path"));
25431
25475
  var agents = /* @__PURE__ */ new Map();
25432
25476
  var config = {
25433
- promptRoot: path10.join(process.cwd(), ".prompts", "coding-agents"),
25434
- runtimeDir: path10.join(process.cwd(), ".coding-agent-runtime"),
25477
+ promptRoot: path11.join(process.cwd(), ".prompts", "coding-agents"),
25478
+ runtimeDir: path11.join(process.cwd(), ".coding-agent-runtime"),
25435
25479
  harness: "codex",
25436
25480
  keepRuns: 20,
25437
25481
  keepThreads: 200
@@ -25470,13 +25514,13 @@ function getCodingAgentsConfig() {
25470
25514
  return config;
25471
25515
  }
25472
25516
  function resolvePromptDir(def) {
25473
- return def.promptDir || path10.join(config.promptRoot, def.id);
25517
+ return def.promptDir || path11.join(config.promptRoot, def.id);
25474
25518
  }
25475
25519
 
25476
25520
  // src/codingAgent/runner.ts
25477
- var fs9 = __toESM(require("fs"));
25521
+ var fs10 = __toESM(require("fs"));
25478
25522
  var fsp = __toESM(require("fs/promises"));
25479
- var path11 = __toESM(require("path"));
25523
+ var path12 = __toESM(require("path"));
25480
25524
  var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
25481
25525
  var inFlight = /* @__PURE__ */ new Set();
25482
25526
  function slug(v) {
@@ -25486,11 +25530,11 @@ function resolveScope(def, opts) {
25486
25530
  const scope = def.scope ?? (def.mode === "chat" ? "thread" : "project");
25487
25531
  if (scope === "thread") {
25488
25532
  const id = slug(opts.threadId || "default");
25489
- return { key: `thread:${id}`, dirName: path11.join("threads", id) };
25533
+ return { key: `thread:${id}`, dirName: path12.join("threads", id) };
25490
25534
  }
25491
25535
  if (scope === "user") {
25492
25536
  const id = slug(opts.userId || "anonymous");
25493
- return { key: `user:${id}`, dirName: path11.join("users", id) };
25537
+ return { key: `user:${id}`, dirName: path12.join("users", id) };
25494
25538
  }
25495
25539
  return { key: "project", dirName: "_project" };
25496
25540
  }
@@ -25499,30 +25543,30 @@ function makeRunId() {
25499
25543
  return `${t}-${Math.random().toString(36).slice(2, 8)}`;
25500
25544
  }
25501
25545
  function statePath(scopeDir) {
25502
- return path11.join(scopeDir, "_state.json");
25546
+ return path12.join(scopeDir, "_state.json");
25503
25547
  }
25504
25548
  function loadState(scopeDir) {
25505
25549
  try {
25506
- return JSON.parse(fs9.readFileSync(statePath(scopeDir), "utf-8"));
25550
+ return JSON.parse(fs10.readFileSync(statePath(scopeDir), "utf-8"));
25507
25551
  } catch {
25508
25552
  return { turns: 0, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
25509
25553
  }
25510
25554
  }
25511
25555
  function saveState(scopeDir, state) {
25512
25556
  try {
25513
- fs9.mkdirSync(scopeDir, { recursive: true });
25514
- fs9.writeFileSync(statePath(scopeDir), JSON.stringify({ ...state, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
25557
+ fs10.mkdirSync(scopeDir, { recursive: true });
25558
+ fs10.writeFileSync(statePath(scopeDir), JSON.stringify({ ...state, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
25515
25559
  } catch (err) {
25516
25560
  logger.warn(`[CodingAgent] failed to persist session state: ${err?.message ?? err}`);
25517
25561
  }
25518
25562
  }
25519
25563
  async function clearTransient(dir) {
25520
- await fsp.rm(path11.join(dir, "input"), { recursive: true, force: true });
25564
+ await fsp.rm(path12.join(dir, "input"), { recursive: true, force: true });
25521
25565
  }
25522
25566
  function createWorkspace(dir, runId) {
25523
- const abs = (rel) => path11.join(dir, rel);
25567
+ const abs = (rel) => path12.join(dir, rel);
25524
25568
  const ensureDir = async (rel) => {
25525
- await fsp.mkdir(path11.dirname(abs(rel)), { recursive: true });
25569
+ await fsp.mkdir(path12.dirname(abs(rel)), { recursive: true });
25526
25570
  };
25527
25571
  return {
25528
25572
  dir,
@@ -25551,7 +25595,7 @@ function createWorkspace(dir, runId) {
25551
25595
  }
25552
25596
  var INSTRUCTIONS_FILE = "system.md";
25553
25597
  async function installInstructions(def, ws) {
25554
- const src = path11.join(resolvePromptDir(def), "system.md");
25598
+ const src = path12.join(resolvePromptDir(def), "system.md");
25555
25599
  try {
25556
25600
  await ws.write(INSTRUCTIONS_FILE, await fsp.readFile(src, "utf-8"));
25557
25601
  } catch {
@@ -25565,7 +25609,7 @@ async function pruneThreads(agentId, threadsDir, keep) {
25565
25609
  const dirs = (await fsp.readdir(threadsDir, { withFileTypes: true })).filter((e) => e.isDirectory());
25566
25610
  if (dirs.length <= keep) return;
25567
25611
  const aged = await Promise.all(dirs.map(async (e) => {
25568
- const dir = path11.join(threadsDir, e.name);
25612
+ const dir = path12.join(threadsDir, e.name);
25569
25613
  const stat2 = await fsp.stat(statePath(dir)).catch(() => fsp.stat(dir));
25570
25614
  return { name: e.name, dir, used: stat2.mtimeMs };
25571
25615
  }));
@@ -25585,7 +25629,7 @@ async function pruneRuns(agentDir, keep) {
25585
25629
  try {
25586
25630
  const entries = (await fsp.readdir(agentDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
25587
25631
  for (const name of entries.slice(0, Math.max(0, entries.length - keep))) {
25588
- await fsp.rm(path11.join(agentDir, name), { recursive: true, force: true });
25632
+ await fsp.rm(path12.join(agentDir, name), { recursive: true, force: true });
25589
25633
  }
25590
25634
  } catch {
25591
25635
  }
@@ -25603,17 +25647,17 @@ async function runCodingAgent(agentId, options = {}) {
25603
25647
  }
25604
25648
  const cfg = getCodingAgentsConfig();
25605
25649
  const runId = makeRunId();
25606
- const agentDir = path11.join(cfg.runtimeDir, def.id);
25650
+ const agentDir = path12.join(cfg.runtimeDir, def.id);
25607
25651
  const policy = def.session ?? {};
25608
25652
  const persistentWorkspace = policy.workspace === "persistent";
25609
25653
  const persistentSession = policy.scope === "persistent";
25610
25654
  const runAsJob = !(options.chat === true && def.mode === "task");
25611
25655
  const { key: scopeKey, dirName } = resolveScope(def, { userId: options.userId, threadId: options.threadId });
25612
- const scopeDir = path11.join(agentDir, dirName);
25613
- const dir = options.workspaceDir || (persistentWorkspace ? scopeDir : path11.join(scopeDir, "runs", runId));
25614
- fs9.mkdirSync(dir, { recursive: true });
25656
+ const scopeDir = path12.join(agentDir, dirName);
25657
+ const dir = options.workspaceDir || (persistentWorkspace ? scopeDir : path12.join(scopeDir, "runs", runId));
25658
+ fs10.mkdirSync(dir, { recursive: true });
25615
25659
  if (persistentWorkspace && !options.workspaceDir) {
25616
- fs9.mkdirSync(path11.join(dir, "memory"), { recursive: true });
25660
+ fs10.mkdirSync(path12.join(dir, "memory"), { recursive: true });
25617
25661
  if (runAsJob) await clearTransient(dir);
25618
25662
  }
25619
25663
  const lockKey = persistentWorkspace || persistentSession ? `${def.id}:${scopeKey}` : `dir:${dir}`;
@@ -25722,7 +25766,7 @@ async function runCodingAgent(agentId, options = {}) {
25722
25766
  onUsage: ctx.onUsage,
25723
25767
  // Opt-in only: see stopOnDeliverable. Letting the turn end naturally
25724
25768
  // is what makes usage reporting work at all.
25725
- ...outputPath && def.stopOnDeliverable ? { doneWhen: () => fs9.existsSync(outputPath) } : {}
25769
+ ...outputPath && def.stopOnDeliverable ? { doneWhen: () => fs10.existsSync(outputPath) } : {}
25726
25770
  },
25727
25771
  timeout.signal
25728
25772
  );
@@ -25827,9 +25871,9 @@ Fix ONLY that, and rewrite the same file at the same path. Do not re-run any que
25827
25871
  logger.info(
25828
25872
  `[CodingAgent:${def.id}] ${runAsJob ? "run" : "chat"}=${runId} status=${record.status} ms=${record.ms} tokens=${record.usage.inputTokens}/${record.usage.outputTokens} tools=${record.usage.toolCalls}` + (record.applied ? ` applied="${record.applied.summary}"` : "") + (record.error ? ` error="${record.error}"` : "")
25829
25873
  );
25830
- if (!options.workspaceDir && !persistentWorkspace) await pruneRuns(path11.join(scopeDir, "runs"), cfg.keepRuns);
25831
- if (!options.workspaceDir && dirName.startsWith(`threads${path11.sep}`)) {
25832
- await pruneThreads(def.id, path11.join(agentDir, "threads"), cfg.keepThreads);
25874
+ if (!options.workspaceDir && !persistentWorkspace) await pruneRuns(path12.join(scopeDir, "runs"), cfg.keepRuns);
25875
+ if (!options.workspaceDir && dirName.startsWith(`threads${path12.sep}`)) {
25876
+ await pruneThreads(def.id, path12.join(agentDir, "threads"), cfg.keepThreads);
25833
25877
  }
25834
25878
  }
25835
25879
  }
@@ -25889,14 +25933,14 @@ ${assertReadOnlySql.toString().replace("export function", "function")}
25889
25933
  `;
25890
25934
 
25891
25935
  // src/codingAgent/tools/shims.ts
25892
- var fs10 = __toESM(require("fs"));
25893
- var path12 = __toESM(require("path"));
25894
- var resolve3 = (target, name) => typeof target === "string" ? path12.join(target, name) : target.pathTo(name);
25936
+ var fs11 = __toESM(require("fs"));
25937
+ var path13 = __toESM(require("path"));
25938
+ var resolve3 = (target, name) => typeof target === "string" ? path13.join(target, name) : target.pathTo(name);
25895
25939
  function writeShims(defs, target) {
25896
25940
  for (const def of defs) {
25897
25941
  const file = resolve3(target, def.name);
25898
- fs10.writeFileSync(file, def.body, "utf-8");
25899
- fs10.chmodSync(file, 493);
25942
+ fs11.writeFileSync(file, def.body, "utf-8");
25943
+ fs11.chmodSync(file, 493);
25900
25944
  }
25901
25945
  return defs.map((def) => ({ name: `./${def.name}`, summary: def.summary }));
25902
25946
  }
@@ -26163,17 +26207,17 @@ console.log(${JSON.stringify(
26163
26207
  }
26164
26208
 
26165
26209
  // src/codingAgent/triggers.ts
26166
- var fs11 = __toESM(require("fs"));
26167
- var path13 = __toESM(require("path"));
26210
+ var fs12 = __toESM(require("fs"));
26211
+ var path14 = __toESM(require("path"));
26168
26212
  var EVENT_BURST_CAP = 200;
26169
26213
  var capEvents = (events) => events.length > EVENT_BURST_CAP ? events.slice(-EVENT_BURST_CAP) : events;
26170
26214
  function statePath2(agentId) {
26171
- return path13.join(getCodingAgentsConfig().runtimeDir, agentId, "_triggers.json");
26215
+ return path14.join(getCodingAgentsConfig().runtimeDir, agentId, "_triggers.json");
26172
26216
  }
26173
26217
  function loadTriggerState(agentId) {
26174
26218
  let raw;
26175
26219
  try {
26176
- raw = JSON.parse(fs11.readFileSync(statePath2(agentId), "utf-8"));
26220
+ raw = JSON.parse(fs12.readFileSync(statePath2(agentId), "utf-8"));
26177
26221
  } catch {
26178
26222
  return { counts: {}, pending: {} };
26179
26223
  }
@@ -26193,8 +26237,8 @@ function loadTriggerState(agentId) {
26193
26237
  function saveTriggerState(agentId, state) {
26194
26238
  try {
26195
26239
  const p = statePath2(agentId);
26196
- fs11.mkdirSync(path13.dirname(p), { recursive: true });
26197
- fs11.writeFileSync(p, JSON.stringify(state, null, 2));
26240
+ fs12.mkdirSync(path14.dirname(p), { recursive: true });
26241
+ fs12.writeFileSync(p, JSON.stringify(state, null, 2));
26198
26242
  } catch (err) {
26199
26243
  logger.warn(`[CodingAgent:${agentId}] failed to persist trigger state: ${err?.message ?? err}`);
26200
26244
  }
@@ -26330,13 +26374,13 @@ function describeTriggers() {
26330
26374
  }
26331
26375
 
26332
26376
  // src/codingAgent/collection.ts
26333
- var fs12 = __toESM(require("fs"));
26334
- var path14 = __toESM(require("path"));
26377
+ var fs13 = __toESM(require("fs"));
26378
+ var path15 = __toESM(require("path"));
26335
26379
  function isChattable(agent) {
26336
26380
  return agent.mode !== "task";
26337
26381
  }
26338
26382
  function registerCodingAgentCollection(sdk, config2 = {}) {
26339
- const runtimeDir = config2.runtimeDir || process.env.CODING_AGENT_RUNTIME_DIR || path14.join(process.cwd(), ".coding-agent-runtime");
26383
+ const runtimeDir = config2.runtimeDir || process.env.CODING_AGENT_RUNTIME_DIR || path15.join(process.cwd(), ".coding-agent-runtime");
26340
26384
  const defaultHarness = config2.harness || process.env.CODING_AGENT_HARNESS || "codex";
26341
26385
  const sessions = /* @__PURE__ */ new Map();
26342
26386
  const running = /* @__PURE__ */ new Set();
@@ -26396,8 +26440,8 @@ function registerCodingAgentCollection(sdk, config2 = {}) {
26396
26440
  ...record.status === "skipped" ? { error: `${def.title} is in the middle of a run \u2014 try again in a moment.` } : record.error ? { error: record.error } : {}
26397
26441
  };
26398
26442
  }
26399
- const cwd = path14.join(runtimeDir, "threads", threadId);
26400
- fs12.mkdirSync(cwd, { recursive: true });
26443
+ const cwd = path15.join(runtimeDir, "threads", threadId);
26444
+ fs13.mkdirSync(cwd, { recursive: true });
26401
26445
  let session = sessions.get(threadId);
26402
26446
  if (!session) {
26403
26447
  session = createCodingAgentSession(harness || defaultHarness, {
@@ -30350,6 +30394,7 @@ var SuperatomSDK = class {
30350
30394
  BM25L,
30351
30395
  CATEGORY_KEYS,
30352
30396
  CODEX_DOC_MAX_BYTES,
30397
+ CODEX_OPENROUTER_KEY_ENV,
30353
30398
  CONTEXT_CONFIG,
30354
30399
  CleanupService,
30355
30400
  DEFAULT_AGENT_CONFIG,
@@ -30378,6 +30423,8 @@ var SuperatomSDK = class {
30378
30423
  bridgePreamble,
30379
30424
  captureContext,
30380
30425
  clearContextTokens,
30426
+ codexDefaultProvider,
30427
+ codexModelFor,
30381
30428
  codexRunConfig,
30382
30429
  constraintPoliciesFromConfig,
30383
30430
  contextTokenCount,