@open-cr-agent/runtime-direct 0.0.0-bootstrap.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @open-cr-agent/runtime-direct
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://ocra.majincheng.com). All `@open-cr-agent` packages are released together at one version. Apache-2.0.
@@ -0,0 +1,2 @@
1
+ export { directRuntimePlugin } from "./plugin.js";
2
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { directRuntimePlugin } from "./plugin.js";
2
+ //# sourceMappingURL=index.js.map
package/dist/loop.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { ModelPrice, ReviewContext, Sampling, ToolDefinition, Usage } from "@open-cr-agent/core";
2
+ import { type AttemptOutcome } from "@open-cr-agent/core/internal";
3
+ import { type Endpoint } from "./openai.js";
4
+ export interface LoopInput {
5
+ endpoint: Endpoint;
6
+ model: string;
7
+ price: ModelPrice;
8
+ system: string;
9
+ user: string;
10
+ tools: readonly ToolDefinition[];
11
+ context: ReviewContext;
12
+ maxSteps: number;
13
+ resume?: string;
14
+ timeoutMs: number;
15
+ sampling?: Sampling;
16
+ signal: AbortSignal;
17
+ onUsage?: (spent: Usage) => void;
18
+ }
19
+ export declare function runLoop(input: LoopInput): Promise<AttemptOutcome>;
20
+ //# sourceMappingURL=loop.d.ts.map
package/dist/loop.js ADDED
@@ -0,0 +1,100 @@
1
+ import { addUsage, emptyUsage, errorMessage, REVIEW_TOOLS, } from "@open-cr-agent/core/internal";
2
+ import { chat, toolSpec } from "./openai.js";
3
+ // The agent loop: ask the model, run the tools it calls against the review
4
+ // context, hand the results back, until it calls task_done, answers without
5
+ // tools, or runs out of steps. The model reaches nothing but these tools and
6
+ // the endpoint; a finding is what it passes to report_finding, kept as given
7
+ // for the pipeline to validate.
8
+ export async function runLoop(input) {
9
+ const timeout = AbortSignal.timeout(input.timeoutMs);
10
+ const signal = AbortSignal.any([input.signal, timeout]);
11
+ const tools = new Map(input.tools.map((t) => [t.name, t]));
12
+ const specs = input.tools.map(toolSpec);
13
+ const messages = [
14
+ { role: "system", content: input.system },
15
+ { role: "user", content: input.user },
16
+ ];
17
+ const outcome = {
18
+ findings: [],
19
+ steps: 0,
20
+ toolCalls: [],
21
+ text: "",
22
+ usage: emptyUsage(),
23
+ };
24
+ const texts = [];
25
+ let done = false;
26
+ while (outcome.steps < input.maxSteps) {
27
+ const response = await chat(input.endpoint, {
28
+ model: input.model,
29
+ messages,
30
+ ...(specs.length > 0 ? { tools: specs } : {}),
31
+ ...input.sampling,
32
+ }, input.price, signal);
33
+ outcome.steps += 1;
34
+ if (!response.ok) {
35
+ outcome.error = timeout.aborted
36
+ ? { message: `timed out after ${Math.round(input.timeoutMs / 1000)}s`, retryable: true }
37
+ : response.error;
38
+ break;
39
+ }
40
+ outcome.usage = addUsage(outcome.usage, response.usage);
41
+ input.onUsage?.(outcome.usage);
42
+ if (response.content)
43
+ texts.push(response.content);
44
+ messages.push({
45
+ role: "assistant",
46
+ content: response.content || null,
47
+ ...(response.toolCalls.length > 0 ? { tool_calls: response.toolCalls } : {}),
48
+ });
49
+ if (response.toolCalls.length === 0) {
50
+ const stoppedEarly = input.resume && !outcome.resumed && texts.join("").trim() === "";
51
+ if (stoppedEarly && outcome.steps < input.maxSteps) {
52
+ outcome.resumed = true;
53
+ messages.push({ role: "user", content: input.resume });
54
+ continue;
55
+ }
56
+ break;
57
+ }
58
+ for (const call of response.toolCalls) {
59
+ outcome.toolCalls.push(call.function.name);
60
+ if (call.function.name === REVIEW_TOOLS.taskDone)
61
+ done = true;
62
+ messages.push({
63
+ role: "tool",
64
+ tool_call_id: call.id,
65
+ content: await runTool(tools, call, input.context, outcome),
66
+ });
67
+ }
68
+ if (done)
69
+ break;
70
+ }
71
+ outcome.text = texts.join("\n").trim();
72
+ return outcome;
73
+ }
74
+ // A tool's answer, or why it gave none: a wrong call is told to the model,
75
+ // which may correct it, and never ends the attempt.
76
+ async function runTool(tools, call, context, outcome) {
77
+ const tool = tools.get(call.function.name);
78
+ if (!tool)
79
+ return `Unknown tool: ${call.function.name}`;
80
+ let args;
81
+ try {
82
+ args = JSON.parse(call.function.arguments || "{}");
83
+ }
84
+ catch {
85
+ return "Invalid arguments: not JSON";
86
+ }
87
+ const parsed = tool.inputSchema.safeParse(args);
88
+ if (!parsed.success) {
89
+ return `Invalid arguments: ${parsed.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; ")}`;
90
+ }
91
+ if (tool.name === REVIEW_TOOLS.reportFinding)
92
+ outcome.findings.push(parsed.data);
93
+ try {
94
+ return await tool.execute(parsed.data, context);
95
+ }
96
+ catch (error) {
97
+ return `Tool failed: ${errorMessage(error)}`;
98
+ }
99
+ }
100
+ //# sourceMappingURL=loop.js.map
@@ -0,0 +1,63 @@
1
+ import type { ModelPrice, ToolDefinition, Usage } from "@open-cr-agent/core";
2
+ import { type QuotaError } from "@open-cr-agent/core/internal";
3
+ import { z } from "zod";
4
+ declare const toolCallSchema: z.ZodObject<{
5
+ id: z.ZodString;
6
+ function: z.ZodObject<{
7
+ name: z.ZodString;
8
+ arguments: z.ZodString;
9
+ }, z.core.$strip>;
10
+ }, z.core.$strip>;
11
+ export type ToolCall = z.infer<typeof toolCallSchema>;
12
+ export type ChatMessage = {
13
+ role: "system" | "user";
14
+ content: string;
15
+ } | {
16
+ role: "assistant";
17
+ content: string | null;
18
+ tool_calls?: ToolCall[];
19
+ } | {
20
+ role: "tool";
21
+ tool_call_id: string;
22
+ content: string;
23
+ };
24
+ export interface ToolSpec {
25
+ type: "function";
26
+ function: {
27
+ name: string;
28
+ description: string;
29
+ parameters: Record<string, unknown>;
30
+ };
31
+ }
32
+ export interface Endpoint {
33
+ baseUrl: string;
34
+ apiKey?: string;
35
+ fetch?: typeof fetch;
36
+ }
37
+ export interface ChatRequest {
38
+ model: string;
39
+ messages: readonly ChatMessage[];
40
+ tools?: readonly ToolSpec[];
41
+ temperature?: number;
42
+ seed?: number;
43
+ }
44
+ export interface ChatError {
45
+ message: string;
46
+ retryable: boolean;
47
+ quota?: QuotaError;
48
+ transient?: boolean;
49
+ }
50
+ export type ChatResponse = {
51
+ ok: true;
52
+ content: string;
53
+ toolCalls: ToolCall[];
54
+ usage: Usage;
55
+ } | {
56
+ ok: false;
57
+ error: ChatError;
58
+ };
59
+ export declare const TRANSIENT_RETRY_MS = 1000;
60
+ export declare function toolSpec(tool: ToolDefinition): ToolSpec;
61
+ export declare function chat(endpoint: Endpoint, request: ChatRequest, price: ModelPrice, signal: AbortSignal): Promise<ChatResponse>;
62
+ export {};
63
+ //# sourceMappingURL=openai.d.ts.map
package/dist/openai.js ADDED
@@ -0,0 +1,160 @@
1
+ import { errorMessage, parseQuotaError, sleep, withoutSecrets, } from "@open-cr-agent/core/internal";
2
+ import { z } from "zod";
3
+ // The subset of the OpenAI chat completions protocol the loop needs: one
4
+ // 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({
7
+ id: z.string(),
8
+ function: z.object({ name: z.string(), arguments: z.string() }),
9
+ });
10
+ 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),
19
+ usage: z
20
+ .object({
21
+ prompt_tokens: z.number().optional(),
22
+ completion_tokens: z.number().optional(),
23
+ prompt_tokens_details: z.object({ cached_tokens: z.number().optional() }).optional(),
24
+ completion_tokens_details: z.object({ reasoning_tokens: z.number().optional() }).optional(),
25
+ })
26
+ .optional(),
27
+ });
28
+ // OpenRouter answers some upstream failures with status 200 and this body.
29
+ const errorBodySchema = z.object({
30
+ error: z.object({ message: z.string(), code: z.number().optional() }),
31
+ });
32
+ const AUTH_STATUS = new Set([401, 403]);
33
+ // How much of an error body an error message keeps: enough to diagnose, not
34
+ // a page of HTML.
35
+ const BODY_EXCERPT = 300;
36
+ // A transient failure is sent once more after this pause; a second failure
37
+ // goes to the failback, which decides what it means for the model.
38
+ export const TRANSIENT_RETRY_MS = 1_000;
39
+ export function toolSpec(tool) {
40
+ const { $schema: _, ...parameters } = z.toJSONSchema(tool.inputSchema);
41
+ return {
42
+ type: "function",
43
+ function: { name: tool.name, description: tool.description, parameters },
44
+ };
45
+ }
46
+ // One request to the endpoint, sent a second time when the first failed in
47
+ // a way a moment may cure. Only the key named for this provider goes out,
48
+ // and only to its base URL.
49
+ export async function chat(endpoint, request, price, signal) {
50
+ const first = await send(endpoint, request, price, signal);
51
+ if (first.ok || !first.error.transient)
52
+ return first;
53
+ await sleep(TRANSIENT_RETRY_MS, signal);
54
+ if (signal.aborted)
55
+ return first;
56
+ return send(endpoint, request, price, signal);
57
+ }
58
+ async function send(endpoint, request, price, signal) {
59
+ const headers = { "content-type": "application/json" };
60
+ if (endpoint.apiKey)
61
+ headers.authorization = `Bearer ${endpoint.apiKey}`;
62
+ const secrets = endpoint.apiKey ? [endpoint.apiKey] : [];
63
+ let response;
64
+ try {
65
+ response = await (endpoint.fetch ?? fetch)(`${endpoint.baseUrl.replace(/\/$/, "")}/chat/completions`, {
66
+ method: "POST",
67
+ headers,
68
+ body: JSON.stringify({ ...request, stream: false }),
69
+ signal,
70
+ });
71
+ }
72
+ catch (error) {
73
+ if (signal.aborted)
74
+ return { ok: false, error: { message: "cancelled", retryable: false } };
75
+ return { ok: false, error: { message: errorMessage(error), retryable: true, transient: true } };
76
+ }
77
+ const body = await response.text().catch(() => "");
78
+ if (!response.ok)
79
+ return { ok: false, error: failure(response, body, secrets) };
80
+ let json;
81
+ try {
82
+ json = JSON.parse(body);
83
+ }
84
+ catch {
85
+ return { ok: false, error: malformed("did not answer with JSON", body, secrets) };
86
+ }
87
+ const reported = errorBodySchema.safeParse(json);
88
+ if (reported.success) {
89
+ return { ok: false, error: failure(response, body, secrets, reported.data.error.code) };
90
+ }
91
+ const parsed = completionSchema.safeParse(json);
92
+ if (!parsed.success) {
93
+ return { ok: false, error: malformed("answered without a chat completion", body, secrets) };
94
+ }
95
+ const choice = parsed.data.choices[0];
96
+ return {
97
+ ok: true,
98
+ content: choice.message.content ?? "",
99
+ toolCalls: choice.message.tool_calls ?? [],
100
+ usage: usageOf(parsed.data.usage, price),
101
+ };
102
+ }
103
+ // An error status, or an error the endpoint reported inside an OK answer;
104
+ // the reported code counts as the status when it is one.
105
+ function failure(response, body, secrets, reportedCode) {
106
+ const inBody = response.ok;
107
+ const status = inBody
108
+ ? reportedCode && reportedCode >= 400
109
+ ? reportedCode
110
+ : 502
111
+ : response.status;
112
+ // An endpoint may echo the request's headers in an error page.
113
+ const shown = excerpt(withoutSecrets(body, secrets));
114
+ const message = inBody ? `error ${status} in an OK answer: ${shown}` : `HTTP ${status}: ${shown}`;
115
+ const quota = parseQuotaError(body, status);
116
+ if (quota && quota.retryAfterMs === undefined) {
117
+ const retryAfter = Number(response.headers.get("retry-after"));
118
+ if (Number.isFinite(retryAfter) && retryAfter > 0)
119
+ quota.retryAfterMs = retryAfter * 1000;
120
+ }
121
+ return {
122
+ message,
123
+ retryable: !AUTH_STATUS.has(status),
124
+ ...(quota ? { quota } : {}),
125
+ ...(!quota && (status >= 500 || status === 408) ? { transient: true } : {}),
126
+ };
127
+ }
128
+ function malformed(what, body, secrets) {
129
+ return {
130
+ message: `the endpoint ${what}: ${excerpt(withoutSecrets(body, secrets))}`,
131
+ retryable: true,
132
+ transient: true,
133
+ };
134
+ }
135
+ // Cached tokens are counted inside the prompt tokens, as OpenAI does; they
136
+ // are priced at the cached rate when the provider declares one.
137
+ function usageOf(usage, price) {
138
+ const prompt = usage?.prompt_tokens ?? 0;
139
+ const cached = Math.min(prompt, usage?.prompt_tokens_details?.cached_tokens ?? 0);
140
+ const input = prompt - cached;
141
+ const output = usage?.completion_tokens ?? 0;
142
+ const reasoning = usage?.completion_tokens_details?.reasoning_tokens ?? 0;
143
+ const perToken = (perMillion) => perMillion / 1_000_000;
144
+ return {
145
+ inputTokens: input,
146
+ outputTokens: output,
147
+ reasoningTokens: reasoning,
148
+ cachedTokens: cached,
149
+ costUsd: input * perToken(price.input) +
150
+ cached * perToken(price.cachedInput ?? price.input) +
151
+ output * perToken(price.output),
152
+ };
153
+ }
154
+ function excerpt(body) {
155
+ const text = body.replace(/\s+/g, " ").trim();
156
+ if (text.length === 0)
157
+ return "(empty body)";
158
+ return text.length > BODY_EXCERPT ? `${text.slice(0, BODY_EXCERPT)}…` : text;
159
+ }
160
+ //# sourceMappingURL=openai.js.map
@@ -0,0 +1,3 @@
1
+ import type { OcraPlugin } from "@open-cr-agent/core";
2
+ export declare const directRuntimePlugin: OcraPlugin;
3
+ //# sourceMappingURL=plugin.d.ts.map
package/dist/plugin.js ADDED
@@ -0,0 +1,8 @@
1
+ import { DirectRuntime } from "./runtime.js";
2
+ export const directRuntimePlugin = {
3
+ name: "runtime-direct",
4
+ configure(ctx) {
5
+ ctx.registerRuntime("direct", (options) => new DirectRuntime(options));
6
+ },
7
+ };
8
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1,18 @@
1
+ import { type AgentEvent, type AgentRuntime, type AgentTaskSpec, type AppliedSampling, type CompletionRequest, type CompletionResult, type RuntimeOptions } from "@open-cr-agent/core";
2
+ export interface DirectRuntimeOptions extends RuntimeOptions {
3
+ fetch?: typeof fetch;
4
+ }
5
+ export declare class DirectRuntime implements AgentRuntime {
6
+ private readonly options;
7
+ readonly name = "direct";
8
+ readonly sampling: AppliedSampling;
9
+ private readonly health;
10
+ private readonly tools;
11
+ private readonly fetch;
12
+ constructor(options: DirectRuntimeOptions);
13
+ runTask(spec: AgentTaskSpec, signal: AbortSignal): AsyncIterable<AgentEvent>;
14
+ complete(request: CompletionRequest, signal: AbortSignal): Promise<CompletionResult>;
15
+ private unreachable;
16
+ private target;
17
+ }
18
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1,120 @@
1
+ import { OcraError, } from "@open-cr-agent/core";
2
+ import { completeWithFailback, MAX_AGENT_STEPS, ModelHealth, parseModel, proxiedFetch, RESUME_MESSAGE, reviewTools, withFailback, } from "@open-cr-agent/core/internal";
3
+ import { runLoop } from "./loop.js";
4
+ // Talks to the declared OpenAI-compatible endpoints itself: no OpenCode
5
+ // process, no catalog fetch, no package install, nothing on disk. A model of
6
+ // a provider that is not declared in configuration is refused, since the
7
+ // runtime knows no other address to send code to.
8
+ export class DirectRuntime {
9
+ options;
10
+ name = "direct";
11
+ // The chat completions protocol takes both settings.
12
+ sampling;
13
+ health = new ModelHealth();
14
+ tools;
15
+ fetch;
16
+ constructor(options) {
17
+ this.options = options;
18
+ this.tools = [...reviewTools, ...options.tools];
19
+ this.fetch = options.fetch ?? proxiedFetch(options.env);
20
+ const { temperature, seed } = options.sampling ?? {};
21
+ this.sampling = {
22
+ ...(temperature === undefined ? {} : { temperature }),
23
+ ...(seed === undefined ? {} : { seed }),
24
+ };
25
+ }
26
+ async *runTask(spec, signal) {
27
+ const chain = this.options.models[spec.modelTier] ?? [];
28
+ const refused = chain.length === 0 ? noModel(spec.modelTier) : this.unreachable(chain);
29
+ if (refused) {
30
+ yield { type: "error", taskId: spec.taskId, error: refused.message, retryable: false };
31
+ return;
32
+ }
33
+ yield* withFailback({
34
+ taskId: spec.taskId,
35
+ tier: spec.modelTier,
36
+ chain,
37
+ health: this.health,
38
+ signal,
39
+ attempt: (model, onUsage) => runLoop({
40
+ ...this.target(model),
41
+ system: spec.systemPrompt,
42
+ user: spec.userPrompt,
43
+ tools: this.tools,
44
+ context: spec.context,
45
+ maxSteps: MAX_AGENT_STEPS,
46
+ resume: RESUME_MESSAGE,
47
+ timeoutMs: spec.timeoutMs,
48
+ sampling: this.sampling,
49
+ signal,
50
+ onUsage,
51
+ }),
52
+ });
53
+ }
54
+ async complete(request, signal) {
55
+ const chain = this.options.models[request.tier] ?? [];
56
+ const refused = chain.length === 0 ? noModel(request.tier) : this.unreachable(chain);
57
+ if (refused)
58
+ throw refused;
59
+ return completeWithFailback({
60
+ tier: request.tier,
61
+ chain,
62
+ health: this.health,
63
+ signal,
64
+ attempt: (model) => runLoop({
65
+ ...this.target(model),
66
+ system: request.system,
67
+ user: request.user,
68
+ tools: [],
69
+ context: NO_CONTEXT,
70
+ maxSteps: 1,
71
+ timeoutMs: request.timeoutMs,
72
+ sampling: this.sampling,
73
+ signal,
74
+ }),
75
+ });
76
+ }
77
+ // Why a chain cannot be served, before any request: a provider the
78
+ // configuration does not declare, a model it gives no price, or a key
79
+ // variable that is not set.
80
+ unreachable(chain) {
81
+ for (const model of chain) {
82
+ const { providerID, modelID } = parseModel(model);
83
+ const provider = this.options.providers?.[providerID];
84
+ if (!provider) {
85
+ 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})`);
86
+ }
87
+ if (!provider.models[modelID]) {
88
+ return new OcraError("CONFIG_INVALID", `"${model}" has no price in the declaration of provider "${providerID}"`);
89
+ }
90
+ if (provider.apiKeyEnv && !this.options.env[provider.apiKeyEnv]) {
91
+ return new OcraError("CONFIG_CREDENTIALS_MISSING", `No API key for provider "${providerID}": set ${provider.apiKeyEnv}`);
92
+ }
93
+ }
94
+ return undefined;
95
+ }
96
+ target(model) {
97
+ const { providerID, modelID } = parseModel(model);
98
+ const provider = this.options.providers?.[providerID];
99
+ const key = provider.apiKeyEnv ? this.options.env[provider.apiKeyEnv] : undefined;
100
+ return {
101
+ endpoint: {
102
+ baseUrl: provider.baseUrl,
103
+ ...(key ? { apiKey: key } : {}),
104
+ fetch: this.fetch,
105
+ },
106
+ model: modelID,
107
+ price: provider.models[modelID],
108
+ };
109
+ }
110
+ }
111
+ // A helper call has no tools, so it gets a context that answers nothing.
112
+ const NO_CONTEXT = {
113
+ readFile: async () => undefined,
114
+ readDiff: () => undefined,
115
+ searchCode: async () => [],
116
+ };
117
+ function noModel(tier) {
118
+ return new OcraError("CONFIG_INVALID", `No ${tier} model configured (set OCRA_MODEL_${tier.toUpperCase()} or models.${tier})`);
119
+ }
120
+ //# sourceMappingURL=runtime.js.map
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@open-cr-agent/runtime-direct",
3
+ "version": "0.0.0-bootstrap.0",
4
+ "description": "Agent runtime for Open-CR-Agent that calls OpenAI-compatible endpoints directly",
5
+ "keywords": [
6
+ "code-review",
7
+ "openai-compatible",
8
+ "agents"
9
+ ],
10
+ "license": "Apache-2.0",
11
+ "homepage": "https://ocra.majincheng.com",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/jma49/Open-CR-Agent.git",
15
+ "directory": "packages/runtime-direct"
16
+ },
17
+ "bugs": "https://github.com/jma49/Open-CR-Agent/issues",
18
+ "engines": {
19
+ "node": ">=22.19"
20
+ },
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "exports": {
24
+ ".": {
25
+ "@open-cr-agent/source": "./src/index.ts",
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "!dist/**/*.map"
34
+ ],
35
+ "dependencies": {
36
+ "@open-cr-agent/core": "0.2.0",
37
+ "zod": "^4.6.5"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }