@open-cr-agent/runtime-direct 0.12.0 → 0.13.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.
@@ -0,0 +1,2 @@
1
+ import { type Wire } from "./wire.js";
2
+ export declare const anthropicWire: Wire;
@@ -0,0 +1,182 @@
1
+ import Anthropic from "@anthropic-ai/sdk";
2
+ import { errorMessage, parseQuotaError, withoutSecrets, } from "@open-cr-agent/core";
3
+ import { z } from "zod";
4
+ import { excerpt, onceMore, pricedUsage, retryableStatus, transientStatus, withoutEffort, } from "./wire.js";
5
+ // Room for an answer with its reasoning; the protocol requires a cap.
6
+ const MAX_OUTPUT_TOKENS = 32_000;
7
+ // Anthropic charges a quarter above the input rate for input it stores.
8
+ const CACHE_WRITE_FACTOR = 1.25;
9
+ const CACHED = { cache_control: { type: "ephemeral" } };
10
+ // How the API names the effort parameters in a 400 that refuses them.
11
+ const EFFORT_PARAMETER = /\b(?:effort|output_config|thinking)\b/i;
12
+ // The API has no level under "low", and its newer models cannot stop
13
+ // reasoning, so the two lowest levels go as "low".
14
+ const LEVELS = {
15
+ none: "low",
16
+ minimal: "low",
17
+ low: "low",
18
+ medium: "medium",
19
+ high: "high",
20
+ };
21
+ // A conversation in Anthropic's Messages protocol, streamed so a long answer
22
+ // does not sit behind an idle connection. The system prompt and the
23
+ // conversation so far are marked for the provider's prompt cache at every
24
+ // request: an agent's next step reads what the last one stored.
25
+ export const anthropicWire = ({ endpoint, model, price, system }) => {
26
+ const client = clientOf(endpoint);
27
+ const secrets = endpoint.apiKey ? [endpoint.apiKey] : [];
28
+ const messages = [];
29
+ const send = (request, signal) => onceMore(() => stream(client, request, price, secrets, signal), signal);
30
+ return {
31
+ say: (text) => {
32
+ messages.push({ role: "user", content: [{ type: "text", text }] });
33
+ },
34
+ ask: async (tools, settings, signal) => {
35
+ const request = (sent) => ({
36
+ model,
37
+ max_tokens: MAX_OUTPUT_TOKENS,
38
+ system: [{ type: "text", text: system, ...CACHED }],
39
+ messages: withBreakpoint(messages),
40
+ ...(tools.length > 0 ? { tools: tools.map(toolSpec) } : {}),
41
+ ...effortParams(sent.effort),
42
+ });
43
+ let reply = await send(request(settings), signal);
44
+ let dropped = false;
45
+ if (!reply.ok && reply.error.effortRefused && settings.effort !== undefined) {
46
+ reply = await send(request(withoutEffort(settings)), signal);
47
+ dropped = true;
48
+ }
49
+ const effortDropped = dropped ? { effortDropped: true } : {};
50
+ if (!reply.ok)
51
+ return { ...reply, ...effortDropped };
52
+ const { content } = reply.message;
53
+ if (content.length > 0)
54
+ messages.push({ role: "assistant", content });
55
+ return {
56
+ ok: true,
57
+ text: content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join(""),
58
+ calls: content.flatMap((block) => block.type === "tool_use" ? [{ id: block.id, name: block.name, input: block.input }] : []),
59
+ usage: reply.usage,
60
+ ...effortDropped,
61
+ };
62
+ },
63
+ answer: (outputs) => {
64
+ messages.push({
65
+ role: "user",
66
+ content: outputs.map(({ call, output }) => ({
67
+ type: "tool_result",
68
+ tool_use_id: call.id,
69
+ content: output,
70
+ })),
71
+ });
72
+ },
73
+ };
74
+ };
75
+ // A key is always given, an empty one for an endpoint that takes none (its
76
+ // header is then left out), so the SDK never looks for a credential of its
77
+ // own in the environment or on disk: only the key named for this provider
78
+ // goes out, and only to its base URL.
79
+ function clientOf(endpoint) {
80
+ return new Anthropic({
81
+ baseURL: endpoint.baseUrl.replace(/\/$/, ""),
82
+ apiKey: endpoint.apiKey ?? "",
83
+ ...(endpoint.apiKey ? {} : { defaultHeaders: { authorization: null } }),
84
+ maxRetries: 0,
85
+ logLevel: "off",
86
+ ...(endpoint.fetch ? { fetch: endpoint.fetch } : {}),
87
+ });
88
+ }
89
+ function toolSpec(tool) {
90
+ const { $schema: _, ...schema } = z.toJSONSchema(tool.inputSchema);
91
+ return {
92
+ name: tool.name,
93
+ description: tool.description,
94
+ input_schema: schema,
95
+ };
96
+ }
97
+ function effortParams(effort) {
98
+ if (effort === undefined)
99
+ return {};
100
+ return {
101
+ output_config: { effort: LEVELS[effort] },
102
+ ...(effort === "none" ? {} : { thinking: { type: "adaptive" } }),
103
+ };
104
+ }
105
+ // The last block of the conversation carries the cache mark; the stored
106
+ // messages stay unmarked, so each request has one.
107
+ function withBreakpoint(messages) {
108
+ const last = messages.at(-1);
109
+ if (!last || typeof last.content === "string")
110
+ return [...messages];
111
+ const blocks = last.content;
112
+ const tail = blocks.at(-1);
113
+ if (tail?.type !== "text" && tail?.type !== "tool_result")
114
+ return [...messages];
115
+ return [
116
+ ...messages.slice(0, -1),
117
+ { ...last, content: [...blocks.slice(0, -1), { ...tail, ...CACHED }] },
118
+ ];
119
+ }
120
+ async function stream(client, request, price, secrets, signal) {
121
+ let message;
122
+ try {
123
+ message = await client.messages.stream(request, { signal }).finalMessage();
124
+ }
125
+ catch (error) {
126
+ if (signal.aborted)
127
+ return { ok: false, error: { message: "cancelled", retryable: false } };
128
+ return { ok: false, error: failure(error, secrets) };
129
+ }
130
+ const cut = cutOff(message);
131
+ if (cut)
132
+ return { ok: false, error: { message: cut, retryable: true } };
133
+ return { ok: true, message, usage: usageOf(message.usage, price) };
134
+ }
135
+ // Why an answer cannot be used as it is. One cut off inside a tool call
136
+ // would run the tool on half its input.
137
+ function cutOff(message) {
138
+ switch (message.stop_reason) {
139
+ case "refusal":
140
+ return `the model declined to answer${message.stop_details?.category ? ` (${message.stop_details.category})` : ""}`;
141
+ case "max_tokens":
142
+ return `the answer was cut off at ${MAX_OUTPUT_TOKENS} output tokens`;
143
+ case "model_context_window_exceeded":
144
+ return "the conversation no longer fits the model's context window";
145
+ default:
146
+ return undefined;
147
+ }
148
+ }
149
+ function failure(error, secrets) {
150
+ // An endpoint may echo the request's headers in an error.
151
+ const shown = excerpt(withoutSecrets(errorMessage(error), secrets));
152
+ if (!(error instanceof Anthropic.APIError) || error.status === undefined) {
153
+ // No status: the connection failed, or the stream was not one the SDK
154
+ // could read to its end.
155
+ return { message: shown, retryable: true, transient: true };
156
+ }
157
+ const { status } = error;
158
+ const quota = parseQuotaError(shown, status);
159
+ if (quota && quota.retryAfterMs === undefined) {
160
+ const retryAfter = Number(error.headers?.get("retry-after"));
161
+ if (Number.isFinite(retryAfter) && retryAfter > 0)
162
+ quota.retryAfterMs = retryAfter * 1000;
163
+ }
164
+ return {
165
+ message: `HTTP ${shown}`,
166
+ retryable: retryableStatus(status),
167
+ ...(status === 400 && EFFORT_PARAMETER.test(shown) ? { effortRefused: true } : {}),
168
+ ...(quota ? { quota } : {}),
169
+ ...(!quota && transientStatus(status) ? { transient: true } : {}),
170
+ };
171
+ }
172
+ // Anthropic counts cached input apart from fresh input, and reasoning
173
+ // inside the output.
174
+ function usageOf(usage, price) {
175
+ return pricedUsage({
176
+ input: usage.input_tokens,
177
+ cached: usage.cache_read_input_tokens ?? 0,
178
+ written: usage.cache_creation_input_tokens ?? 0,
179
+ output: usage.output_tokens,
180
+ reasoning: usage.output_tokens_details?.thinking_tokens ?? 0,
181
+ }, price, CACHE_WRITE_FACTOR);
182
+ }
package/dist/effort.d.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  import type { AppliedSettings, Effort, Sampling } from "@open-cr-agent/core";
2
- import type { CallParams } from "./openai.js";
3
- export type EffortStyle = "openai" | "openrouter";
2
+ import type { CallSettings } from "./wire.js";
4
3
  export declare class EffortLedger {
5
4
  private readonly refused;
6
5
  private readonly applied;
7
6
  private readonly sampling;
8
7
  constructor(sampling: Sampling);
9
- params(agent: string, effort: Effort | undefined, model: string, style?: EffortStyle): CallParams;
8
+ params(agent: string, effort: Effort | undefined, model: string, takesSampling?: boolean): CallSettings;
10
9
  refuse(agent: string, model: string): void;
11
10
  appliedTo(agent: string): AppliedSettings | undefined;
12
11
  private record;
package/dist/effort.js CHANGED
@@ -2,7 +2,8 @@
2
2
  // per agent (ADR-0025). Reasoning models refuse a temperature (OpenAI) or
3
3
  // need their own (Anthropic), so a call that asks for an effort other than
4
4
  // "none" sends no sampling settings, even after its endpoint refused the
5
- // effort: the agent's calls stay alike within a run.
5
+ // effort: the agent's calls stay alike within a run. A protocol that takes
6
+ // no sampling settings (Anthropic's Messages) is sent none at all.
6
7
  export class EffortLedger {
7
8
  // Models whose endpoint refused the effort parameter: later calls go
8
9
  // without it instead of paying for another refusal.
@@ -12,16 +13,19 @@ export class EffortLedger {
12
13
  constructor(sampling) {
13
14
  this.sampling = sampling;
14
15
  }
15
- params(agent, effort, model, style = "openai") {
16
- if (effort === undefined)
17
- return { ...this.sampling };
18
- const keepsSampling = effort === "none";
16
+ params(agent, effort, model, takesSampling = true) {
17
+ const asked = requested(this.sampling);
18
+ if (effort === undefined) {
19
+ if (takesSampling)
20
+ return { ...this.sampling };
21
+ if (asked.length > 0)
22
+ this.record(agent, true, asked);
23
+ return {};
24
+ }
25
+ const keepsSampling = takesSampling && effort === "none";
19
26
  const sends = !this.refused.has(model);
20
- this.record(agent, sends, keepsSampling ? [] : requested(this.sampling));
21
- return {
22
- ...(keepsSampling ? this.sampling : {}),
23
- ...(sends ? effortParam(effort, style) : {}),
24
- };
27
+ this.record(agent, sends, keepsSampling ? [] : asked);
28
+ return { ...(keepsSampling ? this.sampling : {}), ...(sends ? { effort } : {}) };
25
29
  }
26
30
  refuse(agent, model) {
27
31
  this.refused.add(model);
@@ -40,9 +44,6 @@ export class EffortLedger {
40
44
  });
41
45
  }
42
46
  }
43
- function effortParam(effort, style) {
44
- return style === "openrouter" ? { reasoning: { effort } } : { reasoning_effort: effort };
45
- }
46
47
  function requested(sampling) {
47
48
  return ["temperature", "seed"].filter((key) => sampling[key] !== undefined);
48
49
  }
package/dist/loop.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type ModelPrice, type ReviewContext, type TaskAttempt, type ToolDefinition, type Usage } from "@open-cr-agent/core";
2
- import { type CallParams, type Endpoint } from "./openai.js";
2
+ import { type CallSettings, type Endpoint, type Wire } from "./wire.js";
3
3
  export interface LoopInput {
4
+ wire: Wire;
4
5
  endpoint: Endpoint;
5
6
  model: string;
6
7
  price: ModelPrice;
@@ -12,7 +13,7 @@ export interface LoopInput {
12
13
  resume?: string;
13
14
  wrapUp?: WrapUpTurn;
14
15
  timeoutMs: number;
15
- params?: CallParams;
16
+ settings?: CallSettings;
16
17
  onEffortRefused?: () => void;
17
18
  signal: AbortSignal;
18
19
  onUsage?: (spent: Usage) => void;
package/dist/loop.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { addUsage, emptyUsage, errorMessage, exploredBy, REVIEW_TOOLS, } from "@open-cr-agent/core";
2
- import { chat, toolSpec, withoutEffort, } from "./openai.js";
2
+ import { withoutEffort, } from "./wire.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
5
5
  // tools, or runs out of steps. The model reaches nothing but these tools and
@@ -17,13 +17,13 @@ export async function runLoop(input) {
17
17
  wrapUp: () => conversation.turn(wrapUp.message, tools, outcome.steps + wrapUp.steps),
18
18
  };
19
19
  }
20
- // One attempt's messages and outcome, which a later turn continues under the
20
+ // One attempt's dialogue and outcome, which a later turn continues under the
21
21
  // attempt's signal and timeout.
22
22
  class Conversation {
23
23
  input;
24
24
  timeout;
25
25
  signal;
26
- messages;
26
+ dialogue;
27
27
  outcome = {
28
28
  findings: [],
29
29
  steps: 0,
@@ -33,32 +33,26 @@ class Conversation {
33
33
  };
34
34
  texts = [];
35
35
  uses = [];
36
- params;
36
+ settings;
37
37
  constructor(input) {
38
38
  this.input = input;
39
39
  this.timeout = AbortSignal.timeout(input.timeoutMs);
40
40
  this.signal = AbortSignal.any([input.signal, this.timeout]);
41
- this.messages = [{ role: "system", content: input.system }];
42
- this.params = input.params ?? {};
41
+ this.dialogue = input.wire(input);
42
+ this.settings = input.settings ?? {};
43
43
  }
44
44
  // Runs until the done tool, an answer without tools, or `maxSteps` steps
45
45
  // in the whole attempt; returns the attempt's outcome so far.
46
46
  async turn(message, offered, maxSteps, resume) {
47
- const { input, messages, outcome, texts, uses } = this;
47
+ const { input, dialogue, outcome, texts, uses } = this;
48
48
  const tools = new Map(offered.map((t) => [t.name, t]));
49
- const specs = offered.map(toolSpec);
50
49
  let done = false;
51
- messages.push({ role: "user", content: message });
50
+ dialogue.say(message);
52
51
  while (outcome.steps < maxSteps) {
53
- const response = await chat(input.endpoint, {
54
- model: input.model,
55
- messages,
56
- ...(specs.length > 0 ? { tools: specs } : {}),
57
- ...this.params,
58
- }, input.price, this.signal);
52
+ const response = await dialogue.ask(offered, this.settings, this.signal);
59
53
  outcome.steps += 1;
60
54
  if (response.effortDropped) {
61
- this.params = withoutEffort(this.params);
55
+ this.settings = withoutEffort(this.settings);
62
56
  input.onEffortRefused?.();
63
57
  }
64
58
  if (!response.ok) {
@@ -69,32 +63,26 @@ class Conversation {
69
63
  }
70
64
  outcome.usage = addUsage(outcome.usage, response.usage);
71
65
  input.onUsage?.(outcome.usage);
72
- if (response.content)
73
- texts.push(response.content);
74
- messages.push({
75
- role: "assistant",
76
- content: response.content || null,
77
- ...(response.toolCalls.length > 0 ? { tool_calls: response.toolCalls } : {}),
78
- });
79
- if (response.toolCalls.length === 0) {
66
+ if (response.text)
67
+ texts.push(response.text);
68
+ if (response.calls.length === 0) {
80
69
  const stoppedEarly = resume && !outcome.resumed && texts.join("").trim() === "";
81
70
  if (stoppedEarly && outcome.steps < maxSteps) {
82
71
  outcome.resumed = true;
83
- messages.push({ role: "user", content: resume });
72
+ dialogue.say(resume);
84
73
  continue;
85
74
  }
86
75
  break;
87
76
  }
88
- for (const call of response.toolCalls) {
89
- outcome.toolCalls.push(call.function.name);
90
- if (call.function.name === REVIEW_TOOLS.taskDone)
77
+ // Together, as OpenCode runs a step's calls, so its searches share one
78
+ // grep; each call is recorded as it starts, in the order given.
79
+ const outputs = await Promise.all(response.calls.map(async (call) => {
80
+ outcome.toolCalls.push(call.name);
81
+ if (call.name === REVIEW_TOOLS.taskDone)
91
82
  done = true;
92
- messages.push({
93
- role: "tool",
94
- tool_call_id: call.id,
95
- content: await runTool(tools, call, input.context, outcome, uses),
96
- });
97
- }
83
+ return { call, output: await runTool(tools, call, input.context, outcome, uses) };
84
+ }));
85
+ dialogue.answer(outputs);
98
86
  if (done)
99
87
  break;
100
88
  }
@@ -114,17 +102,12 @@ function snapshot(outcome) {
114
102
  // A tool's answer, or why it gave none: a wrong call is told to the model,
115
103
  // which may correct it, and never ends the attempt.
116
104
  async function runTool(tools, call, context, outcome, uses) {
117
- const tool = tools.get(call.function.name);
105
+ const tool = tools.get(call.name);
118
106
  if (!tool)
119
- return `Unknown tool: ${call.function.name}`;
120
- let args;
121
- try {
122
- args = JSON.parse(call.function.arguments || "{}");
123
- }
124
- catch {
107
+ return `Unknown tool: ${call.name}`;
108
+ if (call.malformed)
125
109
  return "Invalid arguments: not JSON";
126
- }
127
- const parsed = tool.inputSchema.safeParse(args);
110
+ const parsed = tool.inputSchema.safeParse(call.input);
128
111
  if (!parsed.success) {
129
112
  return `Invalid arguments: ${parsed.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; ")}`;
130
113
  }
package/dist/openai.d.ts CHANGED
@@ -1,85 +1,3 @@
1
- import { type Effort, type ModelPrice, type QuotaError, type ToolDefinition, type Usage } from "@open-cr-agent/core";
2
- import { z } from "zod";
3
- declare const toolCallSchema: z.ZodPipe<z.ZodObject<{
4
- id: z.ZodString;
5
- function: z.ZodObject<{
6
- name: z.ZodString;
7
- arguments: z.ZodString;
8
- }, z.core.$strip>;
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>;
27
- export type ChatMessage = {
28
- role: "system" | "user";
29
- content: string;
30
- } | {
31
- role: "assistant";
32
- content: string | null;
33
- tool_calls?: ToolCall[];
34
- } | {
35
- role: "tool";
36
- tool_call_id: string;
37
- content: string;
38
- };
39
- export interface ToolSpec {
40
- type: "function";
41
- function: {
42
- name: string;
43
- description: string;
44
- parameters: Record<string, unknown>;
45
- };
46
- }
47
- export interface Endpoint {
48
- baseUrl: string;
49
- apiKey?: string;
50
- fetch?: typeof fetch;
51
- }
52
- export interface ChatRequest {
53
- model: string;
54
- messages: readonly ChatMessage[];
55
- tools?: readonly ToolSpec[];
56
- temperature?: number;
57
- seed?: number;
58
- reasoning_effort?: Effort;
59
- reasoning?: {
60
- effort: Effort;
61
- };
62
- }
63
- export type CallParams = Pick<ChatRequest, "temperature" | "seed" | "reasoning_effort" | "reasoning">;
64
- interface ChatError {
65
- message: string;
66
- retryable: boolean;
67
- quota?: QuotaError;
68
- transient?: boolean;
69
- effortRefused?: boolean;
70
- }
71
- export type ChatResponse = ({
72
- ok: true;
73
- content: string;
74
- toolCalls: ToolCall[];
75
- usage: Usage;
76
- } | {
77
- ok: false;
78
- error: ChatError;
79
- }) & {
80
- effortDropped?: true;
81
- };
82
- export declare function toolSpec(tool: ToolDefinition): ToolSpec;
83
- export declare function chat(endpoint: Endpoint, request: ChatRequest, price: ModelPrice, signal: AbortSignal): Promise<ChatResponse>;
84
- export declare function withoutEffort<T extends CallParams>(params: T): T;
85
- export {};
1
+ import { type Wire } from "./wire.js";
2
+ export type EffortStyle = "openai" | "openrouter";
3
+ export declare function openaiWire(style?: EffortStyle): Wire;
package/dist/openai.js CHANGED
@@ -1,6 +1,6 @@
1
- import { setTimeout } from "node:timers/promises";
2
1
  import { errorMessage, parseQuotaError, withoutSecrets, } from "@open-cr-agent/core";
3
2
  import { z } from "zod";
3
+ import { excerpt, onceMore, pricedUsage, retryableStatus, transientStatus, } from "./wire.js";
4
4
  // The subset of the OpenAI chat completions protocol the loop needs: one
5
5
  // choice, its text and tool calls, and the token counts. Anything else an
6
6
  // endpoint adds is dropped at this boundary, except a tool call's
@@ -36,16 +36,64 @@ const completionSchema = z.object({
36
36
  const errorBodySchema = z.object({
37
37
  error: z.object({ message: z.string(), code: z.number().optional() }),
38
38
  });
39
- const AUTH_STATUS = new Set([401, 403]);
40
39
  // How an endpoint names the effort parameters in a 400 that refuses them.
41
40
  const EFFORT_PARAMETER = /\breasoning(?:_effort)?\b/i;
42
- // How much of an error body an error message keeps: enough to diagnose, not
43
- // a page of HTML.
44
- const BODY_EXCERPT = 300;
45
- // A transient failure is sent once more after this pause; a second failure
46
- // goes to the failback, which decides what it means for the model.
47
- const TRANSIENT_RETRY_MS = 1_000;
48
- export function toolSpec(tool) {
41
+ // A conversation in OpenAI's chat completions protocol, with the effort sent
42
+ // the way the provider declares.
43
+ export function openaiWire(style = "openai") {
44
+ return ({ endpoint, model, price, system }) => {
45
+ const messages = [{ role: "system", content: system }];
46
+ return {
47
+ say: (text) => {
48
+ messages.push({ role: "user", content: text });
49
+ },
50
+ ask: async (tools, settings, signal) => {
51
+ const specs = tools.map(toolSpec);
52
+ const request = {
53
+ model,
54
+ messages,
55
+ ...(specs.length > 0 ? { tools: specs } : {}),
56
+ ...params(settings, style),
57
+ };
58
+ const response = await chat(endpoint, request, price, signal);
59
+ const dropped = response.effortDropped ? { effortDropped: true } : {};
60
+ if (!response.ok)
61
+ return { ...response, ...dropped };
62
+ const { content, toolCalls, usage } = response;
63
+ messages.push({
64
+ role: "assistant",
65
+ content: content || null,
66
+ ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
67
+ });
68
+ return { ok: true, text: content, calls: toolCalls.map(toolRequest), usage, ...dropped };
69
+ },
70
+ answer: (outputs) => {
71
+ for (const { call, output } of outputs) {
72
+ messages.push({ role: "tool", tool_call_id: call.id, content: output });
73
+ }
74
+ },
75
+ };
76
+ };
77
+ }
78
+ function params({ effort, ...sampling }, style) {
79
+ if (effort === undefined)
80
+ return sampling;
81
+ return {
82
+ ...sampling,
83
+ ...(style === "openrouter" ? { reasoning: { effort } } : { reasoning_effort: effort }),
84
+ };
85
+ }
86
+ function toolRequest(call) {
87
+ const { id } = call;
88
+ const { name } = call.function;
89
+ try {
90
+ return { id, name, input: JSON.parse(call.function.arguments || "{}") };
91
+ }
92
+ catch {
93
+ return { id, name, input: undefined, malformed: true };
94
+ }
95
+ }
96
+ function toolSpec(tool) {
49
97
  const { $schema: _, ...parameters } = z.toJSONSchema(tool.inputSchema);
50
98
  return {
51
99
  type: "function",
@@ -55,33 +103,21 @@ export function toolSpec(tool) {
55
103
  // One request to the endpoint. A refused effort parameter is not the model's
56
104
  // failure: the request goes once more without it, so the review still runs
57
105
  // and the failback chain does not move.
58
- export async function chat(endpoint, request, price, signal) {
59
- const first = await sendRetrying(endpoint, request, price, signal);
106
+ async function chat(endpoint, request, price, signal) {
107
+ const sent = (body) => onceMore(() => send(endpoint, body, price, signal), signal);
108
+ const first = await sent(request);
60
109
  if (first.ok || !first.error.effortRefused || !hasEffort(request))
61
110
  return first;
62
- return {
63
- ...(await sendRetrying(endpoint, withoutEffort(request), price, signal)),
64
- effortDropped: true,
65
- };
111
+ return { ...(await sent(withoutEffort(request))), effortDropped: true };
66
112
  }
67
- function hasEffort(params) {
68
- return params.reasoning_effort !== undefined || params.reasoning !== undefined;
113
+ function hasEffort(request) {
114
+ return request.reasoning_effort !== undefined || request.reasoning !== undefined;
69
115
  }
70
- export function withoutEffort(params) {
71
- const { reasoning_effort: _effort, reasoning: _reasoning, ...rest } = params;
116
+ function withoutEffort(request) {
117
+ const { reasoning_effort: _effort, reasoning: _reasoning, ...rest } = request;
72
118
  return rest;
73
119
  }
74
- // Sent a second time when the first failed in a way a moment may cure. Only
75
- // the key named for this provider goes out, and only to its base URL.
76
- async function sendRetrying(endpoint, request, price, signal) {
77
- const first = await send(endpoint, request, price, signal);
78
- if (first.ok || !first.error.transient)
79
- return first;
80
- await setTimeout(TRANSIENT_RETRY_MS, undefined, { signal }).catch(() => undefined);
81
- if (signal.aborted)
82
- return first;
83
- return send(endpoint, request, price, signal);
84
- }
120
+ // Only the key named for this provider goes out, and only to its base URL.
85
121
  async function send(endpoint, request, price, signal) {
86
122
  const headers = { "content-type": "application/json" };
87
123
  if (endpoint.apiKey)
@@ -154,10 +190,10 @@ function failure(response, body, secrets, reportedCode) {
154
190
  }
155
191
  return {
156
192
  message,
157
- retryable: !AUTH_STATUS.has(status),
193
+ retryable: retryableStatus(status),
158
194
  ...(status === 400 && EFFORT_PARAMETER.test(body) ? { effortRefused: true } : {}),
159
195
  ...(quota ? { quota } : {}),
160
- ...(!quota && (status >= 500 || status === 408) ? { transient: true } : {}),
196
+ ...(!quota && transientStatus(status) ? { transient: true } : {}),
161
197
  };
162
198
  }
163
199
  function malformed(what, body, secrets) {
@@ -167,28 +203,14 @@ function malformed(what, body, secrets) {
167
203
  transient: true,
168
204
  };
169
205
  }
170
- // Cached tokens are counted inside the prompt tokens, as OpenAI does; they
171
- // are priced at the cached rate when the provider declares one.
206
+ // Cached tokens are counted inside the prompt tokens, as OpenAI does.
172
207
  function usageOf(usage, price) {
173
208
  const prompt = usage?.prompt_tokens ?? 0;
174
209
  const cached = Math.min(prompt, usage?.prompt_tokens_details?.cached_tokens ?? 0);
175
- const input = prompt - cached;
176
- const output = usage?.completion_tokens ?? 0;
177
- const reasoning = usage?.completion_tokens_details?.reasoning_tokens ?? 0;
178
- const perToken = (perMillion) => perMillion / 1_000_000;
179
- return {
180
- inputTokens: input,
181
- outputTokens: output,
182
- reasoningTokens: reasoning,
183
- cachedTokens: cached,
184
- costUsd: input * perToken(price.input) +
185
- cached * perToken(price.cachedInput ?? price.input) +
186
- output * perToken(price.output),
187
- };
188
- }
189
- function excerpt(body) {
190
- const text = body.replace(/\s+/g, " ").trim();
191
- if (text.length === 0)
192
- return "(empty body)";
193
- return text.length > BODY_EXCERPT ? `${text.slice(0, BODY_EXCERPT)}…` : text;
210
+ return pricedUsage({
211
+ input: prompt - cached,
212
+ cached,
213
+ output: usage?.completion_tokens ?? 0,
214
+ reasoning: usage?.completion_tokens_details?.reasoning_tokens ?? 0,
215
+ }, price);
194
216
  }
package/dist/record.d.ts CHANGED
@@ -12,5 +12,6 @@ export type Recording = z.infer<typeof recordingSchema>;
12
12
  export declare function exchangeKey(request: {
13
13
  messages?: unknown;
14
14
  tools?: unknown;
15
+ system?: unknown;
15
16
  }): string;
16
17
  export declare function recordingFetch(base: typeof fetch, dir: string, secrets: () => readonly string[], warn: (message: string) => void): typeof fetch;
package/dist/record.js CHANGED
@@ -16,15 +16,17 @@ export const recordingSchema = z.object({
16
16
  answers: z.array(z.object({ status: z.number().int(), body: z.string() })),
17
17
  });
18
18
  // What makes two requests the same exchange: the conversation and the tools
19
- // offered. The model and sampling settings are recorded but do not count, so
20
- // a replay of a run does not depend on which model of the chain served it.
19
+ // offered, with the system prompt where the protocol keeps it apart from the
20
+ // messages. The model and sampling settings are recorded but do not count,
21
+ // so a replay of a run does not depend on which model of the chain served it.
21
22
  export function exchangeKey(request) {
23
+ const { messages = [], tools = [], system } = request;
22
24
  return createHash("sha256")
23
- .update(JSON.stringify([request.messages ?? [], request.tools ?? []]))
25
+ .update(JSON.stringify(system === undefined ? [messages, tools] : [messages, tools, system]))
24
26
  .digest("hex")
25
27
  .slice(0, 32);
26
28
  }
27
- // Wraps fetch so every chat completion it sends is recorded in `dir`. The
29
+ // Wraps fetch so every model request it sends is recorded in `dir`. The
28
30
  // directory is created, private to its owner, before any request, so a path
29
31
  // that cannot be one fails the run at once rather than every request.
30
32
  // `secrets` is asked when each request is sent and again at its write, and
package/dist/runtime.js CHANGED
@@ -1,14 +1,18 @@
1
1
  import { ChainRunner, MAX_AGENT_STEPS, OcraError, parseModel, proxiedFetch, RESUME_MESSAGE, reviewTools, WRAP_UP_MESSAGE, WRAP_UP_STEPS, WRAP_UP_TOOLS, } from "@open-cr-agent/core";
2
+ import { anthropicWire } from "./anthropic.js";
2
3
  import { EffortLedger } from "./effort.js";
3
4
  import { runLoop } from "./loop.js";
5
+ import { openaiWire } from "./openai.js";
4
6
  import { RECORD_DIR_ENV, recordingFetch } from "./record.js";
5
- // Talks to the declared OpenAI-compatible endpoints itself: no OpenCode
6
- // process, no catalog fetch, no package install, nothing on disk. A model of
7
+ // Talks to the declared endpoints itself, in OpenAI's chat completions or
8
+ // Anthropic's Messages protocol as each declares: no OpenCode process, no
9
+ // catalog fetch, no package install, nothing on disk. A model of
7
10
  // a provider that is not declared in configuration is refused, since the
8
11
  // runtime knows no other address to send code to.
9
12
  export class DirectRuntime {
10
13
  name = "direct";
11
- // The chat completions protocol takes both settings.
14
+ // The chat completions protocol takes both settings; an agent on a
15
+ // Messages endpoint reports them as not applied.
12
16
  sampling;
13
17
  chains;
14
18
  tools;
@@ -110,9 +114,9 @@ export class DirectRuntime {
110
114
  // effort is recorded.
111
115
  call({ agent, effort, model }) {
112
116
  const { providerID } = parseModel(model);
113
- const style = this.options.providers?.[providerID]?.effort;
117
+ const takesSampling = this.options.providers?.[providerID]?.api !== "anthropic";
114
118
  return {
115
- params: this.efforts.params(agent, effort, model, style),
119
+ settings: this.efforts.params(agent, effort, model, takesSampling),
116
120
  onEffortRefused: () => this.efforts.refuse(agent, model),
117
121
  };
118
122
  }
@@ -121,7 +125,7 @@ export class DirectRuntime {
121
125
  const { providerID, modelID } = parseModel(model);
122
126
  const provider = this.options.providers?.[providerID];
123
127
  if (!provider) {
124
- 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})`);
128
+ return new OcraError("CONFIG_INVALID", `"${model}" names no provider declared in configuration; the direct runtime reaches only declared endpoints (use the opencode runtime for ${providerID})`);
125
129
  }
126
130
  const price = provider.models[modelID];
127
131
  if (!price) {
@@ -137,6 +141,7 @@ export class DirectRuntime {
137
141
  const { provider, modelID, price } = declared;
138
142
  const key = provider.apiKeyEnv ? this.options.env[provider.apiKeyEnv] : undefined;
139
143
  return {
144
+ wire: provider.api === "anthropic" ? anthropicWire : openaiWire(provider.effort),
140
145
  endpoint: {
141
146
  baseUrl: provider.baseUrl,
142
147
  ...(key ? { apiKey: key } : {}),
package/dist/wire.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { Effort, ModelPrice, QuotaError, ToolDefinition, Usage } from "@open-cr-agent/core";
2
+ export interface Endpoint {
3
+ baseUrl: string;
4
+ apiKey?: string;
5
+ fetch?: typeof fetch;
6
+ }
7
+ export interface CallSettings {
8
+ temperature?: number;
9
+ seed?: number;
10
+ effort?: Effort;
11
+ }
12
+ export interface ToolRequest {
13
+ id: string;
14
+ name: string;
15
+ input: unknown;
16
+ malformed?: true;
17
+ }
18
+ export interface CallError {
19
+ message: string;
20
+ retryable: boolean;
21
+ quota?: QuotaError;
22
+ transient?: boolean;
23
+ effortRefused?: boolean;
24
+ }
25
+ export type Answer = ({
26
+ ok: true;
27
+ text: string;
28
+ calls: ToolRequest[];
29
+ usage: Usage;
30
+ } | {
31
+ ok: false;
32
+ error: CallError;
33
+ }) & {
34
+ effortDropped?: true;
35
+ };
36
+ export interface Dialogue {
37
+ say(text: string): void;
38
+ ask(tools: readonly ToolDefinition[], settings: CallSettings, signal: AbortSignal): Promise<Answer>;
39
+ answer(outputs: readonly {
40
+ call: ToolRequest;
41
+ output: string;
42
+ }[]): void;
43
+ }
44
+ interface DialogueStart {
45
+ endpoint: Endpoint;
46
+ model: string;
47
+ price: ModelPrice;
48
+ system: string;
49
+ }
50
+ export type Wire = (start: DialogueStart) => Dialogue;
51
+ export declare function withoutEffort(settings: CallSettings): CallSettings;
52
+ export declare function onceMore<R extends {
53
+ ok: true;
54
+ } | {
55
+ ok: false;
56
+ error: CallError;
57
+ }>(send: () => Promise<R>, signal: AbortSignal): Promise<R>;
58
+ export declare function retryableStatus(status: number): boolean;
59
+ export declare function transientStatus(status: number): boolean;
60
+ export declare function excerpt(body: string): string;
61
+ export declare function pricedUsage(tokens: {
62
+ input: number;
63
+ cached: number;
64
+ written?: number;
65
+ output: number;
66
+ reasoning: number;
67
+ }, price: ModelPrice, writeFactor?: number): Usage;
68
+ export {};
package/dist/wire.js ADDED
@@ -0,0 +1,50 @@
1
+ import { setTimeout } from "node:timers/promises";
2
+ export function withoutEffort(settings) {
3
+ const { effort: _, ...rest } = settings;
4
+ return rest;
5
+ }
6
+ // A transient failure is sent once more after this pause; a second failure
7
+ // goes to the failback, which decides what it means for the model.
8
+ const TRANSIENT_RETRY_MS = 1_000;
9
+ export async function onceMore(send, signal) {
10
+ const first = await send();
11
+ if (first.ok || !first.error.transient)
12
+ return first;
13
+ await setTimeout(TRANSIENT_RETRY_MS, undefined, { signal }).catch(() => undefined);
14
+ if (signal.aborted)
15
+ return first;
16
+ return send();
17
+ }
18
+ const AUTH_STATUS = new Set([401, 403]);
19
+ // How much of an error body an error message keeps: enough to diagnose, not
20
+ // a page of HTML.
21
+ const BODY_EXCERPT = 300;
22
+ export function retryableStatus(status) {
23
+ return !AUTH_STATUS.has(status);
24
+ }
25
+ export function transientStatus(status) {
26
+ return status >= 500 || status === 408;
27
+ }
28
+ export function excerpt(body) {
29
+ const text = body.replace(/\s+/g, " ").trim();
30
+ if (text.length === 0)
31
+ return "(empty body)";
32
+ return text.length > BODY_EXCERPT ? `${text.slice(0, BODY_EXCERPT)}…` : text;
33
+ }
34
+ const perToken = (perMillion) => perMillion / 1_000_000;
35
+ // Tokens as the engine counts them: cached input apart from fresh input, at
36
+ // the cached rate when the provider declares one. `writeFactor` is what the
37
+ // provider charges above the input rate for the input it stores.
38
+ export function pricedUsage(tokens, price, writeFactor = 1) {
39
+ const written = tokens.written ?? 0;
40
+ return {
41
+ inputTokens: tokens.input + written,
42
+ outputTokens: tokens.output,
43
+ reasoningTokens: tokens.reasoning,
44
+ cachedTokens: tokens.cached,
45
+ costUsd: tokens.input * perToken(price.input) +
46
+ written * perToken(price.input) * writeFactor +
47
+ tokens.cached * perToken(price.cachedInput ?? price.input) +
48
+ tokens.output * perToken(price.output),
49
+ };
50
+ }
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@open-cr-agent/runtime-direct",
3
- "version": "0.12.0",
4
- "description": "Agent runtime for Open-CR-Agent that calls OpenAI-compatible endpoints directly",
3
+ "version": "0.13.0",
4
+ "description": "Agent runtime for Open-CR-Agent that calls declared OpenAI-compatible and Anthropic endpoints directly",
5
5
  "keywords": [
6
6
  "code-review",
7
7
  "openai-compatible",
8
+ "anthropic",
8
9
  "agents"
9
10
  ],
10
11
  "license": "Apache-2.0",
@@ -33,7 +34,8 @@
33
34
  "!dist/**/*.map"
34
35
  ],
35
36
  "dependencies": {
36
- "@open-cr-agent/core": "0.12.0",
37
+ "@anthropic-ai/sdk": "^1.12.0",
38
+ "@open-cr-agent/core": "0.13.0",
37
39
  "zod": "^4.6.6"
38
40
  },
39
41
  "publishConfig": {