@open-cr-agent/runtime-direct 0.5.0 → 0.7.0

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/README.md CHANGED
@@ -1,3 +1,3 @@
1
1
  # @open-cr-agent/runtime-direct
2
2
 
3
- The agent runtime of [Open-CR-Agent](https://github.com/jma49/Open-CR-Agent), the multi-agent code reviewer, that calls the OpenAI-compatible model endpoints declared in its configuration itself, with nothing else on the network. Most users want [`@open-cr-agent/cli`](https://www.npmjs.com/package/@open-cr-agent/cli), which provides the `ocra` command and installs this package; see the [manual](https://ocracloud.com). All `@open-cr-agent` packages are released together at one version. Apache-2.0.
3
+ The agent runtime of [Open-CR-Agent](https://github.com/jma49/Open-CR-Agent), the multi-agent code reviewer, that calls the OpenAI-compatible endpoints declared in its configuration itself, with nothing else on the network. Most users want [`@open-cr-agent/cli`](https://www.npmjs.com/package/@open-cr-agent/cli) (the `ocra` command) and the [manual](https://ocracloud.com). All packages share one version. Apache-2.0.
package/dist/effort.d.ts CHANGED
@@ -2,13 +2,12 @@ import type { AppliedSettings, Effort, Sampling } from "@open-cr-agent/core";
2
2
  import type { CallParams } from "./openai.js";
3
3
  export type EffortStyle = "openai" | "openrouter";
4
4
  export declare class EffortLedger {
5
- private readonly sampling;
6
5
  private readonly refused;
7
6
  private readonly applied;
7
+ private readonly sampling;
8
8
  constructor(sampling: Sampling);
9
9
  params(agent: string, effort: Effort | undefined, model: string, style?: EffortStyle): CallParams;
10
10
  refuse(agent: string, model: string): void;
11
11
  appliedTo(agent: string): AppliedSettings | undefined;
12
12
  private record;
13
13
  }
14
- //# sourceMappingURL=effort.d.ts.map
package/dist/effort.js CHANGED
@@ -4,11 +4,11 @@
4
4
  // "none" sends no sampling settings, even after its endpoint refused the
5
5
  // effort: the agent's calls stay alike within a run.
6
6
  export class EffortLedger {
7
- sampling;
8
7
  // Models whose endpoint refused the effort parameter: later calls go
9
8
  // without it instead of paying for another refusal.
10
9
  refused = new Set();
11
10
  applied = new Map();
11
+ sampling;
12
12
  constructor(sampling) {
13
13
  this.sampling = sampling;
14
14
  }
@@ -46,4 +46,3 @@ function effortParam(effort, style) {
46
46
  function requested(sampling) {
47
47
  return ["temperature", "seed"].filter((key) => sampling[key] !== undefined);
48
48
  }
49
- //# sourceMappingURL=effort.js.map
package/dist/index.d.ts CHANGED
@@ -1,2 +1 @@
1
1
  export { directRuntimePlugin } from "./plugin.js";
2
- //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,2 +1 @@
1
1
  export { directRuntimePlugin } from "./plugin.js";
2
- //# sourceMappingURL=index.js.map
package/dist/loop.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import type { ModelPrice, ReviewContext, ToolDefinition, Usage } from "@open-cr-agent/core";
2
- import { type AttemptOutcome } from "@open-cr-agent/core/internal";
1
+ import { type AttemptOutcome, type ModelPrice, type ReviewContext, type ToolDefinition, type Usage } from "@open-cr-agent/core";
3
2
  import { type CallParams, type Endpoint } from "./openai.js";
4
3
  export interface LoopInput {
5
4
  endpoint: Endpoint;
@@ -18,4 +17,3 @@ export interface LoopInput {
18
17
  onUsage?: (spent: Usage) => void;
19
18
  }
20
19
  export declare function runLoop(input: LoopInput): Promise<AttemptOutcome>;
21
- //# sourceMappingURL=loop.d.ts.map
package/dist/loop.js CHANGED
@@ -1,4 +1,4 @@
1
- import { addUsage, emptyUsage, errorMessage, REVIEW_TOOLS, } from "@open-cr-agent/core/internal";
1
+ import { addUsage, emptyUsage, errorMessage, exploredBy, REVIEW_TOOLS, } from "@open-cr-agent/core";
2
2
  import { chat, toolSpec, withoutEffort, } from "./openai.js";
3
3
  // The agent loop: ask the model, run the tools it calls against the review
4
4
  // context, hand the results back, until it calls task_done, answers without
@@ -22,6 +22,7 @@ export async function runLoop(input) {
22
22
  usage: emptyUsage(),
23
23
  };
24
24
  const texts = [];
25
+ const uses = [];
25
26
  let done = false;
26
27
  let params = input.params ?? {};
27
28
  while (outcome.steps < input.maxSteps) {
@@ -67,18 +68,20 @@ export async function runLoop(input) {
67
68
  messages.push({
68
69
  role: "tool",
69
70
  tool_call_id: call.id,
70
- content: await runTool(tools, call, input.context, outcome),
71
+ content: await runTool(tools, call, input.context, outcome, uses),
71
72
  });
72
73
  }
73
74
  if (done)
74
75
  break;
75
76
  }
76
77
  outcome.text = texts.join("\n").trim();
77
- return outcome;
78
+ if (!done && !outcome.error && outcome.steps >= input.maxSteps)
79
+ outcome.atStepCap = true;
80
+ return { ...outcome, ...exploredBy(uses) };
78
81
  }
79
82
  // A tool's answer, or why it gave none: a wrong call is told to the model,
80
83
  // which may correct it, and never ends the attempt.
81
- async function runTool(tools, call, context, outcome) {
84
+ async function runTool(tools, call, context, outcome, uses) {
82
85
  const tool = tools.get(call.function.name);
83
86
  if (!tool)
84
87
  return `Unknown tool: ${call.function.name}`;
@@ -93,6 +96,7 @@ async function runTool(tools, call, context, outcome) {
93
96
  if (!parsed.success) {
94
97
  return `Invalid arguments: ${parsed.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; ")}`;
95
98
  }
99
+ uses.push({ name: tool.name, input: parsed.data });
96
100
  if (tool.name === REVIEW_TOOLS.reportFinding)
97
101
  outcome.findings.push(parsed.data);
98
102
  try {
@@ -102,4 +106,3 @@ async function runTool(tools, call, context, outcome) {
102
106
  return `Tool failed: ${errorMessage(error)}`;
103
107
  }
104
108
  }
105
- //# sourceMappingURL=loop.js.map
package/dist/openai.d.ts CHANGED
@@ -1,14 +1,29 @@
1
- import type { Effort, ModelPrice, ToolDefinition, Usage } from "@open-cr-agent/core";
2
- import { type QuotaError } from "@open-cr-agent/core/internal";
1
+ import { type Effort, type ModelPrice, type QuotaError, type ToolDefinition, type Usage } from "@open-cr-agent/core";
3
2
  import { z } from "zod";
4
- declare const toolCallSchema: z.ZodObject<{
3
+ declare const toolCallSchema: z.ZodPipe<z.ZodObject<{
5
4
  id: z.ZodString;
6
5
  function: z.ZodObject<{
7
6
  name: z.ZodString;
8
7
  arguments: z.ZodString;
9
8
  }, z.core.$strip>;
10
- }, z.core.$strip>;
11
- export type ToolCall = z.infer<typeof toolCallSchema>;
9
+ extra_content: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
10
+ }, z.core.$strip>, z.ZodTransform<{
11
+ id: string;
12
+ function: {
13
+ name: string;
14
+ arguments: string;
15
+ };
16
+ extra_content?: Record<string, unknown> | undefined;
17
+ type: "function";
18
+ }, {
19
+ id: string;
20
+ function: {
21
+ name: string;
22
+ arguments: string;
23
+ };
24
+ extra_content?: Record<string, unknown> | undefined;
25
+ }>>;
26
+ export type ToolCall = z.output<typeof toolCallSchema>;
12
27
  export type ChatMessage = {
13
28
  role: "system" | "user";
14
29
  content: string;
@@ -46,7 +61,7 @@ export interface ChatRequest {
46
61
  };
47
62
  }
48
63
  export type CallParams = Pick<ChatRequest, "temperature" | "seed" | "reasoning_effort" | "reasoning">;
49
- export interface ChatError {
64
+ interface ChatError {
50
65
  message: string;
51
66
  retryable: boolean;
52
67
  quota?: QuotaError;
@@ -64,9 +79,7 @@ export type ChatResponse = ({
64
79
  }) & {
65
80
  effortDropped?: true;
66
81
  };
67
- export declare const TRANSIENT_RETRY_MS = 1000;
68
82
  export declare function toolSpec(tool: ToolDefinition): ToolSpec;
69
83
  export declare function chat(endpoint: Endpoint, request: ChatRequest, price: ModelPrice, signal: AbortSignal): Promise<ChatResponse>;
70
84
  export declare function withoutEffort<T extends CallParams>(params: T): T;
71
85
  export {};
72
- //# sourceMappingURL=openai.d.ts.map
package/dist/openai.js CHANGED
@@ -1,21 +1,28 @@
1
- import { errorMessage, parseQuotaError, sleep, withoutSecrets, } from "@open-cr-agent/core/internal";
1
+ import { setTimeout } from "node:timers/promises";
2
+ import { errorMessage, parseQuotaError, withoutSecrets, } from "@open-cr-agent/core";
2
3
  import { z } from "zod";
3
4
  // The subset of the OpenAI chat completions protocol the loop needs: one
4
5
  // choice, its text and tool calls, and the token counts. Anything else an
5
- // endpoint adds is dropped at this boundary.
6
- const toolCallSchema = z.object({
6
+ // endpoint adds is dropped at this boundary, except a tool call's
7
+ // `extra_content`: Gemini 3 puts its thought signature there and refuses the
8
+ // next request unless the call comes back with it.
9
+ const toolCallSchema = z
10
+ .object({
7
11
  id: z.string(),
8
12
  function: z.object({ name: z.string(), arguments: z.string() }),
13
+ extra_content: z.record(z.string(), z.unknown()).optional(),
14
+ })
15
+ // A call goes back with its type, which Vertex AI requires.
16
+ .transform((call) => ({ ...call, type: "function" }));
17
+ const choiceSchema = z.object({
18
+ message: z.object({
19
+ content: z.string().nullable().optional(),
20
+ tool_calls: z.array(toolCallSchema).optional(),
21
+ }),
9
22
  });
10
23
  const completionSchema = z.object({
11
- choices: z
12
- .array(z.object({
13
- message: z.object({
14
- content: z.string().nullable().optional(),
15
- tool_calls: z.array(toolCallSchema).optional(),
16
- }),
17
- }))
18
- .min(1),
24
+ // At least one: the first is the answer.
25
+ choices: z.tuple([choiceSchema], choiceSchema),
19
26
  usage: z
20
27
  .object({
21
28
  prompt_tokens: z.number().optional(),
@@ -37,7 +44,7 @@ const EFFORT_PARAMETER = /\breasoning(?:_effort)?\b/i;
37
44
  const BODY_EXCERPT = 300;
38
45
  // A transient failure is sent once more after this pause; a second failure
39
46
  // goes to the failback, which decides what it means for the model.
40
- export const TRANSIENT_RETRY_MS = 1_000;
47
+ const TRANSIENT_RETRY_MS = 1_000;
41
48
  export function toolSpec(tool) {
42
49
  const { $schema: _, ...parameters } = z.toJSONSchema(tool.inputSchema);
43
50
  return {
@@ -70,7 +77,7 @@ async function sendRetrying(endpoint, request, price, signal) {
70
77
  const first = await send(endpoint, request, price, signal);
71
78
  if (first.ok || !first.error.transient)
72
79
  return first;
73
- await sleep(TRANSIENT_RETRY_MS, signal);
80
+ await setTimeout(TRANSIENT_RETRY_MS, undefined, { signal }).catch(() => undefined);
74
81
  if (signal.aborted)
75
82
  return first;
76
83
  return send(endpoint, request, price, signal);
@@ -92,7 +99,14 @@ async function send(endpoint, request, price, signal) {
92
99
  catch (error) {
93
100
  if (signal.aborted)
94
101
  return { ok: false, error: { message: "cancelled", retryable: false } };
95
- return { ok: false, error: { message: errorMessage(error), retryable: true, transient: true } };
102
+ return {
103
+ ok: false,
104
+ error: {
105
+ message: errorMessage(error),
106
+ retryable: true,
107
+ transient: true,
108
+ },
109
+ };
96
110
  }
97
111
  const body = await response.text().catch(() => "");
98
112
  if (!response.ok)
@@ -112,7 +126,7 @@ async function send(endpoint, request, price, signal) {
112
126
  if (!parsed.success) {
113
127
  return { ok: false, error: malformed("answered without a chat completion", body, secrets) };
114
128
  }
115
- const choice = parsed.data.choices[0];
129
+ const [choice] = parsed.data.choices;
116
130
  return {
117
131
  ok: true,
118
132
  content: choice.message.content ?? "",
@@ -178,4 +192,3 @@ function excerpt(body) {
178
192
  return "(empty body)";
179
193
  return text.length > BODY_EXCERPT ? `${text.slice(0, BODY_EXCERPT)}…` : text;
180
194
  }
181
- //# sourceMappingURL=openai.js.map
package/dist/plugin.d.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  import type { OcraPlugin } from "@open-cr-agent/core";
2
2
  export declare const directRuntimePlugin: OcraPlugin;
3
- //# sourceMappingURL=plugin.d.ts.map
package/dist/plugin.js CHANGED
@@ -5,4 +5,3 @@ export const directRuntimePlugin = {
5
5
  ctx.registerRuntime("direct", (options) => new DirectRuntime(options));
6
6
  },
7
7
  };
8
- //# sourceMappingURL=plugin.js.map
@@ -0,0 +1,14 @@
1
+ export declare const RECORD_DIR_ENV = "OCRA_RECORD_DIR";
2
+ export interface Recording {
3
+ version: 1;
4
+ request: Record<string, unknown>;
5
+ answers: {
6
+ status: number;
7
+ body: string;
8
+ }[];
9
+ }
10
+ export declare function exchangeKey(request: {
11
+ messages?: unknown;
12
+ tools?: unknown;
13
+ }): string;
14
+ export declare function recordingFetch(base: typeof fetch, dir: string, secrets: readonly string[]): typeof fetch;
package/dist/record.js ADDED
@@ -0,0 +1,50 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { errorMessage, OcraError, withoutSecrets } from "@open-cr-agent/core";
5
+ // Where the direct runtime writes every model exchange, for replaying a run
6
+ // without a model (tests) or reading what a model was sent and answered.
7
+ export const RECORD_DIR_ENV = "OCRA_RECORD_DIR";
8
+ // What makes two requests the same exchange: the conversation and the tools
9
+ // offered. The model and sampling settings are recorded but do not count, so
10
+ // a replay of a run does not depend on which model of the chain served it.
11
+ export function exchangeKey(request) {
12
+ return createHash("sha256")
13
+ .update(JSON.stringify([request.messages ?? [], request.tools ?? []]))
14
+ .digest("hex")
15
+ .slice(0, 32);
16
+ }
17
+ // Wraps fetch so every chat completion it sends is recorded in `dir`. The
18
+ // directory is created, private to its owner, before any request, so a path
19
+ // that cannot be one fails the run at once rather than every request.
20
+ export function recordingFetch(base, dir, secrets) {
21
+ try {
22
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
23
+ }
24
+ catch (error) {
25
+ throw new OcraError("CONFIG_INVALID", `${RECORD_DIR_ENV} names a directory ocra cannot create: ${errorMessage(error)}`);
26
+ }
27
+ return async (input, init) => {
28
+ const response = await base(input, init);
29
+ if (typeof init?.body !== "string")
30
+ return response;
31
+ const body = await response.text();
32
+ // Synchronous, so two answers to the same request cannot interleave.
33
+ append(dir, JSON.parse(init.body), response.status, body, secrets);
34
+ return new Response(body, {
35
+ status: response.status,
36
+ statusText: response.statusText,
37
+ headers: response.headers,
38
+ });
39
+ };
40
+ }
41
+ function append(dir, request, status, body, secrets) {
42
+ const path = join(dir, `${exchangeKey(request)}.json`);
43
+ const { stream: _, ...sent } = request;
44
+ const recording = existsSync(path)
45
+ ? JSON.parse(readFileSync(path, "utf8"))
46
+ : { version: 1, request: sent, answers: [] };
47
+ recording.answers.push({ status, body });
48
+ const text = withoutSecrets(`${JSON.stringify(recording, null, 2)}\n`, secrets);
49
+ writeFileSync(path, text, { mode: 0o600 });
50
+ }
package/dist/runtime.d.ts CHANGED
@@ -3,19 +3,22 @@ export interface DirectRuntimeOptions extends RuntimeOptions {
3
3
  fetch?: typeof fetch;
4
4
  }
5
5
  export declare class DirectRuntime implements AgentRuntime {
6
- private readonly options;
7
6
  readonly name = "direct";
8
7
  readonly sampling: AppliedSampling;
9
- private readonly health;
8
+ private readonly chains;
10
9
  private readonly tools;
11
10
  private readonly fetch;
12
11
  private readonly efforts;
12
+ private readonly options;
13
13
  constructor(options: DirectRuntimeOptions);
14
+ private recorded;
14
15
  appliedTo(agent: string): AppliedSettings | undefined;
15
16
  runTask(spec: AgentTaskSpec, signal: AbortSignal): AsyncIterable<AgentEvent>;
16
17
  complete(request: CompletionRequest, signal: AbortSignal): Promise<CompletionResult>;
18
+ private attemptTask;
19
+ private attemptCompletion;
17
20
  private unreachable;
18
21
  private call;
22
+ private declared;
19
23
  private target;
20
24
  }
21
- //# sourceMappingURL=runtime.d.ts.map
package/dist/runtime.js CHANGED
@@ -1,85 +1,80 @@
1
- import { OcraError, } from "@open-cr-agent/core";
2
- import { callChain, completeWithFailback, MAX_AGENT_STEPS, ModelHealth, parseModel, proxiedFetch, RESUME_MESSAGE, reviewTools, withFailback, } from "@open-cr-agent/core/internal";
1
+ import { ChainRunner, MAX_AGENT_STEPS, OcraError, parseModel, proxiedFetch, RESUME_MESSAGE, reviewTools, } from "@open-cr-agent/core";
3
2
  import { EffortLedger } from "./effort.js";
4
3
  import { runLoop } from "./loop.js";
4
+ import { RECORD_DIR_ENV, recordingFetch } from "./record.js";
5
5
  // Talks to the declared OpenAI-compatible endpoints itself: no OpenCode
6
6
  // process, no catalog fetch, no package install, nothing on disk. A model of
7
7
  // a provider that is not declared in configuration is refused, since the
8
8
  // runtime knows no other address to send code to.
9
9
  export class DirectRuntime {
10
- options;
11
10
  name = "direct";
12
11
  // The chat completions protocol takes both settings.
13
12
  sampling;
14
- health = new ModelHealth();
13
+ chains;
15
14
  tools;
16
15
  fetch;
17
16
  efforts;
17
+ options;
18
18
  constructor(options) {
19
19
  this.options = options;
20
20
  this.tools = [...reviewTools, ...options.tools];
21
- this.fetch = options.fetch ?? proxiedFetch(options.env);
21
+ this.fetch = this.recorded(options.fetch ?? proxiedFetch(options.env));
22
22
  const { temperature, seed } = options.sampling ?? {};
23
23
  this.sampling = {
24
24
  ...(temperature === undefined ? {} : { temperature }),
25
25
  ...(seed === undefined ? {} : { seed }),
26
26
  };
27
27
  this.efforts = new EffortLedger(this.sampling);
28
+ this.chains = new ChainRunner(options.models, {
29
+ refuse: (chain) => this.unreachable(chain),
30
+ task: (model, spec, signal, onUsage) => this.attemptTask(model, spec, signal, onUsage),
31
+ complete: (model, request, signal) => this.attemptCompletion(model, request, signal),
32
+ });
33
+ }
34
+ // Every exchange goes to the recording directory when one is set, with the
35
+ // keys of all declared providers taken out.
36
+ recorded(base) {
37
+ const dir = this.options.env[RECORD_DIR_ENV];
38
+ if (!dir)
39
+ return base;
40
+ const keys = Object.values(this.options.providers ?? {}).flatMap((p) => p.apiKeyEnv && this.options.env[p.apiKeyEnv] ? [this.options.env[p.apiKeyEnv]] : []);
41
+ return recordingFetch(base, dir, keys);
28
42
  }
29
43
  appliedTo(agent) {
30
44
  return this.efforts.appliedTo(agent);
31
45
  }
32
- async *runTask(spec, signal) {
33
- const chain = callChain(this.options.models, spec.modelTier, spec.models);
34
- const refused = chain.length === 0 ? noModel(spec.modelTier) : this.unreachable(chain);
35
- if (refused) {
36
- yield { type: "error", taskId: spec.taskId, error: refused.message, retryable: false };
37
- return;
38
- }
39
- yield* withFailback({
40
- taskId: spec.taskId,
41
- tier: spec.modelTier,
42
- ...(spec.models?.length ? { agent: spec.reviewer } : {}),
43
- chain,
44
- health: this.health,
46
+ runTask(spec, signal) {
47
+ return this.chains.runTask(spec, signal);
48
+ }
49
+ complete(request, signal) {
50
+ return this.chains.complete(request, signal);
51
+ }
52
+ attemptTask(model, spec, signal, onUsage) {
53
+ return runLoop({
54
+ ...this.target(model),
55
+ ...this.call({ agent: spec.reviewer, effort: spec.effort, model }),
56
+ system: spec.systemPrompt,
57
+ user: spec.userPrompt,
58
+ tools: this.tools,
59
+ context: spec.context,
60
+ maxSteps: MAX_AGENT_STEPS,
61
+ resume: RESUME_MESSAGE,
62
+ timeoutMs: spec.timeoutMs,
45
63
  signal,
46
- attempt: (model, onUsage) => runLoop({
47
- ...this.target(model),
48
- ...this.call({ agent: spec.reviewer, effort: spec.effort, model }),
49
- system: spec.systemPrompt,
50
- user: spec.userPrompt,
51
- tools: this.tools,
52
- context: spec.context,
53
- maxSteps: MAX_AGENT_STEPS,
54
- resume: RESUME_MESSAGE,
55
- timeoutMs: spec.timeoutMs,
56
- signal,
57
- onUsage,
58
- }),
64
+ onUsage,
59
65
  });
60
66
  }
61
- async complete(request, signal) {
62
- const chain = callChain(this.options.models, request.tier, request.models);
63
- const refused = chain.length === 0 ? noModel(request.tier) : this.unreachable(chain);
64
- if (refused)
65
- throw refused;
66
- return completeWithFailback({
67
- tier: request.tier,
68
- ...(request.models?.length ? { agent: request.agent ?? request.tier } : {}),
69
- chain,
70
- health: this.health,
67
+ attemptCompletion(model, request, signal) {
68
+ return runLoop({
69
+ ...this.target(model),
70
+ ...this.call({ agent: request.agent ?? request.tier, effort: request.effort, model }),
71
+ system: request.system,
72
+ user: request.user,
73
+ tools: [],
74
+ context: NO_CONTEXT,
75
+ maxSteps: 1,
76
+ timeoutMs: request.timeoutMs,
71
77
  signal,
72
- attempt: (model) => runLoop({
73
- ...this.target(model),
74
- ...this.call({ agent: request.agent ?? request.tier, effort: request.effort, model }),
75
- system: request.system,
76
- user: request.user,
77
- tools: [],
78
- context: NO_CONTEXT,
79
- maxSteps: 1,
80
- timeoutMs: request.timeoutMs,
81
- signal,
82
- }),
83
78
  });
84
79
  }
85
80
  // Why a chain cannot be served, before any request: a provider the
@@ -87,16 +82,12 @@ export class DirectRuntime {
87
82
  // variable that is not set.
88
83
  unreachable(chain) {
89
84
  for (const model of chain) {
90
- const { providerID, modelID } = parseModel(model);
91
- const provider = this.options.providers?.[providerID];
92
- if (!provider) {
93
- return new OcraError("CONFIG_INVALID", `"${model}" names no provider declared in configuration; the direct runtime reaches only declared OpenAI-compatible endpoints (use the opencode runtime for ${providerID})`);
94
- }
95
- if (!provider.models[modelID]) {
96
- return new OcraError("CONFIG_INVALID", `"${model}" has no price in the declaration of provider "${providerID}"`);
97
- }
98
- if (provider.apiKeyEnv && !this.options.env[provider.apiKeyEnv]) {
99
- return new OcraError("CONFIG_CREDENTIALS_MISSING", `No API key for provider "${providerID}": set ${provider.apiKeyEnv}`);
85
+ const declared = this.declared(model);
86
+ if (declared instanceof OcraError)
87
+ return declared;
88
+ const { apiKeyEnv } = declared.provider;
89
+ if (apiKeyEnv && !this.options.env[apiKeyEnv]) {
90
+ return new OcraError("CONFIG_CREDENTIALS_MISSING", `No API key for provider "${parseModel(model).providerID}": set ${apiKeyEnv}`);
100
91
  }
101
92
  }
102
93
  return undefined;
@@ -111,9 +102,25 @@ export class DirectRuntime {
111
102
  onEffortRefused: () => this.efforts.refuse(agent, model),
112
103
  };
113
104
  }
114
- target(model) {
105
+ // A model's provider and price, from the configuration's declaration.
106
+ declared(model) {
115
107
  const { providerID, modelID } = parseModel(model);
116
108
  const provider = this.options.providers?.[providerID];
109
+ if (!provider) {
110
+ return new OcraError("CONFIG_INVALID", `"${model}" names no provider declared in configuration; the direct runtime reaches only declared OpenAI-compatible endpoints (use the opencode runtime for ${providerID})`);
111
+ }
112
+ const price = provider.models[modelID];
113
+ if (!price) {
114
+ return new OcraError("CONFIG_INVALID", `"${model}" has no price in the declaration of provider "${providerID}"`);
115
+ }
116
+ return { provider, modelID, price };
117
+ }
118
+ // Only for a model unreachable() let through, so declared() cannot fail.
119
+ target(model) {
120
+ const declared = this.declared(model);
121
+ if (declared instanceof OcraError)
122
+ throw declared;
123
+ const { provider, modelID, price } = declared;
117
124
  const key = provider.apiKeyEnv ? this.options.env[provider.apiKeyEnv] : undefined;
118
125
  return {
119
126
  endpoint: {
@@ -122,7 +129,7 @@ export class DirectRuntime {
122
129
  fetch: this.fetch,
123
130
  },
124
131
  model: modelID,
125
- price: provider.models[modelID],
132
+ price,
126
133
  };
127
134
  }
128
135
  }
@@ -132,7 +139,3 @@ const NO_CONTEXT = {
132
139
  readDiff: () => undefined,
133
140
  searchCode: async () => [],
134
141
  };
135
- function noModel(tier) {
136
- return new OcraError("CONFIG_INVALID", `No ${tier} model configured (set OCRA_MODEL_${tier.toUpperCase()} or models.${tier})`);
137
- }
138
- //# sourceMappingURL=runtime.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-cr-agent/runtime-direct",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Agent runtime for Open-CR-Agent that calls OpenAI-compatible endpoints directly",
5
5
  "keywords": [
6
6
  "code-review",
@@ -33,7 +33,7 @@
33
33
  "!dist/**/*.map"
34
34
  ],
35
35
  "dependencies": {
36
- "@open-cr-agent/core": "0.5.0",
36
+ "@open-cr-agent/core": "0.7.0",
37
37
  "zod": "^4.6.5"
38
38
  },
39
39
  "publishConfig": {