opencode-agent-orchestration-kit 1.0.38 → 1.0.39

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
@@ -327,7 +327,7 @@ After a tagged release is published, you can install the same CLI directly
327
327
  from GitHub without keeping a checkout:
328
328
 
329
329
  ```bash
330
- npm install --global "git+https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit.git#v1.0.38"
330
+ npm install --global "git+https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit.git#v1.0.39"
331
331
  oc-switch
332
332
  ```
333
333
 
@@ -732,7 +732,7 @@ Validate only the canonical identity and current release note with:
732
732
 
733
733
  ```bash
734
734
  npm run check:version
735
- node scripts/version.mjs --check-tag v1.0.38
735
+ node scripts/version.mjs --check-tag v1.0.39
736
736
  ```
737
737
 
738
738
  Tag validation compares an explicitly supplied tag with the package identity.
@@ -37,6 +37,8 @@ NODE
37
37
  RUN pnpm --filter @open-design/daemon build \
38
38
  && (pnpm build || pnpm -r build)
39
39
 
40
+ COPY entrypoint.mjs /usr/local/bin/open-design-entrypoint.mjs
41
+
40
42
  ENV OD_HOST=0.0.0.0
41
43
  ENV OD_PORT=7456
42
44
  ENV OPENCODE_CONFIG_DIR=/home/opencode/.config/opencode
@@ -47,4 +49,4 @@ RUN mkdir -p /home/opencode/.config/opencode /home/opencode/.local/share/opencod
47
49
  USER opencode
48
50
  EXPOSE 7456
49
51
 
50
- CMD ["sh", "-lc", "node apps/daemon/dist/cli.js --port ${OD_PORT:-7456} --no-open"]
52
+ ENTRYPOINT ["node", "/usr/local/bin/open-design-entrypoint.mjs"]
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { spawn } from "node:child_process";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const DEFAULT_PORT = "7456";
8
+ const DAEMON_ENTRYPOINT = "apps/daemon/dist/cli.js";
9
+
10
+ export function parsePort(rawPort) {
11
+ if (typeof rawPort !== "string" || !/^[0-9]+$/.test(rawPort)) {
12
+ throw new Error("OD_PORT must be a decimal TCP port between 1 and 65535");
13
+ }
14
+
15
+ const port = Number(rawPort);
16
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65535) {
17
+ throw new Error("OD_PORT must be a decimal TCP port between 1 and 65535");
18
+ }
19
+
20
+ return port;
21
+ }
22
+
23
+ export function daemonArguments(port) {
24
+ return [DAEMON_ENTRYPOINT, "--port", String(port), "--no-open"];
25
+ }
26
+
27
+ function main() {
28
+ let port;
29
+ try {
30
+ port = parsePort(process.env.OD_PORT ?? DEFAULT_PORT);
31
+ } catch (error) {
32
+ console.error(`Open Design startup failed: ${error.message}`);
33
+ process.exitCode = 1;
34
+ return;
35
+ }
36
+
37
+ const daemon = spawn(process.execPath, daemonArguments(port), { stdio: "inherit" });
38
+ const forwardSignal = (signal) => daemon.kill(signal);
39
+ const cleanup = () => {
40
+ process.removeListener("SIGINT", onSigint);
41
+ process.removeListener("SIGTERM", onSigterm);
42
+ };
43
+ const onSigint = () => forwardSignal("SIGINT");
44
+ const onSigterm = () => forwardSignal("SIGTERM");
45
+
46
+ process.once("SIGINT", onSigint);
47
+ process.once("SIGTERM", onSigterm);
48
+ daemon.once("error", (error) => {
49
+ cleanup();
50
+ console.error(`Open Design daemon failed to start: ${error.message}`);
51
+ process.exitCode = 1;
52
+ });
53
+ daemon.once("exit", (code, signal) => {
54
+ cleanup();
55
+ process.exitCode = signal ? 1 : (code ?? 1);
56
+ });
57
+ }
58
+
59
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
60
+ main();
61
+ }
@@ -45,6 +45,11 @@ The compose file mounts:
45
45
 
46
46
  Do not commit `data` or `opencode-auth`.
47
47
 
48
+ `OD_PORT` must be a decimal TCP port from `1` to `65535`; it defaults to
49
+ `7456`. The image validates this value before starting the daemon and passes it
50
+ as a separate argument without a shell. Invalid values stop the container with
51
+ a deterministic startup error.
52
+
48
53
  ## HTTP LAN and crypto.randomUUID
49
54
 
50
55
  Some browser APIs require a secure context. If Open Design frontend code calls `crypto.randomUUID` and your browser blocks it over HTTP LAN, prefer HTTPS. Only patch upstream frontend code as a local operational workaround.
package/docs/models.md CHANGED
@@ -26,7 +26,7 @@ oc-switch
26
26
  Once a release tag exists, a checkout is optional:
27
27
 
28
28
  ```bash
29
- npm install --global "git+https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit.git#v1.0.38"
29
+ npm install --global "git+https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit.git#v1.0.39"
30
30
  oc-switch
31
31
  ```
32
32
 
@@ -23,3 +23,11 @@ Do not use project or file URLs.
23
23
  ## Security
24
24
 
25
25
  Do not expose Open Design directly to the Internet without authentication, VPN, Tailscale, WireGuard, or a secure reverse proxy.
26
+
27
+ ## Runtime budgets
28
+
29
+ The Open Design client uses fixed safety budgets for remote calls: 5 seconds to
30
+ receive response headers, 15 seconds of read-idle time, 120 seconds total per
31
+ request, 1 MiB for JSON responses, 8 MiB for SSE responses, 2 MiB per stdout or
32
+ stderr channel, and 10,000 SSE events. Oversized, stalled, or incomplete
33
+ responses fail with a bounded diagnostic instead of being retained indefinitely.
@@ -0,0 +1,44 @@
1
+ # v1.0.39 - Safe lifecycle and canonical release identity
2
+
3
+ This release hardens the Open Design HTTP and SSE transport and its Docker
4
+ entrypoint for bounded, fail-closed operation.
5
+
6
+ ## Highlights
7
+
8
+ - Bound Open Design connection, total, and idle-read timeouts.
9
+ - Bound JSON response bodies, SSE bytes, event counts, and captured output.
10
+ - Keep transport failures and diagnostics from returning unbounded remote data.
11
+ - Harden the Open Design Docker entrypoint's startup and signal lifecycle.
12
+
13
+ ## Installation or upgrade
14
+
15
+ Install or upgrade the public kit using the normal manifest-owned flow:
16
+
17
+ ```bash
18
+ ./install.sh --dry-run
19
+ ./install.sh
20
+ ./upgrade.sh --dry-run
21
+ ./upgrade.sh
22
+ ```
23
+
24
+ After installation, run `oak check` and review the installed target before
25
+ using the harness.
26
+
27
+ ## Migration
28
+
29
+ No migration is required. Existing Open Design configuration remains valid;
30
+ requests that exceed the transport budgets now fail closed with bounded error
31
+ messages.
32
+
33
+ ## Validation performed
34
+
35
+ The public contract checker, unit and script tests, type checks, dependency
36
+ audits, signature checks, installation smoke, package smoke, and canonical
37
+ version/tag checks pass for this release.
38
+
39
+ ## Public safety boundary
40
+
41
+ The public release excludes private OpenCode and Pi configuration, local
42
+ providers and MCP wiring, credentials, authentication files, raw transcripts,
43
+ private evidence, absolute machine paths, and runtime state. Pi uses its own
44
+ native model catalog and is not included in this OpenCode package.
@@ -0,0 +1,45 @@
1
+ export type OpenDesignHttpOptions = {
2
+ fetchImpl?: typeof fetch
3
+ connectTimeoutMs?: number
4
+ totalTimeoutMs?: number
5
+ idleTimeoutMs?: number
6
+ maxJsonBytes?: number
7
+ maxSseBytes?: number
8
+ maxOutputBytes?: number
9
+ maxEvents?: number
10
+ maxDiagnosticBytes?: number
11
+ }
12
+
13
+ export const OPEN_DESIGN_HTTP_LIMITS: Readonly<{
14
+ connectTimeoutMs: number
15
+ totalTimeoutMs: number
16
+ idleTimeoutMs: number
17
+ maxJsonBytes: number
18
+ maxSseBytes: number
19
+ maxOutputBytes: number
20
+ maxEvents: number
21
+ maxDiagnosticBytes: number
22
+ }>
23
+
24
+ export function requestJson(
25
+ base: string,
26
+ path: string,
27
+ init?: RequestInit,
28
+ options?: OpenDesignHttpOptions,
29
+ ): Promise<unknown>
30
+
31
+ export function parseSseFrames(buffer: string): {
32
+ frames: Array<{ event: string; data: unknown }>
33
+ rest: string
34
+ }
35
+
36
+ export function streamOpenDesignChat(
37
+ base: string,
38
+ body: unknown,
39
+ options?: OpenDesignHttpOptions,
40
+ ): Promise<{
41
+ stdout: string
42
+ stderr: string
43
+ end: unknown
44
+ eventsCount: number
45
+ }>
@@ -0,0 +1,387 @@
1
+ const DEFAULT_LIMITS = Object.freeze({
2
+ connectTimeoutMs: 5_000,
3
+ totalTimeoutMs: 120_000,
4
+ idleTimeoutMs: 15_000,
5
+ maxJsonBytes: 1_048_576,
6
+ maxSseBytes: 8_388_608,
7
+ maxOutputBytes: 2_097_152,
8
+ maxEvents: 10_000,
9
+ maxDiagnosticBytes: 4_000,
10
+ });
11
+
12
+ const LIMIT_BOUNDS = Object.freeze({
13
+ connectTimeoutMs: [100, 60_000],
14
+ totalTimeoutMs: [1_000, 300_000],
15
+ idleTimeoutMs: [100, 60_000],
16
+ maxJsonBytes: [1_024, 8_388_608],
17
+ maxSseBytes: [1_024, 16_777_216],
18
+ maxOutputBytes: [1_024, 8_388_608],
19
+ maxEvents: [1, 100_000],
20
+ maxDiagnosticBytes: [256, 16_000],
21
+ });
22
+
23
+ const encoder = new TextEncoder();
24
+
25
+ export const OPEN_DESIGN_HTTP_LIMITS = DEFAULT_LIMITS;
26
+
27
+ function resolveLimits(overrides = {}) {
28
+ return Object.fromEntries(
29
+ Object.entries(DEFAULT_LIMITS).map(([name, fallback]) => {
30
+ const [minimum, maximum] = LIMIT_BOUNDS[name];
31
+ const value = Number(overrides[name]);
32
+ return [
33
+ name,
34
+ Number.isFinite(value)
35
+ ? Math.min(maximum, Math.max(minimum, Math.floor(value)))
36
+ : fallback,
37
+ ];
38
+ }),
39
+ );
40
+ }
41
+
42
+ function stringify(value) {
43
+ if (typeof value === "string") return value;
44
+ try {
45
+ return JSON.stringify(value, null, 2);
46
+ } catch {
47
+ return String(value);
48
+ }
49
+ }
50
+
51
+ function preview(value, maxBytes) {
52
+ const text = stringify(value);
53
+ if (encoder.encode(text).byteLength <= maxBytes) return text;
54
+
55
+ let result = text.slice(0, Math.max(0, maxBytes - 3));
56
+ while (result && encoder.encode(`${result}...`).byteLength > maxBytes) {
57
+ result = result.slice(0, -1);
58
+ }
59
+ return `${result}...`;
60
+ }
61
+
62
+ function tailPreview(value, maxBytes) {
63
+ const text = stringify(value);
64
+ if (encoder.encode(text).byteLength <= maxBytes) return text;
65
+
66
+ let result = text.slice(-Math.max(0, maxBytes - 3));
67
+ while (result && encoder.encode(`...${result}`).byteLength > maxBytes) {
68
+ result = result.slice(1);
69
+ }
70
+ return `...${result}`;
71
+ }
72
+
73
+ function timeoutError(message) {
74
+ return new Error(`Open Design request ${message}`);
75
+ }
76
+
77
+ function createBudget(limits) {
78
+ const controller = new AbortController();
79
+ let failure = null;
80
+ let connectTimer;
81
+ let totalTimer;
82
+ let rejectConnectTimeout;
83
+ let rejectTotalTimeout;
84
+
85
+ const abort = (error) => {
86
+ if (failure) return failure;
87
+ failure = error instanceof Error ? error : new Error(String(error));
88
+ controller.abort(failure);
89
+ return failure;
90
+ };
91
+
92
+ const connectTimeout = new Promise((_, reject) => {
93
+ rejectConnectTimeout = reject;
94
+ connectTimer = setTimeout(() => {
95
+ const error = abort(timeoutError("timed out while connecting"));
96
+ rejectConnectTimeout(error);
97
+ }, limits.connectTimeoutMs);
98
+ });
99
+ const totalTimeout = new Promise((_, reject) => {
100
+ rejectTotalTimeout = reject;
101
+ totalTimer = setTimeout(() => {
102
+ const error = abort(timeoutError("timed out"));
103
+ rejectTotalTimeout(error);
104
+ }, limits.totalTimeoutMs);
105
+ });
106
+ void totalTimeout.catch(() => {});
107
+
108
+ return {
109
+ signal: controller.signal,
110
+ connectTimeout,
111
+ totalTimeout,
112
+ markHeadersReceived() {
113
+ clearTimeout(connectTimer);
114
+ },
115
+ abort,
116
+ errorOr(error) {
117
+ return failure || error;
118
+ },
119
+ dispose() {
120
+ clearTimeout(connectTimer);
121
+ clearTimeout(totalTimer);
122
+ },
123
+ };
124
+ }
125
+
126
+ async function fetchWithBudget(url, init, options) {
127
+ const limits = resolveLimits(options);
128
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
129
+ if (typeof fetchImpl !== "function") {
130
+ throw new Error("Open Design requires a fetch implementation");
131
+ }
132
+
133
+ const budget = createBudget(limits);
134
+ try {
135
+ const response = await Promise.race([
136
+ Promise.resolve().then(() => fetchImpl(url, { ...init, signal: budget.signal })),
137
+ budget.connectTimeout,
138
+ budget.totalTimeout,
139
+ ]);
140
+ budget.markHeadersReceived();
141
+ return { response, budget, limits };
142
+ } catch (error) {
143
+ const failure = budget.errorOr(error);
144
+ budget.dispose();
145
+ throw failure;
146
+ }
147
+ }
148
+
149
+ async function readWithIdleTimeout(reader, budget, idleTimeoutMs) {
150
+ let timer;
151
+ try {
152
+ return await Promise.race([
153
+ reader.read(),
154
+ new Promise((_, reject) => {
155
+ timer = setTimeout(() => {
156
+ reject(budget.abort(timeoutError("timed out while reading")));
157
+ }, idleTimeoutMs);
158
+ }),
159
+ budget.totalTimeout,
160
+ ]);
161
+ } catch (error) {
162
+ throw budget.errorOr(error);
163
+ } finally {
164
+ clearTimeout(timer);
165
+ }
166
+ }
167
+
168
+ async function cancelResponseBody(response) {
169
+ try {
170
+ await response.body?.cancel?.();
171
+ } catch {
172
+ // The response is already being aborted; cancellation is best-effort.
173
+ }
174
+ }
175
+
176
+ async function readBoundedText(response, budget, limits, label, maxBytes = limits.maxJsonBytes) {
177
+ const contentLength = Number(response.headers?.get?.("content-length"));
178
+ if (Number.isFinite(contentLength) && contentLength > maxBytes) {
179
+ const error = new Error(`${label} response exceeds ${maxBytes} bytes`);
180
+ budget.abort(error);
181
+ await cancelResponseBody(response);
182
+ throw error;
183
+ }
184
+
185
+ if (!response.body) return "";
186
+
187
+ const reader = response.body.getReader();
188
+ const decoder = new TextDecoder();
189
+ const parts = [];
190
+ let bytes = 0;
191
+
192
+ try {
193
+ while (true) {
194
+ const { value, done } = await readWithIdleTimeout(reader, budget, limits.idleTimeoutMs);
195
+ if (done) break;
196
+
197
+ bytes += value.byteLength;
198
+ if (bytes > maxBytes) {
199
+ const error = new Error(`${label} response exceeds ${maxBytes} bytes`);
200
+ budget.abort(error);
201
+ throw error;
202
+ }
203
+ parts.push(decoder.decode(value, { stream: true }));
204
+ }
205
+ parts.push(decoder.decode());
206
+ return parts.join("");
207
+ } catch (error) {
208
+ budget.abort(error);
209
+ await reader.cancel().catch(() => {});
210
+ throw budget.errorOr(error);
211
+ } finally {
212
+ reader.releaseLock();
213
+ }
214
+ }
215
+
216
+ export async function requestJson(base, path, init = {}, options = {}) {
217
+ const { response, budget, limits } = await fetchWithBudget(`${base}${path}`, {
218
+ ...init,
219
+ headers: {
220
+ "Content-Type": "application/json",
221
+ ...(init.headers || {}),
222
+ },
223
+ }, options);
224
+
225
+ try {
226
+ const text = await readBoundedText(response, budget, limits, `Open Design ${path}`);
227
+ let body = text;
228
+
229
+ try {
230
+ body = text ? JSON.parse(text) : null;
231
+ } catch {
232
+ body = text;
233
+ }
234
+
235
+ if (!response.ok) {
236
+ throw new Error(
237
+ `Open Design ${path} failed (${response.status}): ${preview(body, limits.maxDiagnosticBytes)}`,
238
+ );
239
+ }
240
+
241
+ return body;
242
+ } finally {
243
+ budget.dispose();
244
+ }
245
+ }
246
+
247
+ function eventDelimiter(input) {
248
+ const candidates = [
249
+ [input.indexOf("\r\n\r\n"), 4],
250
+ [input.indexOf("\n\n"), 2],
251
+ [input.indexOf("\r\r"), 2],
252
+ ].filter(([index]) => index !== -1);
253
+
254
+ return candidates.sort(([left], [right]) => left - right)[0] ?? null;
255
+ }
256
+
257
+ export function parseSseFrames(buffer) {
258
+ const frames = [];
259
+ let rest = buffer;
260
+
261
+ while (true) {
262
+ const delimiter = eventDelimiter(rest);
263
+ if (!delimiter) break;
264
+
265
+ const [index, length] = delimiter;
266
+ const raw = rest.slice(0, index);
267
+ rest = rest.slice(index + length);
268
+
269
+ let event = "message";
270
+ const dataLines = [];
271
+ for (const line of raw.split(/\r\n|\n|\r/)) {
272
+ if (line.startsWith("event:")) event = line.slice(6).trim();
273
+ if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
274
+ }
275
+
276
+ const dataText = dataLines.join("\n");
277
+ let data = dataText;
278
+ try {
279
+ data = dataText ? JSON.parse(dataText) : null;
280
+ } catch {
281
+ // Keep non-JSON SSE payloads as text.
282
+ }
283
+ frames.push({ event, data });
284
+ }
285
+
286
+ return { frames, rest };
287
+ }
288
+
289
+ function appendOutput(parts, bytes, value, limits) {
290
+ const text = String(value ?? "");
291
+ const nextBytes = bytes + encoder.encode(text).byteLength;
292
+ if (nextBytes > limits.maxOutputBytes) {
293
+ throw new Error(`Open Design stdout/stderr output exceeds ${limits.maxOutputBytes} bytes`);
294
+ }
295
+ parts.push(text);
296
+ return nextBytes;
297
+ }
298
+
299
+ export async function streamOpenDesignChat(base, body, options = {}) {
300
+ const { response, budget, limits } = await fetchWithBudget(`${base}/api/chat`, {
301
+ method: "POST",
302
+ headers: { "Content-Type": "application/json" },
303
+ body: JSON.stringify(body),
304
+ }, options);
305
+
306
+ try {
307
+ if (!response.ok || !response.body) {
308
+ const text = await readBoundedText(response, budget, limits, "Open Design chat");
309
+ throw new Error(`Open Design chat failed (${response.status}): ${preview(text, limits.maxDiagnosticBytes)}`);
310
+ }
311
+
312
+ const reader = response.body.getReader();
313
+ const decoder = new TextDecoder();
314
+ const stdoutParts = [];
315
+ const stderrParts = [];
316
+ let stdoutBytes = 0;
317
+ let stderrBytes = 0;
318
+ let buffer = "";
319
+ let streamBytes = 0;
320
+ let end = null;
321
+ let eventsCount = 0;
322
+
323
+ try {
324
+ while (true) {
325
+ const { value, done } = await readWithIdleTimeout(reader, budget, limits.idleTimeoutMs);
326
+ if (done) {
327
+ buffer += decoder.decode();
328
+ break;
329
+ }
330
+
331
+ streamBytes += value.byteLength;
332
+ if (streamBytes > limits.maxSseBytes) {
333
+ throw new Error(`Open Design SSE response exceeds ${limits.maxSseBytes} bytes`);
334
+ }
335
+
336
+ buffer += decoder.decode(value, { stream: true });
337
+ const parsed = parseSseFrames(buffer);
338
+ buffer = parsed.rest;
339
+
340
+ for (const frame of parsed.frames) {
341
+ eventsCount += 1;
342
+ if (eventsCount > limits.maxEvents) {
343
+ throw new Error(`Open Design SSE event count exceeds ${limits.maxEvents}`);
344
+ }
345
+
346
+ if (frame.event === "stdout") {
347
+ stdoutBytes = appendOutput(stdoutParts, stdoutBytes, frame.data?.chunk, limits);
348
+ }
349
+ if (frame.event === "stderr") {
350
+ stderrBytes = appendOutput(stderrParts, stderrBytes, frame.data?.chunk, limits);
351
+ }
352
+ if (frame.event === "agent") {
353
+ if (typeof frame.data?.delta === "string") {
354
+ stdoutBytes = appendOutput(stdoutParts, stdoutBytes, frame.data.delta, limits);
355
+ }
356
+ if (typeof frame.data?.text === "string") {
357
+ stdoutBytes = appendOutput(stdoutParts, stdoutBytes, frame.data.text, limits);
358
+ }
359
+ }
360
+ if (frame.event === "end") end = frame.data;
361
+ if (frame.event === "error") {
362
+ throw new Error(
363
+ `Open Design agent error: ${preview(frame.data?.message ?? frame.data, limits.maxDiagnosticBytes)}`,
364
+ );
365
+ }
366
+ }
367
+ }
368
+
369
+ if (buffer.trim()) {
370
+ throw new Error("Open Design SSE stream ended with an incomplete event");
371
+ }
372
+ if (end && typeof end.code === "number" && end.code !== 0) {
373
+ throw new Error(`Open Design agent exited with code ${end.code}\n${tailPreview(stderrParts.join(""), 1_000)}`);
374
+ }
375
+
376
+ return { stdout: stdoutParts.join(""), stderr: stderrParts.join(""), end, eventsCount };
377
+ } catch (error) {
378
+ budget.abort(error);
379
+ await reader.cancel().catch(() => {});
380
+ throw budget.errorOr(error);
381
+ } finally {
382
+ reader.releaseLock();
383
+ }
384
+ } finally {
385
+ budget.dispose();
386
+ }
387
+ }
@@ -1,4 +1,5 @@
1
1
  import { tool } from "@opencode-ai/plugin"
