@ligeti/step-opencode-v2 0.0.0-stage → 1.0.1

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,201 @@
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 2026 Viktor "Bika" Nagy
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.
package/README.md CHANGED
@@ -1,3 +1,96 @@
1
- # Temporary Holding Version
1
+ # @ligeti/step-opencode-v2
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Launches [OpenCode](https://opencode.ai/) **2.x** under herdr or a bare subprocess for a single
4
+ prompt, and collects its result, as the `opencode-v2.launch` resource step and the
5
+ `opencode-v2.collect-result` step. It runs opencode 2.x only.
6
+
7
+ Settings, attempt paths, the backend abstraction, `agentSpawnEnv`, `createCollectResult`,
8
+ `createReadTurnResult`, `CallEnv` and the `LaunchAgentOutput`/`AgentResult` schemas are the shared
9
+ code of `@ligeti/agent-runtime`; see [its README](../../packages/agent-runtime/README.md) for them.
10
+
11
+ ## What is specific to opencode 2.x
12
+
13
+ - **No named commands.** opencode 2.x `run` has no `--command`, so `opencode-v2.launch` has no
14
+ `command` input and `wrapper.sh` rejects `--command` as an unknown argument (exit 64).
15
+ `launchOpenCodeV2Agent`'s input schema rejects a `command`, so a workflow that still passes one
16
+ fails loudly instead of running its prompt without the command.
17
+ - **A private server per run.** `wrapper.sh` runs `opencode run --standalone`. Without it, 2.x
18
+ attaches to a shared background service that outlives the run and the attempt.
19
+ - **Stdin is `/dev/null`.** opencode 2.x appends piped input to the prompt, so `wrapper.sh` never
20
+ leaves it a stdin to read.
21
+ - **`model`** also accepts `provider/model#variant`.
22
+ - **Binary and version check.** The binary is `LIGETI_OPENCODE2_BIN`, not `LIGETI_OPENCODE_BIN`, so
23
+ the variable of another major version does not move it. Before running anything `wrapper.sh` calls
24
+ `opencode --version` (2.x prints `opencode v2.4.1`); any other major version, an unreadable version,
25
+ or a binary that cannot be executed fails the run at once with a message naming the installed
26
+ version, and opencode is not started.
27
+ - **Error events** carry `error: { type, message }`; `AgentResult.failureReason` is
28
+ `authentication_failed` once any of them has type `provider.auth`; a later error does not unset it.
29
+ The terminal reason is the message of the first error event.
30
+
31
+ ## Steps
32
+
33
+ - **`opencode-v2.launch`** (`launchOpenCodeV2Agent`, a resource step) -- reserves the attempt's
34
+ paths, writes the prompt file, and spawns `wrapper.sh` under the configured backend. Input:
35
+ `prompt`, `workdir`, `model`, `session`, `forkSession`, `beadsActor` and `env`, with the same
36
+ `LaunchAgentOutput` as in `@ligeti/agent-runtime`; there is no `command`. `retry.maxAttempts` is 1.
37
+ - **`opencode-v2.collect-result`** (`collectResult`) -- parses the attempt's `output.json` into an
38
+ `AgentResult`.
39
+ - **`opencode-v2.read-turn-result`** (`readTurnResult`) -- reads and validates the turn result file
40
+ the agent wrote.
41
+ - **`runOpenCodeV2(ctx, input)`** composes launch, `ctx.waitForCallback` and collect. `input` is
42
+ `{ prompt, workdir, model, timeoutSeconds, session?, forkSession?, beadsActor?, env? }`. A missing
43
+ callback yields a `"timed_out"` `AgentResult` rather than throwing. The caller declares
44
+ `launchOpenCodeV2Agent` and `collectResult` in its own `steps`.
45
+
46
+ ## Sessions
47
+
48
+ opencode 2.x `run --session <id>` appends to that session, creating it when it does not exist;
49
+ adding `--fork` forks onto a new id, which the run's events report.
50
+
51
+ - `session` alone resumes with `--session <id> --fork`. The new id is known only once the run
52
+ finishes, so `LaunchAgentOutput.sessionId` is `null` and `AgentResult.sessionId` is the id the turn
53
+ _ended_ on.
54
+ - `session` with `forkSession: false` passes `--no-fork` to `wrapper.sh`, which drops `--fork`: the
55
+ run appends to `session`, and `sessionId` is that id from spawn on. `forkSession: false` without
56
+ `session` is rejected, and `wrapper.sh` exits 64 on `--no-fork` without `--session`.
57
+
58
+ Two runs must never append to the same session concurrently. A retry's spawn that starts a second
59
+ opencode against the same session id, while the first is still up, has no defined outcome.
60
+
61
+ ## Prerequisites
62
+
63
+ - The `opencode` CLI, **version 2.x**, logged into a provider. opencode 2.x is distributed through
64
+ GitHub releases and Homebrew, not npm. Point `LIGETI_OPENCODE2_BIN` at it when it is not `opencode`
65
+ on `PATH`.
66
+ - For the default `LIGETI_AGENT_BACKEND=herdr` backend, the `herdr` CLI on `PATH`; set
67
+ `LIGETI_AGENT_BACKEND=subprocess` to run without it.
68
+ - An `opencode` exit of 137 with no structured error is reported as a SIGKILL; on macOS that is
69
+ commonly an invalid code signature on the binary, and `agent.log` has the details.
70
+
71
+ The prompt reaches opencode as a positional argument after a literal `--`; `wrapper.sh` refuses to
72
+ launch opencode with a prompt over 100 KB.
73
+
74
+ ## Environment variables
75
+
76
+ Read by `@ligeti/agent-runtime`'s `loadAgentSettings` in the worker process; see
77
+ [its README](../../packages/agent-runtime/README.md#environment-variables) for the full table. This
78
+ package uses:
79
+
80
+ | Variable | Required | Default | Purpose |
81
+ | -------------------------------------- | -------- | ---------- | -------------------------------------------------------------------------------- |
82
+ | `LIGETI_AGENT_BACKEND` | no | `herdr` | `herdr` or `subprocess` -- which backend spawns the agent. |
83
+ | `LIGETI_OPENCODE2_BIN` | no | `opencode` | The opencode 2.x binary `wrapper.sh` invokes. |
84
+ | `LIGETI_STATE_DIR` | no | `./var` | Where per-attempt metadata is written. |
85
+ | `LIGETI_HERDR_BIN` | no | `herdr` | The `herdr` binary, for the `herdr` backend. |
86
+ | `LIGETI_WRAPPER_CALLBACK_MAX_ATTEMPTS` | no | unset | Overrides `wrapper.sh`'s callback retry count (its own default is 30). |
87
+ | `LIGETI_WRAPPER_CALLBACK_RETRY_DELAY` | no | unset | Overrides `wrapper.sh`'s callback retry delay in seconds (its own default is 2). |
88
+
89
+ ## `wrapper.sh` and `collect.mjs`
90
+
91
+ `wrapper.sh <attempt_dir> --model <value> [--session <value> [--no-fork]]` runs
92
+ `opencode run --standalone --format json --model <value> [--session <value> [--fork]] -- <prompt>`
93
+ with stdin from `/dev/null`, captures the NDJSON stdout to `opencode-raw-output.json`, and
94
+ `collect.mjs` normalizes it into `output.json`, writes the `session-id` file and always delivers the
95
+ callback. `--model` is required
96
+ (`wrapper.sh` exits 68 without it).
package/collect.mjs ADDED
@@ -0,0 +1,234 @@
1
+ #!/usr/bin/env node
2
+ // ABOUTME: Normalizes opencode 2.x's `opencode run --format json` NDJSON stdout into the same output.json shape
3
+ // ABOUTME: that the shared collect-result of @ligeti/agent-runtime parses (result, cost, session id and an optional failure_reason).
4
+ import { readFile, writeFile, rename, stat, open } from "node:fs/promises";
5
+ import { realpathSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const RAW_FILE_MAX_BYTES = 10 * 1024 * 1024;
10
+ const RESULT_TEXT_MAX_CHARS = 900 * 1024;
11
+
12
+ const GENERIC_NO_OUTPUT_MESSAGE =
13
+ "opencode produced no parseable output (no text, no error, and no recognizable NDJSON lines)";
14
+
15
+ function errorEventMessage(error) {
16
+ if (typeof error?.message === "string" && error.message !== "") {
17
+ return error.message;
18
+ }
19
+ return typeof error?.type === "string"
20
+ ? error.type
21
+ : "opencode reported an error with no message";
22
+ }
23
+
24
+ function retryClause(retryMessage) {
25
+ return retryMessage === null ? "" : ` while retrying after: ${retryMessage}`;
26
+ }
27
+
28
+ export function parseOpencodeOutput(rawText, exitCode, failureMessage = "") {
29
+ const lines = rawText.split("\n").filter((line) => line.trim() !== "");
30
+
31
+ let resultText = "";
32
+ let sawTextEvent = false;
33
+ let textTruncated = false;
34
+ let costUsd = null;
35
+ let errorMessage = null;
36
+ let sawErrorEvent = false;
37
+ let sessionId = null;
38
+ let failureReason = null;
39
+ let lastRetryMessage = null;
40
+ let parsedAnyLine = false;
41
+
42
+ for (const line of lines) {
43
+ let event;
44
+ try {
45
+ event = JSON.parse(line);
46
+ } catch {
47
+ continue;
48
+ }
49
+ if (event === null || typeof event !== "object") {
50
+ continue;
51
+ }
52
+ parsedAnyLine = true;
53
+
54
+ if (typeof event.sessionID === "string" && event.sessionID !== "") {
55
+ sessionId = event.sessionID;
56
+ }
57
+
58
+ if (event.type === "text" && typeof event.part?.text === "string") {
59
+ sawTextEvent = true;
60
+ const remaining = RESULT_TEXT_MAX_CHARS - resultText.length;
61
+ if (event.part.text.length <= remaining) {
62
+ resultText += event.part.text;
63
+ } else {
64
+ resultText += event.part.text.slice(0, Math.max(0, remaining));
65
+ textTruncated = true;
66
+ }
67
+ } else if (event.type === "step_finish" && typeof event.part?.cost === "number") {
68
+ costUsd = (costUsd ?? 0) + event.part.cost;
69
+ } else if (event.type === "retry") {
70
+ lastRetryMessage = errorEventMessage(event.error);
71
+ } else if (event.type === "error") {
72
+ sawErrorEvent = true;
73
+ errorMessage ??= errorEventMessage(event.error);
74
+ if (event.error?.type === "provider.auth") {
75
+ failureReason = "authentication_failed";
76
+ }
77
+ }
78
+ }
79
+
80
+ if (textTruncated) {
81
+ resultText = `${resultText}\n...[truncated by collect.mjs, over ${String(RESULT_TEXT_MAX_CHARS)} chars]`;
82
+ }
83
+
84
+ const exitCodeNumber = Number(exitCode);
85
+ const exitCodeIsInvalid = exitCode === "" || Number.isNaN(exitCodeNumber);
86
+ const exitCodeIsNonZero = exitCodeIsInvalid || exitCodeNumber !== 0;
87
+ let isError = errorMessage !== null || exitCodeIsNonZero;
88
+
89
+ if (failureMessage !== "") {
90
+ isError = true;
91
+ errorMessage = failureMessage;
92
+ } else if (exitCodeIsInvalid && errorMessage === null) {
93
+ errorMessage = `collect.mjs received an invalid exit code argument: ${JSON.stringify(exitCode)}`;
94
+ } else if (exitCodeNumber === 137 && errorMessage === null) {
95
+ errorMessage = `opencode was killed by SIGKILL (exit 137)${retryClause(lastRetryMessage)}; on macOS this is commonly an invalid code signature on the opencode binary -- see agent.log`;
96
+ } else if (exitCodeIsNonZero && errorMessage === null) {
97
+ errorMessage =
98
+ lastRetryMessage === null
99
+ ? `opencode exited with code ${String(exitCodeNumber)} (no structured error or output was produced; see agent.log)`
100
+ : `opencode exited with code ${String(exitCodeNumber)}${retryClause(lastRetryMessage)} (no structured error was produced; see agent.log)`;
101
+ }
102
+
103
+ if (!parsedAnyLine && resultText === "" && !isError) {
104
+ isError = true;
105
+ errorMessage = GENERIC_NO_OUTPUT_MESSAGE;
106
+ }
107
+
108
+ if (!isError && !sawTextEvent && !sawErrorEvent) {
109
+ isError = true;
110
+ errorMessage =
111
+ "opencode exited successfully but produced no text output and no error -- check agent.log for the raw NDJSON";
112
+ }
113
+
114
+ return { resultText, costUsd, errorMessage, sessionId, failureReason, isError };
115
+ }
116
+
117
+ export function buildOutputJson(
118
+ { resultText, costUsd, errorMessage, sessionId, failureReason = null, isError },
119
+ cwd = null,
120
+ ) {
121
+ return {
122
+ type: "result",
123
+ subtype: isError ? "error" : "success",
124
+ is_error: isError,
125
+ result: isError ? resultText || errorMessage : resultText || null,
126
+ session_id: sessionId,
127
+ cwd,
128
+ ...(costUsd !== null ? { total_cost_usd: costUsd } : {}),
129
+ ...(isError && errorMessage !== null ? { terminal_reason: errorMessage } : {}),
130
+ ...(isError && failureReason !== null ? { failure_reason: failureReason } : {}),
131
+ };
132
+ }
133
+
134
+ export async function readUpTo(handle, maxBytes) {
135
+ const buffer = Buffer.alloc(maxBytes);
136
+ let totalRead = 0;
137
+ while (totalRead < maxBytes) {
138
+ const { bytesRead } = await handle.read({
139
+ buffer,
140
+ offset: totalRead,
141
+ length: maxBytes - totalRead,
142
+ position: totalRead,
143
+ });
144
+ if (bytesRead === 0) {
145
+ break;
146
+ }
147
+ totalRead += bytesRead;
148
+ }
149
+ return buffer.subarray(0, totalRead).toString("utf8");
150
+ }
151
+
152
+ async function writeOutputAtomically(outputJsonPath, contents) {
153
+ const tmpPath = path.join(
154
+ path.dirname(outputJsonPath),
155
+ `.${path.basename(outputJsonPath)}.tmp-${String(process.pid)}`,
156
+ );
157
+ await writeFile(tmpPath, JSON.stringify(contents));
158
+ await rename(tmpPath, outputJsonPath);
159
+ }
160
+
161
+ async function main() {
162
+ const [rawOutputPath, outputJsonPath, exitCodeArg, failureMessageArg = ""] =
163
+ process.argv.slice(2);
164
+ if (!rawOutputPath || !outputJsonPath || exitCodeArg === undefined) {
165
+ process.stderr.write(
166
+ "usage: collect.mjs <rawOutputPath> <outputJsonPath> <exitCode> [failureMessage]\n",
167
+ );
168
+ process.exitCode = 1;
169
+ return;
170
+ }
171
+
172
+ let rawText;
173
+ try {
174
+ const { size } = await stat(rawOutputPath);
175
+ if (size > RAW_FILE_MAX_BYTES) {
176
+ const handle = await open(rawOutputPath, "r");
177
+ try {
178
+ rawText = await readUpTo(handle, RAW_FILE_MAX_BYTES);
179
+ } finally {
180
+ await handle.close();
181
+ }
182
+ } else {
183
+ rawText = await readFile(rawOutputPath, "utf8");
184
+ }
185
+ } catch {
186
+ rawText = "";
187
+ }
188
+
189
+ const parsed = parseOpencodeOutput(rawText, exitCodeArg, failureMessageArg);
190
+ if (parsed.sessionId !== null) {
191
+ await writeFile(path.join(path.dirname(outputJsonPath), "session-id"), parsed.sessionId, {
192
+ mode: 0o600,
193
+ });
194
+ }
195
+ await writeOutputAtomically(outputJsonPath, buildOutputJson(parsed, process.cwd()));
196
+ process.exitCode = parsed.isError ? 1 : 0;
197
+ }
198
+
199
+ // QUIRK(node): the main module is loaded by its real path, so an unresolved argv[1] through a symlinked directory never equals import.meta.url and main() is silently skipped https://nodejs.org/api/cli.html#--preserve-symlinks-main
200
+ function resolveInvokedPath(argvPath) {
201
+ const resolved = path.resolve(argvPath);
202
+ try {
203
+ return realpathSync(resolved);
204
+ } catch {
205
+ return resolved;
206
+ }
207
+ }
208
+
209
+ if (process.argv[1] && fileURLToPath(import.meta.url) === resolveInvokedPath(process.argv[1])) {
210
+ main().catch((err) => {
211
+ process.stderr.write(`collect.mjs: unexpected error: ${String(err)}\n`);
212
+ const outputJsonPath = process.argv[3];
213
+ const fallback = buildOutputJson({
214
+ resultText: "",
215
+ costUsd: null,
216
+ errorMessage: `collect.mjs failed unexpectedly: ${String(err)}`,
217
+ sessionId: null,
218
+ isError: true,
219
+ });
220
+ if (outputJsonPath) {
221
+ writeOutputAtomically(outputJsonPath, fallback)
222
+ .catch((writeErr) => {
223
+ process.stderr.write(
224
+ `collect.mjs: could not write fallback output.json: ${String(writeErr)}\n`,
225
+ );
226
+ })
227
+ .finally(() => {
228
+ process.exitCode = 1;
229
+ });
230
+ } else {
231
+ process.exitCode = 1;
232
+ }
233
+ });
234
+ }
@@ -0,0 +1,3 @@
1
+ import { createCollectResult } from "@ligeti/agent-runtime";
2
+ export declare const collectResult: ReturnType<typeof createCollectResult>;
3
+ //# sourceMappingURL=collect-result.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collect-result.d.ts","sourceRoot":"","sources":["../src/collect-result.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAG5D,eAAO,MAAM,aAAa,EAAE,UAAU,CAAC,OAAO,mBAAmB,CAGhE,CAAC"}
@@ -0,0 +1,6 @@
1
+ // ABOUTME: collectResult, the step that parses the agent's output.json into a AgentResult, registered
2
+ // ABOUTME: under @ligeti/step-opencode-v2's own package identity (plan §4). See createCollectResult.
3
+ import { createCollectResult } from "@ligeti/agent-runtime";
4
+ import pkg from "../package.json" with { type: "json" };
5
+ export const collectResult = createCollectResult(pkg, "opencode-v2.collect-result");
6
+ //# sourceMappingURL=collect-result.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collect-result.js","sourceRoot":"","sources":["../src/collect-result.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,qGAAqG;AACrG,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,GAAG,MAAM,iBAAiB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AAExD,MAAM,CAAC,MAAM,aAAa,GAA2C,mBAAmB,CACtF,GAAG,EACH,4BAA4B,CAC7B,CAAC"}
@@ -0,0 +1,7 @@
1
+ export { launchOpenCodeV2Agent, NO_CONTROL_CHARS } from "./launch.js";
2
+ export { collectResult } from "./collect-result.js";
3
+ export { readTurnResult } from "./read-turn-result.js";
4
+ export { runOpenCodeV2 } from "./run-opencode-v2.js";
5
+ export { LaunchAgentOutput, AgentResult, CallEnv } from "@ligeti/agent-runtime";
6
+ export { wrapperPath } from "./wrapper-path.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ // ABOUTME: Public entry point of @ligeti/step-opencode-v2: the OpenCode 2.x launch step, collectResult, and
2
+ // ABOUTME: the input/output schemas a workflow needs to type its own run.
3
+ export { launchOpenCodeV2Agent, NO_CONTROL_CHARS } from "./launch.js";
4
+ export { collectResult } from "./collect-result.js";
5
+ export { readTurnResult } from "./read-turn-result.js";
6
+ export { runOpenCodeV2 } from "./run-opencode-v2.js";
7
+ export { LaunchAgentOutput, AgentResult, CallEnv } from "@ligeti/agent-runtime";
8
+ export { wrapperPath } from "./wrapper-path.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,4GAA4G;AAC5G,0EAA0E;AAC1E,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,26 @@
1
+ import { z } from "@ligeti/sdk";
2
+ import { NO_CONTROL_CHARS } from "@ligeti/agent-runtime";
3
+ export { NO_CONTROL_CHARS };
4
+ export declare const launchOpenCodeV2Agent: import("@ligeti/sdk").ResourceStepDefinition<z.ZodObject<{
5
+ prompt: z.ZodString;
6
+ workdir: z.ZodString;
7
+ model: z.ZodDefault<z.ZodString>;
8
+ session: z.ZodOptional<z.ZodString>;
9
+ beadsActor: z.ZodOptional<z.ZodString>;
10
+ forkSession: z.ZodOptional<z.ZodBoolean>;
11
+ env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
12
+ }, z.core.$strict>, z.ZodObject<{
13
+ backend: z.ZodEnum<{
14
+ herdr: "herdr";
15
+ subprocess: "subprocess";
16
+ }>;
17
+ agentId: z.ZodString;
18
+ sessionId: z.ZodNullable<z.ZodString>;
19
+ promptPath: z.ZodString;
20
+ outputPath: z.ZodString;
21
+ logPath: z.ZodString;
22
+ }, z.core.$strip>, z.ZodObject<{
23
+ attemptId: z.ZodString;
24
+ exitCode: z.ZodNumber;
25
+ }, z.core.$strip>>;
26
+ //# sourceMappingURL=launch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"launch.d.ts","sourceRoot":"","sources":["../src/launch.ts"],"names":[],"mappings":"AAIA,OAAO,EAAsB,CAAC,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EAWL,gBAAgB,EAMjB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,gBAAgB,EAAE,CAAC;AAc5B,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;kBAyJhC,CAAC"}
package/dist/launch.js ADDED
@@ -0,0 +1,159 @@
1
+ // ABOUTME: launchOpenCodeV2Agent, the resource step that reserves paths, writes the prompt file, and
2
+ // ABOUTME: spawns `wrapper.sh` under the configured backend; `opencode run --standalone` needs no session or hook machinery.
3
+ import { mkdir, readFile, stat } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { defineResourceStep, z } from "@ligeti/sdk";
6
+ import pkg from "../package.json" with { type: "json" };
7
+ import { backendFromCloseData, displayAgentId, pathsFor, readBackendMarker, writeBackendMarker, writeCallbackFiles, writePromptOnce, getBackend, loadAgentSettings, LaunchAgentOutput, NO_CONTROL_CHARS, CallEnv, AGENT_STEP_ENV_VARS, agentSpawnEnv, } from "@ligeti/agent-runtime";
8
+ import { wrapperPath } from "./wrapper-path.js";
9
+ export { NO_CONTROL_CHARS };
10
+ async function readSessionId(paths) {
11
+ try {
12
+ const raw = (await readFile(paths.sessionIdPath, "utf8")).trim();
13
+ return raw === "" ? null : raw;
14
+ }
15
+ catch (err) {
16
+ if (err.code === "ENOENT") {
17
+ return null;
18
+ }
19
+ throw err;
20
+ }
21
+ }
22
+ export const launchOpenCodeV2Agent = defineResourceStep({
23
+ name: "opencode-v2.launch",
24
+ envVars: AGENT_STEP_ENV_VARS,
25
+ description: "Launches an OpenCode 2.x agent for a single prompt via the configured backend.",
26
+ package: { name: pkg.name, version: pkg.version },
27
+ input: z
28
+ .strictObject({
29
+ prompt: z.string(),
30
+ workdir: z.string().min(1),
31
+ model: z
32
+ .string()
33
+ .min(1)
34
+ .regex(NO_CONTROL_CHARS, "must not contain control characters")
35
+ .default("nebius/zai-org/GLM-5.3-Flash")
36
+ .describe("OpenCode model, as provider/model or provider/model#variant"),
37
+ session: z
38
+ .string()
39
+ .min(1)
40
+ .regex(NO_CONTROL_CHARS, "must not contain control characters")
41
+ .optional()
42
+ .describe("Previous OpenCode session id to resume via --session; forked onto a new id unless forkSession is false"),
43
+ beadsActor: z
44
+ .string()
45
+ .min(1)
46
+ .optional()
47
+ .describe("Beads actor the agent writes beads and comments under; exported to the agent as BEADS_ACTOR"),
48
+ forkSession: z
49
+ .boolean()
50
+ .optional()
51
+ .describe("false resumes session by appending to it instead of forking a new id; requires session"),
52
+ env: CallEnv.optional(),
53
+ }, {
54
+ error: (issue) => issue.code === "unrecognized_keys" && issue.keys.includes("command")
55
+ ? "opencode 2.x has no named commands, so opencode-v2.launch takes no command"
56
+ : undefined,
57
+ })
58
+ .refine((input) => input.forkSession !== false || input.session !== undefined, {
59
+ message: "forkSession: false requires session",
60
+ path: ["forkSession"],
61
+ }),
62
+ output: LaunchAgentOutput,
63
+ callbackPayload: z.object({
64
+ attemptId: z.string().regex(/^[A-Za-z0-9_-]+$/),
65
+ exitCode: z.number().int(),
66
+ }),
67
+ retry: { maxAttempts: 1 },
68
+ async spawn(sctx, input, res) {
69
+ const workdir = path.resolve(process.cwd(), input.workdir);
70
+ let workdirStat;
71
+ try {
72
+ workdirStat = await stat(workdir);
73
+ }
74
+ catch {
75
+ throw new Error(`opencode-v2.launch: workdir does not exist: ${workdir}`);
76
+ }
77
+ if (!workdirStat.isDirectory()) {
78
+ throw new Error(`opencode-v2.launch: workdir is not a directory: ${workdir}`);
79
+ }
80
+ const settings = loadAgentSettings();
81
+ const paths = pathsFor(settings.stateDir, sctx.workflowId, res.attemptId);
82
+ await mkdir(paths.dir, { recursive: true, mode: 0o700 });
83
+ await writePromptOnce(paths.promptPath, input.prompt);
84
+ await writeBackendMarker(paths, settings.agentBackend);
85
+ if (res.callback === undefined) {
86
+ throw new Error("opencode-v2.launch: no callback target was minted");
87
+ }
88
+ await writeCallbackFiles(paths, res.callback.url, res.attemptId);
89
+ const backend = getBackend(settings, sctx.logger);
90
+ const wrapperArgs = ["--model", input.model];
91
+ if (input.session !== undefined) {
92
+ wrapperArgs.push("--session", input.session);
93
+ if (input.forkSession === false) {
94
+ wrapperArgs.push("--no-fork");
95
+ }
96
+ }
97
+ const command = ["/bin/bash", wrapperPath(), paths.dir, ...wrapperArgs];
98
+ const env = {
99
+ ...input.env,
100
+ LIGETI_OPENCODE2_BIN: settings.opencode2Bin,
101
+ };
102
+ if (settings.wrapperCallbackMaxAttempts !== undefined) {
103
+ env.LIGETI_WRAPPER_CALLBACK_MAX_ATTEMPTS = settings.wrapperCallbackMaxAttempts;
104
+ }
105
+ if (settings.wrapperCallbackRetryDelay !== undefined) {
106
+ env.LIGETI_WRAPPER_CALLBACK_RETRY_DELAY = settings.wrapperCallbackRetryDelay;
107
+ }
108
+ if (input.beadsActor !== undefined) {
109
+ env.BEADS_ACTOR = input.beadsActor;
110
+ }
111
+ const handle = await backend.spawn({
112
+ label: res.resourceKey,
113
+ cwd: workdir,
114
+ command,
115
+ env: agentSpawnEnv(settings.agentBackend, env, sctx.logger),
116
+ signal: sctx.signal,
117
+ logger: sctx.logger,
118
+ });
119
+ return {
120
+ handle,
121
+ output: {
122
+ backend: settings.agentBackend,
123
+ agentId: displayAgentId(settings.agentBackend, handle),
124
+ sessionId: input.session !== undefined && input.forkSession === false ? input.session : null,
125
+ promptPath: paths.promptPath,
126
+ outputPath: paths.outputPath,
127
+ logPath: paths.logPath,
128
+ },
129
+ };
130
+ },
131
+ async find(fctx, resourceKey) {
132
+ const settings = loadAgentSettings();
133
+ const paths = pathsFor(settings.stateDir, fctx.workflowId, fctx.attemptId);
134
+ const recordedBackend = (await readBackendMarker(paths)) ?? settings.agentBackend;
135
+ const backend = getBackend({ ...settings, agentBackend: recordedBackend }, fctx.logger);
136
+ const handle = await backend.findByLabel(resourceKey);
137
+ if (handle === null) {
138
+ return null;
139
+ }
140
+ return {
141
+ handle,
142
+ output: {
143
+ backend: recordedBackend,
144
+ agentId: displayAgentId(recordedBackend, handle),
145
+ sessionId: await readSessionId(paths),
146
+ promptPath: paths.promptPath,
147
+ outputPath: paths.outputPath,
148
+ logPath: paths.logPath,
149
+ },
150
+ };
151
+ },
152
+ async close(cctx, handle) {
153
+ const settings = loadAgentSettings();
154
+ const backendName = backendFromCloseData(cctx.data) ?? settings.agentBackend;
155
+ const backend = getBackend({ ...settings, agentBackend: backendName }, cctx.logger);
156
+ await backend.close(handle, cctx.resourceKey);
157
+ },
158
+ });
159
+ //# sourceMappingURL=launch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"launch.js","sourceRoot":"","sources":["../src/launch.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,6HAA6H;AAC7H,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,kBAAkB,EAAE,CAAC,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,GAAG,MAAM,iBAAiB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AACxD,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,QAAQ,EACR,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,eAAe,EACf,UAAU,EACV,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,OAAO,EAGP,mBAAmB,EACnB,aAAa,GACd,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,gBAAgB,EAAE,CAAC;AAE5B,KAAK,UAAU,aAAa,CAAC,KAAkB;IAC7C,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,CAAC,MAAM,QAAQ,CAAC,KAAK,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACjE,OAAO,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC;IACjC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAK,GAA6B,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACrD,OAAO,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AC;QAC/F,MAAM,OAAO,GAAG,UAAU,CAAC,EAAE,GAAG,QAAQ,EAAE,YAAY,EAAE,eAAe,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACxF,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;QACtD,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;YACpB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO;YACL,MAAM;YACN,MAAM,EAAE;gBACN,OAAO,EAAE,eAAe;gBACxB,OAAO,EAAE,cAAc,CAAC,eAAe,EAAE,MAAM,CAAC;gBAChD,SAAS,EAAE,MAAM,aAAa,CAAC,KAAK,CAAC;gBACrC,UAAU,EAAE,KAAK,CAAC,UAAU;gBAC5B,UAAU,EAAE,KAAK,CAAC,UAAU;gBAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB;SACF,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM;QACtB,MAAM,QAAQ,GAAG,iBAAiB,EAAE,CAAC;QACrC,MAAM,WAAW,GAAG,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,YAAY,CAAC;QAC7E,MAAM,OAAO,GAAG,UAAU,CAAC,EAAE,GAAG,QAAQ,EAAE,YAAY,EAAE,WAAW,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACpF,MAAM,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAChD,CAAC;CACF,CAAC,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { createReadTurnResult } from "@ligeti/agent-runtime";
2
+ export declare const readTurnResult: ReturnType<typeof createReadTurnResult>;
3
+ //# sourceMappingURL=read-turn-result.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-turn-result.d.ts","sourceRoot":"","sources":["../src/read-turn-result.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAG7D,eAAO,MAAM,cAAc,EAAE,UAAU,CAAC,OAAO,oBAAoB,CAGlE,CAAC"}
@@ -0,0 +1,6 @@
1
+ // ABOUTME: readTurnResult, the step that reads and validates the turn result file an agent wrote, registered
2
+ // ABOUTME: under @ligeti/step-opencode-v2's own package identity (plan §4). See createReadTurnResult.
3
+ import { createReadTurnResult } from "@ligeti/agent-runtime";
4
+ import pkg from "../package.json" with { type: "json" };
5
+ export const readTurnResult = createReadTurnResult(pkg, "opencode-v2.read-turn-result");
6
+ //# sourceMappingURL=read-turn-result.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-turn-result.js","sourceRoot":"","sources":["../src/read-turn-result.ts"],"names":[],"mappings":"AAAA,6GAA6G;AAC7G,sGAAsG;AACtG,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,GAAG,MAAM,iBAAiB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AAExD,MAAM,CAAC,MAAM,cAAc,GAA4C,oBAAoB,CACzF,GAAG,EACH,8BAA8B,CAC/B,CAAC"}
@@ -0,0 +1,13 @@
1
+ import type { WorkflowContext } from "@ligeti/sdk";
2
+ import { type AgentResult } from "@ligeti/agent-runtime";
3
+ export declare function runOpenCodeV2(ctx: WorkflowContext, input: {
4
+ prompt: string;
5
+ workdir: string;
6
+ model: string;
7
+ timeoutSeconds: number;
8
+ session?: string | undefined;
9
+ forkSession?: boolean | undefined;
10
+ beadsActor?: string | undefined;
11
+ env?: Record<string, string> | undefined;
12
+ }): Promise<AgentResult>;
13
+ //# sourceMappingURL=run-opencode-v2.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-opencode-v2.d.ts","sourceRoot":"","sources":["../src/run-opencode-v2.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAkB,KAAK,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAIzE,wBAAsB,aAAa,CACjC,GAAG,EAAE,eAAe,EACpB,KAAK,EAAE;IACL,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,WAAW,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAClC,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAAC;CAC1C,GACA,OAAO,CAAC,WAAW,CAAC,CA+BtB"}
@@ -0,0 +1,33 @@
1
+ import { timedOutResult } from "@ligeti/agent-runtime";
2
+ import { collectResult } from "./collect-result.js";
3
+ import { launchOpenCodeV2Agent } from "./launch.js";
4
+ export async function runOpenCodeV2(ctx, input) {
5
+ const agent = await ctx.run(launchOpenCodeV2Agent, {
6
+ prompt: input.prompt,
7
+ workdir: input.workdir,
8
+ model: input.model,
9
+ ...(input.session === undefined ? {} : { session: input.session }),
10
+ ...(input.forkSession === undefined ? {} : { forkSession: input.forkSession }),
11
+ ...(input.beadsActor === undefined ? {} : { beadsActor: input.beadsActor }),
12
+ ...(input.env === undefined ? {} : { env: input.env }),
13
+ });
14
+ await ctx.status("waiting_for_reviewer", {
15
+ agentId: agent.output.agentId,
16
+ logPath: agent.output.logPath,
17
+ });
18
+ const message = await ctx.waitForCallback(launchOpenCodeV2Agent, agent, {
19
+ timeoutSeconds: input.timeoutSeconds,
20
+ });
21
+ if (message === null) {
22
+ await ctx.close(agent);
23
+ return timedOutResult("the OpenCode 2.x agent did not respond before the timeout");
24
+ }
25
+ const result = await ctx.run(collectResult, {
26
+ outputPath: agent.output.outputPath,
27
+ logPath: agent.output.logPath,
28
+ exitCode: message.payload.exitCode,
29
+ });
30
+ await ctx.close(agent);
31
+ return result;
32
+ }
33
+ //# sourceMappingURL=run-opencode-v2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-opencode-v2.js","sourceRoot":"","sources":["../src/run-opencode-v2.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAoB,MAAM,uBAAuB,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,GAAoB,EACpB,KASC;IAED,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,GAAG,CAAC,qBAAqB,EAAE;QACjD,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,GAAG,CAAC,KAAK,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;QAClE,GAAG,CAAC,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE,CAAC;QAC9E,GAAG,CAAC,KAAK,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,CAAC;QAC3E,GAAG,CAAC,KAAK,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,CAAC;KACvD,CAAC,CAAC;IAEH,MAAM,GAAG,CAAC,MAAM,CAAC,sBAAsB,EAAE;QACvC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAO;QAC7B,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAO;KAC9B,CAAC,CAAC;IAEH,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,eAAe,CAAC,qBAAqB,EAAE,KAAK,EAAE;QACtE,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;IACH,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;QACrB,MAAM,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACvB,OAAO,cAAc,CAAC,2DAA2D,CAAC,CAAC;IACrF,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,GAAG,CAAC,aAAa,EAAE;QAC1C,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU;QACnC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAO;QAC7B,QAAQ,EAAE,OAAO,CAAC,OAAO,CAAC,QAAQ;KACnC,CAAC,CAAC;IACH,MAAM,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACvB,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export declare function wrapperPath(): string;
2
+ //# sourceMappingURL=wrapper-path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wrapper-path.d.ts","sourceRoot":"","sources":["../src/wrapper-path.ts"],"names":[],"mappings":"AAKA,wBAAgB,WAAW,IAAI,MAAM,CAGpC"}
@@ -0,0 +1,9 @@
1
+ // ABOUTME: Resolves the absolute path to wrapper.sh, shipped as package data next to `dist/` and
2
+ // ABOUTME: `src/` alike (both one level below the package root), so it works built or from source.
3
+ import { fileURLToPath } from "node:url";
4
+ import path from "node:path";
5
+ export function wrapperPath() {
6
+ const here = path.dirname(fileURLToPath(import.meta.url));
7
+ return path.join(here, "..", "wrapper.sh");
8
+ }
9
+ //# sourceMappingURL=wrapper-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wrapper-path.js","sourceRoot":"","sources":["../src/wrapper-path.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,mGAAmG;AACnG,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,MAAM,UAAU,WAAW;IACzB,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1D,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,CAAC,CAAC;AAC7C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@ligeti/step-opencode-v2",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.1",
4
+ "description": "Ligeti step package: launches OpenCode 2.x under herdr or a bare subprocess and collects its result.",
5
+ "keywords": [
6
+ "ligeti-step"
7
+ ],
8
+ "ligeti": {
9
+ "kind": "step",
10
+ "sdk": "^2.0.0"
11
+ },
12
+ "type": "module",
13
+ "license": "Apache-2.0",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://gitlab.com/nagyv-projects/ligeti.git",
17
+ "directory": "steps/opencode-v2"
18
+ },
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "wrapper.sh",
28
+ "collect.mjs"
29
+ ],
30
+ "dependencies": {
31
+ "@ligeti/agent-runtime": "^2.4.0"
32
+ },
33
+ "peerDependencies": {
34
+ "@ligeti/sdk": "^2.5.0"
35
+ },
36
+ "devDependencies": {
37
+ "@ligeti/sdk": "2.5.0",
38
+ "@ligeti/testing": "2.1.0"
39
+ },
40
+ "scripts": {}
6
41
  }
