@open-cr-agent/runtime-opencode 0.5.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 +1 -1
- package/dist/binary.d.ts +0 -1
- package/dist/binary.js +0 -1
- package/dist/effort-setup.d.ts +13 -0
- package/dist/effort-setup.js +42 -0
- package/dist/effort.d.ts +26 -0
- package/dist/effort.js +148 -0
- package/dist/index.d.ts +0 -1
- package/dist/index.js +0 -1
- package/dist/opencode-config.d.ts +100 -0
- package/dist/opencode-config.js +136 -0
- package/dist/opencode-server.d.ts +0 -1
- package/dist/opencode-server.js +0 -1
- package/dist/plugin.d.ts +0 -1
- package/dist/plugin.js +0 -1
- package/dist/runtime.d.ts +8 -103
- package/dist/runtime.js +85 -176
- package/dist/server-env.d.ts +0 -3
- package/dist/server-env.js +2 -3
- package/dist/session-outcome.d.ts +36 -34
- package/dist/session-outcome.js +47 -3
- package/dist/session-prompt.d.ts +3 -11
- package/dist/session-prompt.js +25 -15
- package/dist/tool-server.d.ts +0 -1
- package/dist/tool-server.js +1 -2
- package/dist/transport.d.ts +0 -1
- package/dist/transport.js +4 -1
- package/package.json +3 -3
package/dist/runtime.js
CHANGED
|
@@ -2,58 +2,32 @@ import { rmSync } from "node:fs";
|
|
|
2
2
|
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { OcraError, } from "@open-cr-agent/core";
|
|
6
|
-
import { callChain, completeWithFailback, MAX_AGENT_STEPS, ModelHealth, parseModel, RESUME_MESSAGE, REVIEW_TOOLS, reviewTools, withFailback, withoutSecrets, } from "@open-cr-agent/core/internal";
|
|
5
|
+
import { ChainRunner, MAX_AGENT_STEPS, OcraError, parseModel, RESUME_MESSAGE, REVIEW_TOOLS, reviewTools, withoutSecrets, } from "@open-cr-agent/core";
|
|
7
6
|
import { createOpencodeClient } from "@opencode-ai/sdk/v2";
|
|
8
7
|
import { resolveOpencodeBinary } from "./binary.js";
|
|
8
|
+
import { AppliedEfforts } from "./effort.js";
|
|
9
|
+
import { setUpEfforts } from "./effort-setup.js";
|
|
10
|
+
import { DISABLED_BUILTINS, HELPER_AGENT, MCP_SERVER, openCodeConfig, openCodeSampling, REVIEW_AGENT, WITHOUT_SAMPLING, } from "./opencode-config.js";
|
|
9
11
|
import { startOpencodeServer } from "./opencode-server.js";
|
|
10
12
|
import { credentialValues, missingCredentials, serverEnv } from "./server-env.js";
|
|
11
13
|
import { promptSession } from "./session-prompt.js";
|
|
12
14
|
import { startToolServer } from "./tool-server.js";
|
|
13
15
|
import { createUntimedDispatcher, untimedFetch } from "./transport.js";
|
|
14
|
-
export const MCP_SERVER = "ocra";
|
|
15
|
-
const REVIEW_AGENT = "ocra-reviewer";
|
|
16
|
-
const HELPER_AGENT = "ocra-helper";
|
|
17
|
-
// Must not be empty: OpenCode falls back to its full coding prompt otherwise.
|
|
18
|
-
const REVIEW_AGENT_PROMPT = "You are a code review agent run by ocra. Follow the review instructions below.";
|
|
19
|
-
const HELPER_AGENT_PROMPT = "You answer exactly as the instructions below ask, with no tools.";
|
|
20
|
-
// The helper answers in one step and has no tools. It still needs two:
|
|
21
|
-
// OpenCode appends an assistant message on an agent's last allowed step, and
|
|
22
|
-
// Gemini rejects a request that ends with a model turn (#66).
|
|
23
|
-
export const HELPER_AGENT_STEPS = 2;
|
|
24
16
|
// Sent once to a review agent that stopped before finishing (session-prompt.ts).
|
|
25
|
-
|
|
17
|
+
const REVIEW_RESUME = {
|
|
26
18
|
doneTool: REVIEW_TOOLS.taskDone,
|
|
27
19
|
maxSteps: MAX_AGENT_STEPS,
|
|
28
20
|
message: RESUME_MESSAGE,
|
|
29
21
|
};
|
|
30
|
-
// Every OpenCode built-in tool of the pinned version; a test fails when an
|
|
31
|
-
// upgrade adds one, so a new write-capable tool can never be enabled silently.
|
|
32
|
-
export const OPENCODE_BUILTIN_TOOLS = [
|
|
33
|
-
"invalid",
|
|
34
|
-
"question",
|
|
35
|
-
"bash",
|
|
36
|
-
"read",
|
|
37
|
-
"glob",
|
|
38
|
-
"grep",
|
|
39
|
-
"edit",
|
|
40
|
-
"write",
|
|
41
|
-
"task",
|
|
42
|
-
"webfetch",
|
|
43
|
-
"todowrite",
|
|
44
|
-
"websearch",
|
|
45
|
-
"skill",
|
|
46
|
-
"apply_patch",
|
|
47
|
-
];
|
|
48
|
-
const DISABLED_BUILTINS = Object.fromEntries(OPENCODE_BUILTIN_TOOLS.map((t) => [t, false]));
|
|
49
22
|
export class OpenCodeRuntime {
|
|
50
|
-
options;
|
|
51
23
|
name = "opencode";
|
|
52
24
|
sampling;
|
|
53
25
|
infra;
|
|
54
26
|
context;
|
|
55
|
-
|
|
27
|
+
chains;
|
|
56
28
|
helperTools;
|
|
29
|
+
applied;
|
|
30
|
+
options;
|
|
57
31
|
constructor(options) {
|
|
58
32
|
this.options = options;
|
|
59
33
|
const mcpTools = [...reviewTools, ...options.tools].map((t) => [
|
|
@@ -62,60 +36,28 @@ export class OpenCodeRuntime {
|
|
|
62
36
|
]);
|
|
63
37
|
this.helperTools = { ...DISABLED_BUILTINS, ...Object.fromEntries(mcpTools) };
|
|
64
38
|
this.sampling = openCodeSampling(options.sampling);
|
|
39
|
+
this.applied = new AppliedEfforts(options.sampling);
|
|
40
|
+
this.chains = new ChainRunner(options.models, {
|
|
41
|
+
refuse: (chain, own) => this.unprepared(chain, own),
|
|
42
|
+
ready: async () => {
|
|
43
|
+
await this.start();
|
|
44
|
+
},
|
|
45
|
+
task: (model, spec, signal, onUsage) => this.attemptTask(model, spec, signal, onUsage),
|
|
46
|
+
complete: (model, request, signal) => this.attemptCompletion(model, request, signal),
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
appliedTo(agent) {
|
|
50
|
+
return this.applied.appliedTo(agent);
|
|
65
51
|
}
|
|
66
52
|
async *runTask(spec, signal) {
|
|
67
53
|
if (this.context && this.context !== spec.context) {
|
|
68
54
|
throw new OcraError("INTERNAL", "An OpenCodeRuntime instance serves a single review run");
|
|
69
55
|
}
|
|
70
56
|
this.context = spec.context;
|
|
71
|
-
|
|
72
|
-
const refused = chain.length === 0 ? noModel(spec.modelTier) : this.unprepared(spec.models);
|
|
73
|
-
if (refused) {
|
|
74
|
-
yield { type: "error", taskId: spec.taskId, retryable: false, error: refused };
|
|
75
|
-
return;
|
|
76
|
-
}
|
|
77
|
-
const infra = await this.start();
|
|
78
|
-
yield* withFailback({
|
|
79
|
-
taskId: spec.taskId,
|
|
80
|
-
tier: spec.modelTier,
|
|
81
|
-
...(spec.models?.length ? { agent: spec.reviewer } : {}),
|
|
82
|
-
chain,
|
|
83
|
-
health: this.health,
|
|
84
|
-
signal,
|
|
85
|
-
attempt: (model, onUsage) => this.prompt(infra, {
|
|
86
|
-
title: `ocra ${spec.taskId}`,
|
|
87
|
-
agent: REVIEW_AGENT,
|
|
88
|
-
model,
|
|
89
|
-
system: spec.systemPrompt,
|
|
90
|
-
user: spec.userPrompt,
|
|
91
|
-
tools: DISABLED_BUILTINS,
|
|
92
|
-
toolPrefix: `${MCP_SERVER}_`,
|
|
93
|
-
resume: REVIEW_RESUME,
|
|
94
|
-
}, signal, onUsage),
|
|
95
|
-
});
|
|
57
|
+
yield* this.chains.runTask(spec, signal);
|
|
96
58
|
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
const refused = chain.length === 0 ? noModel(request.tier) : this.unprepared(request.models);
|
|
100
|
-
if (refused)
|
|
101
|
-
throw new OcraError("CONFIG_INVALID", refused);
|
|
102
|
-
const infra = await this.start();
|
|
103
|
-
return completeWithFailback({
|
|
104
|
-
tier: request.tier,
|
|
105
|
-
...(request.models?.length ? { agent: request.agent ?? request.tier } : {}),
|
|
106
|
-
chain,
|
|
107
|
-
health: this.health,
|
|
108
|
-
signal,
|
|
109
|
-
attempt: (model) => this.prompt(infra, {
|
|
110
|
-
title: "ocra helper",
|
|
111
|
-
agent: HELPER_AGENT,
|
|
112
|
-
model,
|
|
113
|
-
system: request.system,
|
|
114
|
-
user: request.user,
|
|
115
|
-
tools: this.helperTools,
|
|
116
|
-
toolPrefix: `${MCP_SERVER}_`,
|
|
117
|
-
}, signal),
|
|
118
|
-
});
|
|
59
|
+
complete(request, signal) {
|
|
60
|
+
return this.chains.complete(request, signal);
|
|
119
61
|
}
|
|
120
62
|
async dispose() {
|
|
121
63
|
const infra = await this.infra?.catch(() => undefined);
|
|
@@ -126,6 +68,45 @@ export class OpenCodeRuntime {
|
|
|
126
68
|
await Promise.allSettled([infra.server.close(), infra.tools.close(), infra.dispatcher.close()]);
|
|
127
69
|
await rm(infra.root, { recursive: true, force: true });
|
|
128
70
|
}
|
|
71
|
+
async attemptTask(model, spec, signal, onUsage) {
|
|
72
|
+
const infra = await this.start();
|
|
73
|
+
return this.prompt(infra, {
|
|
74
|
+
title: `ocra ${spec.taskId}`,
|
|
75
|
+
...this.effortCall(infra, REVIEW_AGENT, spec.reviewer, spec.effort, model),
|
|
76
|
+
model,
|
|
77
|
+
system: spec.systemPrompt,
|
|
78
|
+
user: spec.userPrompt,
|
|
79
|
+
tools: DISABLED_BUILTINS,
|
|
80
|
+
toolPrefix: `${MCP_SERVER}_`,
|
|
81
|
+
resume: REVIEW_RESUME,
|
|
82
|
+
}, signal, onUsage);
|
|
83
|
+
}
|
|
84
|
+
async attemptCompletion(model, request, signal) {
|
|
85
|
+
const infra = await this.start();
|
|
86
|
+
return this.prompt(infra, {
|
|
87
|
+
title: "ocra helper",
|
|
88
|
+
...this.effortCall(infra, HELPER_AGENT, request.agent ?? request.tier, request.effort, model),
|
|
89
|
+
model,
|
|
90
|
+
system: request.system,
|
|
91
|
+
user: request.user,
|
|
92
|
+
tools: this.helperTools,
|
|
93
|
+
toolPrefix: `${MCP_SERVER}_`,
|
|
94
|
+
}, signal);
|
|
95
|
+
}
|
|
96
|
+
// The OpenCode agent and variant one attempt runs with, recorded for the
|
|
97
|
+
// agent's provenance.
|
|
98
|
+
effortCall(infra, base, agent, effort, model) {
|
|
99
|
+
if (effort === undefined)
|
|
100
|
+
return { agent: base };
|
|
101
|
+
const route = infra.efforts.route(model, effort);
|
|
102
|
+
const keepsSampling = this.applied.record(agent, effort, model, route !== undefined);
|
|
103
|
+
return {
|
|
104
|
+
agent: keepsSampling || this.options.sampling?.temperature === undefined
|
|
105
|
+
? base
|
|
106
|
+
: `${base}${WITHOUT_SAMPLING}`,
|
|
107
|
+
...(route?.variant ? { variant: route.variant } : {}),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
129
110
|
prompt(infra, input, signal, onUsage) {
|
|
130
111
|
return promptSession(infra.client.session, input, `${MCP_SERVER}_${REVIEW_TOOLS.reportFinding}`, signal, onUsage ? { onUsage } : {}).then((outcome) => outcome.error
|
|
131
112
|
? {
|
|
@@ -140,14 +121,14 @@ export class OpenCodeRuntime {
|
|
|
140
121
|
// The server holds the credentials of the providers it started with; an
|
|
141
122
|
// agent's own chain naming another would fail at OpenCode as "model not
|
|
142
123
|
// found". The tier chains are always among them.
|
|
143
|
-
unprepared(own) {
|
|
144
|
-
if (!own
|
|
124
|
+
unprepared(chain, own) {
|
|
125
|
+
if (!own)
|
|
145
126
|
return undefined;
|
|
146
127
|
const prepared = new Set(providersOf(this.options));
|
|
147
|
-
const model =
|
|
128
|
+
const model = chain.find((m) => !prepared.has(parseModel(m).providerID));
|
|
148
129
|
return model === undefined
|
|
149
130
|
? undefined
|
|
150
|
-
: `"${model}" is not among the models the runtime was started with (RuntimeOptions.models or agentModels)
|
|
131
|
+
: new OcraError("CONFIG_INVALID", `"${model}" is not among the models the runtime was started with (RuntimeOptions.models or agentModels)`);
|
|
151
132
|
}
|
|
152
133
|
start() {
|
|
153
134
|
this.infra ??= this.launch();
|
|
@@ -165,7 +146,8 @@ export class OpenCodeRuntime {
|
|
|
165
146
|
state: join(root, "state"),
|
|
166
147
|
};
|
|
167
148
|
const workspace = join(root, "workspace");
|
|
168
|
-
|
|
149
|
+
const probe = join(root, "probe");
|
|
150
|
+
await Promise.all([...Object.values(dirs), workspace, probe].map((d) => mkdir(d, { recursive: true })));
|
|
169
151
|
const tools = await startToolServer([...reviewTools, ...this.options.tools], () => this.context);
|
|
170
152
|
let started;
|
|
171
153
|
try {
|
|
@@ -177,12 +159,13 @@ export class OpenCodeRuntime {
|
|
|
177
159
|
});
|
|
178
160
|
started = server;
|
|
179
161
|
const dispatcher = createUntimedDispatcher();
|
|
180
|
-
const
|
|
162
|
+
const clientFor = (directory) => createOpencodeClient({
|
|
181
163
|
baseUrl: server.url,
|
|
182
|
-
directory
|
|
164
|
+
directory,
|
|
183
165
|
headers: { Authorization: server.authorization },
|
|
184
166
|
fetch: untimedFetch(dispatcher),
|
|
185
167
|
});
|
|
168
|
+
const client = clientFor(workspace);
|
|
186
169
|
// A second Ctrl-C exits at once, before dispose() can run: stop
|
|
187
170
|
// OpenCode and remove its directory synchronously on the way out.
|
|
188
171
|
const onExit = () => {
|
|
@@ -190,8 +173,15 @@ export class OpenCodeRuntime {
|
|
|
190
173
|
rmSync(root, { recursive: true, force: true });
|
|
191
174
|
};
|
|
192
175
|
process.on("exit", onExit);
|
|
176
|
+
const efforts = await setUpEfforts({
|
|
177
|
+
models: chainModels(this.options),
|
|
178
|
+
custom,
|
|
179
|
+
probe: clientFor(probe).config,
|
|
180
|
+
workspace: client.config,
|
|
181
|
+
file: join(dirs.config, "opencode.json"),
|
|
182
|
+
});
|
|
193
183
|
const secrets = credentialValues(this.options.env, providersOf(this.options), custom);
|
|
194
|
-
return { root, tools, server, client, dispatcher, onExit, secrets };
|
|
184
|
+
return { root, tools, server, client, efforts, dispatcher, onExit, secrets };
|
|
195
185
|
}
|
|
196
186
|
catch (error) {
|
|
197
187
|
await Promise.allSettled([tools.close(), started?.close()]);
|
|
@@ -200,93 +190,12 @@ export class OpenCodeRuntime {
|
|
|
200
190
|
}
|
|
201
191
|
}
|
|
202
192
|
}
|
|
203
|
-
//
|
|
204
|
-
//
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
function openCodeSampling(sampling = {}) {
|
|
208
|
-
return {
|
|
209
|
-
...(sampling.temperature === undefined ? {} : { temperature: sampling.temperature }),
|
|
210
|
-
...(sampling.seed === undefined ? {} : { notApplied: ["seed"] }),
|
|
211
|
-
};
|
|
193
|
+
// Every model a call may run on: the tiers' chains and the agents' own
|
|
194
|
+
// (ADR-0025).
|
|
195
|
+
function chainModels(options) {
|
|
196
|
+
return [...Object.values(options.models), ...Object.values(options.agentModels ?? {})].flatMap((chain) => [...(chain ?? [])]);
|
|
212
197
|
}
|
|
213
|
-
|
|
214
|
-
const permission = { edit: "deny", bash: "deny", webfetch: "deny", skill: "deny" };
|
|
215
|
-
const { temperature } = sampling;
|
|
216
|
-
const agentSampling = temperature === undefined ? {} : { temperature };
|
|
217
|
-
return {
|
|
218
|
-
share: "disabled",
|
|
219
|
-
autoupdate: false,
|
|
220
|
-
...(Object.keys(custom).length > 0
|
|
221
|
-
? { provider: providerConfig(custom, temperature !== undefined) }
|
|
222
|
-
: {}),
|
|
223
|
-
mcp: {
|
|
224
|
-
[MCP_SERVER]: {
|
|
225
|
-
type: "remote",
|
|
226
|
-
url: tools.url,
|
|
227
|
-
headers: tools.headers,
|
|
228
|
-
oauth: false,
|
|
229
|
-
enabled: true,
|
|
230
|
-
},
|
|
231
|
-
},
|
|
232
|
-
agent: {
|
|
233
|
-
[REVIEW_AGENT]: {
|
|
234
|
-
mode: "primary",
|
|
235
|
-
prompt: REVIEW_AGENT_PROMPT,
|
|
236
|
-
steps: MAX_AGENT_STEPS,
|
|
237
|
-
tools: DISABLED_BUILTINS,
|
|
238
|
-
permission,
|
|
239
|
-
...agentSampling,
|
|
240
|
-
},
|
|
241
|
-
[HELPER_AGENT]: {
|
|
242
|
-
mode: "primary",
|
|
243
|
-
prompt: HELPER_AGENT_PROMPT,
|
|
244
|
-
steps: HELPER_AGENT_STEPS,
|
|
245
|
-
tools: helperTools,
|
|
246
|
-
permission,
|
|
247
|
-
...agentSampling,
|
|
248
|
-
},
|
|
249
|
-
},
|
|
250
|
-
};
|
|
251
|
-
}
|
|
252
|
-
// OpenCode's form of a provider declared in configuration. OpenCode bundles
|
|
253
|
-
// the OpenAI-compatible client, so nothing is installed to reach it
|
|
254
|
-
// (docs/spikes/0002). The key stays in the environment: OpenCode reads
|
|
255
|
-
// {env:NAME} itself, and the configuration, which OpenCode may log, never
|
|
256
|
-
// holds it. Prices are per million tokens, as OpenCode's catalog has them.
|
|
257
|
-
// OpenCode assumes a declared model takes no temperature and drops one;
|
|
258
|
-
// with a temperature configured, the models are marked as taking it.
|
|
259
|
-
function providerConfig(custom, temperature) {
|
|
260
|
-
return Object.fromEntries(Object.entries(custom).map(([id, provider]) => [
|
|
261
|
-
id,
|
|
262
|
-
{
|
|
263
|
-
npm: "@ai-sdk/openai-compatible",
|
|
264
|
-
name: id,
|
|
265
|
-
options: {
|
|
266
|
-
baseURL: provider.baseUrl,
|
|
267
|
-
...(provider.apiKeyEnv ? { apiKey: `{env:${provider.apiKeyEnv}}` } : {}),
|
|
268
|
-
},
|
|
269
|
-
models: Object.fromEntries(Object.entries(provider.models).map(([model, price]) => [
|
|
270
|
-
model,
|
|
271
|
-
{
|
|
272
|
-
name: model,
|
|
273
|
-
...(temperature ? { temperature: true } : {}),
|
|
274
|
-
cost: {
|
|
275
|
-
input: price.input,
|
|
276
|
-
output: price.output,
|
|
277
|
-
...(price.cachedInput === undefined ? {} : { cache_read: price.cachedInput }),
|
|
278
|
-
},
|
|
279
|
-
},
|
|
280
|
-
])),
|
|
281
|
-
},
|
|
282
|
-
]));
|
|
283
|
-
}
|
|
284
|
-
// The providers of every chain a call may run on: the tiers' and the
|
|
285
|
-
// agents' own (ADR-0025), so each gets its credentials like a tier's.
|
|
198
|
+
// The providers of those models, so each gets its credentials like a tier's.
|
|
286
199
|
export function providersOf(options) {
|
|
287
|
-
return
|
|
288
|
-
}
|
|
289
|
-
function noModel(tier) {
|
|
290
|
-
return `No model configured for the "${tier}" tier; set models.${tier} in .ocra/config.json or OCRA_MODEL_${tier.toUpperCase()}`;
|
|
200
|
+
return chainModels(options).map((m) => parseModel(m).providerID);
|
|
291
201
|
}
|
|
292
|
-
//# sourceMappingURL=runtime.js.map
|
package/dist/server-env.d.ts
CHANGED
|
@@ -6,9 +6,6 @@ export interface IsolatedDirs {
|
|
|
6
6
|
}
|
|
7
7
|
type CustomProviders = Readonly<Record<string, CustomProvider>>;
|
|
8
8
|
export declare function missingCredentials(base: Env, providers: readonly string[], custom?: CustomProviders): string[];
|
|
9
|
-
export declare const EXTRA_ENV_VARIABLE = "OCRA_RUNTIME_ENV";
|
|
10
|
-
export declare function credentialNames(base: Env, providers: readonly string[], custom?: CustomProviders): string[];
|
|
11
9
|
export declare function credentialValues(base: Env, providers: readonly string[], custom?: CustomProviders): string[];
|
|
12
10
|
export declare function serverEnv(base: Env, dirs: IsolatedDirs, providers: readonly string[], custom?: CustomProviders): Record<string, string>;
|
|
13
11
|
export {};
|
|
14
|
-
//# sourceMappingURL=server-env.d.ts.map
|
package/dist/server-env.js
CHANGED
|
@@ -88,7 +88,7 @@ export function missingCredentials(base, providers, custom = {}) {
|
|
|
88
88
|
}
|
|
89
89
|
const GOOGLE_KEY = "GOOGLE_GENERATIVE_AI_API_KEY";
|
|
90
90
|
const GOOGLE_KEY_ALIASES = ["GEMINI_API_KEY", "GOOGLE_API_KEY"];
|
|
91
|
-
|
|
91
|
+
const EXTRA_ENV_VARIABLE = "OCRA_RUNTIME_ENV";
|
|
92
92
|
// OpenCode installs its plugin package from npm into every config directory
|
|
93
93
|
// when it starts, and the SDK of a provider it does not bundle when a model
|
|
94
94
|
// first uses it; no flag turns either off. ocra loads no OpenCode plugins and
|
|
@@ -121,7 +121,7 @@ const NEVER_BY_PREFIX = [
|
|
|
121
121
|
// a provider declared in configuration only the one it names, for a known
|
|
122
122
|
// catalog provider its variables, for any other every variable with its
|
|
123
123
|
// prefix that is not a platform token.
|
|
124
|
-
|
|
124
|
+
function credentialNames(base, providers, custom = {}) {
|
|
125
125
|
const names = [];
|
|
126
126
|
for (const provider of new Set(providers)) {
|
|
127
127
|
const declared = custom[provider];
|
|
@@ -191,4 +191,3 @@ export function serverEnv(base, dirs, providers, custom = {}) {
|
|
|
191
191
|
env.XDG_STATE_HOME = dirs.state;
|
|
192
192
|
return env;
|
|
193
193
|
}
|
|
194
|
-
//# sourceMappingURL=server-env.js.map
|
|
@@ -1,36 +1,38 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
info: {
|
|
5
|
-
role:
|
|
6
|
-
cost
|
|
7
|
-
tokens
|
|
8
|
-
input
|
|
9
|
-
output
|
|
10
|
-
reasoning
|
|
11
|
-
cache
|
|
12
|
-
read
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
error
|
|
16
|
-
name
|
|
17
|
-
data
|
|
18
|
-
message
|
|
19
|
-
statusCode
|
|
20
|
-
isRetryable
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
parts: {
|
|
25
|
-
type:
|
|
26
|
-
text
|
|
27
|
-
tool
|
|
28
|
-
state
|
|
29
|
-
status
|
|
30
|
-
input
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
}
|
|
1
|
+
import { type AttemptOutcome, type Usage } from "@open-cr-agent/core";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
declare const sessionMessageSchema: z.ZodObject<{
|
|
4
|
+
info: z.ZodObject<{
|
|
5
|
+
role: z.ZodString;
|
|
6
|
+
cost: z.ZodOptional<z.ZodNumber>;
|
|
7
|
+
tokens: z.ZodOptional<z.ZodObject<{
|
|
8
|
+
input: z.ZodOptional<z.ZodNumber>;
|
|
9
|
+
output: z.ZodOptional<z.ZodNumber>;
|
|
10
|
+
reasoning: z.ZodOptional<z.ZodNumber>;
|
|
11
|
+
cache: z.ZodOptional<z.ZodObject<{
|
|
12
|
+
read: z.ZodOptional<z.ZodNumber>;
|
|
13
|
+
}, z.core.$strip>>;
|
|
14
|
+
}, z.core.$strip>>;
|
|
15
|
+
error: z.ZodOptional<z.ZodObject<{
|
|
16
|
+
name: z.ZodOptional<z.ZodString>;
|
|
17
|
+
data: z.ZodOptional<z.ZodObject<{
|
|
18
|
+
message: z.ZodOptional<z.ZodString>;
|
|
19
|
+
statusCode: z.ZodOptional<z.ZodNumber>;
|
|
20
|
+
isRetryable: z.ZodOptional<z.ZodBoolean>;
|
|
21
|
+
}, z.core.$strip>>;
|
|
22
|
+
}, z.core.$strip>>;
|
|
23
|
+
}, z.core.$strip>;
|
|
24
|
+
parts: z.ZodArray<z.ZodObject<{
|
|
25
|
+
type: z.ZodString;
|
|
26
|
+
text: z.ZodOptional<z.ZodString>;
|
|
27
|
+
tool: z.ZodOptional<z.ZodString>;
|
|
28
|
+
state: z.ZodOptional<z.ZodObject<{
|
|
29
|
+
status: z.ZodOptional<z.ZodString>;
|
|
30
|
+
input: z.ZodOptional<z.ZodUnknown>;
|
|
31
|
+
}, z.core.$strip>>;
|
|
32
|
+
}, z.core.$strip>>;
|
|
33
|
+
}, z.core.$strip>;
|
|
34
|
+
export type SessionMessage = z.output<typeof sessionMessageSchema>;
|
|
35
|
+
export declare function parseSessionMessages(data: unknown): SessionMessage[];
|
|
34
36
|
export declare function summarizeSession(messages: readonly SessionMessage[], reportTool: string, toolPrefix?: string): AttemptOutcome;
|
|
35
37
|
export declare function sessionUsage(messages: readonly SessionMessage[]): Usage;
|
|
36
|
-
|
|
38
|
+
export {};
|
package/dist/session-outcome.js
CHANGED
|
@@ -1,4 +1,44 @@
|
|
|
1
|
-
import { parseQuotaError } from "@open-cr-agent/core
|
|
1
|
+
import { exploredBy, parseQuotaError } from "@open-cr-agent/core";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
// The part of OpenCode's session messages ocra reads, validated rather than
|
|
4
|
+
// cast: the SDK's types are not checked at runtime, and a server of another
|
|
5
|
+
// version could answer in another shape. Unknown fields are dropped.
|
|
6
|
+
const sessionMessageSchema = z.object({
|
|
7
|
+
info: z.object({
|
|
8
|
+
role: z.string(),
|
|
9
|
+
cost: z.number().optional(),
|
|
10
|
+
tokens: z
|
|
11
|
+
.object({
|
|
12
|
+
input: z.number().optional(),
|
|
13
|
+
output: z.number().optional(),
|
|
14
|
+
reasoning: z.number().optional(),
|
|
15
|
+
cache: z.object({ read: z.number().optional() }).optional(),
|
|
16
|
+
})
|
|
17
|
+
.optional(),
|
|
18
|
+
error: z
|
|
19
|
+
.object({
|
|
20
|
+
name: z.string().optional(),
|
|
21
|
+
data: z
|
|
22
|
+
.object({
|
|
23
|
+
message: z.string().optional(),
|
|
24
|
+
statusCode: z.number().optional(),
|
|
25
|
+
isRetryable: z.boolean().optional(),
|
|
26
|
+
})
|
|
27
|
+
.optional(),
|
|
28
|
+
})
|
|
29
|
+
.optional(),
|
|
30
|
+
}),
|
|
31
|
+
parts: z.array(z.object({
|
|
32
|
+
type: z.string(),
|
|
33
|
+
text: z.string().optional(),
|
|
34
|
+
tool: z.string().optional(),
|
|
35
|
+
state: z.object({ status: z.string().optional(), input: z.unknown().optional() }).optional(),
|
|
36
|
+
})),
|
|
37
|
+
});
|
|
38
|
+
// Throws when the answer is not a list of messages ocra can read.
|
|
39
|
+
export function parseSessionMessages(data) {
|
|
40
|
+
return z.array(sessionMessageSchema).parse(data ?? []);
|
|
41
|
+
}
|
|
2
42
|
const AUTH_STATUS = new Set([401, 403]);
|
|
3
43
|
const AUTH_MESSAGE = /api key|unauthori[sz]ed|permission denied|forbidden/i;
|
|
4
44
|
// Tool names come back with the MCP server's prefix (MCP_SERVER in
|
|
@@ -6,12 +46,17 @@ const AUTH_MESSAGE = /api key|unauthori[sz]ed|permission denied|forbidden/i;
|
|
|
6
46
|
export function summarizeSession(messages, reportTool, toolPrefix = "") {
|
|
7
47
|
const assistant = messages.filter((m) => m.info.role === "assistant");
|
|
8
48
|
const tools = assistant.flatMap((m) => m.parts.filter((p) => p.type === "tool"));
|
|
49
|
+
const names = tools.map((p) => (p.tool ?? "unknown").replace(toolPrefix, ""));
|
|
9
50
|
const outcome = {
|
|
10
51
|
findings: tools
|
|
11
52
|
.filter((p) => p.tool === reportTool && p.state?.status === "completed")
|
|
12
53
|
.map((p) => p.state?.input),
|
|
13
54
|
steps: assistant.reduce((n, m) => n + m.parts.filter((p) => p.type === "step-start").length, 0),
|
|
14
|
-
toolCalls:
|
|
55
|
+
toolCalls: names,
|
|
56
|
+
// A call that did not complete never showed the reviewer anything.
|
|
57
|
+
...exploredBy(tools.flatMap((p, i) => p.state?.status === "completed"
|
|
58
|
+
? [{ name: names[i] ?? "unknown", input: p.state.input }]
|
|
59
|
+
: [])),
|
|
15
60
|
text: assistant
|
|
16
61
|
.flatMap((m) => m.parts.filter((p) => p.type === "text").map((p) => p.text ?? ""))
|
|
17
62
|
.join("\n")
|
|
@@ -52,4 +97,3 @@ function isAuthError(error) {
|
|
|
52
97
|
function sum(messages, pick) {
|
|
53
98
|
return messages.reduce((total, m) => total + (pick(m) ?? 0), 0);
|
|
54
99
|
}
|
|
55
|
-
//# sourceMappingURL=session-outcome.js.map
|
package/dist/session-prompt.d.ts
CHANGED
|
@@ -1,10 +1,5 @@
|
|
|
1
|
-
import { type Usage } from "@open-cr-agent/core";
|
|
2
|
-
import { type AttemptOutcome } from "@open-cr-agent/core/internal";
|
|
1
|
+
import { type AttemptOutcome, type Usage } from "@open-cr-agent/core";
|
|
3
2
|
import type { OpencodeClient } from "@opencode-ai/sdk/v2";
|
|
4
|
-
import { type SessionMessage } from "./session-outcome.js";
|
|
5
|
-
export declare const HARVEST_TIMEOUT_MS = 5000;
|
|
6
|
-
export declare const INACTIVITY_MS: number;
|
|
7
|
-
export declare const ACTIVITY_POLL_MS = 10000;
|
|
8
3
|
export interface ActivityOptions {
|
|
9
4
|
inactivityMs?: number;
|
|
10
5
|
pollMs?: number;
|
|
@@ -14,21 +9,18 @@ export interface PromptInput {
|
|
|
14
9
|
title: string;
|
|
15
10
|
agent: string;
|
|
16
11
|
model: string;
|
|
12
|
+
variant?: string;
|
|
17
13
|
system: string;
|
|
18
14
|
user: string;
|
|
19
15
|
tools: Record<string, boolean>;
|
|
20
16
|
toolPrefix?: string;
|
|
21
17
|
resume?: ResumeOptions;
|
|
22
18
|
}
|
|
23
|
-
|
|
19
|
+
interface ResumeOptions {
|
|
24
20
|
doneTool: string;
|
|
25
21
|
maxSteps: number;
|
|
26
22
|
message: string;
|
|
27
23
|
}
|
|
28
|
-
export declare function stoppedEarly(outcome: AttemptOutcome, resume: ResumeOptions): boolean;
|
|
29
24
|
type SessionApi = Pick<OpencodeClient["session"], "create" | "prompt" | "messages" | "abort">;
|
|
30
25
|
export declare function promptSession(session: SessionApi, input: PromptInput, reportTool: string, signal: AbortSignal, activity?: ActivityOptions): Promise<AttemptOutcome>;
|
|
31
|
-
export declare function activitySignature(messages: readonly SessionMessage[]): string;
|
|
32
|
-
export declare function emptyOutcome(): AttemptOutcome;
|
|
33
26
|
export {};
|
|
34
|
-
//# sourceMappingURL=session-prompt.d.ts.map
|