@open-cr-agent/runtime-direct 0.7.0 → 0.9.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/dist/loop.d.ts +9 -2
- package/dist/loop.js +93 -61
- package/dist/record.d.ts +11 -9
- package/dist/record.js +51 -5
- package/dist/runtime.js +18 -4
- package/package.json +3 -3
package/dist/loop.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type ModelPrice, type ReviewContext, type TaskAttempt, type ToolDefinition, type Usage } from "@open-cr-agent/core";
|
|
2
2
|
import { type CallParams, type Endpoint } from "./openai.js";
|
|
3
3
|
export interface LoopInput {
|
|
4
4
|
endpoint: Endpoint;
|
|
@@ -10,10 +10,17 @@ export interface LoopInput {
|
|
|
10
10
|
context: ReviewContext;
|
|
11
11
|
maxSteps: number;
|
|
12
12
|
resume?: string;
|
|
13
|
+
wrapUp?: WrapUpTurn;
|
|
13
14
|
timeoutMs: number;
|
|
14
15
|
params?: CallParams;
|
|
15
16
|
onEffortRefused?: () => void;
|
|
16
17
|
signal: AbortSignal;
|
|
17
18
|
onUsage?: (spent: Usage) => void;
|
|
18
19
|
}
|
|
19
|
-
|
|
20
|
+
interface WrapUpTurn {
|
|
21
|
+
message: string;
|
|
22
|
+
tools: readonly string[];
|
|
23
|
+
steps: number;
|
|
24
|
+
}
|
|
25
|
+
export declare function runLoop(input: LoopInput): Promise<TaskAttempt>;
|
|
26
|
+
export {};
|
package/dist/loop.js
CHANGED
|
@@ -6,78 +6,110 @@ import { chat, toolSpec, withoutEffort, } from "./openai.js";
|
|
|
6
6
|
// the endpoint; a finding is what it passes to report_finding, kept as given
|
|
7
7
|
// for the pipeline to validate.
|
|
8
8
|
export async function runLoop(input) {
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
9
|
+
const conversation = new Conversation(input);
|
|
10
|
+
const outcome = await conversation.turn(input.user, input.tools, input.maxSteps, input.resume);
|
|
11
|
+
const { wrapUp } = input;
|
|
12
|
+
if (!wrapUp)
|
|
13
|
+
return outcome;
|
|
14
|
+
const tools = input.tools.filter((t) => wrapUp.tools.includes(t.name));
|
|
15
|
+
return {
|
|
16
|
+
...outcome,
|
|
17
|
+
wrapUp: () => conversation.turn(wrapUp.message, tools, outcome.steps + wrapUp.steps),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
// One attempt's messages and outcome, which a later turn continues under the
|
|
21
|
+
// attempt's signal and timeout.
|
|
22
|
+
class Conversation {
|
|
23
|
+
input;
|
|
24
|
+
timeout;
|
|
25
|
+
signal;
|
|
26
|
+
messages;
|
|
27
|
+
outcome = {
|
|
18
28
|
findings: [],
|
|
19
29
|
steps: 0,
|
|
20
30
|
toolCalls: [],
|
|
21
31
|
text: "",
|
|
22
32
|
usage: emptyUsage(),
|
|
23
33
|
};
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
...(response.toolCalls.length > 0 ? { tool_calls: response.toolCalls } : {}),
|
|
54
|
-
});
|
|
55
|
-
if (response.toolCalls.length === 0) {
|
|
56
|
-
const stoppedEarly = input.resume && !outcome.resumed && texts.join("").trim() === "";
|
|
57
|
-
if (stoppedEarly && outcome.steps < input.maxSteps) {
|
|
58
|
-
outcome.resumed = true;
|
|
59
|
-
messages.push({ role: "user", content: input.resume });
|
|
60
|
-
continue;
|
|
34
|
+
texts = [];
|
|
35
|
+
uses = [];
|
|
36
|
+
params;
|
|
37
|
+
constructor(input) {
|
|
38
|
+
this.input = input;
|
|
39
|
+
this.timeout = AbortSignal.timeout(input.timeoutMs);
|
|
40
|
+
this.signal = AbortSignal.any([input.signal, this.timeout]);
|
|
41
|
+
this.messages = [{ role: "system", content: input.system }];
|
|
42
|
+
this.params = input.params ?? {};
|
|
43
|
+
}
|
|
44
|
+
// Runs until the done tool, an answer without tools, or `maxSteps` steps
|
|
45
|
+
// in the whole attempt; returns the attempt's outcome so far.
|
|
46
|
+
async turn(message, offered, maxSteps, resume) {
|
|
47
|
+
const { input, messages, outcome, texts, uses } = this;
|
|
48
|
+
const tools = new Map(offered.map((t) => [t.name, t]));
|
|
49
|
+
const specs = offered.map(toolSpec);
|
|
50
|
+
let done = false;
|
|
51
|
+
messages.push({ role: "user", content: message });
|
|
52
|
+
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);
|
|
59
|
+
outcome.steps += 1;
|
|
60
|
+
if (response.effortDropped) {
|
|
61
|
+
this.params = withoutEffort(this.params);
|
|
62
|
+
input.onEffortRefused?.();
|
|
61
63
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
64
|
+
if (!response.ok) {
|
|
65
|
+
outcome.error = this.timeout.aborted
|
|
66
|
+
? { message: `timed out after ${Math.round(input.timeoutMs / 1000)}s`, retryable: true }
|
|
67
|
+
: response.error;
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
outcome.usage = addUsage(outcome.usage, response.usage);
|
|
71
|
+
input.onUsage?.(outcome.usage);
|
|
72
|
+
if (response.content)
|
|
73
|
+
texts.push(response.content);
|
|
68
74
|
messages.push({
|
|
69
|
-
role: "
|
|
70
|
-
|
|
71
|
-
|
|
75
|
+
role: "assistant",
|
|
76
|
+
content: response.content || null,
|
|
77
|
+
...(response.toolCalls.length > 0 ? { tool_calls: response.toolCalls } : {}),
|
|
72
78
|
});
|
|
79
|
+
if (response.toolCalls.length === 0) {
|
|
80
|
+
const stoppedEarly = resume && !outcome.resumed && texts.join("").trim() === "";
|
|
81
|
+
if (stoppedEarly && outcome.steps < maxSteps) {
|
|
82
|
+
outcome.resumed = true;
|
|
83
|
+
messages.push({ role: "user", content: resume });
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
for (const call of response.toolCalls) {
|
|
89
|
+
outcome.toolCalls.push(call.function.name);
|
|
90
|
+
if (call.function.name === REVIEW_TOOLS.taskDone)
|
|
91
|
+
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
|
+
}
|
|
98
|
+
if (done)
|
|
99
|
+
break;
|
|
73
100
|
}
|
|
74
|
-
|
|
75
|
-
|
|
101
|
+
outcome.text = texts.join("\n").trim();
|
|
102
|
+
if (!done && !outcome.error && outcome.steps >= maxSteps)
|
|
103
|
+
outcome.atStepCap = true;
|
|
104
|
+
else
|
|
105
|
+
delete outcome.atStepCap;
|
|
106
|
+
return { ...snapshot(outcome), ...exploredBy(uses) };
|
|
76
107
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
108
|
+
}
|
|
109
|
+
// A later turn adds to the outcome; what an earlier turn returned stays as
|
|
110
|
+
// it was.
|
|
111
|
+
function snapshot(outcome) {
|
|
112
|
+
return { ...outcome, findings: [...outcome.findings], toolCalls: [...outcome.toolCalls] };
|
|
81
113
|
}
|
|
82
114
|
// A tool's answer, or why it gave none: a wrong call is told to the model,
|
|
83
115
|
// which may correct it, and never ends the attempt.
|
package/dist/record.d.ts
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
1
2
|
export declare const RECORD_DIR_ENV = "OCRA_RECORD_DIR";
|
|
2
|
-
export
|
|
3
|
-
version: 1
|
|
4
|
-
request:
|
|
5
|
-
answers: {
|
|
6
|
-
status:
|
|
7
|
-
body:
|
|
8
|
-
}
|
|
9
|
-
}
|
|
3
|
+
export declare const recordingSchema: z.ZodObject<{
|
|
4
|
+
version: z.ZodLiteral<1>;
|
|
5
|
+
request: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
6
|
+
answers: z.ZodArray<z.ZodObject<{
|
|
7
|
+
status: z.ZodNumber;
|
|
8
|
+
body: z.ZodString;
|
|
9
|
+
}, z.core.$strip>>;
|
|
10
|
+
}, z.core.$strip>;
|
|
11
|
+
export type Recording = z.infer<typeof recordingSchema>;
|
|
10
12
|
export declare function exchangeKey(request: {
|
|
11
13
|
messages?: unknown;
|
|
12
14
|
tools?: unknown;
|
|
13
15
|
}): string;
|
|
14
|
-
export declare function recordingFetch(base: typeof fetch, dir: string, secrets: readonly string[]): typeof fetch;
|
|
16
|
+
export declare function recordingFetch(base: typeof fetch, dir: string, secrets: () => readonly string[], warn: (message: string) => void): typeof fetch;
|
package/dist/record.js
CHANGED
|
@@ -2,9 +2,19 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { errorMessage, OcraError, withoutSecrets } from "@open-cr-agent/core";
|
|
5
|
+
import { z } from "zod";
|
|
5
6
|
// Where the direct runtime writes every model exchange, for replaying a run
|
|
6
7
|
// without a model (tests) or reading what a model was sent and answered.
|
|
7
8
|
export const RECORD_DIR_ENV = "OCRA_RECORD_DIR";
|
|
9
|
+
// One file per distinct request, named by exchangeKey(): the request as sent
|
|
10
|
+
// and each answer it got, in order (a request sent again after a transient
|
|
11
|
+
// failure gets a second answer). Headers and the endpoint's address are not
|
|
12
|
+
// kept, and every key is replaced by "<key>".
|
|
13
|
+
export const recordingSchema = z.object({
|
|
14
|
+
version: z.literal(1),
|
|
15
|
+
request: z.record(z.string(), z.unknown()),
|
|
16
|
+
answers: z.array(z.object({ status: z.number().int(), body: z.string() })),
|
|
17
|
+
});
|
|
8
18
|
// What makes two requests the same exchange: the conversation and the tools
|
|
9
19
|
// offered. The model and sampling settings are recorded but do not count, so
|
|
10
20
|
// a replay of a run does not depend on which model of the chain served it.
|
|
@@ -17,20 +27,37 @@ export function exchangeKey(request) {
|
|
|
17
27
|
// Wraps fetch so every chat completion it sends is recorded in `dir`. The
|
|
18
28
|
// directory is created, private to its owner, before any request, so a path
|
|
19
29
|
// that cannot be one fails the run at once rather than every request.
|
|
20
|
-
|
|
30
|
+
// `secrets` is asked when each request is sent and again at its write, and
|
|
31
|
+
// every key seen is kept: a key renewed during the run (the ocra Cloud
|
|
32
|
+
// token), even while a request was in flight, is taken out as well. A recording that cannot be written is
|
|
33
|
+
// a warning, never a failed request: the answer was paid for, and a thrown
|
|
34
|
+
// error here would read as a network failure and send the request again.
|
|
35
|
+
export function recordingFetch(base, dir, secrets, warn) {
|
|
21
36
|
try {
|
|
22
37
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
23
38
|
}
|
|
24
39
|
catch (error) {
|
|
25
40
|
throw new OcraError("CONFIG_INVALID", `${RECORD_DIR_ENV} names a directory ocra cannot create: ${errorMessage(error)}`);
|
|
26
41
|
}
|
|
42
|
+
const seen = new Set();
|
|
43
|
+
const remember = () => {
|
|
44
|
+
for (const s of secrets())
|
|
45
|
+
seen.add(s);
|
|
46
|
+
return [...seen];
|
|
47
|
+
};
|
|
27
48
|
return async (input, init) => {
|
|
49
|
+
remember();
|
|
28
50
|
const response = await base(input, init);
|
|
29
51
|
if (typeof init?.body !== "string")
|
|
30
52
|
return response;
|
|
31
53
|
const body = await response.text();
|
|
32
|
-
|
|
33
|
-
|
|
54
|
+
try {
|
|
55
|
+
// Synchronous, so two answers to the same request cannot interleave.
|
|
56
|
+
append(dir, JSON.parse(init.body), response.status, body, remember());
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
warn(`could not record a model exchange in ${RECORD_DIR_ENV}: ${errorMessage(error)}`);
|
|
60
|
+
}
|
|
34
61
|
return new Response(body, {
|
|
35
62
|
status: response.status,
|
|
36
63
|
statusText: response.statusText,
|
|
@@ -42,9 +69,28 @@ function append(dir, request, status, body, secrets) {
|
|
|
42
69
|
const path = join(dir, `${exchangeKey(request)}.json`);
|
|
43
70
|
const { stream: _, ...sent } = request;
|
|
44
71
|
const recording = existsSync(path)
|
|
45
|
-
? JSON.parse(readFileSync(path, "utf8"))
|
|
72
|
+
? recordingSchema.parse(JSON.parse(readFileSync(path, "utf8")))
|
|
46
73
|
: { version: 1, request: sent, answers: [] };
|
|
47
74
|
recording.answers.push({ status, body });
|
|
48
|
-
const text =
|
|
75
|
+
const text = `${JSON.stringify(redacted(recording, withEscaped(secrets)), null, 2)}\n`;
|
|
49
76
|
writeFileSync(path, text, { mode: 0o600 });
|
|
50
77
|
}
|
|
78
|
+
// Each secret as it is and as it reads inside a JSON string: an answer's body
|
|
79
|
+
// is the endpoint's JSON text, where a key with a quote or backslash is
|
|
80
|
+
// escaped.
|
|
81
|
+
function withEscaped(secrets) {
|
|
82
|
+
const forms = secrets.flatMap((s) => [s, JSON.stringify(s).slice(1, -1)]);
|
|
83
|
+
return [...new Set(forms.filter((s) => s.length > 0))].sort((a, b) => b.length - a.length);
|
|
84
|
+
}
|
|
85
|
+
// Redacted string by string before serializing, since JSON.stringify escapes
|
|
86
|
+
// a secret with a quote or backslash out of its plain form.
|
|
87
|
+
function redacted(value, secrets) {
|
|
88
|
+
if (typeof value === "string")
|
|
89
|
+
return withoutSecrets(value, secrets);
|
|
90
|
+
if (Array.isArray(value))
|
|
91
|
+
return value.map((v) => redacted(v, secrets));
|
|
92
|
+
if (value !== null && typeof value === "object") {
|
|
93
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [withoutSecrets(k, secrets), redacted(v, secrets)]));
|
|
94
|
+
}
|
|
95
|
+
return value;
|
|
96
|
+
}
|
package/dist/runtime.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ChainRunner, MAX_AGENT_STEPS, OcraError, parseModel, proxiedFetch, RESUME_MESSAGE, reviewTools, } from "@open-cr-agent/core";
|
|
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
2
|
import { EffortLedger } from "./effort.js";
|
|
3
3
|
import { runLoop } from "./loop.js";
|
|
4
4
|
import { RECORD_DIR_ENV, recordingFetch } from "./record.js";
|
|
@@ -32,13 +32,26 @@ export class DirectRuntime {
|
|
|
32
32
|
});
|
|
33
33
|
}
|
|
34
34
|
// Every exchange goes to the recording directory when one is set, with the
|
|
35
|
-
// keys of all declared providers taken out
|
|
35
|
+
// keys of all declared providers taken out as they are at each write: the
|
|
36
|
+
// environment may be live, renewing a key while the run lasts. The first
|
|
37
|
+
// recording that fails is said once on stderr, which a review's output
|
|
38
|
+
// (stdout) does not share.
|
|
36
39
|
recorded(base) {
|
|
37
40
|
const dir = this.options.env[RECORD_DIR_ENV];
|
|
38
41
|
if (!dir)
|
|
39
42
|
return base;
|
|
40
|
-
const
|
|
41
|
-
|
|
43
|
+
const { env, providers } = this.options;
|
|
44
|
+
const keys = () => Object.values(providers ?? {}).flatMap((p) => {
|
|
45
|
+
const key = p.apiKeyEnv ? env[p.apiKeyEnv] : undefined;
|
|
46
|
+
return key ? [key] : [];
|
|
47
|
+
});
|
|
48
|
+
let warned = false;
|
|
49
|
+
return recordingFetch(base, dir, keys, (message) => {
|
|
50
|
+
if (warned)
|
|
51
|
+
return;
|
|
52
|
+
warned = true;
|
|
53
|
+
process.stderr.write(`ocra: ${message}; the review goes on without recording it\n`);
|
|
54
|
+
});
|
|
42
55
|
}
|
|
43
56
|
appliedTo(agent) {
|
|
44
57
|
return this.efforts.appliedTo(agent);
|
|
@@ -59,6 +72,7 @@ export class DirectRuntime {
|
|
|
59
72
|
context: spec.context,
|
|
60
73
|
maxSteps: MAX_AGENT_STEPS,
|
|
61
74
|
resume: RESUME_MESSAGE,
|
|
75
|
+
wrapUp: { message: WRAP_UP_MESSAGE, tools: WRAP_UP_TOOLS, steps: WRAP_UP_STEPS },
|
|
62
76
|
timeoutMs: spec.timeoutMs,
|
|
63
77
|
signal,
|
|
64
78
|
onUsage,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-cr-agent/runtime-direct",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Agent runtime for Open-CR-Agent that calls OpenAI-compatible endpoints directly",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"code-review",
|
|
@@ -33,8 +33,8 @@
|
|
|
33
33
|
"!dist/**/*.map"
|
|
34
34
|
],
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@open-cr-agent/core": "0.
|
|
37
|
-
"zod": "^4.6.
|
|
36
|
+
"@open-cr-agent/core": "0.9.0",
|
|
37
|
+
"zod": "^4.6.6"
|
|
38
38
|
},
|
|
39
39
|
"publishConfig": {
|
|
40
40
|
"access": "public"
|