opencode-agent-orchestration-kit 1.0.38 → 1.0.40

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.
Files changed (49) hide show
  1. package/README.md +12 -3
  2. package/docker/open-design/Dockerfile +3 -1
  3. package/docker/open-design/entrypoint.mjs +61 -0
  4. package/docs/docker-open-design.md +5 -0
  5. package/docs/models.md +1 -1
  6. package/docs/open-design.md +8 -0
  7. package/docs/performance/native-tools-benchmark.md +33 -0
  8. package/docs/releases/v1.0.39.md +44 -0
  9. package/docs/releases/v1.0.40.md +55 -0
  10. package/docs/sync-boundary.md +27 -0
  11. package/opencode/commands/loop-status.md +24 -0
  12. package/opencode/commands/loop.md +8 -0
  13. package/opencode/docs/ai/harness/agents.md +8 -0
  14. package/opencode/docs/ai/harness/checks.md +6 -0
  15. package/opencode/docs/ai/harness/commands.md +10 -0
  16. package/opencode/docs/ai/harness/orchestration-contracts.json +9 -1
  17. package/opencode/docs/ai/specs/mission-runtime.md +44 -0
  18. package/opencode/plugins/mission-runtime.test.mjs +46 -0
  19. package/opencode/plugins/mission-runtime.ts +41 -0
  20. package/opencode/scripts/check-harness.mjs +111 -0
  21. package/opencode/scripts/check-harness.test.mjs +37 -1
  22. package/opencode/scripts/loop-state.mjs +5 -0
  23. package/opencode/scripts/loop-state.test.mjs +13 -0
  24. package/opencode/scripts/mission-runtime-observer.d.mts +25 -0
  25. package/opencode/scripts/mission-runtime-observer.mjs +124 -0
  26. package/opencode/scripts/mission-runtime.test.mjs +97 -0
  27. package/opencode/scripts/mission-status.mjs +136 -0
  28. package/opencode/scripts/mission-status.test.mjs +196 -0
  29. package/opencode/scripts/project-capability-snapshot.mjs +2 -1
  30. package/opencode/scripts/project-capability-snapshot.test.mjs +17 -0
  31. package/opencode/scripts/runtime-permission-policy.mjs +72 -0
  32. package/opencode/scripts/runtime-permission-policy.test.mjs +89 -0
  33. package/opencode/tools/open-design-http.d.mts +45 -0
  34. package/opencode/tools/open-design-http.mjs +387 -0
  35. package/opencode/tools/open_design.ts +2 -103
  36. package/package.json +3 -3
  37. package/scripts/benchmark-tool-paths.mjs +226 -0
  38. package/scripts/benchmark-tool-paths.test.mjs +29 -0
  39. package/scripts/check-public-boundary.mjs +89 -0
  40. package/scripts/check-public-boundary.test.mjs +32 -0
  41. package/scripts/check.sh +17 -10
  42. package/scripts/install-smoke.sh +17 -0
  43. package/scripts/manage-installation.mjs +90 -7
  44. package/scripts/manage-installation.test.mjs +36 -0
  45. package/scripts/open-design-entrypoint.test.mjs +54 -0
  46. package/scripts/open-design-http.test.mjs +211 -0
  47. package/scripts/package-smoke.mjs +52 -3
  48. package/scripts/package-smoke.test.mjs +6 -6
  49. package/scripts/version.test.mjs +2 -2
@@ -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> }
@@ -39,38 +40,13 @@ function baseUrl(input?: string) {
39
40
  }
40
41
 
41
42
  const url = raw.replace(/\/+$/, "")
42
- if (/\/projects\//.test(url)) {
43
+ if (/\/projects(?:\/|$)/.test(url)) {
43
44
  throw new Error("OPEN_DESIGN_URL must be the Open Design base URL, not a project or file URL.")
44
45
  }
45
46
 
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.40",
4
4
  "private": false,
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -35,8 +35,8 @@
35
35
  "check:compatibility": "node scripts/check-compatibility.mjs",
36
36
  "check:supply-chain": "node scripts/check-supply-chain.mjs",
37
37
  "contract-check": "bash scripts/check.sh",
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",
38
+ "unit-and-script-tests": "node --test scripts/*.test.mjs opencode/scripts/*.test.mjs opencode/plugins/mission-runtime.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 opencode/plugins/mission-runtime.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",