@llmguard/opencode 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/MANUAL-TEST-G.md +167 -0
  2. package/README.md +334 -2
  3. package/RELEASE.md +122 -0
  4. package/bin/darwin-amd64/helper +0 -0
  5. package/bin/darwin-arm64/helper +0 -0
  6. package/bin/linux-amd64/helper +0 -0
  7. package/bin/linux-arm64/helper +0 -0
  8. package/bin/manifest.json +51 -0
  9. package/bin/windows-amd64/helper.exe +0 -0
  10. package/bin/windows-arm64/helper.exe +0 -0
  11. package/bridge/client.d.ts +55 -0
  12. package/bridge/client.js +425 -0
  13. package/bridge/framing.d.ts +19 -0
  14. package/bridge/framing.js +110 -0
  15. package/bridge/process.d.ts +38 -0
  16. package/bridge/process.js +378 -0
  17. package/bridge/protocol.d.ts +184 -0
  18. package/bridge/protocol.js +683 -0
  19. package/connection-catalog.d.ts +69 -0
  20. package/connection-catalog.js +287 -0
  21. package/connections-tui.d.ts +11 -0
  22. package/connections-tui.js +394 -0
  23. package/demasking.d.ts +2 -0
  24. package/demasking.js +445 -0
  25. package/gui-experimental.cjs +33 -0
  26. package/hook-trace.d.ts +2 -0
  27. package/hook-trace.js +35 -0
  28. package/index.d.ts +1 -0
  29. package/index.js +1 -0
  30. package/licenses/Go-LICENSE +27 -0
  31. package/messages.d.ts +230 -0
  32. package/messages.js +231 -0
  33. package/native/index.d.ts +1 -0
  34. package/native/index.js +1 -0
  35. package/native/tui.d.ts +1 -0
  36. package/native/tui.js +1 -0
  37. package/package.json +49 -4
  38. package/plugin-runtime.d.ts +3 -0
  39. package/plugin-runtime.js +3 -0
  40. package/plugin-settings.d.ts +77 -0
  41. package/plugin-settings.js +487 -0
  42. package/plugin.d.ts +41 -0
  43. package/plugin.js +10 -0
  44. package/response-diagnostics.d.ts +13 -0
  45. package/response-diagnostics.js +142 -0
  46. package/runtime/attachments.d.ts +4 -0
  47. package/runtime/attachments.js +19 -0
  48. package/runtime/errors.d.ts +18 -0
  49. package/runtime/errors.js +26 -0
  50. package/runtime/json.d.ts +14 -0
  51. package/runtime/json.js +243 -0
  52. package/runtime/limits.d.ts +2 -0
  53. package/runtime/limits.js +3 -0
  54. package/runtime/native-edit.d.ts +14 -0
  55. package/runtime/native-edit.js +73 -0
  56. package/runtime/runtime.d.ts +43 -0
  57. package/runtime/runtime.js +345 -0
  58. package/runtime/session-state.d.ts +13 -0
  59. package/runtime/session-state.js +73 -0
  60. package/runtime/text-layout.d.ts +9 -0
  61. package/runtime/text-layout.js +47 -0
  62. package/server.d.ts +1 -0
  63. package/server.js +1 -0
  64. package/settings-rpc.d.ts +511 -0
  65. package/settings-rpc.js +197 -0
  66. package/tui-messages.d.ts +1 -0
  67. package/tui-messages.js +84 -0
  68. package/tui.d.ts +17 -0
  69. package/tui.js +427 -0
  70. package/v1/hooks.d.ts +81 -0
  71. package/v1/hooks.js +97 -0
  72. package/v1/projection.d.ts +32 -0
  73. package/v1/projection.js +217 -0
  74. package/v1.d.ts +2 -0
  75. package/v1.js +2 -0
  76. package/v2/projection.d.ts +36 -0
  77. package/v2/projection.js +374 -0
  78. package/v2/server.d.ts +6 -0
  79. package/v2/server.js +633 -0
