@open-cr-agent/runtime-opencode 0.6.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/README.md CHANGED
@@ -1,3 +1,3 @@
1
1
  # @open-cr-agent/runtime-opencode
2
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://ocracloud.com). All `@open-cr-agent` packages are released together at one version. Apache-2.0.
3
+ The [OpenCode](https://opencode.ai) agent runtime 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) (the `ocra` command) and the [manual](https://ocracloud.com). All packages share one version. Apache-2.0.
package/dist/binary.d.ts CHANGED
@@ -8,4 +8,3 @@ export interface Host {
8
8
  export declare function resolveOpencodeBinary(env: Env, opencodePackage?: string): string;
9
9
  export declare function isNativeExecutable(path: string): boolean;
10
10
  export declare function binaryVariants(host: Host): string[];
11
- //# sourceMappingURL=binary.d.ts.map
package/dist/binary.js CHANGED
@@ -100,4 +100,3 @@ function lacksAvx2(platform) {
100
100
  catch { }
101
101
  return false;
102
102
  }
103
- //# sourceMappingURL=binary.js.map
@@ -1,4 +1,4 @@
1
- import type { CustomProvider } from "@open-cr-agent/core";
1
+ import { type CustomProvider } from "@open-cr-agent/core";
2
2
  import type { OpencodeClient } from "@opencode-ai/sdk/v2";
3
3
  import { EffortRoutes } from "./effort.js";
4
4
  type ConfigApi = Pick<OpencodeClient["config"], "providers">;
@@ -8,7 +8,7 @@ export interface EffortSetup {
8
8
  probe: ConfigApi;
9
9
  workspace: ConfigApi;
10
10
  file: string;
11
+ secrets?: readonly string[];
11
12
  }
12
13
  export declare function setUpEfforts(setup: EffortSetup): Promise<EffortRoutes>;
13
14
  export {};
14
- //# sourceMappingURL=effort-setup.d.ts.map
@@ -1,11 +1,12 @@
1
1
  import { writeFile } from "node:fs/promises";
2
+ import { errorMessage, withoutSecrets } from "@open-cr-agent/core";
2
3
  import { EffortRoutes } from "./effort.js";
3
4
  const CATALOG_TIMEOUT_MS = 30_000;
4
5
  // The variants derive thinking budgets from the models' output limits,
5
6
  // which only OpenCode's catalog knows, and the catalog is loaded only once
6
7
  // OpenCode runs: the variants are written after it started and before the
7
8
  // workspace is first used. Any failure leaves effort unsent, with a warning
8
- // per agent, and never fails the review.
9
+ // per agent that gives the cause, and never fails the review.
9
10
  export async function setUpEfforts(setup) {
10
11
  const { models, custom = {} } = setup;
11
12
  const everyModel = new Map(models.map((m) => [m, 0]));
@@ -23,8 +24,8 @@ export async function setUpEfforts(setup) {
23
24
  routes.keepLoaded(new Map([...loaded].map(([model, entry]) => [model, entry.variants])));
24
25
  return routes;
25
26
  }
26
- catch {
27
- return new EffortRoutes([]);
27
+ catch (error) {
28
+ return EffortRoutes.unavailable(`OpenCode's model catalog could not be read (${withoutSecrets(errorMessage(error), setup.secrets ?? [])})`);
28
29
  }
29
30
  }
30
31
  async function catalogModels(config) {
@@ -40,4 +41,3 @@ async function catalogModels(config) {
40
41
  }
41
42
  return models;
42
43
  }
43
- //# sourceMappingURL=effort-setup.js.map
package/dist/effort.d.ts CHANGED
@@ -3,6 +3,9 @@ type Options = Record<string, unknown>;
3
3
  export declare function effortOptions(model: string, level: Effort, custom?: Readonly<Record<string, CustomProvider>>, outputLimit?: number): Options | undefined;
4
4
  export declare class EffortRoutes {
5
5
  private readonly routes;
6
+ unsentBecause?: string;
7
+ /** No routes at all, and why. */
8
+ static unavailable(reason: string): EffortRoutes;
6
9
  constructor(models: readonly string[], custom?: Readonly<Record<string, CustomProvider>>, known?: ReadonlyMap<string, number>);
7
10
  get empty(): boolean;
8
11
  providerConfig(): Record<string, {
@@ -19,9 +22,8 @@ export declare class AppliedEfforts {
19
22
  private readonly applied;
20
23
  private readonly sampling;
21
24
  constructor(sampling?: Sampling);
22
- record(agent: string, effort: Effort, model: string, sent: boolean): boolean;
25
+ record(agent: string, effort: Effort, model: string, sent: boolean, unsentBecause?: string): boolean;
23
26
  appliedTo(agent: string): AppliedSettings | undefined;
24
27
  private requested;
25
28
  }
26
29
  export {};
27
- //# sourceMappingURL=effort.d.ts.map
package/dist/effort.js CHANGED
@@ -59,6 +59,14 @@ export function effortOptions(model, level, custom = {}, outputLimit) {
59
59
  // accept it at a price of 0.
60
60
  export class EffortRoutes {
61
61
  routes = new Map();
62
+ // Why no level can be sent to any model, when the routes could not be set up.
63
+ unsentBecause;
64
+ /** No routes at all, and why. */
65
+ static unavailable(reason) {
66
+ const routes = new EffortRoutes([]);
67
+ routes.unsentBecause = reason;
68
+ return routes;
69
+ }
62
70
  constructor(models, custom = {},
63
71
  // Output limits by model, from OpenCode's catalog; 0 when it has none.
64
72
  known = new Map()) {
@@ -123,17 +131,23 @@ export class AppliedEfforts {
123
131
  constructor(sampling = {}) {
124
132
  this.sampling = sampling;
125
133
  }
126
- // Whether the call keeps the configured sampling.
127
- record(agent, effort, model, sent) {
134
+ // Whether the call keeps the configured sampling. `unsentBecause`: why
135
+ // the level could not be sent, when it is not the capability table.
136
+ record(agent, effort, model, sent, unsentBecause) {
128
137
  const keepsSampling = effort === "none";
129
138
  const before = this.applied.get(agent);
130
139
  const notApplied = [
131
140
  ...new Set([...(before?.notApplied ?? []), ...(keepsSampling ? [] : this.requested())]),
132
141
  ];
133
- const unsupported = [...new Set([...(before?.unsupported ?? []), ...(sent ? [] : [model])])];
142
+ const tableSays = !sent && unsentBecause === undefined;
143
+ const unsupported = [
144
+ ...new Set([...(before?.unsupported ?? []), ...(tableSays ? [model] : [])]),
145
+ ];
146
+ const because = before?.unsentBecause ?? (sent ? undefined : unsentBecause);
134
147
  this.applied.set(agent, {
135
148
  effort: (before?.effort ?? true) && sent,
136
149
  ...(unsupported.length > 0 ? { unsupported } : {}),
150
+ ...(because !== undefined ? { unsentBecause: because } : {}),
137
151
  ...(notApplied.length > 0 ? { notApplied } : {}),
138
152
  });
139
153
  return keepsSampling;
@@ -146,4 +160,3 @@ export class AppliedEfforts {
146
160
  return ["temperature", "seed"].filter((key) => this.sampling[key] !== undefined);
147
161
  }
148
162
  }
149
- //# sourceMappingURL=effort.js.map
package/dist/index.d.ts CHANGED
@@ -1,2 +1 @@
1
1
  export { opencodeRuntimePlugin } from "./plugin.js";
2
- //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,2 +1 @@
1
1
  export { opencodeRuntimePlugin } from "./plugin.js";
2
- //# sourceMappingURL=index.js.map
@@ -3,12 +3,14 @@ import type { ToolServer } from "./tool-server.js";
3
3
  export declare const MCP_SERVER = "ocra";
4
4
  export declare const REVIEW_AGENT = "ocra-reviewer";
5
5
  export declare const HELPER_AGENT = "ocra-helper";
6
+ export declare const WRAP_UP_AGENT = "ocra-wrap-up";
6
7
  export declare const WITHOUT_SAMPLING = "-effort";
7
8
  export declare const HELPER_AGENT_STEPS = 2;
8
9
  export declare const OPENCODE_BUILTIN_TOOLS: readonly ["invalid", "question", "bash", "read", "glob", "grep", "edit", "write", "task", "webfetch", "todowrite", "websearch", "skill", "apply_patch"];
9
10
  export declare const DISABLED_BUILTINS: {
10
11
  [k: string]: boolean;
11
12
  };
13
+ export declare function wrapUpTools(helperTools: Record<string, boolean>): Record<string, boolean>;
12
14
  export declare function openCodeSampling(sampling?: Sampling): AppliedSampling;
13
15
  export declare function openCodeConfig(tools: Pick<ToolServer, "url" | "headers">, helperTools: Record<string, boolean>, custom?: Readonly<Record<string, CustomProvider>>, sampling?: Sampling): {
14
16
  share: string;
@@ -68,6 +70,17 @@ export declare function openCodeConfig(tools: Pick<ToolServer, "url" | "headers"
68
70
  webfetch: string;
69
71
  skill: string;
70
72
  };
73
+ } | {
74
+ mode: string;
75
+ prompt: string;
76
+ steps: number;
77
+ tools: Record<string, boolean>;
78
+ permission: {
79
+ edit: string;
80
+ bash: string;
81
+ webfetch: string;
82
+ skill: string;
83
+ };
71
84
  };
72
85
  } | {
73
86
  "ocra-reviewer": {
@@ -96,6 +109,17 @@ export declare function openCodeConfig(tools: Pick<ToolServer, "url" | "headers"
96
109
  skill: string;
97
110
  };
98
111
  };
112
+ "ocra-wrap-up": {
113
+ mode: string;
114
+ prompt: string;
115
+ steps: number;
116
+ tools: Record<string, boolean>;
117
+ permission: {
118
+ edit: string;
119
+ bash: string;
120
+ webfetch: string;
121
+ skill: string;
122
+ };
123
+ };
99
124
  };
100
125
  };
101
- //# sourceMappingURL=opencode-config.d.ts.map
@@ -1,7 +1,10 @@
1
- import { MAX_AGENT_STEPS, OcraError, } from "@open-cr-agent/core";
1
+ import { MAX_AGENT_STEPS, OcraError, WRAP_UP_STEPS, WRAP_UP_TOOLS, } from "@open-cr-agent/core";
2
2
  export const MCP_SERVER = "ocra";
3
3
  export const REVIEW_AGENT = "ocra-reviewer";
4
4
  export const HELPER_AGENT = "ocra-helper";
5
+ // A review's wrap-up turn (WRAP_UP_MESSAGE): its own agent, since OpenCode
6
+ // caps steps per agent, not per prompt.
7
+ export const WRAP_UP_AGENT = "ocra-wrap-up";
5
8
  // The same agents without the configured temperature, for calls that send
6
9
  // an effort (ADR-0025): OpenCode sets sampling per agent.
7
10
  export const WITHOUT_SAMPLING = "-effort";
@@ -31,6 +34,13 @@ export const OPENCODE_BUILTIN_TOOLS = [
31
34
  "apply_patch",
32
35
  ];
33
36
  export const DISABLED_BUILTINS = Object.fromEntries(OPENCODE_BUILTIN_TOOLS.map((t) => [t, false]));
37
+ // The helper's tools (every one off) with only the reporting tools on.
38
+ export function wrapUpTools(helperTools) {
39
+ return {
40
+ ...helperTools,
41
+ ...Object.fromEntries(WRAP_UP_TOOLS.map((t) => [`${MCP_SERVER}_${t}`, true])),
42
+ };
43
+ }
34
44
  // OpenCode 1.18.32 takes a temperature per agent and sends it when the
35
45
  // model's catalog entry says the model accepts one; a model declared in
36
46
  // configuration is marked so (providerConfig). It has no seed setting: the
@@ -59,6 +69,13 @@ export function openCodeConfig(tools, helperTools, custom = {}, sampling = {}) {
59
69
  tools: helperTools,
60
70
  permission,
61
71
  },
72
+ [WRAP_UP_AGENT]: {
73
+ mode: "primary",
74
+ prompt: REVIEW_AGENT_PROMPT,
75
+ steps: WRAP_UP_STEPS,
76
+ tools: wrapUpTools(helperTools),
77
+ permission,
78
+ },
62
79
  };
63
80
  return {
64
81
  share: "disabled",
@@ -134,4 +151,3 @@ function checkProvider(id, provider) {
134
151
  throw new OcraError("CONFIG_INVALID", `Provider "${id}": apiKeyEnv must be an environment variable name`);
135
152
  }
136
153
  }
137
- //# sourceMappingURL=opencode-config.js.map
@@ -12,4 +12,3 @@ export interface StartOptions {
12
12
  startupTimeoutMs?: number;
13
13
  }
14
14
  export declare function startOpencodeServer(options: StartOptions): Promise<OpencodeServer>;
15
- //# sourceMappingURL=opencode-server.d.ts.map
@@ -83,4 +83,3 @@ function freePort() {
83
83
  });
84
84
  });
85
85
  }
86
- //# sourceMappingURL=opencode-server.js.map
package/dist/plugin.d.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  import type { OcraPlugin } from "@open-cr-agent/core";
2
2
  export declare const opencodeRuntimePlugin: OcraPlugin;
3
- //# sourceMappingURL=plugin.d.ts.map
package/dist/plugin.js CHANGED
@@ -5,4 +5,3 @@ export const opencodeRuntimePlugin = {
5
5
  ctx.registerRuntime("opencode", (options) => new OpenCodeRuntime(options));
6
6
  },
7
7
  };
8
- //# sourceMappingURL=plugin.js.map
package/dist/runtime.d.ts CHANGED
@@ -25,4 +25,3 @@ export declare class OpenCodeRuntime implements AgentRuntime {
25
25
  private launch;
26
26
  }
27
27
  export declare function providersOf(options: Pick<RuntimeOptions, "models" | "agentModels">): string[];
28
- //# sourceMappingURL=runtime.d.ts.map
package/dist/runtime.js CHANGED
@@ -2,12 +2,12 @@ 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 { ChainRunner, MAX_AGENT_STEPS, OcraError, parseModel, RESUME_MESSAGE, REVIEW_TOOLS, reviewTools, withoutSecrets, } from "@open-cr-agent/core";
5
+ import { ChainRunner, MAX_AGENT_STEPS, OcraError, parseModel, RESUME_MESSAGE, REVIEW_TOOLS, reviewTools, WRAP_UP_MESSAGE, withoutSecrets, } from "@open-cr-agent/core";
6
6
  import { createOpencodeClient } from "@opencode-ai/sdk/v2";
7
7
  import { resolveOpencodeBinary } from "./binary.js";
8
8
  import { AppliedEfforts } from "./effort.js";
9
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";
10
+ import { DISABLED_BUILTINS, HELPER_AGENT, MCP_SERVER, openCodeConfig, openCodeSampling, REVIEW_AGENT, WITHOUT_SAMPLING, WRAP_UP_AGENT, wrapUpTools, } from "./opencode-config.js";
11
11
  import { startOpencodeServer } from "./opencode-server.js";
12
12
  import { credentialValues, missingCredentials, serverEnv } from "./server-env.js";
13
13
  import { promptSession } from "./session-prompt.js";
@@ -79,6 +79,11 @@ export class OpenCodeRuntime {
79
79
  tools: DISABLED_BUILTINS,
80
80
  toolPrefix: `${MCP_SERVER}_`,
81
81
  resume: REVIEW_RESUME,
82
+ wrapUp: {
83
+ ...this.effortCall(infra, WRAP_UP_AGENT, spec.reviewer, spec.effort, model),
84
+ tools: wrapUpTools(this.helperTools),
85
+ message: WRAP_UP_MESSAGE,
86
+ },
82
87
  }, signal, onUsage);
83
88
  }