2
+ import { requestJson, streamOpenDesignChat } from "./open-design-http.mjs"
2
3
 
3
4
  type RuntimeGlobals = {
4
5
  process?: { env?: Record<string, string | undefined> }
@@ -46,31 +47,6 @@ function baseUrl(input?: string) {
46
47
  return url
47
48
  }
48
49
 
49
- async function requestJson(base: string, path: string, init: RequestInit = {}) {
50
- const res = await fetch(`${base}${path}`, {
51
- ...init,
52
- headers: {
53
- "Content-Type": "application/json",
54
- ...(init.headers || {}),
55
- },
56
- })
57
-
58
- const text = await res.text()
59
- let body: unknown = text
60
-
61
- try {
62
- body = text ? JSON.parse(text) : null
63
- } catch {
64
- body = text
65
- }
66
-
67
- if (!res.ok) {
68
- throw new Error(`Open Design ${path} failed (${res.status}): ${JSON.stringify(body, null, 2)}`)
69
- }
70
-
71
- return body
72
- }
73
-
74
50
  function safeSlug(input: string) {
75
51
  return input
76
52
  .toLowerCase()
@@ -126,83 +102,6 @@ function composeSystemPrompt(input: {
126
102
  ].join("\n")
127
103
  }
128
104
 
129
- function parseSseFrames(buffer: string) {
130
- const frames: Array<{ event: string; data: any }> = []
131
- let rest = buffer
132
-
133
- while (true) {
134
- const idx = rest.indexOf("\n\n")
135
- if (idx === -1) break
136
- const raw = rest.slice(0, idx)
137
- rest = rest.slice(idx + 2)
138
-
139
- let event = "message"
140
- let data = ""
141
- for (const line of raw.split("\n")) {
142
- if (line.startsWith("event: ")) event = line.slice(7).trim()
143
- if (line.startsWith("data: ")) data += line.slice(6)
144
- }
145
-
146
- try {
147
- frames.push({ event, data: JSON.parse(data) })
148
- } catch {
149
- frames.push({ event, data })
150
- }
151
- }
152
-
153
- return { frames, rest }
154
- }
155
-
156
- async function streamOpenDesignChat(base: string, body: unknown) {
157
- const res = await fetch(`${base}/api/chat`, {
158
- method: "POST",
159
- headers: { "Content-Type": "application/json" },
160
- body: JSON.stringify(body),
161
- })
162
-
163
- if (!res.ok || !res.body) {
164
- const text = await res.text().catch(() => "")
165
- throw new Error(`Open Design chat failed (${res.status}): ${text}`)
166
- }
167
-
168
- const reader = res.body.getReader()
169
- const decoder = new TextDecoder()
170
- let buffer = ""
171
- let stdout = ""
172
- let stderr = ""
173
- let end: any = null
174
- let eventsCount = 0
175
-
176
- while (true) {
177
- const { value, done } = await reader.read()
178
- if (done) break
179
-
180
- buffer += decoder.decode(value, { stream: true })
181
- const parsed = parseSseFrames(buffer)
182
- buffer = parsed.rest
183
-
184
- for (const frame of parsed.frames) {
185
- eventsCount += 1
186
- if (frame.event === "stdout") stdout += String(frame.data?.chunk ?? "")
187
- if (frame.event === "stderr") stderr += String(frame.data?.chunk ?? "")
188
- if (frame.event === "agent") {
189
- if (typeof frame.data?.delta === "string") stdout += frame.data.delta
190
- if (typeof frame.data?.text === "string") stdout += frame.data.text
191
- }
192
- if (frame.event === "end") end = frame.data
193
- if (frame.event === "error") {
194
- throw new Error(`Open Design agent error: ${String(frame.data?.message ?? JSON.stringify(frame.data))}`)
195
- }
196
- }
197
- }
198
-
199
- if (end && typeof end.code === "number" && end.code !== 0) {
200
- throw new Error(`Open Design agent exited with code ${end.code}\n${stderr.slice(-1000)}`)
201
- }
202
-
203
- return { stdout, stderr, end, eventsCount }
204
- }
205
-
206
105
  export const health = tool({
207
106
  description: "Check whether the Open Design workbench is reachable.",
208
107
  args: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-agent-orchestration-kit",
3
- "version": "1.0.38",
3
+ "version": "1.0.39",
4
4
  "private": false,
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -36,7 +36,7 @@
36
36
  "check:supply-chain": "node scripts/check-supply-chain.mjs",
37
37
  "contract-check": "bash scripts/check.sh",
38
38
  "unit-and-script-tests": "node --test scripts/*.test.mjs opencode/scripts/*.test.mjs",
39
- "typecheck": "npm --prefix opencode exec -- tsc --noEmit --jsx preserve --jsxImportSource @opentui/solid --module NodeNext --moduleResolution NodeNext --target ES2022 --strict --skipLibCheck opencode/plugins/token-tree-usage.tsx opencode/plugins/shell-export-guard.ts",
39
+ "typecheck": "npm --prefix opencode exec -- tsc --noEmit --jsx preserve --jsxImportSource @opentui/solid --module NodeNext --moduleResolution NodeNext --target ES2022 --strict --skipLibCheck opencode/plugins/token-tree-usage.tsx opencode/plugins/shell-export-guard.ts opencode/tools/open_design.ts",
40
40
  "dependency-audit": "npm --prefix opencode audit --omit=dev --audit-level=low",
41
41
  "dependency-signature-audit": "npm --prefix opencode audit signatures",
42
42
  "installation-smoke": "bash scripts/install-smoke.sh",
package/scripts/check.sh CHANGED
@@ -49,6 +49,8 @@ opencode/package-lock.json
49
49
  opencode/plugins/token-tree-usage.tsx
50
50
  opencode/plugins/shell-export-guard.ts
51
51
  opencode/tools/open_design.ts
52
+ opencode/tools/open-design-http.mjs
53
+ opencode/tools/open-design-http.d.mts
52
54
  opencode/scripts/check-harness.mjs
53
55
  opencode/scripts/shell-export-policy.mjs
54
56
  opencode/scripts/shell-export-policy.d.mts
@@ -0,0 +1,54 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import test from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ import { daemonArguments, parsePort } from "../docker/open-design/entrypoint.mjs";
10
+
11
+ const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
12
+ const ENTRYPOINT = path.join(ROOT, "docker/open-design/entrypoint.mjs");
13
+ const DOCKERFILE = path.join(ROOT, "docker/open-design/Dockerfile");
14
+
15
+ test("[OD001] parsePort accepts decimal ports in the valid range", () => {
16
+ for (const [raw, expected] of [["1", 1], ["7456", 7456], ["65535", 65535], ["07456", 7456]]) {
17
+ assert.equal(parsePort(raw), expected, raw);
18
+ }
19
+ });
20
+
21
+ for (const raw of ["", "0", "65536", "7456 ", " 7456", "+7456", "7456; touch marker", "7456\n--help"]) {
22
+ test(`[OD002] parsePort rejects unsafe value ${JSON.stringify(raw)}`, () => {
23
+ assert.throws(() => parsePort(raw), /OD_PORT.*1 and 65535/);
24
+ });
25
+ }
26
+
27
+ test("[OD003] daemon arguments keep the port as one argument", () => {
28
+ assert.deepEqual(daemonArguments(parsePort("7456")), [
29
+ "apps/daemon/dist/cli.js",
30
+ "--port",
31
+ "7456",
32
+ "--no-open",
33
+ ]);
34
+ });
35
+
36
+ test("[OD004] a shell metacharacter fails before any daemon can start", () => {
37
+ const marker = path.join(os.tmpdir(), `open-design-entrypoint-${process.pid}-marker`);
38
+ const result = spawnSync(process.execPath, [ENTRYPOINT], {
39
+ cwd: ROOT,
40
+ encoding: "utf8",
41
+ env: { ...process.env, OD_PORT: `7456; touch ${marker}` },
42
+ });
43
+
44
+ assert.equal(result.status, 1, result.stderr);
45
+ assert.match(result.stderr, /OD_PORT/);
46
+ assert.equal(fs.existsSync(marker), false);
47
+ });
48
+
49
+ test("[OD005] Docker uses an exec-form Node entrypoint without shell interpolation", () => {
50
+ const dockerfile = fs.readFileSync(DOCKERFILE, "utf8");
51
+ assert.match(dockerfile, /COPY entrypoint\.mjs \/usr\/local\/bin\/open-design-entrypoint\.mjs/);
52
+ assert.match(dockerfile, /ENTRYPOINT \["node", "\/usr\/local\/bin\/open-design-entrypoint\.mjs"\]/);
53
+ assert.doesNotMatch(dockerfile, /sh\s+-lc|\$\{OD_PORT/);
54
+ });
@@ -0,0 +1,211 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import test from "node:test";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const openDesign = await import("../opencode/tools/open-design-http.mjs");
8
+ const { requestJson, streamOpenDesignChat } = openDesign;
9
+ const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
10
+
11
+ function trackedStream(chunks, state = {}) {
12
+ let index = 0;
13
+ return new ReadableStream({
14
+ pull(controller) {
15
+ if (index < chunks.length) {
16
+ controller.enqueue(new TextEncoder().encode(chunks[index++]));
17
+ } else {
18
+ controller.close();
19
+ }
20
+ },
21
+ cancel() {
22
+ state.cancelled = true;
23
+ },
24
+ });
25
+ }
26
+
27
+ function chatResponse(chunks, state = {}) {
28
+ return new Response(trackedStream(chunks, state), { status: 200 });
29
+ }
30
+
31
+ function options(fetchImpl, overrides = {}) {
32
+ return { fetchImpl, ...overrides };
33
+ }
34
+
35
+ test("Open Design exposes bounded HTTP and SSE transport helpers", () => {
36
+ assert.equal(typeof requestJson, "function");
37
+ assert.equal(typeof streamOpenDesignChat, "function");
38
+ });
39
+
40
+ test("the Open Design tool delegates network reads to the bounded transport", () => {
41
+ const source = fs.readFileSync(path.join(ROOT, "opencode/tools/open_design.ts"), "utf8");
42
+ assert.match(source, /from ["']\.\/open-design-http\.mjs["']/);
43
+ assert.doesNotMatch(source, /await fetch\(/);
44
+ assert.doesNotMatch(source, /await res\.text\(/);
45
+ });
46
+
47
+ test("requestJson aborts a request that stalls before response headers", async () => {
48
+ await assert.rejects(
49
+ requestJson("http://open-design.test", "/api/health", {}, options(() => new Promise(() => {}), {
50
+ connectTimeoutMs: 100,
51
+ })),
52
+ /timed out while connecting/,
53
+ );
54
+ });
55
+
56
+ test("requestJson cancels an oversized response before parsing it", async () => {
57
+ const state = {};
58
+ const response = new Response(trackedStream(["x".repeat(2_048), "x"], state), {
59
+ status: 200,
60
+ headers: { "content-length": "2048" },
61
+ });
62
+
63
+ await assert.rejects(
64
+ requestJson("http://open-design.test", "/api/health", {}, options(async () => response, {
65
+ maxJsonBytes: 1_024,
66
+ })),
67
+ /response exceeds 1024 bytes/,
68
+ );
69
+ assert.equal(state.cancelled, true);
70
+ });
71
+
72
+ test("streamOpenDesignChat parses partial CRLF-framed SSE events", async () => {
73
+ const chunks = [
74
+ "event: stdout\r\ndata: {\"chunk\":\"hel",
75
+ "lo\"}\r\n\r\nevent: agent\r\ndata: {\"delta\":\" world\"}\r\n\r\nevent: end\r\ndata: {\"code\":0}\r\n\r\n",
76
+ ];
77
+
78
+ const result = await streamOpenDesignChat(
79
+ "http://open-design.test",
80
+ { prompt: "test" },
81
+ options(async () => chatResponse(chunks), { maxEvents: 10 }),
82
+ );
83
+
84
+ assert.equal(result.stdout, "hello world");
85
+ assert.equal(result.stderr, "");
86
+ assert.equal(result.eventsCount, 3);
87
+ assert.deepEqual(result.end, { code: 0 });
88
+ });
89
+
90
+ test("streamOpenDesignChat keeps the tail of bounded stderr on non-zero exit", async () => {
91
+ const stderr = `head-marker ${"x".repeat(1_500)} tail-marker`;
92
+ const frames = [
93
+ `event: stderr\ndata: ${JSON.stringify({ chunk: stderr })}\n\n`,
94
+ "event: end\ndata: {\"code\":2}\n\n",
95
+ ];
96
+
97
+ await assert.rejects(
98
+ streamOpenDesignChat(
99
+ "http://open-design.test",
100
+ { prompt: "test" },
101
+ options(async () => chatResponse(frames)),
102
+ ),
103
+ /tail-marker/,
104
+ );
105
+ });
106
+
107
+ test("streamOpenDesignChat cancels the reader when output exceeds its cap", async () => {
108
+ const state = {};
109
+ const frame = `event: stdout\ndata: ${JSON.stringify({ chunk: "x".repeat(1_500) })}\n\n`;
110
+
111
+ await assert.rejects(
112
+ streamOpenDesignChat(
113
+ "http://open-design.test",
114
+ { prompt: "test" },
115
+ options(async () => chatResponse([frame, frame], state), { maxOutputBytes: 1_024 }),
116
+ ),
117
+ /stdout\/stderr output exceeds 1024 bytes/,
118
+ );
119
+ assert.equal(state.cancelled, true);
120
+ });
121
+
122
+ test("streamOpenDesignChat rejects an oversized SSE body and cancels the reader", async () => {
123
+ const state = {};
124
+ const oversizedComment = `: ${"x".repeat(1_500)}\n\n`;
125
+
126
+ await assert.rejects(
127
+ streamOpenDesignChat(
128
+ "http://open-design.test",
129
+ { prompt: "test" },
130
+ options(async () => chatResponse([oversizedComment, oversizedComment], state), {
131
+ maxSseBytes: 1_024,
132
+ }),
133
+ ),
134
+ /SSE response exceeds 1024 bytes/,
135
+ );
136
+ assert.equal(state.cancelled, true);
137
+ });
138
+
139
+ test("streamOpenDesignChat rejects an excessive event count and cancels the reader", async () => {
140
+ const state = {};
141
+ const frame = "event: stdout\ndata: {\"chunk\":\"x\"}\n\n";
142
+
143
+ await assert.rejects(
144
+ streamOpenDesignChat(
145
+ "http://open-design.test",
146
+ { prompt: "test" },
147
+ options(async () => chatResponse([frame + frame + frame, frame], state), { maxEvents: 2 }),
148
+ ),
149
+ /SSE event count exceeds 2/,
150
+ );
151
+ assert.equal(state.cancelled, true);
152
+ });
153
+
154
+ test("streamOpenDesignChat cancels an idle stream deterministically", async () => {
155
+ const state = {};
156
+ const response = new Response(new ReadableStream({
157
+ pull() {
158
+ return new Promise(() => {});
159
+ },
160
+ cancel() {
161
+ state.cancelled = true;
162
+ },
163
+ }), { status: 200 });
164
+
165
+ await assert.rejects(
166
+ streamOpenDesignChat(
167
+ "http://open-design.test",
168
+ { prompt: "test" },
169
+ options(async () => response, { idleTimeoutMs: 100, totalTimeoutMs: 2_000 }),
170
+ ),
171
+ /timed out while reading/,
172
+ );
173
+ assert.equal(state.cancelled, true);
174
+ });
175
+
176
+ test("streamOpenDesignChat enforces the total request timeout", async () => {
177
+ const state = {};
178
+ const response = new Response(new ReadableStream({
179
+ pull() {
180
+ return new Promise(() => {});
181
+ },
182
+ cancel() {
183
+ state.cancelled = true;
184
+ },
185
+ }), { status: 200 });
186
+
187
+ await assert.rejects(
188
+ streamOpenDesignChat(
189
+ "http://open-design.test",
190
+ { prompt: "test" },
191
+ options(async () => response, { idleTimeoutMs: 2_000, totalTimeoutMs: 1_000 }),
192
+ ),
193
+ /Open Design request timed out$/,
194
+ );
195
+ assert.equal(state.cancelled, true);
196
+ });
197
+
198
+ test("streamOpenDesignChat cancels the reader on an agent error event", async () => {
199
+ const state = {};
200
+ const errorFrame = "event: error\ndata: {\"message\":\"upstream failed\"}\n\n";
201
+
202
+ await assert.rejects(
203
+ streamOpenDesignChat(
204
+ "http://open-design.test",
205
+ { prompt: "test" },
206
+ options(async () => chatResponse([errorFrame, "event: stdout\ndata: {}\n\n"], state)),
207
+ ),
208
+ /Open Design agent error: upstream failed/,
209
+ );
210
+ assert.equal(state.cancelled, true);
211
+ });
@@ -17,7 +17,7 @@ import {
17
17
 
18
18
  const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
19
19
  const HASH = "a".repeat(64);
20
- const BASENAME = "opencode-agent-orchestration-kit-1.0.38.tgz";
20
+ const BASENAME = "opencode-agent-orchestration-kit-1.0.39.tgz";
21
21
  const REQUIRED = [
22
22
  "package/package.json",
23
23
  "package/supply-chain.json",
@@ -210,7 +210,7 @@ test("smokeTarball validates both archive listings before extraction", async ()
210
210
  await assert.rejects(
211
211
  smokeTarball({
212
212
  repositoryRoot: ROOT,
213
- tarball: "/public/opencode-agent-orchestration-kit-1.0.38.tgz",
213
+ tarball: "/public/opencode-agent-orchestration-kit-1.0.39.tgz",
214
214
  captureTarball(_source, destination) {
215
215
  fs.writeFileSync(destination, "fixture");
216
216
  return { size: 1 };
@@ -109,7 +109,7 @@ test("[V004] direct version entrypoints are exact and mutation-free", (t) => {
109
109
  for (const args of [["scripts/version.mjs"], ["scripts/manage-installation.mjs", "--version"]]) {
110
110
  const result = run(process.execPath, args, { HOME: home });
111
111
  assert.equal(result.status, 0, result.stderr);
112
- assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.38\n");
112
+ assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.39\n");
113
113
  assert.equal(fs.existsSync(target), false);
114
114
  }
115
115
  });
@@ -118,7 +118,7 @@ test("[V005] all lifecycle wrappers expose the canonical version", () => {
118
118
  for (const wrapper of ["install.sh", "upgrade.sh", "doctor.sh", "uninstall.sh", "rollback.sh"]) {
119
119
  const result = run(path.join(REPOSITORY_ROOT, wrapper), ["--version"]);
120
120
  assert.equal(result.status, 0, `${wrapper}: ${result.stderr}`);
121
- assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.38\n", wrapper);
121
+ assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.39\n", wrapper);
122
122
  }
123
123
  });
124
124