@open-cr-agent/runtime-opencode 0.1.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-opencode
2
+
3
+ The agent runtime backed by [OpenCode](https://opencode.ai) of [Open-CR-Agent](https://github.com/jma49/Open-CR-Agent), the multi-agent code reviewer. 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,10 @@
1
+ import type { Env } from "@open-cr-agent/core";
2
+ export interface Host {
3
+ platform: string;
4
+ arch: string;
5
+ musl: boolean;
6
+ baseline: boolean;
7
+ }
8
+ export declare function resolveOpencodeBinary(env: Env): string;
9
+ export declare function binaryVariants(host: Host): string[];
10
+ //# sourceMappingURL=binary.d.ts.map
package/dist/binary.js ADDED
@@ -0,0 +1,71 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { dirname, join } from "node:path";
5
+ const PLATFORMS = { darwin: "darwin", linux: "linux", win32: "windows" };
6
+ // Resolved from opencode-ai's platform packages directly, because newer npm
7
+ // versions block the postinstall script that would otherwise place it.
8
+ export function resolveOpencodeBinary(env) {
9
+ const override = env.OCRA_OPENCODE_BIN;
10
+ if (override)
11
+ return override;
12
+ const platform = PLATFORMS[process.platform] ?? process.platform;
13
+ const executable = platform === "windows" ? "opencode.exe" : "opencode";
14
+ const fromOpencode = createRequire(createRequire(import.meta.url).resolve("opencode-ai/package.json"));
15
+ for (const variant of binaryVariants(currentHost(platform))) {
16
+ try {
17
+ const pkg = fromOpencode.resolve(`opencode-${platform}-${process.arch}${variant}/package.json`);
18
+ const binary = join(dirname(pkg), "bin", executable);
19
+ if (existsSync(binary))
20
+ return binary;
21
+ }
22
+ catch { }
23
+ }
24
+ throw new Error(`No OpenCode binary for ${platform}-${process.arch}; set OCRA_OPENCODE_BIN`);
25
+ }
26
+ // The builds to try, best first. npm installs every build whose os and cpu
27
+ // match, and the glibc builds declare no libc, so musl Linux has both kinds;
28
+ // the order follows opencode-ai's own install script.
29
+ export function binaryVariants(host) {
30
+ const glibc = host.arch !== "x64" ? [""] : host.baseline ? ["-baseline", ""] : ["", "-baseline"];
31
+ if (host.platform !== "linux")
32
+ return glibc;
33
+ const musl = glibc.map((variant) => `${variant}-musl`);
34
+ return host.musl ? [...musl, ...glibc] : [...glibc, ...musl];
35
+ }
36
+ function currentHost(platform) {
37
+ const x64 = process.arch === "x64";
38
+ return {
39
+ platform,
40
+ arch: process.arch,
41
+ musl: platform === "linux" && isMusl(),
42
+ baseline: x64 && lacksAvx2(platform),
43
+ };
44
+ }
45
+ // Node's diagnostic report names the glibc it runs on; a musl build has none.
46
+ function isMusl() {
47
+ try {
48
+ const report = process.report.getReport();
49
+ return !report.header?.glibcVersionRuntime;
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ }
55
+ // Unknown counts as AVX2 present: the default build is tried first, as before.
56
+ function lacksAvx2(platform) {
57
+ try {
58
+ if (platform === "linux")
59
+ return !/\bavx2\b/.test(readFileSync("/proc/cpuinfo", "utf8"));
60
+ if (platform === "darwin") {
61
+ const sysctl = spawnSync("sysctl", ["-n", "hw.optional.avx2_0"], {
62
+ encoding: "utf8",
63
+ timeout: 1500,
64
+ });
65
+ return sysctl.status === 0 && sysctl.stdout.trim() === "0";
66
+ }
67
+ }
68
+ catch { }
69
+ return false;
70
+ }
71
+ //# sourceMappingURL=binary.js.map
@@ -0,0 +1,14 @@
1
+ import { type AgentEvent, type ModelTier } from "@open-cr-agent/core";
2
+ import type { ModelHealth } from "./models.js";
3
+ import type { SessionOutcome } from "./session-outcome.js";
4
+ export interface FailbackOptions {
5
+ taskId: string;
6
+ tier: ModelTier;
7
+ chain: readonly string[];
8
+ health: ModelHealth;
9
+ signal: AbortSignal;
10
+ attempt(model: string): Promise<SessionOutcome>;
11
+ }
12
+ export declare function withFailback(options: FailbackOptions): AsyncGenerator<AgentEvent>;
13
+ export declare function toolSummary(toolCalls: readonly string[]): string;
14
+ //# sourceMappingURL=failback.d.ts.map
@@ -0,0 +1,81 @@
1
+ import { REVIEW_TOOLS } from "@open-cr-agent/core";
2
+ import { sleep } from "./quota.js";
3
+ // Findings from a failed attempt are still emitted: the pipeline deduplicates
4
+ // by fingerprint, so a retry on the next model cannot double-report them.
5
+ export async function* withFailback(options) {
6
+ const { taskId, health, signal } = options;
7
+ let lastError = "";
8
+ for (const model of health.order(options.chain)) {
9
+ for (;;) {
10
+ if (signal.aborted)
11
+ return;
12
+ const pause = health.pausedFor(model);
13
+ if (pause > 0) {
14
+ yield {
15
+ type: "progress",
16
+ taskId,
17
+ message: `${model} is rate limited; waiting ${Math.ceil(pause / 1000)}s`,
18
+ };
19
+ await sleep(pause, signal);
20
+ if (signal.aborted)
21
+ return;
22
+ }
23
+ yield { type: "progress", taskId, message: `reviewing with ${model}` };
24
+ const outcome = await options.attempt(model);
25
+ yield { type: "usage", taskId, ...outcome.usage };
26
+ yield { type: "progress", taskId, message: attemptSummary(model, outcome) };
27
+ for (const finding of outcome.findings)
28
+ yield { type: "finding", taskId, finding };
29
+ if (!outcome.error) {
30
+ health.recordSuccess(model);
31
+ yield { type: "done", taskId };
32
+ return;
33
+ }
34
+ if (!outcome.error.retryable) {
35
+ yield {
36
+ type: "error",
37
+ taskId,
38
+ error: `${model}: ${outcome.error.message}`,
39
+ retryable: false,
40
+ };
41
+ return;
42
+ }
43
+ if (outcome.error.quota && health.recordQuota(model, outcome.error.quota) === "wait") {
44
+ continue;
45
+ }
46
+ if (!outcome.error.quota)
47
+ health.recordFailure(model);
48
+ lastError = `${model}: ${outcome.error.message}`;
49
+ yield { type: "progress", taskId, message: `${lastError}; trying the next model` };
50
+ break;
51
+ }
52
+ }
53
+ yield {
54
+ type: "error",
55
+ taskId,
56
+ error: lastError
57
+ ? `every ${options.tier} model failed (${lastError})`
58
+ : `every ${options.tier} model is out of quota for this run`,
59
+ retryable: true,
60
+ };
61
+ }
62
+ // Which tools an attempt spent its steps on, and whether it finished: a
63
+ // review that never called task_done was cut off, usually by the step cap.
64
+ function attemptSummary(model, outcome) {
65
+ const { inputTokens, outputTokens, reasoningTokens, costUsd } = outcome.usage;
66
+ const resumed = outcome.resumed ? ", resumed after stopping early" : "";
67
+ return `${model}: ${outcome.steps} step(s), ${toolSummary(outcome.toolCalls)}${resumed}, ${inputTokens} in / ${outputTokens} out / ${reasoningTokens} reasoning tokens, $${costUsd.toFixed(4)}`;
68
+ }
69
+ export function toolSummary(toolCalls) {
70
+ if (toolCalls.length === 0)
71
+ return "no tool calls";
72
+ // MCP tools carry the server's name as a prefix (MCP_SERVER in runtime.ts).
73
+ const names = toolCalls.map((t) => t.replace(/^ocra_/, ""));
74
+ const counts = new Map();
75
+ for (const name of names)
76
+ counts.set(name, (counts.get(name) ?? 0) + 1);
77
+ const byUse = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
78
+ const finished = names.includes(REVIEW_TOOLS.taskDone) ? "" : "; no task_done";
79
+ return `${toolCalls.length} tool call(s) (${byUse.map(([n, c]) => `${n} ${c}`).join(", ")}${finished})`;
80
+ }
81
+ //# sourceMappingURL=failback.js.map
@@ -0,0 +1,4 @@
1
+ export * from "./models.js";
2
+ export * from "./plugin.js";
3
+ export * from "./runtime.js";
4
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./models.js";
2
+ export * from "./plugin.js";
3
+ export * from "./runtime.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,30 @@
1
+ import { type QuotaError } from "./quota.js";
2
+ export interface ModelRef {
3
+ providerID: string;
4
+ modelID: string;
5
+ }
6
+ export declare function parseModel(model: string): ModelRef;
7
+ export interface CircuitOptions {
8
+ threshold?: number;
9
+ cooldownMs?: number;
10
+ maxCooldownMs?: number;
11
+ now?: () => number;
12
+ }
13
+ export declare class ModelHealth {
14
+ private readonly circuits;
15
+ private readonly quotas;
16
+ private readonly outOfQuota;
17
+ private readonly threshold;
18
+ private readonly cooldownMs;
19
+ private readonly maxCooldownMs;
20
+ private readonly now;
21
+ constructor(options?: CircuitOptions);
22
+ order(chain: readonly string[]): string[];
23
+ state(model: string): "closed" | "open" | "half-open";
24
+ recordFailure(model: string): void;
25
+ recordSuccess(model: string): void;
26
+ pausedFor(model: string): number;
27
+ isOutOfQuota(model: string): boolean;
28
+ recordQuota(model: string, quota: QuotaError): "wait" | "out_of_quota";
29
+ }
30
+ //# sourceMappingURL=models.d.ts.map
package/dist/models.js ADDED
@@ -0,0 +1,88 @@
1
+ import { MAX_QUOTA_WAIT_MS, QUOTA_RETRIES } from "./quota.js";
2
+ export function parseModel(model) {
3
+ const slash = model.indexOf("/");
4
+ if (slash <= 0 || slash === model.length - 1) {
5
+ throw new Error(`Model "${model}" must be written as provider/model, for example google/gemini-flash-lite-latest`);
6
+ }
7
+ return { providerID: model.slice(0, slash), modelID: model.slice(slash + 1) };
8
+ }
9
+ // A circuit breaker per model: after `threshold` consecutive failures the
10
+ // model is skipped (open) for a cooldown, then one attempt is let through
11
+ // (half-open). Success closes the circuit; failure reopens it for twice as
12
+ // long, up to a limit. Tasks go straight to the fallback instead of paying
13
+ // for a model that is down.
14
+ export class ModelHealth {
15
+ circuits = new Map();
16
+ quotas = new Map();
17
+ outOfQuota = new Set();
18
+ threshold;
19
+ cooldownMs;
20
+ maxCooldownMs;
21
+ now;
22
+ constructor(options = {}) {
23
+ this.threshold = options.threshold ?? 2;
24
+ this.cooldownMs = options.cooldownMs ?? 60_000;
25
+ this.maxCooldownMs = options.maxCooldownMs ?? 10 * 60_000;
26
+ this.now = options.now ?? Date.now;
27
+ }
28
+ // Models whose circuit is closed or half-open, in chain order. When every
29
+ // circuit is open, all models in the order they reopen: a review should
30
+ // still try rather than fail without a request.
31
+ // Models out of quota are left out entirely: another request would only be
32
+ // refused again.
33
+ order(chain) {
34
+ const now = this.now();
35
+ const usable = chain.filter((m) => !this.outOfQuota.has(m));
36
+ const available = usable.filter((m) => (this.circuits.get(m)?.openUntil ?? 0) <= now);
37
+ if (available.length > 0)
38
+ return available;
39
+ return [...usable].sort((a, b) => (this.circuits.get(a)?.openUntil ?? 0) - (this.circuits.get(b)?.openUntil ?? 0));
40
+ }
41
+ state(model) {
42
+ const circuit = this.circuits.get(model);
43
+ if (circuit?.openUntil === undefined)
44
+ return "closed";
45
+ return circuit.openUntil > this.now() ? "open" : "half-open";
46
+ }
47
+ recordFailure(model) {
48
+ const circuit = this.circuits.get(model) ?? { failures: 0, cooldownMs: this.cooldownMs };
49
+ const probing = this.state(model) === "half-open";
50
+ circuit.failures += 1;
51
+ if (probing || circuit.failures >= this.threshold) {
52
+ circuit.openUntil = this.now() + circuit.cooldownMs;
53
+ circuit.cooldownMs = Math.min(circuit.cooldownMs * 2, this.maxCooldownMs);
54
+ circuit.failures = 0;
55
+ }
56
+ this.circuits.set(model, circuit);
57
+ }
58
+ recordSuccess(model) {
59
+ this.circuits.delete(model);
60
+ this.quotas.delete(model);
61
+ }
62
+ // How long every task should hold off this model (a shared rate-limit pause).
63
+ pausedFor(model) {
64
+ return Math.max(0, (this.quotas.get(model)?.pausedUntil ?? 0) - this.now());
65
+ }
66
+ isOutOfQuota(model) {
67
+ return this.outOfQuota.has(model);
68
+ }
69
+ // A rate limit with a short, stated wait pauses the model for every task;
70
+ // a daily limit, no stated wait, a long one, or too many waits in a row
71
+ // mean the model is out of quota for the rest of the run.
72
+ recordQuota(model, quota) {
73
+ const state = this.quotas.get(model) ?? { waits: 0, pausedUntil: 0 };
74
+ const wait = quota.retryAfterMs;
75
+ if (quota.daily ||
76
+ wait === undefined ||
77
+ wait > MAX_QUOTA_WAIT_MS ||
78
+ state.waits >= QUOTA_RETRIES) {
79
+ this.outOfQuota.add(model);
80
+ return "out_of_quota";
81
+ }
82
+ state.waits += 1;
83
+ state.pausedUntil = Math.max(state.pausedUntil, this.now() + wait);
84
+ this.quotas.set(model, state);
85
+ return "wait";
86
+ }
87
+ }
88
+ //# sourceMappingURL=models.js.map
@@ -0,0 +1,14 @@
1
+ export interface OpencodeServer {
2
+ url: string;
3
+ authorization: string;
4
+ close(): Promise<void>;
5
+ killNow(): void;
6
+ }
7
+ export interface StartOptions {
8
+ binary: string;
9
+ env: Record<string, string>;
10
+ config: unknown;
11
+ startupTimeoutMs?: number;
12
+ }
13
+ export declare function startOpencodeServer(options: StartOptions): Promise<OpencodeServer>;
14
+ //# sourceMappingURL=opencode-server.d.ts.map
@@ -0,0 +1,84 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { createServer } from "node:net";
4
+ const LISTENING = /opencode server listening on (https?:\/\/\S+)/;
5
+ export async function startOpencodeServer(options) {
6
+ const port = await freePort();
7
+ const password = randomBytes(24).toString("hex");
8
+ const child = spawn(options.binary, ["serve", "--hostname=127.0.0.1", `--port=${port}`], {
9
+ env: {
10
+ ...options.env,
11
+ OPENCODE_CONFIG_CONTENT: JSON.stringify(options.config),
12
+ OPENCODE_SERVER_PASSWORD: password,
13
+ },
14
+ stdio: ["ignore", "pipe", "pipe"],
15
+ });
16
+ const url = await waitForListening(child, options.startupTimeoutMs ?? 30_000);
17
+ return {
18
+ url,
19
+ authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`,
20
+ close: () => stop(child),
21
+ killNow: () => {
22
+ if (child.exitCode === null && child.signalCode === null)
23
+ child.kill("SIGKILL");
24
+ },
25
+ };
26
+ }
27
+ const STARTUP_OUTPUT_CHARS = 16_000;
28
+ function waitForListening(child, timeoutMs) {
29
+ return new Promise((resolve, reject) => {
30
+ let output = "";
31
+ const fail = (message) => {
32
+ clearTimeout(timer);
33
+ void stop(child);
34
+ reject(new Error(`${message}${output.trim() ? `\n${output.trim()}` : ""}`));
35
+ };
36
+ const timer = setTimeout(() => fail(`OpenCode did not start within ${timeoutMs}ms`), timeoutMs);
37
+ // Only the tail matters for a startup error message.
38
+ const keep = (chunk) => {
39
+ output = (output + chunk.toString()).slice(-STARTUP_OUTPUT_CHARS);
40
+ };
41
+ const onData = (chunk) => {
42
+ keep(chunk);
43
+ const match = LISTENING.exec(output);
44
+ if (match?.[1]) {
45
+ clearTimeout(timer);
46
+ // Past startup the output is not needed, but it must still be read:
47
+ // a full pipe would block OpenCode's next write.
48
+ child.stdout?.off("data", onData);
49
+ child.stderr?.off("data", keep);
50
+ child.stdout?.resume();
51
+ child.stderr?.resume();
52
+ resolve(match[1]);
53
+ }
54
+ };
55
+ child.stdout?.on("data", onData);
56
+ child.stderr?.on("data", keep);
57
+ child.once("error", (error) => fail(`OpenCode failed to start: ${error.message}`));
58
+ child.once("exit", (code) => fail(`OpenCode exited with code ${code} during startup`));
59
+ });
60
+ }
61
+ function stop(child) {
62
+ if (child.exitCode !== null || child.signalCode !== null)
63
+ return Promise.resolve();
64
+ return new Promise((resolve) => {
65
+ const kill = setTimeout(() => child.kill("SIGKILL"), 5_000);
66
+ child.once("exit", () => {
67
+ clearTimeout(kill);
68
+ resolve();
69
+ });
70
+ child.kill("SIGTERM");
71
+ });
72
+ }
73
+ function freePort() {
74
+ return new Promise((resolve, reject) => {
75
+ const server = createServer();
76
+ server.once("error", reject);
77
+ server.listen(0, "127.0.0.1", () => {
78
+ const address = server.address();
79
+ const port = typeof address === "object" && address ? address.port : 0;
80
+ server.close(() => resolve(port));
81
+ });
82
+ });
83
+ }
84
+ //# sourceMappingURL=opencode-server.js.map
@@ -0,0 +1,3 @@
1
+ import type { OcraPlugin } from "@open-cr-agent/core";
2
+ export declare const opencodeRuntimePlugin: OcraPlugin;
3
+ //# sourceMappingURL=plugin.d.ts.map
package/dist/plugin.js ADDED
@@ -0,0 +1,8 @@
1
+ import { OpenCodeRuntime } from "./runtime.js";
2
+ export const opencodeRuntimePlugin = {
3
+ name: "runtime-opencode",
4
+ configure(ctx) {
5
+ ctx.registerRuntime("opencode", (options) => new OpenCodeRuntime(options));
6
+ },
7
+ };
8
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1,9 @@
1
+ export interface QuotaError {
2
+ retryAfterMs?: number;
3
+ daily: boolean;
4
+ }
5
+ export declare const MAX_QUOTA_WAIT_MS = 90000;
6
+ export declare const QUOTA_RETRIES = 3;
7
+ export declare function parseQuotaError(message: string, statusCode?: number): QuotaError | undefined;
8
+ export declare function sleep(ms: number, signal: AbortSignal): Promise<void>;
9
+ //# sourceMappingURL=quota.d.ts.map