@@ -0,0 +1,19 @@
1
+ import type { Writable } from "node:stream";
2
+ export declare class FrameDecoder {
3
+ private header;
4
+ private headerUsed;
5
+ private payload;
6
+ private used;
7
+ private broken;
8
+ push(chunk: Uint8Array): Buffer[];
9
+ finish(): void;
10
+ }
11
+ export declare class FrameWriter {
12
+ private readonly stream;
13
+ private queued;
14
+ private broken;
15
+ private tail;
16
+ private readonly onError;
17
+ constructor(stream: Writable);
18
+ write(payload: Uint8Array): Promise<void>;
19
+ }
@@ -0,0 +1,110 @@
1
+ import { limits, maxFrame, ProtocolError } from "./protocol.js";
2
+ // Incremental framing keeps at most one bounded payload plus its header.
3
+ // Consumers must dispatch returned frames before admitting more input.
4
+ export class FrameDecoder {
5
+ header = Buffer.alloc(4);
6
+ headerUsed = 0;
7
+ payload;
8
+ used = 0;
9
+ broken = false;
10
+ push(chunk) {
11
+ if (this.broken) {
12
+ throw new ProtocolError("invalid_state");
13
+ }
14
+ const frames = [];
15
+ let offset = 0;
16
+ while (offset < chunk.byteLength) {
17
+ if (!this.payload) {
18
+ const n = Math.min(4 - this.headerUsed, chunk.byteLength - offset);
19
+ this.header.set(chunk.subarray(offset, offset + n), this.headerUsed);
20
+ this.headerUsed += n;
21
+ offset += n;
22
+ if (this.headerUsed < 4) {
23
+ continue;
24
+ }
25
+ const length = this.header.readUInt32BE();
26
+ if (length === 0 || length > maxFrame) {
27
+ this.broken = true;
28
+ throw new ProtocolError("invalid_envelope");
29
+ }
30
+ this.payload = Buffer.alloc(length);
31
+ this.used = 0;
32
+ }
33
+ const n = Math.min(this.payload.length - this.used, chunk.byteLength - offset);
34
+ this.payload.set(chunk.subarray(offset, offset + n), this.used);
35
+ this.used += n;
36
+ offset += n;
37
+ if (this.used === this.payload.length) {
38
+ frames.push(this.payload);
39
+ this.payload = undefined;
40
+ this.headerUsed = 0;
41
+ this.used = 0;
42
+ }
43
+ }
44
+ return frames;
45
+ }
46
+ finish() {
47
+ if (this.broken || this.headerUsed !== 0 || this.payload) {
48
+ this.broken = true;
49
+ throw new ProtocolError("invalid_envelope");
50
+ }
51
+ this.broken = true;
52
+ }
53
+ }
54
+ // One callback-confirmed write at a time; the bound includes the active frame.
55
+ // Caller owns stream lifecycle and cancels all operations on transport failure.
56
+ export class FrameWriter {
57
+ stream;
58
+ queued = 0;
59
+ broken = false;
60
+ tail = Promise.resolve();
61
+ onError = () => {
62
+ this.broken = true;
63
+ };
64
+ constructor(stream) {
65
+ this.stream = stream;
66
+ stream.on("error", this.onError);
67
+ }
68
+ write(payload) {
69
+ if (this.broken || this.stream.destroyed) {
70
+ return Promise.reject(new ProtocolError("invalid_state"));
71
+ }
72
+ if (payload.byteLength === 0 || payload.byteLength > maxFrame) {
73
+ return Promise.reject(new ProtocolError("invalid_envelope"));
74
+ }
75
+ const length = payload.byteLength + 4;
76
+ if (this.queued + length > limits.max_writer_queue_bytes) {
77
+ return Promise.reject(new ProtocolError("resource_exhausted"));
78
+ }
79
+ const frame = Buffer.alloc(length);
80
+ frame.writeUInt32BE(payload.byteLength);
81
+ frame.set(payload, 4);
82
+ this.queued += length;
83
+ const pending = this.tail.then(async () => {
84
+ if (this.broken || this.stream.destroyed) {
85
+ throw new ProtocolError("invalid_state");
86
+ }
87
+ await new Promise((resolve, reject) => {
88
+ try {
89
+ this.stream.write(frame, (error) => {
90
+ if (error) {
91
+ this.broken = true;
92
+ reject(new ProtocolError("invalid_state"));
93
+ }
94
+ else {
95
+ resolve();
96
+ }
97
+ });
98
+ }
99
+ catch {
100
+ this.broken = true;
101
+ reject(new ProtocolError("invalid_state"));
102
+ }
103
+ });
104
+ });
105
+ this.tail = pending.catch(() => { });
106
+ return pending.finally(() => {
107
+ this.queued -= length;
108
+ });
109
+ }
110
+ }
@@ -0,0 +1,38 @@
1
+ import type { Method, Params, Results } from "./protocol.js";
2
+ export declare function helperURL(platform?: string, arch?: string): URL;
3
+ export interface RequestOptions {
4
+ deadline: number;
5
+ signal?: AbortSignal;
6
+ }
7
+ export declare class HelperProcess {
8
+ private readonly onFailure;
9
+ private readonly child;
10
+ private readonly writer;
11
+ private readonly decoder;
12
+ private readonly pending;
13
+ private ordinary;
14
+ private controls;
15
+ private readonly jobs;
16
+ private queuedBytes;
17
+ private nextID;
18
+ private pumping;
19
+ private dead;
20
+ private closing;
21
+ private closed;
22
+ private readonly exited;
23
+ private stopPromise;
24
+ private processEpoch;
25
+ constructor(url: URL, onFailure: () => void);
26
+ get epoch(): string;
27
+ handshake(timeoutMS?: number): Promise<void>;
28
+ request<M extends Method>(method: M, params: Params[M], options: RequestOptions): Promise<Results[M]>;
29
+ private pump;
30
+ private releaseBytes;
31
+ private settle;
32
+ private cancel;
33
+ private receive;
34
+ private fail;
35
+ terminate(): Promise<void>;
36
+ stop(): Promise<void>;
37
+ private stopGracefully;
38
+ }
@@ -0,0 +1,378 @@
1
+ import { spawn } from "node:child_process";
2
+ import { isAbsolute } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { FrameDecoder, FrameWriter } from "./framing.js";
5
+ import { decodeEnvelope, decodeParams, decodeResult, limits, maxBudgetMS, ProtocolError, } from "./protocol.js";
6
+ export function helperURL(platform = process.platform, arch = process.arch) {
7
+ if (!["linux", "darwin", "win32"].includes(platform) ||
8
+ !["x64", "arm64"].includes(arch)) {
9
+ throw new ProtocolError("invalid_state");
10
+ }
11
+ const os = platform === "win32" ? "windows" : platform;
12
+ const cpu = arch === "x64" ? "amd64" : "arm64";
13
+ return new URL(`../bin/${os}-${cpu}/helper${os === "windows" ? ".exe" : ""}`, import.meta.url);
14
+ }
15
+ // Internal transport, never a package export or hook option. URL injection is
16
+ // used only by process/protocol failure tests; production uses helperURL().
17
+ export class HelperProcess {
18
+ onFailure;
19
+ child;
20
+ writer;
21
+ decoder = new FrameDecoder();
22
+ pending = new Map();
23
+ ordinary = [];
24
+ controls = [];
25
+ jobs = new Set();
26
+ queuedBytes = 0;
27
+ nextID = 0;
28
+ pumping = false;
29
+ dead = false;
30
+ closing = false;
31
+ closed = false;
32
+ exited;
33
+ stopPromise;
34
+ processEpoch = "";
35
+ constructor(url, onFailure) {
36
+ this.onFailure = onFailure;
37
+ const path = fileURLToPath(url);
38
+ if (!isAbsolute(path)) {
39
+ throw new ProtocolError("invalid_state");
40
+ }
41
+ try {
42
+ this.child = spawn(path, [], {
43
+ shell: false,
44
+ windowsHide: true,
45
+ stdio: ["pipe", "pipe", "pipe"],
46
+ });
47
+ }
48
+ catch {
49
+ throw new ProtocolError("invalid_state");
50
+ }
51
+ this.writer = new FrameWriter(this.child.stdin);
52
+ this.exited = new Promise((resolve) => {
53
+ this.child.once("close", () => {
54
+ this.closed = true;
55
+ resolve();
56
+ });
57
+ });
58
+ // Drain without retaining, decoding or logging untrusted stderr.
59
+ this.child.stderr.resume();
60
+ this.child.on("error", () => this.fail("invalid_state"));
61
+ this.child.stdin.on("error", () => this.fail("invalid_state"));
62
+ this.child.stdout.on("error", () => this.fail("invalid_state"));
63
+ this.child.stdout.on("data", (chunk) => {
64
+ if (this.dead) {
65
+ return;
66
+ }
67
+ try {
68
+ for (const frame of this.decoder.push(chunk)) {
69
+ this.receive(frame);
70
+ }
71
+ }
72
+ catch {
73
+ this.fail("invalid_envelope");
74
+ }
75
+ });
76
+ this.child.stdout.on("end", () => {
77
+ try {
78
+ this.decoder.finish();
79
+ }
80
+ catch {
81
+ this.fail("invalid_envelope");
82
+ return;
83
+ }
84
+ if (!this.closing) {
85
+ this.fail("invalid_state");
86
+ }
87
+ });
88
+ this.child.on("exit", () => {
89
+ if (!this.closing) {
90
+ this.fail("invalid_state");
91
+ }
92
+ });
93
+ }
94
+ get epoch() {
95
+ return this.processEpoch;
96
+ }
97
+ async handshake(timeoutMS = 5000) {
98
+ if (!Number.isFinite(timeoutMS) || timeoutMS <= 0 || timeoutMS > 5000) {
99
+ throw new ProtocolError("invalid_params");
100
+ }
101
+ const result = await this.request("hello", {
102
+ protocols: [1],
103
+ required_features: ["ipc.v1", "restoration"],
104
+ }, { deadline: performance.now() + timeoutMS });
105
+ if (!["ipc.v1", "restoration"].every((f) => result.features.includes(f))) {
106
+ this.fail("unsupported_protocol");
107
+ throw new ProtocolError("unsupported_protocol");
108
+ }
109
+ }
110
+ request(method, params, options) {
111
+ if (this.dead || (this.closing && method !== "shutdown")) {
112
+ return Promise.reject(new ProtocolError("invalid_state"));
113
+ }
114
+ if (!Number.isFinite(options.deadline) ||
115
+ options.deadline <= performance.now()) {
116
+ return Promise.reject(new ProtocolError("timeout"));
117
+ }
118
+ if (options.deadline - performance.now() > maxBudgetMS) {
119
+ return Promise.reject(new ProtocolError("invalid_params"));
120
+ }
121
+ if (options.signal?.aborted) {
122
+ return Promise.reject(new ProtocolError("cancelled"));
123
+ }
124
+ const control = method !== "operation.check" && method !== "connection.test";
125
+ const count = [...this.jobs].filter((j) => j.control === control).length;
126
+ if (count >= (control ? 64 : limits.max_pending)) {
127
+ return Promise.reject(new ProtocolError("resource_exhausted"));
128
+ }
129
+ let snapshot;
130
+ let bytes;
131
+ try {
132
+ snapshot = structuredClone(params);
133
+ decodeParams(method, snapshot);
134
+ bytes = Buffer.byteLength(JSON.stringify(snapshot)) + 300;
135
+ }
136
+ catch {
137
+ return Promise.reject(new ProtocolError("invalid_params"));
138
+ }
139
+ if (bytes + this.queuedBytes > limits.max_writer_queue_bytes) {
140
+ return Promise.reject(new ProtocolError("resource_exhausted"));
141
+ }
142
+ return new Promise((resolve, reject) => {
143
+ const job = {
144
+ method,
145
+ params: snapshot,
146
+ deadline: options.deadline,
147
+ signal: options.signal,
148
+ resolve: (value) => resolve(value),
149
+ reject,
150
+ timer: setTimeout(() => this.cancel(job, "timeout"), Math.max(1, options.deadline - performance.now())),
151
+ abort: () => this.cancel(job, "cancelled"),
152
+ settled: false,
153
+ bytes,
154
+ control,
155
+ };
156
+ this.jobs.add(job);
157
+ this.queuedBytes += bytes;
158
+ options.signal?.addEventListener("abort", job.abort, { once: true });
159
+ (control ? this.controls : this.ordinary).push(job);
160
+ void this.pump();
161
+ });
162
+ }
163
+ async pump() {
164
+ if (this.pumping || this.dead) {
165
+ return;
166
+ }
167
+ this.pumping = true;
168
+ try {
169
+ for (;;) {
170
+ const job = this.controls.shift() ?? this.ordinary.shift();
171
+ if (!job || this.dead) {
172
+ break;
173
+ }
174
+ if (job.settled) {
175
+ continue;
176
+ }
177
+ if (job.deadline <= performance.now() || job.signal?.aborted) {
178
+ this.cancel(job, job.signal?.aborted ? "cancelled" : "timeout");
179
+ continue;
180
+ }
181
+ if (this.nextID >= Number.MAX_SAFE_INTEGER) {
182
+ this.fail("invalid_state");
183
+ break;
184
+ }
185
+ if (job.method === "operation.check" ||
186
+ job.method === "connection.test") {
187
+ const remaining = Math.floor(job.deadline - performance.now());
188
+ if (remaining <= 0 || remaining > maxBudgetMS) {
189
+ this.cancel(job, "timeout");
190
+ continue;
191
+ }
192
+ job.params.budget_ms = remaining;
193
+ }
194
+ // Assign only as this frame becomes the next write. Priority controls
195
+ // therefore cannot overtake an already assigned smaller request ID.
196
+ job.id = `r-${++this.nextID}`;
197
+ this.pending.set(job.id, job);
198
+ const raw = Buffer.from(JSON.stringify({
199
+ v: 1,
200
+ kind: "request",
201
+ id: job.id,
202
+ epoch: this.processEpoch,
203
+ method: job.method,
204
+ params: job.params,
205
+ }));
206
+ try {
207
+ await this.writer.write(raw);
208
+ }
209
+ catch {
210
+ this.fail("invalid_state");
211
+ break;
212
+ }
213
+ finally {
214
+ this.releaseBytes(job);
215
+ }
216
+ }
217
+ }
218
+ finally {
219
+ this.pumping = false;
220
+ }
221
+ }
222
+ releaseBytes(job) {
223
+ this.queuedBytes -= job.bytes;
224
+ job.bytes = 0;
225
+ }
226
+ settle(job, value, error) {
227
+ if (job.settled) {
228
+ return;
229
+ }
230
+ job.settled = true;
231
+ clearTimeout(job.timer);
232
+ job.signal?.removeEventListener("abort", job.abort);
233
+ this.jobs.delete(job);
234
+ if (job.id) {
235
+ this.pending.delete(job.id);
236
+ }
237
+ else {
238
+ this.ordinary = this.ordinary.filter((j) => j !== job);
239
+ this.controls = this.controls.filter((j) => j !== job);
240
+ this.releaseBytes(job);
241
+ }
242
+ if (error) {
243
+ job.reject(error);
244
+ }
245
+ else {
246
+ job.resolve(value);
247
+ }
248
+ }
249
+ cancel(job, code) {
250
+ if (job.settled) {
251
+ return;
252
+ }
253
+ const target = job.id;
254
+ this.settle(job, undefined, new ProtocolError(code));
255
+ if (target &&
256
+ (job.method === "operation.check" || job.method === "connection.test") &&
257
+ !this.dead &&
258
+ !this.closing) {
259
+ void this.request("operation.cancel", { target }, { deadline: performance.now() + 1000 }).catch(() => { });
260
+ }
261
+ }
262
+ receive(raw) {
263
+ const envelope = decodeEnvelope(raw);
264
+ if (envelope.kind !== "response") {
265
+ this.fail("invalid_envelope");
266
+ return;
267
+ }
268
+ const job = this.pending.get(envelope.id);
269
+ if (!job) {
270
+ // Timed out/cancelled/consumed IDs are never reused. A late response can
271
+ // only be discarded; an ID never issued by this process is a failure.
272
+ const n = /^r-([1-9][0-9]*)$/.exec(envelope.id)?.[1];
273
+ if (!n || !Number.isSafeInteger(Number(n)) || Number(n) > this.nextID) {
274
+ this.fail("invalid_state");
275
+ }
276
+ return;
277
+ }
278
+ if (job.deadline <= performance.now() || job.signal?.aborted) {
279
+ this.cancel(job, job.signal?.aborted ? "cancelled" : "timeout");
280
+ return;
281
+ }
282
+ if (job.method !== "hello" && envelope.epoch !== this.processEpoch) {
283
+ this.fail("invalid_state");
284
+ return;
285
+ }
286
+ if (!envelope.ok) {
287
+ this.settle(job, undefined, new ProtocolError(envelope.error.code));
288
+ return;
289
+ }
290
+ const result = decodeResult(job.method, envelope.result);
291
+ if (job.method === "hello") {
292
+ const hello = result;
293
+ if (this.processEpoch !== "" || envelope.epoch !== hello.epoch) {
294
+ this.fail("invalid_state");
295
+ return;
296
+ }
297
+ this.processEpoch = hello.epoch;
298
+ }
299
+ if (job.method === "operation.check") {
300
+ const check = result;
301
+ const params = job.params;
302
+ const localRoute = params.route_path !== undefined &&
303
+ params.route_path !== "/route-status" &&
304
+ check.local_route === true &&
305
+ (check.decision === "deny" || check.decision === "transform");
306
+ if (check.generation !== params.generation ||
307
+ (params.route_path !== undefined &&
308
+ params.route_path !== "/route-status" &&
309
+ check.authorization !== "blocked" &&
310
+ check.authorization !== "observed" &&
311
+ params.session_id !== undefined &&
312
+ check.local_route === false &&
313
+ check.route_lease === undefined) ||
314
+ (check.route_lease !== undefined &&
315
+ (params.route_path === undefined ||
316
+ params.route_path === "/route-status")) ||
317
+ (check.authorization === "allow" &&
318
+ (check.check_code !== "success" ||
319
+ (check.decision !== "allow" && !localRoute))) ||
320
+ (check.authorization === "transformed" &&
321
+ (check.check_code !== "success" || check.decision !== "transform"))) {
322
+ this.fail("invalid_state");
323
+ return;
324
+ }
325
+ }
326
+ this.settle(job, result);
327
+ }
328
+ fail(code) {
329
+ if (this.dead) {
330
+ return;
331
+ }
332
+ this.dead = true;
333
+ for (const job of [...this.jobs]) {
334
+ this.settle(job, undefined, new ProtocolError(code));
335
+ }
336
+ this.child.kill("SIGKILL");
337
+ if (!this.closing) {
338
+ this.onFailure();
339
+ }
340
+ }
341
+ async terminate() {
342
+ this.closing = true;
343
+ this.fail("cancelled");
344
+ if (!this.closed) {
345
+ this.child.kill("SIGKILL");
346
+ }
347
+ await this.exited;
348
+ }
349
+ stop() {
350
+ if (this.stopPromise) {
351
+ return this.stopPromise;
352
+ }
353
+ this.stopPromise = this.stopGracefully();
354
+ return this.stopPromise;
355
+ }
356
+ async stopGracefully() {
357
+ this.closing = true;
358
+ for (const job of [...this.jobs]) {
359
+ this.settle(job, undefined, new ProtocolError("cancelled"));
360
+ }
361
+ if (this.dead || this.closed) {
362
+ await this.terminate();
363
+ return;
364
+ }
365
+ const force = setTimeout(() => {
366
+ void this.terminate();
367
+ }, 2000);
368
+ try {
369
+ await this.request("shutdown", {}, { deadline: performance.now() + 1000 }).catch(() => { });
370
+ this.child.stdin.end();
371
+ await this.exited;
372
+ }
373
+ finally {
374
+ clearTimeout(force);
375
+ this.dead = true;
376
+ }
377
+ }
378
+ }