package/wrapper.sh ADDED
@@ -0,0 +1,222 @@
1
+ #!/usr/bin/env bash
2
+ # ABOUTME: Runs `opencode run --standalone` (opencode 2.x) non-interactively in the agent process, normalizes its NDJSON
3
+ # ABOUTME: output, then POSTs a signed callback with the exit code -- always, even if opencode fails.
4
+ set -euo pipefail
5
+
6
+ usage="usage: wrapper.sh <attempt_dir> [--model <value>] [--session <value> [--no-fork]]"
7
+
8
+ if [ "$#" -lt 1 ]; then
9
+ echo "$usage" >&2
10
+ exit 64
11
+ fi
12
+
13
+ script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
14
+
15
+ attempt_dir="$1"
16
+ shift
17
+
18
+ model=""
19
+ have_model=0
20
+ session=""
21
+ fork=1
22
+
23
+ while [ "$#" -gt 0 ]; do
24
+ case "$1" in
25
+ --model|--session)
26
+ if [ "$#" -lt 2 ]; then
27
+ echo "wrapper.sh: missing value for $1" >&2
28
+ echo "$usage" >&2
29
+ exit 64
30
+ fi
31
+ case "$1" in
32
+ --model)
33
+ model="$2"
34
+ have_model=1
35
+ ;;
36
+ --session)
37
+ session="$2"
38
+ ;;
39
+ esac
40
+ shift 2
41
+ ;;
42
+ --no-fork)
43
+ fork=0
44
+ shift
45
+ ;;
46
+ *)
47
+ echo "wrapper.sh: unknown argument: $1" >&2
48
+ echo "$usage" >&2
49
+ exit 64
50
+ ;;
51
+ esac
52
+ done
53
+
54
+ if [ "$fork" -eq 0 ] && [ -z "$session" ]; then
55
+ echo "wrapper.sh: --no-fork requires --session" >&2
56
+ echo "$usage" >&2
57
+ exit 64
58
+ fi
59
+
60
+ callback_url_file="$attempt_dir/callback-url"
61
+ attempt_id_file="$attempt_dir/attempt-id"
62
+ prompt_file="$attempt_dir/prompt.txt"
63
+ raw_output_file="$attempt_dir/opencode-raw-output.json"
64
+ output_json="$attempt_dir/output.json"
65
+ log_file="$attempt_dir/agent.log"
66
+
67
+ if [ ! -f "$callback_url_file" ] || [ ! -f "$attempt_id_file" ] || [ ! -f "$prompt_file" ]; then
68
+ echo "wrapper.sh: attempt dir missing required file(s): $attempt_dir" >&2
69
+ exit 64
70
+ fi
71
+
72
+ callback_url="$(cat "$callback_url_file")"
73
+ attempt_id="$(cat "$attempt_id_file")"
74
+
75
+ case "$attempt_id" in
76
+ *[!A-Za-z0-9_-]*|"")
77
+ echo "wrapper.sh: invalid attempt_id: $attempt_id" >&2
78
+ exit 65
79
+ ;;
80
+ esac
81
+
82
+ if ! command -v curl >/dev/null 2>&1; then
83
+ echo "wrapper.sh: FATAL: curl not found on PATH -- cannot deliver callback" >&2
84
+ exit 66
85
+ fi
86
+
87
+ if ! command -v node >/dev/null 2>&1; then
88
+ echo "wrapper.sh: FATAL: node not found on PATH -- cannot run collect.mjs" >&2
89
+ exit 67
90
+ fi
91
+
92
+ opencode_bin="${LIGETI_OPENCODE2_BIN:-opencode}"
93
+
94
+ if [ "$have_model" -ne 1 ] || [ -z "$model" ]; then
95
+ echo "wrapper.sh: FATAL: --model must be set" >&2
96
+ exit 68
97
+ fi
98
+
99
+ log() {
100
+ printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" >>"$log_file" 2>/dev/null || true
101
+ }
102
+
103
+ rm -f "$raw_output_file" "$output_json" "$attempt_dir/session-id"
104
+
105
+ exit_code=0
106
+ failure_message=""
107
+
108
+ check_opencode_version() {
109
+ local version_output=""
110
+ local version_status=0
111
+ version_output="$("$opencode_bin" --version 2>>"$log_file" </dev/null)" || version_status=$?
112
+ local first_line=""
113
+ local line=""
114
+ while IFS= read -r line; do
115
+ if [[ "$line" =~ [^[:space:]] ]]; then
116
+ first_line="$line"
117
+ break
118
+ fi
119
+ done <<<"$version_output"
120
+ local version_pattern='([0-9]+)\.[0-9]+\.[0-9]+'
121
+
122
+ if [ "$version_status" -ne 0 ]; then
123
+ failure_message="could not run '$opencode_bin --version' (exit $version_status); is opencode 2.x installed and is LIGETI_OPENCODE2_BIN correct? see agent.log"
124
+ elif [[ "$first_line" =~ $version_pattern ]]; then
125
+ if [ "${BASH_REMATCH[1]}" -ne 2 ]; then
126
+ failure_message="opencode ${BASH_REMATCH[0]} is installed at $opencode_bin, but @ligeti/step-opencode-v2 requires opencode 2.x; install opencode 2.x, or point LIGETI_OPENCODE2_BIN at it"
127
+ fi
128
+ else
129
+ failure_message="could not determine the version of the opencode at $opencode_bin (\`--version\` printed: ${first_line:-nothing}), but @ligeti/step-opencode-v2 requires opencode 2.x; install opencode 2.x or point LIGETI_OPENCODE2_BIN at it"
130
+ fi
131
+ }
132
+
133
+ check_opencode_version
134
+
135
+ prompt_size="$(wc -c <"$prompt_file" | tr -d ' ')"
136
+ if [ -n "$failure_message" ]; then
137
+ log "FATAL: $failure_message -- not running opencode"
138
+ exit_code=1
139
+ elif [ "$prompt_size" -gt 100000 ]; then
140
+ log "FATAL: prompt.txt is ${prompt_size} bytes (over the 100000 byte limit) -- refusing to launch opencode with it as an argv element"
141
+ exit_code=1
142
+ else
143
+ session_args=()
144
+ if [ -n "$session" ]; then
145
+ session_args=(--session "$session")
146
+ if [ "$fork" -eq 1 ]; then
147
+ session_args+=(--fork)
148
+ fi
149
+ fi
150
+
151
+ log "starting: $opencode_bin run --standalone --format json --model $model ${session_args[*]:-} -- <prompt>"
152
+ # QUIRK(bash): bash before 4.4 fails "${arr[@]}" on an empty array under set -u, hence the ${arr[@]+"${arr[@]}"} form https://github.com/bminor/bash/blob/master/CHANGES
153
+ "$opencode_bin" run --standalone --format json --model "$model" \
154
+ ${session_args[@]+"${session_args[@]}"} \
155
+ -- "$(cat "$prompt_file")" \
156
+ </dev/null >"$raw_output_file" 2>>"$log_file" || exit_code=$?
157
+
158
+ log "opencode exited with code $exit_code"
159
+ fi
160
+
161
+ set +e
162
+ node "$script_dir/collect.mjs" "$raw_output_file" "$output_json" "$exit_code" "$failure_message"
163
+ exit_code=$?
164
+ set -e
165
+ log "collect.mjs exited with code $exit_code"
166
+
167
+ payload="{\"attemptId\":\"${attempt_id}\",\"exitCode\":${exit_code}}"
168
+
169
+ callback_url_redacted="${callback_url%%/callbacks/*}/callbacks/REDACTED"
170
+ log "posting callback to $callback_url_redacted"
171
+
172
+ callback_max_attempts="${LIGETI_WRAPPER_CALLBACK_MAX_ATTEMPTS:-30}"
173
+ callback_retry_delay="${LIGETI_WRAPPER_CALLBACK_RETRY_DELAY:-2}"
174
+ callback_body_file="$(mktemp)"
175
+ callback_err_file="$(mktemp)"
176
+ callback_attempt=0
177
+ callback_delivered=0
178
+ callback_final_error=""
179
+
180
+ while [ "$callback_attempt" -lt "$callback_max_attempts" ]; do
181
+ callback_attempt=$((callback_attempt + 1))
182
+ http_code=""
183
+ curl_exit=0
184
+ http_code=$(printf 'url = "%s"\n' "$callback_url" | curl -sS --config - \
185
+ -o "$callback_body_file" -w '%{http_code}' --max-time 10 \
186
+ -X POST -H 'Content-Type: application/json' --data "$payload" \
187
+ 2>"$callback_err_file") || curl_exit=$?
188
+ log "callback attempt $callback_attempt: curl exit=$curl_exit http_code=${http_code:-none} $(cat "$callback_err_file" 2>/dev/null || true)"
189
+
190
+ if [ "$curl_exit" -ne 0 ]; then
191
+ callback_final_error="curl exit code $curl_exit (connection failure)"
192
+ else
193
+ case "$http_code" in
194
+ 2??)
195
+ callback_delivered=1
196
+ break
197
+ ;;
198
+ 4??)
199
+ callback_final_error="HTTP $http_code (permanent, not retrying)"
200
+ break
201
+ ;;
202
+ *)
203
+ callback_final_error="HTTP ${http_code:-none}"
204
+ ;;
205
+ esac
206
+ fi
207
+
208
+ if [ "$callback_attempt" -lt "$callback_max_attempts" ]; then
209
+ sleep "$callback_retry_delay"
210
+ fi
211
+ done
212
+
213
+ rm -f "$callback_body_file" "$callback_err_file"
214
+
215
+ if [ "$callback_delivered" -ne 1 ]; then
216
+ log "callback delivery failed after $callback_attempt attempt(s): $callback_final_error"
217
+ exit 1
218
+ fi
219
+
220
+ log "callback delivered"
221
+
222
+ exit "$exit_code"