@superatomai/sdk-node 0.0.90-dsp → 0.0.91-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,14 @@ 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
+ ...provider?.config ?? {},
24825
24866
  // Last: a deployment's own value wins.
24826
24867
  ...opts.extraConfig ?? {}
24827
24868
  };
24828
24869
  }
24829
24870
  function createCodexSession(opts) {
24830
- const model = opts.model ?? process.env.CODEX_AGENT_MODEL;
24871
+ const provider = opts.apiKey || opts.baseUrl ? null : codexDefaultProvider();
24872
+ const model = codexModelFor(opts.model ?? process.env.CODEX_AGENT_MODEL, provider);
24831
24873
  let thread = null;
24832
24874
  let resumeId = opts.resumeId;
24833
24875
  let threadId = opts.resumeId;
@@ -24848,11 +24890,11 @@ function createCodexSession(opts) {
24848
24890
  async function ensureThread() {
24849
24891
  if (thread) return thread;
24850
24892
  const { Codex } = await loadCodex();
24851
- const config2 = codexRunConfig(opts);
24893
+ const config2 = codexRunConfig(opts, provider);
24852
24894
  const codex = new Codex({
24853
24895
  ...opts.apiKey ? { apiKey: opts.apiKey } : {},
24854
24896
  ...opts.baseUrl ? { baseUrl: opts.baseUrl } : {},
24855
- env: buildEnv(opts),
24897
+ env: buildEnv(opts, provider),
24856
24898
  config: config2
24857
24899
  });
24858
24900
  thread = resumeId ? codex.resumeThread(resumeId, threadOptions()) : codex.startThread(threadOptions());
@@ -25015,8 +25057,8 @@ ${marker}
25015
25057
 
25016
25058
  // src/codingAgent/drivers/pi.ts
25017
25059
  var crypto3 = __toESM(require("crypto"));
25018
- var fs8 = __toESM(require("fs"));
25019
- var path9 = __toESM(require("path"));
25060
+ var fs9 = __toESM(require("fs"));
25061
+ var path10 = __toESM(require("path"));
25020
25062
  var dynamicImport2 = new Function("specifier", "return import(specifier)");
25021
25063
  var piModulePromise = null;
25022
25064
  function loadPi() {
@@ -25183,9 +25225,9 @@ function startSweeper() {
25183
25225
  }
25184
25226
  function readInstructions(opts) {
25185
25227
  if (!opts.instructionsFile) return void 0;
25186
- const file = path9.resolve(opts.cwd, opts.instructionsFile);
25228
+ const file = path10.resolve(opts.cwd, opts.instructionsFile);
25187
25229
  try {
25188
- return { file, content: fs8.readFileSync(file, "utf-8") };
25230
+ return { file, content: fs9.readFileSync(file, "utf-8") };
25189
25231
  } catch {
25190
25232
  return void 0;
25191
25233
  }
@@ -25208,7 +25250,7 @@ function createPiSession(opts) {
25208
25250
  agentsFilesOverride: (base) => instructions ? { agentsFiles: [{ path: instructions.file, content: instructions.content }] } : base
25209
25251
  });
25210
25252
  await resourceLoader.reload();
25211
- const sessionManager = resumeFile && fs8.existsSync(resumeFile) ? pi.SessionManager.open(resumeFile) : pi.SessionManager.create(opts.cwd);
25253
+ const sessionManager = resumeFile && fs9.existsSync(resumeFile) ? pi.SessionManager.open(resumeFile) : pi.SessionManager.create(opts.cwd);
25212
25254
  const live = {
25213
25255
  running: false,
25214
25256
  transcript: [],
@@ -25427,11 +25469,11 @@ function createCodingAgentSession(harness, opts) {
25427
25469
  }
25428
25470
 
25429
25471
  // src/codingAgent/registry.ts
25430
- var path10 = __toESM(require("path"));
25472
+ var path11 = __toESM(require("path"));
25431
25473
  var agents = /* @__PURE__ */ new Map();
25432
25474
  var config = {
25433
- promptRoot: path10.join(process.cwd(), ".prompts", "coding-agents"),
25434
- runtimeDir: path10.join(process.cwd(), ".coding-agent-runtime"),
25475
+ promptRoot: path11.join(process.cwd(), ".prompts", "coding-agents"),
25476
+ runtimeDir: path11.join(process.cwd(), ".coding-agent-runtime"),
25435
25477
  harness: "codex",
25436
25478
  keepRuns: 20,
25437
25479
  keepThreads: 200
@@ -25470,13 +25512,13 @@ function getCodingAgentsConfig() {
25470
25512
  return config;
25471
25513
  }
25472
25514
  function resolvePromptDir(def) {
25473
- return def.promptDir || path10.join(config.promptRoot, def.id);
25515
+ return def.promptDir || path11.join(config.promptRoot, def.id);
25474
25516
  }
25475
25517
 
25476
25518
  // src/codingAgent/runner.ts
25477
- var fs9 = __toESM(require("fs"));
25519
+ var fs10 = __toESM(require("fs"));
25478
25520
  var fsp = __toESM(require("fs/promises"));
25479
- var path11 = __toESM(require("path"));
25521
+ var path12 = __toESM(require("path"));
25480
25522
  var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
25481
25523
  var inFlight = /* @__PURE__ */ new Set();
25482
25524
  function slug(v) {
@@ -25486,11 +25528,11 @@ function resolveScope(def, opts) {
25486
25528
  const scope = def.scope ?? (def.mode === "chat" ? "thread" : "project");
25487
25529
  if (scope === "thread") {
25488
25530
  const id = slug(opts.threadId || "default");
25489
- return { key: `thread:${id}`, dirName: path11.join("threads", id) };
25531
+ return { key: `thread:${id}`, dirName: path12.join("threads", id) };
25490
25532
  }
25491
25533
  if (scope === "user") {
25492
25534
  const id = slug(opts.userId || "anonymous");
25493
- return { key: `user:${id}`, dirName: path11.join("users", id) };
25535
+ return { key: `user:${id}`, dirName: path12.join("users", id) };
25494
25536
  }
25495
25537
  return { key: "project", dirName: "_project" };
25496
25538
  }
@@ -25499,30 +25541,30 @@ function makeRunId() {
25499
25541
  return `${t}-${Math.random().toString(36).slice(2, 8)}`;
25500
25542
  }
25501
25543
  function statePath(scopeDir) {
25502
- return path11.join(scopeDir, "_state.json");
25544
+ return path12.join(scopeDir, "_state.json");
25503
25545
  }
25504
25546
  function loadState(scopeDir) {
25505
25547
  try {
25506
- return JSON.parse(fs9.readFileSync(statePath(scopeDir), "utf-8"));
25548
+ return JSON.parse(fs10.readFileSync(statePath(scopeDir), "utf-8"));
25507
25549
  } catch {
25508
25550
  return { turns: 0, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
25509
25551
  }
25510
25552
  }
25511
25553
  function saveState(scopeDir, state) {
25512
25554
  try {
25513
- fs9.mkdirSync(scopeDir, { recursive: true });
25514
- fs9.writeFileSync(statePath(scopeDir), JSON.stringify({ ...state, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
25555
+ fs10.mkdirSync(scopeDir, { recursive: true });
25556
+ fs10.writeFileSync(statePath(scopeDir), JSON.stringify({ ...state, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
25515
25557
  } catch (err) {
25516
25558
  logger.warn(`[CodingAgent] failed to persist session state: ${err?.message ?? err}`);
25517
25559
  }
25518
25560
  }
25519
25561
  async function clearTransient(dir) {
25520
- await fsp.rm(path11.join(dir, "input"), { recursive: true, force: true });
25562
+ await fsp.rm(path12.join(dir, "input"), { recursive: true, force: true });
25521
25563
  }
25522
25564
  function createWorkspace(dir, runId) {
25523
- const abs = (rel) => path11.join(dir, rel);
25565
+ const abs = (rel) => path12.join(dir, rel);
25524
25566
  const ensureDir = async (rel) => {
25525
- await fsp.mkdir(path11.dirname(abs(rel)), { recursive: true });
25567
+ await fsp.mkdir(path12.dirname(abs(rel)), { recursive: true });
25526
25568
  };
25527
25569
  return {
25528
25570
  dir,
@@ -25551,7 +25593,7 @@ function createWorkspace(dir, runId) {
25551
25593
  }
25552
25594
  var INSTRUCTIONS_FILE = "system.md";
25553
25595
  async function installInstructions(def, ws) {
25554
- const src = path11.join(resolvePromptDir(def), "system.md");
25596
+ const src = path12.join(resolvePromptDir(def), "system.md");
25555
25597
  try {
25556
25598
  await ws.write(INSTRUCTIONS_FILE, await fsp.readFile(src, "utf-8"));
25557
25599
  } catch {
@@ -25565,7 +25607,7 @@ async function pruneThreads(agentId, threadsDir, keep) {
25565
25607
  const dirs = (await fsp.readdir(threadsDir, { withFileTypes: true })).filter((e) => e.isDirectory());
25566
25608
  if (dirs.length <= keep) return;
25567
25609
  const aged = await Promise.all(dirs.map(async (e) => {
25568
- const dir = path11.join(threadsDir, e.name);
25610
+ const dir = path12.join(threadsDir, e.name);
25569
25611
  const stat2 = await fsp.stat(statePath(dir)).catch(() => fsp.stat(dir));
25570
25612
  return { name: e.name, dir, used: stat2.mtimeMs };
25571
25613
  }));
@@ -25585,7 +25627,7 @@ async function pruneRuns(agentDir, keep) {
25585
25627
  try {
25586
25628
  const entries = (await fsp.readdir(agentDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
25587
25629
  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 });
25630
+ await fsp.rm(path12.join(agentDir, name), { recursive: true, force: true });
25589
25631
  }
25590
25632
  } catch {
25591
25633
  }
@@ -25603,17 +25645,17 @@ async function runCodingAgent(agentId, options = {}) {
25603
25645
  }
25604
25646
  const cfg = getCodingAgentsConfig();
25605
25647
  const runId = makeRunId();
25606
- const agentDir = path11.join(cfg.runtimeDir, def.id);
25648
+ const agentDir = path12.join(cfg.runtimeDir, def.id);
25607
25649
  const policy = def.session ?? {};
25608
25650
  const persistentWorkspace = policy.workspace === "persistent";
25609
25651
  const persistentSession = policy.scope === "persistent";
25610
25652
  const runAsJob = !(options.chat === true && def.mode === "task");
25611
25653
  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 });
25654
+ const scopeDir = path12.join(agentDir, dirName);
25655
+ const dir = options.workspaceDir || (persistentWorkspace ? scopeDir : path12.join(scopeDir, "runs", runId));
25656
+ fs10.mkdirSync(dir, { recursive: true });
25615
25657
  if (persistentWorkspace && !options.workspaceDir) {
25616
- fs9.mkdirSync(path11.join(dir, "memory"), { recursive: true });
25658
+ fs10.mkdirSync(path12.join(dir, "memory"), { recursive: true });
25617
25659
  if (runAsJob) await clearTransient(dir);
25618
25660
  }
25619
25661
  const lockKey = persistentWorkspace || persistentSession ? `${def.id}:${scopeKey}` : `dir:${dir}`;
@@ -25722,7 +25764,7 @@ async function runCodingAgent(agentId, options = {}) {
25722
25764
  onUsage: ctx.onUsage,
25723
25765
  // Opt-in only: see stopOnDeliverable. Letting the turn end naturally
25724
25766
  // is what makes usage reporting work at all.
25725
- ...outputPath && def.stopOnDeliverable ? { doneWhen: () => fs9.existsSync(outputPath) } : {}
25767
+ ...outputPath && def.stopOnDeliverable ? { doneWhen: () => fs10.existsSync(outputPath) } : {}
25726
25768
  },
25727
25769
  timeout.signal
25728
25770
  );
@@ -25827,9 +25869,9 @@ Fix ONLY that, and rewrite the same file at the same path. Do not re-run any que
25827
25869
  logger.info(
25828
25870
  `[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
25871
  );
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);
25872
+ if (!options.workspaceDir && !persistentWorkspace) await pruneRuns(path12.join(scopeDir, "runs"), cfg.keepRuns);
25873
+ if (!options.workspaceDir && dirName.startsWith(`threads${path12.sep}`)) {
25874
+ await pruneThreads(def.id, path12.join(agentDir, "threads"), cfg.keepThreads);
25833
25875
  }
25834
25876
  }
25835
25877
  }
@@ -25889,14 +25931,14 @@ ${assertReadOnlySql.toString().replace("export function", "function")}
25889
25931
  `;
25890
25932
 
25891
25933
  // 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);
25934
+ var fs11 = __toESM(require("fs"));
25935
+ var path13 = __toESM(require("path"));
25936
+ var resolve3 = (target, name) => typeof target === "string" ? path13.join(target, name) : target.pathTo(name);
25895
25937
  function writeShims(defs, target) {
25896
25938
  for (const def of defs) {
25897
25939
  const file = resolve3(target, def.name);
25898
- fs10.writeFileSync(file, def.body, "utf-8");
25899
- fs10.chmodSync(file, 493);
25940
+ fs11.writeFileSync(file, def.body, "utf-8");
25941
+ fs11.chmodSync(file, 493);
25900
25942
  }
25901
25943
  return defs.map((def) => ({ name: `./${def.name}`, summary: def.summary }));
25902
25944
  }
@@ -26163,17 +26205,17 @@ console.log(${JSON.stringify(
26163
26205
  }
26164
26206
 
26165
26207
  // src/codingAgent/triggers.ts
26166
- var fs11 = __toESM(require("fs"));
26167
- var path13 = __toESM(require("path"));
26208
+ var fs12 = __toESM(require("fs"));
26209
+ var path14 = __toESM(require("path"));
26168
26210
  var EVENT_BURST_CAP = 200;
26169
26211
  var capEvents = (events) => events.length > EVENT_BURST_CAP ? events.slice(-EVENT_BURST_CAP) : events;
26170
26212
  function statePath2(agentId) {
26171
- return path13.join(getCodingAgentsConfig().runtimeDir, agentId, "_triggers.json");
26213
+ return path14.join(getCodingAgentsConfig().runtimeDir, agentId, "_triggers.json");
26172
26214
  }
26173
26215
  function loadTriggerState(agentId) {
26174
26216
  let raw;
26175
26217
  try {
26176
- raw = JSON.parse(fs11.readFileSync(statePath2(agentId), "utf-8"));
26218
+ raw = JSON.parse(fs12.readFileSync(statePath2(agentId), "utf-8"));
26177
26219
  } catch {
26178
26220
  return { counts: {}, pending: {} };
26179
26221
  }
@@ -26193,8 +26235,8 @@ function loadTriggerState(agentId) {
26193
26235
  function saveTriggerState(agentId, state) {
26194
26236
  try {
26195
26237
  const p = statePath2(agentId);
26196
- fs11.mkdirSync(path13.dirname(p), { recursive: true });
26197
- fs11.writeFileSync(p, JSON.stringify(state, null, 2));
26238
+ fs12.mkdirSync(path14.dirname(p), { recursive: true });
26239
+ fs12.writeFileSync(p, JSON.stringify(state, null, 2));
26198
26240
  } catch (err) {
26199
26241
  logger.warn(`[CodingAgent:${agentId}] failed to persist trigger state: ${err?.message ?? err}`);
26200
26242
  }
@@ -26330,13 +26372,13 @@ function describeTriggers() {
26330
26372
  }
26331
26373
 
26332
26374
  // src/codingAgent/collection.ts
26333
- var fs12 = __toESM(require("fs"));
26334
- var path14 = __toESM(require("path"));
26375
+ var fs13 = __toESM(require("fs"));
26376
+ var path15 = __toESM(require("path"));
26335
26377
  function isChattable(agent) {
26336
26378
  return agent.mode !== "task";
26337
26379
  }
26338
26380
  function registerCodingAgentCollection(sdk, config2 = {}) {
26339
- const runtimeDir = config2.runtimeDir || process.env.CODING_AGENT_RUNTIME_DIR || path14.join(process.cwd(), ".coding-agent-runtime");
26381
+ const runtimeDir = config2.runtimeDir || process.env.CODING_AGENT_RUNTIME_DIR || path15.join(process.cwd(), ".coding-agent-runtime");
26340
26382
  const defaultHarness = config2.harness || process.env.CODING_AGENT_HARNESS || "codex";
26341
26383
  const sessions = /* @__PURE__ */ new Map();
26342
26384
  const running = /* @__PURE__ */ new Set();
@@ -26396,8 +26438,8 @@ function registerCodingAgentCollection(sdk, config2 = {}) {
26396
26438
  ...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
26439
  };
26398
26440
  }
26399
- const cwd = path14.join(runtimeDir, "threads", threadId);
26400
- fs12.mkdirSync(cwd, { recursive: true });
26441
+ const cwd = path15.join(runtimeDir, "threads", threadId);
26442
+ fs13.mkdirSync(cwd, { recursive: true });
26401
26443
  let session = sessions.get(threadId);
26402
26444
  if (!session) {
26403
26445
  session = createCodingAgentSession(harness || defaultHarness, {
@@ -30350,6 +30392,7 @@ var SuperatomSDK = class {
30350
30392
  BM25L,
30351
30393
  CATEGORY_KEYS,
30352
30394
  CODEX_DOC_MAX_BYTES,
30395
+ CODEX_OPENROUTER_KEY_ENV,
30353
30396
  CONTEXT_CONFIG,
30354
30397
  CleanupService,
30355
30398
  DEFAULT_AGENT_CONFIG,
@@ -30378,6 +30421,8 @@ var SuperatomSDK = class {
30378
30421
  bridgePreamble,
30379
30422
  captureContext,
30380
30423
  clearContextTokens,
30424
+ codexDefaultProvider,
30425
+ codexModelFor,
30381
30426
  codexRunConfig,
30382
30427
  constraintPoliciesFromConfig,
30383
30428
  contextTokenCount,