@open-cr-agent/runtime-direct 0.6.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
@@ -11,4 +11,3 @@ export declare class EffortLedger {
11
11
  appliedTo(agent: string): AppliedSettings | undefined;
12
12
  private record;
13
13
  }
14
- //# sourceMappingURL=effort.d.ts.map
package/dist/effort.js CHANGED
@@ -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
@@ -17,4 +17,3 @@ export interface LoopInput {
17
17
  onUsage?: (spent: Usage) => void;
18
18
  }
19
19
  export declare function runLoop(input: LoopInput): Promise<AttemptOutcome>;
20
- //# 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";
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,13 +1,29 @@
1
1
  import { type Effort, type ModelPrice, type QuotaError, type ToolDefinition, type Usage } from "@open-cr-agent/core";
2
2
  import { z } from "zod";
3
- declare const toolCallSchema: z.ZodObject<{
3
+ declare const toolCallSchema: z.ZodPipe<z.ZodObject<{
4
4
  id: z.ZodString;
5
5
  function: z.ZodObject<{
6
6
  name: z.ZodString;
7
7
  arguments: z.ZodString;
8
8
  }, z.core.$strip>;
9
- }, z.core.$strip>;
10
- 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>;
11
27
  export type ChatMessage = {
12
28
  role: "system" | "user";
13
29
  content: string;
@@ -67,4 +83,3 @@ export declare function toolSpec(tool: ToolDefinition): ToolSpec;
67
83
  export declare function chat(endpoint: Endpoint, request: ChatRequest, price: ModelPrice, signal: AbortSignal): Promise<ChatResponse>;
68
84
  export declare function withoutEffort<T extends CallParams>(params: T): T;
69
85
  export {};
70
- //# sourceMappingURL=openai.d.ts.map
package/dist/openai.js CHANGED
@@ -3,11 +3,17 @@ import { errorMessage, parseQuotaError, withoutSecrets, } from "@open-cr-agent/c
3
3
  import { z } from "zod";
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
- // endpoint adds is dropped at this boundary.
7
- 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({
8
11
  id: z.string(),
9
12
  function: z.object({ name: z.string(), arguments: z.string() }),
10
- });
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" }));
11
17
  const choiceSchema = z.object({
12
18
  message: z.object({
13
19
  content: z.string().nullable().optional(),
@@ -186,4 +192,3 @@ function excerpt(body) {
186
192
  return "(empty body)";
187
193
  return text.length > BODY_EXCERPT ? `${text.slice(0, BODY_EXCERPT)}…` : text;
188
194
  }
189
- //# 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
@@ -11,6 +11,7 @@ export declare class DirectRuntime implements AgentRuntime {
11
11
  private readonly efforts;
12
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>;
@@ -21,4 +22,3 @@ export declare class DirectRuntime implements AgentRuntime {
21
22
  private declared;
22
23
  private target;
23
24
  }
24
- //# sourceMappingURL=runtime.d.ts.map
package/dist/runtime.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { ChainRunner, MAX_AGENT_STEPS, OcraError, parseModel, proxiedFetch, RESUME_MESSAGE, reviewTools, } from "@open-cr-agent/core";
2
2
  import { EffortLedger } from "./effort.js";
3
3
  import { runLoop } from "./loop.js";
4
+ import { RECORD_DIR_ENV, recordingFetch } from "./record.js";
4
5
  // Talks to the declared OpenAI-compatible endpoints itself: no OpenCode
5
6
  // process, no catalog fetch, no package install, nothing on disk. A model of
6
7
  // a provider that is not declared in configuration is refused, since the
@@ -17,7 +18,7 @@ export class DirectRuntime {
17
18
  constructor(options) {
18
19
  this.options = options;
19
20
  this.tools = [...reviewTools, ...options.tools];
20
- this.fetch = options.fetch ?? proxiedFetch(options.env);
21
+ this.fetch = this.recorded(options.fetch ?? proxiedFetch(options.env));
21
22
  const { temperature, seed } = options.sampling ?? {};
22
23
  this.sampling = {
23
24
  ...(temperature === undefined ? {} : { temperature }),
@@ -30,6 +31,15 @@ export class DirectRuntime {
30
31
  complete: (model, request, signal) => this.attemptCompletion(model, request, signal),
31
32
  });
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);
42
+ }
33
43
  appliedTo(agent) {
34
44
  return this.efforts.appliedTo(agent);
35
45
  }
@@ -129,4 +139,3 @@ const NO_CONTEXT = {
129
139
  readDiff: () => undefined,
130
140
  searchCode: async () => [],
131
141
  };
132
- //# 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.6.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.6.0",
36
+ "@open-cr-agent/core": "0.7.0",
37
37
  "zod": "^4.6.5"
38
38
  },
39
39
  "publishConfig": {