84
89
  async attemptCompletion(model, request, signal) {
@@ -99,7 +104,7 @@ export class OpenCodeRuntime {
99
104
  if (effort === undefined)
100
105
  return { agent: base };
101
106
  const route = infra.efforts.route(model, effort);
102
- const keepsSampling = this.applied.record(agent, effort, model, route !== undefined);
107
+ const keepsSampling = this.applied.record(agent, effort, model, route !== undefined, infra.efforts.unsentBecause);
103
108
  return {
104
109
  agent: keepsSampling || this.options.sampling?.temperature === undefined
105
110
  ? base
@@ -107,8 +112,9 @@ export class OpenCodeRuntime {
107
112
  ...(route?.variant ? { variant: route.variant } : {}),
108
113
  };
109
114
  }
110
- prompt(infra, input, signal, onUsage) {
111
- return promptSession(infra.client.session, input, `${MCP_SERVER}_${REVIEW_TOOLS.reportFinding}`, signal, onUsage ? { onUsage } : {}).then((outcome) => outcome.error
115
+ async prompt(infra, input, signal, onUsage) {
116
+ const attempt = await promptSession(infra.client.session, input, `${MCP_SERVER}_${REVIEW_TOOLS.reportFinding}`, signal, onUsage ? { onUsage } : {});
117
+ const redacted = (outcome) => outcome.error
112
118
  ? {
113
119
  ...outcome,
114
120
  error: {
@@ -116,7 +122,12 @@ export class OpenCodeRuntime {
116
122
  message: withoutSecrets(outcome.error.message, infra.secrets),
117
123
  },
118
124
  }
119
- : outcome);
125
+ : outcome;
126
+ const { wrapUp } = attempt;
127
+ return {
128
+ ...redacted(attempt),
129
+ ...(wrapUp ? { wrapUp: async () => redacted(await wrapUp()) } : {}),
130
+ };
120
131
  }
121
132
  // The server holds the credentials of the providers it started with; an
122
133
  // agent's own chain naming another would fail at OpenCode as "model not
@@ -173,14 +184,15 @@ export class OpenCodeRuntime {
173
184
  rmSync(root, { recursive: true, force: true });
174
185
  };
175
186
  process.on("exit", onExit);
187
+ const secrets = credentialValues(this.options.env, providersOf(this.options), custom);
176
188
  const efforts = await setUpEfforts({
177
189
  models: chainModels(this.options),
178
190
  custom,
179
191
  probe: clientFor(probe).config,
180
192
  workspace: client.config,
181
193
  file: join(dirs.config, "opencode.json"),
194
+ secrets,
182
195
  });
183
- const secrets = credentialValues(this.options.env, providersOf(this.options), custom);
184
196
  return { root, tools, server, client, efforts, dispatcher, onExit, secrets };
185
197
  }
186
198
  catch (error) {
@@ -199,4 +211,3 @@ function chainModels(options) {
199
211
  export function providersOf(options) {
200
212
  return chainModels(options).map((m) => parseModel(m).providerID);
201
213
  }
202
- //# sourceMappingURL=runtime.js.map
@@ -9,4 +9,3 @@ export declare function missingCredentials(base: Env, providers: readonly string
9
9
  export declare function credentialValues(base: Env, providers: readonly string[], custom?: CustomProviders): string[];
10
10
  export declare function serverEnv(base: Env, dirs: IsolatedDirs, providers: readonly string[], custom?: CustomProviders): Record<string, string>;
11
11
  export {};
12
- //# sourceMappingURL=server-env.d.ts.map
@@ -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
@@ -32,8 +32,11 @@ declare const sessionMessageSchema: z.ZodObject<{
32
32
  }, z.core.$strip>>;
33
33
  }, z.core.$strip>;
34
34
  export type SessionMessage = z.output<typeof sessionMessageSchema>;
35
- export declare function parseSessionMessages(data: unknown): SessionMessage[];
35
+ export declare function parseSessionMessages(data: unknown): {
36
+ messages: SessionMessage[];
37
+ unread: number;
38
+ };
39
+ export declare function readSession(data: unknown, reportTool: string, toolPrefix?: string): AttemptOutcome;
36
40
  export declare function summarizeSession(messages: readonly SessionMessage[], reportTool: string, toolPrefix?: string): AttemptOutcome;
37
41
  export declare function sessionUsage(messages: readonly SessionMessage[]): Usage;
38
42
  export {};
39
- //# sourceMappingURL=session-outcome.d.ts.map
@@ -1,4 +1,4 @@
1
- import { parseQuotaError } from "@open-cr-agent/core";
1
+ import { exploredBy, parseQuotaError } from "@open-cr-agent/core";
2
2
  import { z } from "zod";
3
3
  // The part of OpenCode's session messages ocra reads, validated rather than
4
4
  // cast: the SDK's types are not checked at runtime, and a server of another
@@ -35,9 +35,27 @@ const sessionMessageSchema = z.object({
35
35
  state: z.object({ status: z.string().optional(), input: z.unknown().optional() }).optional(),
36
36
  })),
37
37
  });
38
- // Throws when the answer is not a list of messages ocra can read.
38
+ // The messages ocra can read, and how many it could not: one message in an
39
+ // unexpected shape must not cost the attempt its findings and usage. Throws
40
+ // when the answer is not a list.
39
41
  export function parseSessionMessages(data) {
40
- return z.array(sessionMessageSchema).parse(data ?? []);
42
+ const messages = [];
43
+ let unread = 0;
44
+ for (const raw of z.array(z.unknown()).parse(data ?? [])) {
45
+ const parsed = sessionMessageSchema.safeParse(raw);
46
+ if (parsed.success)
47
+ messages.push(parsed.data);
48
+ else
49
+ unread += 1;
50
+ }
51
+ return { messages, unread };
52
+ }
53
+ // The attempt as the session's messages tell it, with the count of those
54
+ // that could not be read.
55
+ export function readSession(data, reportTool, toolPrefix = "") {
56
+ const { messages, unread } = parseSessionMessages(data);
57
+ const outcome = summarizeSession(messages, reportTool, toolPrefix);
58
+ return unread > 0 ? { ...outcome, unreadMessages: unread } : outcome;
41
59
  }
42
60
  const AUTH_STATUS = new Set([401, 403]);
43
61
  const AUTH_MESSAGE = /api key|unauthori[sz]ed|permission denied|forbidden/i;
@@ -46,12 +64,17 @@ const AUTH_MESSAGE = /api key|unauthori[sz]ed|permission denied|forbidden/i;
46
64
  export function summarizeSession(messages, reportTool, toolPrefix = "") {
47
65
  const assistant = messages.filter((m) => m.info.role === "assistant");
48
66
  const tools = assistant.flatMap((m) => m.parts.filter((p) => p.type === "tool"));
67
+ const names = tools.map((p) => (p.tool ?? "unknown").replace(toolPrefix, ""));
49
68
  const outcome = {
50
69
  findings: tools
51
70
  .filter((p) => p.tool === reportTool && p.state?.status === "completed")
52
71
  .map((p) => p.state?.input),
53
72
  steps: assistant.reduce((n, m) => n + m.parts.filter((p) => p.type === "step-start").length, 0),
54
- toolCalls: tools.map((p) => (p.tool ?? "unknown").replace(toolPrefix, "")),
73
+ toolCalls: names,
74
+ // A call that did not complete never showed the reviewer anything.
75
+ ...exploredBy(tools.flatMap((p, i) => p.state?.status === "completed"
76
+ ? [{ name: names[i] ?? "unknown", input: p.state.input }]
77
+ : [])),
55
78
  text: assistant
56
79
  .flatMap((m) => m.parts.filter((p) => p.type === "text").map((p) => p.text ?? ""))
57
80
  .join("\n")
@@ -92,4 +115,3 @@ function isAuthError(error) {
92
115
  function sum(messages, pick) {
93
116
  return messages.reduce((total, m) => total + (pick(m) ?? 0), 0);
94
117
  }
95
- //# sourceMappingURL=session-outcome.js.map
@@ -1,4 +1,4 @@
1
- import { type AttemptOutcome, type Usage } from "@open-cr-agent/core";
1
+ import { type TaskAttempt, type Usage } from "@open-cr-agent/core";
2
2
  import type { OpencodeClient } from "@opencode-ai/sdk/v2";
3
3
  export interface ActivityOptions {
4
4
  inactivityMs?: number;
@@ -15,13 +15,19 @@ export interface PromptInput {
15
15
  tools: Record<string, boolean>;
16
16
  toolPrefix?: string;
17
17
  resume?: ResumeOptions;
18
+ wrapUp?: Turn;
18
19
  }
19
20
  interface ResumeOptions {
20
21
  doneTool: string;
21
22
  maxSteps: number;
22
23
  message: string;
23
24
  }
25
+ interface Turn {
26
+ agent: string;
27
+ variant?: string;
28
+ tools: Record<string, boolean>;
29
+ message: string;
30
+ }
24
31
  type SessionApi = Pick<OpencodeClient["session"], "create" | "prompt" | "messages" | "abort">;
25
- export declare function promptSession(session: SessionApi, input: PromptInput, reportTool: string, signal: AbortSignal, activity?: ActivityOptions): Promise<AttemptOutcome>;
32
+ export declare function promptSession(session: SessionApi, input: PromptInput, reportTool: string, signal: AbortSignal, activity?: ActivityOptions): Promise<TaskAttempt>;
26
33
  export {};
27
- //# sourceMappingURL=session-prompt.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { emptyUsage, errorMessage, OcraError, parseModel, } from "@open-cr-agent/core";
2
- import { parseSessionMessages, sessionUsage, summarizeSession, } from "./session-outcome.js";
2
+ import { parseSessionMessages, readSession, sessionUsage, } from "./session-outcome.js";
3
3
  // A session that was cut off has still spent tokens and may have reported
4
4
  // findings; this bounds the one extra request that collects them.
5
5
  const HARVEST_TIMEOUT_MS = 5_000;
@@ -22,25 +22,73 @@ function stoppedEarly(outcome, resume) {
22
22
  outcome.steps < resume.maxSteps &&
23
23
  outcome.text.trim() === "");
24
24
  }
25
+ // OpenCode caps each prompt's steps, so the cap ended an attempt when its
26
+ // last turn alone used them all.
27
+ function capped(outcome, lastTurnSteps, resume) {
28
+ const atCap = !outcome.error &&
29
+ !outcome.toolCalls.includes(resume.doneTool) &&
30
+ lastTurnSteps >= resume.maxSteps;
31
+ return atCap ? { ...outcome, atStepCap: true } : outcome;
32
+ }
25
33
  export async function promptSession(session, input, reportTool, signal, activity = {}) {
26
34
  const created = await session.create({ title: input.title }, { signal });
27
35
  if (!created.data) {
28
36
  throw new OcraError("RUNTIME_FAILED", `OpenCode could not create a session: ${JSON.stringify(created.error)}`);
29
37
  }
30
- const sessionID = created.data.id;
38
+ const opened = {
39
+ session,
40
+ sessionID: created.data.id,
41
+ input,
42
+ reportTool,
43
+ signal,
44
+ activity,
45
+ };
46
+ const turn = (t) => runTurn(opened, t);
47
+ const review = {
48
+ agent: input.agent,
49
+ ...(input.variant ? { variant: input.variant } : {}),
50
+ tools: input.tools,
51
+ };
52
+ let outcome = await turn({ ...review, message: input.user });
53
+ let lastTurnFrom = 0;
54
+ if (!outcome.error && input.resume && stoppedEarly(outcome, input.resume)) {
55
+ lastTurnFrom = outcome.steps;
56
+ // Both turns are in the session: their findings and their spend.
57
+ outcome = { ...(await turn({ ...review, message: input.resume.message })), resumed: true };
58
+ }
59
+ if (input.resume)
60
+ outcome = capped(outcome, outcome.steps - lastTurnFrom, input.resume);
61
+ const { wrapUp } = input;
62
+ if (!wrapUp)
63
+ return outcome;
64
+ const resumed = outcome.resumed;
65
+ return {
66
+ ...outcome,
67
+ wrapUp: async () => ({ ...(await turn(wrapUp)), ...(resumed ? { resumed } : {}) }),
68
+ };
69
+ }
70
+ // Sends one turn and returns what the whole session has come to, every
71
+ // earlier turn included.
72
+ async function runTurn({ session, sessionID, input, reportTool, signal, activity }, turn) {
31
73
  const stop = () => void session.abort({ sessionID }).catch(() => { });
74
+ if (signal.aborted) {
75
+ return {
76
+ ...(await harvest(session, sessionID, reportTool, input.toolPrefix)),
77
+ error: { message: "cancelled", retryable: false },
78
+ };
79
+ }
32
80
  signal.addEventListener("abort", stop, { once: true });
33
81
  const silence = watchActivity(session, sessionID, activity);
34
82
  const attempt = AbortSignal.any([signal, silence.signal]);
35
83
  try {
36
84
  const response = await session.prompt({
37
85
  sessionID,
38
- agent: input.agent,
86
+ agent: turn.agent,
39
87
  model: parseModel(input.model),
40
- ...(input.variant ? { variant: input.variant } : {}),
88
+ ...(turn.variant ? { variant: turn.variant } : {}),
41
89
  system: input.system,
42
- tools: input.tools,
43
- parts: [{ type: "text", text: input.user }],
90
+ tools: turn.tools,
91
+ parts: [{ type: "text", text: turn.message }],
44
92
  }, { signal: attempt });
45
93
  // The session ran even when the answer is an error, and it may have
46
94
  // spent tokens and reported findings: keep them.
@@ -50,10 +98,9 @@ export async function promptSession(session, input, reportTool, signal, activity
50
98
  error: { message: JSON.stringify(response.error), retryable: false },
51
99
  };
52
100
  }
53
- let outcome;
54
101
  try {
55
102
  const messages = await session.messages({ sessionID }, { signal: attempt });
56
- outcome = summarizeSession(parseSessionMessages(messages.data), reportTool, input.toolPrefix);
103
+ return readSession(messages.data, reportTool, input.toolPrefix);
57
104
  }
58
105
  catch (error) {
59
106
  // The session finished; running it again on the next model would pay
@@ -66,25 +113,6 @@ export async function promptSession(session, input, reportTool, signal, activity
66
113
  },
67
114
  };
68
115
  }
69
- if (!input.resume || !stoppedEarly(outcome, input.resume))
70
- return outcome;
71
- const again = await session.prompt({
72
- sessionID,
73
- agent: input.agent,
74
- model: parseModel(input.model),
75
- ...(input.variant ? { variant: input.variant } : {}),
76
- system: input.system,
77
- tools: input.tools,
78
- parts: [{ type: "text", text: input.resume.message }],
79
- }, { signal: attempt });
80
- // Both turns are in the session: their findings and their spend.
81
- const resumed = {
82
- ...(await harvest(session, sessionID, reportTool, input.toolPrefix)),
83
- resumed: true,
84
- };
85
- if (again.error)
86
- resumed.error = { message: JSON.stringify(again.error), retryable: false };
87
- return resumed;
88
116
  }
89
117
  catch (error) {
90
118
  // Aborted or cut off by the transport: OpenCode may still be running the
@@ -121,7 +149,7 @@ function watchActivity(session, sessionID, options) {
121
149
  polling = true;
122
150
  try {
123
151
  const messages = await session.messages({ sessionID }, { signal: AbortSignal.timeout(HARVEST_TIMEOUT_MS) });
124
- const list = parseSessionMessages(messages.data);
152
+ const list = parseSessionMessages(messages.data).messages;
125
153
  if (options.onUsage) {
126
154
  const spent = sessionUsage(list);
127
155
  if (spent.costUsd > reported.costUsd || spent.inputTokens > reported.inputTokens) {
@@ -157,7 +185,7 @@ function activitySignature(messages) {
157
185
  async function harvest(session, sessionID, reportTool, toolPrefix) {
158
186
  try {
159
187
  const messages = await session.messages({ sessionID }, { signal: AbortSignal.timeout(HARVEST_TIMEOUT_MS) });
160
- return summarizeSession(parseSessionMessages(messages.data), reportTool, toolPrefix);
188
+ return readSession(messages.data, reportTool, toolPrefix);
161
189
  }
162
190
  catch {
163
191
  return emptyOutcome();
@@ -166,4 +194,3 @@ async function harvest(session, sessionID, reportTool, toolPrefix) {
166
194
  function emptyOutcome() {
167
195
  return { findings: [], steps: 0, toolCalls: [], text: "", usage: emptyUsage() };
168
196
  }
169
- //# sourceMappingURL=session-prompt.js.map
@@ -5,4 +5,3 @@ export interface ToolServer {
5
5
  close(): Promise<void>;
6
6
  }
7
7
  export declare function startToolServer(tools: readonly ToolDefinition[], context: () => ReviewContext | undefined): Promise<ToolServer>;
8
- //# sourceMappingURL=tool-server.d.ts.map
@@ -60,4 +60,3 @@ function authorized(req, expected) {
60
60
  const actual = Buffer.from(req.headers.authorization ?? "");
61
61
  return actual.length === expected.length && timingSafeEqual(actual, expected);
62
62
  }
63
- //# sourceMappingURL=tool-server.js.map
@@ -1,4 +1,3 @@
1
1
  import { Agent, type Dispatcher } from "undici";
2
2
  export declare function createUntimedDispatcher(): Agent;
3
3
  export declare function untimedFetch(dispatcher: Dispatcher): typeof fetch;
4
- //# sourceMappingURL=transport.d.ts.map
package/dist/transport.js CHANGED
@@ -26,4 +26,3 @@ export function untimedFetch(dispatcher) {
26
26
  return response;
27
27
  };
28
28
  }
29
- //# sourceMappingURL=transport.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-cr-agent/runtime-opencode",
3
- "version": "0.6.0",
3
+ "version": "0.9.0",
4
4
  "description": "OpenCode-based agent runtime for Open-CR-Agent",
5
5
  "keywords": [
6
6
  "code-review",
@@ -33,12 +33,12 @@
33
33
  "!dist/**/*.map"
34
34
  ],
35
35
  "dependencies": {
36
- "@modelcontextprotocol/sdk": "^1.30.1",
37
- "@open-cr-agent/core": "0.6.0",
36
+ "@modelcontextprotocol/sdk": "^1.31.0",
37
+ "@open-cr-agent/core": "0.9.0",
38
38
  "@opencode-ai/sdk": "1.18.32",
39
39
  "opencode-ai": "1.18.32",
40
- "undici": "^8.11.2",
41
- "zod": "^4.6.5"
40
+ "undici": "^8.12.3",
41
+ "zod": "^4.6.6"
42
42
  },
43
43
  "publishConfig": {
44
44
  "access": "public"