@llmguard/opencode 0.0.0-stage → 0.1.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.
Files changed (77) hide show
  1. package/README.md +53 -2
  2. package/bin/darwin-amd64/helper +0 -0
  3. package/bin/darwin-arm64/helper +0 -0
  4. package/bin/linux-amd64/helper +0 -0
  5. package/bin/linux-arm64/helper +0 -0
  6. package/bin/manifest.json +51 -0
  7. package/bin/windows-amd64/helper.exe +0 -0
  8. package/bin/windows-arm64/helper.exe +0 -0
  9. package/bridge/client.d.ts +55 -0
  10. package/bridge/client.js +425 -0
  11. package/bridge/framing.d.ts +19 -0
  12. package/bridge/framing.js +110 -0
  13. package/bridge/process.d.ts +38 -0
  14. package/bridge/process.js +378 -0
  15. package/bridge/protocol.d.ts +184 -0
  16. package/bridge/protocol.js +683 -0
  17. package/connection-catalog.d.ts +69 -0
  18. package/connection-catalog.js +287 -0
  19. package/connections-tui.d.ts +11 -0
  20. package/connections-tui.js +394 -0
  21. package/demasking.d.ts +2 -0
  22. package/demasking.js +445 -0
  23. package/gui-experimental.cjs +33 -0
  24. package/hook-trace.d.ts +2 -0
  25. package/hook-trace.js +35 -0
  26. package/index.d.ts +1 -0
  27. package/index.js +1 -0
  28. package/licenses/Go-LICENSE +27 -0
  29. package/messages.d.ts +230 -0
  30. package/messages.js +231 -0
  31. package/native/index.d.ts +1 -0
  32. package/native/index.js +1 -0
  33. package/native/tui.d.ts +1 -0
  34. package/native/tui.js +1 -0
  35. package/package.json +47 -4
  36. package/plugin-runtime.d.ts +3 -0
  37. package/plugin-runtime.js +3 -0
  38. package/plugin-settings.d.ts +77 -0
  39. package/plugin-settings.js +487 -0
  40. package/plugin.d.ts +41 -0
  41. package/plugin.js +10 -0
  42. package/response-diagnostics.d.ts +13 -0
  43. package/response-diagnostics.js +142 -0
  44. package/runtime/attachments.d.ts +4 -0
  45. package/runtime/attachments.js +19 -0
  46. package/runtime/errors.d.ts +18 -0
  47. package/runtime/errors.js +26 -0
  48. package/runtime/json.d.ts +14 -0
  49. package/runtime/json.js +243 -0
  50. package/runtime/limits.d.ts +2 -0
  51. package/runtime/limits.js +3 -0
  52. package/runtime/native-edit.d.ts +14 -0
  53. package/runtime/native-edit.js +73 -0
  54. package/runtime/runtime.d.ts +43 -0
  55. package/runtime/runtime.js +345 -0
  56. package/runtime/session-state.d.ts +13 -0
  57. package/runtime/session-state.js +73 -0
  58. package/runtime/text-layout.d.ts +9 -0
  59. package/runtime/text-layout.js +47 -0
  60. package/server.d.ts +1 -0
  61. package/server.js +1 -0
  62. package/settings-rpc.d.ts +511 -0
  63. package/settings-rpc.js +197 -0
  64. package/tui-messages.d.ts +1 -0
  65. package/tui-messages.js +84 -0
  66. package/tui.d.ts +17 -0
  67. package/tui.js +427 -0
  68. package/v1/hooks.d.ts +81 -0
  69. package/v1/hooks.js +97 -0
  70. package/v1/projection.d.ts +32 -0
  71. package/v1/projection.js +217 -0
  72. package/v1.d.ts +2 -0
  73. package/v1.js +2 -0
  74. package/v2/projection.d.ts +36 -0
  75. package/v2/projection.js +374 -0
  76. package/v2/server.d.ts +6 -0
  77. package/v2/server.js +633 -0
@@ -0,0 +1,345 @@
1
+ import { BridgeClient } from "../bridge/client.js";
2
+ import { ProtocolError } from "../bridge/protocol.js";
3
+ import { NumberToken } from "./json.js";
4
+ import { encodeLossless, parseLossless } from "./json.js";
5
+ import { demaskBody } from "../demasking.js";
6
+ import { blocked, object, OpenCodeGuardError, } from "./errors.js";
7
+ import { SessionState } from "./session-state.js";
8
+ import { layoutField, modelField, plainModel } from "./text-layout.js";
9
+ export const DEFAULT_GUARD_TIMEOUT_MS = 10_000;
10
+ const applyReserveMS = 250;
11
+ const names = {
12
+ "experimental.chat.messages.transform": "v1.model.messages",
13
+ "experimental.chat.system.transform": "v1.model.system",
14
+ "session.context": "v2.model.context",
15
+ "session.compaction": "v2.model.compaction",
16
+ "session.generate": "v2.model.generate",
17
+ "session.title": "v2.model.title",
18
+ };
19
+ // Internal bridge seam. Production hooks never accept a Checker or arbitrary
20
+ // executable path; process tests may supply a client bound to a real helper.
21
+ export function createOpenCodeRuntime(options, supplied, shared) {
22
+ options = { ...options };
23
+ const timeout = options.timeoutMs ?? DEFAULT_GUARD_TIMEOUT_MS;
24
+ if (!options.token ||
25
+ !options.baseURL ||
26
+ !options.projectSID ||
27
+ !Number.isSafeInteger(timeout) ||
28
+ timeout < 1 ||
29
+ timeout > 180_000) {
30
+ blocked();
31
+ }
32
+ const state = new SessionState();
33
+ const bridge = supplied ?? new BridgeClient();
34
+ let initializing = true;
35
+ const unsubscribe = bridge.subscribeInvalidation(() => {
36
+ if (!initializing) {
37
+ state.clear();
38
+ }
39
+ });
40
+ const configured = shared?.configured ??
41
+ bridge.configure({
42
+ origin: options.baseURL,
43
+ project_sid: options.projectSID,
44
+ token: options.token,
45
+ allow_loopback_http: options.allowLoopbackHTTP ?? false,
46
+ timeout_ms: timeout,
47
+ });
48
+ void configured.catch(() => { });
49
+ void configured
50
+ .finally(() => {
51
+ initializing = false;
52
+ })
53
+ .catch(() => { });
54
+ const restore = (session, text) => state.restoreText(session, text);
55
+ // Configuration belongs to the shared runtime; only this caller's wait is
56
+ // bounded here. A timed-out hook must not cancel startup for other hooks.
57
+ function waitConfigured(deadline) {
58
+ const remaining = deadline - performance.now();
59
+ if (!Number.isFinite(remaining) || remaining <= 0) {
60
+ return Promise.reject(new OpenCodeGuardError());
61
+ }
62
+ return new Promise((resolve, reject) => {
63
+ const fail = () => reject(new OpenCodeGuardError());
64
+ const timer = setTimeout(fail, remaining);
65
+ void configured.then(() => {
66
+ clearTimeout(timer);
67
+ resolve();
68
+ }, () => {
69
+ clearTimeout(timer);
70
+ fail();
71
+ });
72
+ });
73
+ }
74
+ async function routeLeaseAction(session, token, action, identity) {
75
+ const deadline = performance.now() + Math.min(timeout, 5000);
76
+ await waitConfigured(deadline);
77
+ if (bridge.generation !== identity.generation ||
78
+ bridge.epoch !== identity.epoch) {
79
+ throw new ProtocolError("stale_generation");
80
+ }
81
+ return bridge.routeLease(session, token, action, { deadline });
82
+ }
83
+ async function checked(profile, payload, session, tool, sourcePayload, commit, deadline, attachments) {
84
+ const revision = state.revision;
85
+ if (state.disposed) {
86
+ blocked();
87
+ }
88
+ try {
89
+ const wire = encodeLossless(payload);
90
+ await waitConfigured(deadline);
91
+ if (state.disposed ||
92
+ state.revision !== revision ||
93
+ performance.now() >= deadline) {
94
+ blocked();
95
+ }
96
+ let layout;
97
+ if (sourcePayload?.[layoutField]) {
98
+ const metadata = sourcePayload[layoutField];
99
+ if (metadata.version !== 1 || !Array.isArray(metadata.items)) {
100
+ blocked();
101
+ }
102
+ layout = metadata.items;
103
+ }
104
+ // Metadata only: an unusable value is dropped, never a reason to block.
105
+ const modelValue = sourcePayload?.[modelField];
106
+ const model = plainModel(modelValue);
107
+ const prepared = await bridge.check({
108
+ profile,
109
+ session_id: session,
110
+ ...(model === undefined ? {} : { model }),
111
+ projected_json_b64: Buffer.from(wire).toString("base64"),
112
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
113
+ ...(tool ? { call_id: tool.callID, tool_name: tool.tool } : {}),
114
+ ...(layout === undefined ? {} : { layout }),
115
+ ...(attachments?.length ? { attachments } : {}),
116
+ }, { deadline });
117
+ const result = prepared.take();
118
+ const candidate = parseLossless(Buffer.from(result.prepared_json_b64, "base64"));
119
+ const bindings = new Map(result.bindings.map(({ token, original }) => [token, original]));
120
+ const publish = bindings.size ? state.stage(session, bindings) : () => { };
121
+ if (typeof publish === "string") {
122
+ return blocked();
123
+ }
124
+ if (state.disposed ||
125
+ state.revision !== revision ||
126
+ performance.now() >= deadline) {
127
+ blocked();
128
+ }
129
+ // Masked plain-text attachments, by position. Only an attachment that was
130
+ // handed over can be replaced.
131
+ const replacements = (result.attachment_replacements ?? []).map((r) => ({
132
+ index: r.index,
133
+ data: Buffer.from(r.data_b64, "base64"),
134
+ }));
135
+ if (replacements.some((r) => r.index >= (attachments?.length ?? 0))) {
136
+ blocked();
137
+ }
138
+ // No await from final local/native snapshot validation through publication.
139
+ commit(candidate, replacements);
140
+ publish();
141
+ }
142
+ catch (error) {
143
+ if (error instanceof OpenCodeGuardError) {
144
+ throw error;
145
+ }
146
+ if (error instanceof ProtocolError) {
147
+ throw new OpenCodeGuardError(error.code === "timeout" ? "timeout" : "unavailable");
148
+ }
149
+ blocked();
150
+ }
151
+ }
152
+ async function model(name, texts, session, sourcePayload, commit, deadline = performance.now() + timeout + applyReserveMS, attachments) {
153
+ const profile = names[name];
154
+ if (!profile) {
155
+ return blocked();
156
+ }
157
+ const snapshot = [...texts];
158
+ let candidate;
159
+ await checked(profile, { texts: snapshot }, session, undefined, sourcePayload, (value, replacements) => {
160
+ if (replacements.length > 0 && !commit) {
161
+ blocked();
162
+ }
163
+ const projected = object(value).texts;
164
+ if (!Array.isArray(projected) ||
165
+ projected.length !== snapshot.length ||
166
+ !projected.every((x) => typeof x === "string") ||
167
+ texts.length !== snapshot.length ||
168
+ !texts.every((x, i) => x === snapshot[i])) {
169
+ blocked();
170
+ }
171
+ candidate = projected;
172
+ commit?.(candidate, replacements);
173
+ }, deadline, attachments);
174
+ return candidate ?? blocked();
175
+ }
176
+ async function tool(input, argsValue, commit, deadline = performance.now() + timeout + applyReserveMS, profile = "v1.tool.before") {
177
+ const args = object(parseLossless(encodeLossless(object(argsValue))));
178
+ const walk = (node) => {
179
+ for (const [key, value] of Object.entries(node)) {
180
+ if (typeof value === "string") {
181
+ node[key] = restore(input.sessionID, value);
182
+ }
183
+ else if (value &&
184
+ typeof value === "object" &&
185
+ !(value instanceof NumberToken)) {
186
+ walk(value);
187
+ }
188
+ }
189
+ };
190
+ walk(args);
191
+ let candidate;
192
+ await checked(profile, args, input.sessionID, input, undefined, (value) => {
193
+ candidate = object(value);
194
+ commit?.(candidate);
195
+ }, deadline);
196
+ return candidate ?? blocked();
197
+ }
198
+ return {
199
+ deadline: (started = performance.now()) => started + timeout + applyReserveMS,
200
+ checkModelTexts: model,
201
+ // Whether the helper inspects attachments now. When that cannot be learned,
202
+ // the answer is "yes": the check that follows then fails closed, instead of
203
+ // attachments being sent unchecked.
204
+ async inspectsAttachments(deadline) {
205
+ try {
206
+ await waitConfigured(deadline);
207
+ return (await bridge.attachmentsPolicy({ deadline })).inspect;
208
+ }
209
+ catch {
210
+ return true;
211
+ }
212
+ },
213
+ async routeStatus(session) {
214
+ const deadline = performance.now() + timeout + applyReserveMS;
215
+ await waitConfigured(deadline);
216
+ const prepared = await bridge.check({
217
+ profile: "v2.model.generate",
218
+ session_id: session,
219
+ projected_json_b64: Buffer.from("{}").toString("base64"),
220
+ route_path: "/route-status",
221
+ }, { deadline });
222
+ const result = prepared.take();
223
+ const value = object(parseLossless(Buffer.from(result.prepared_json_b64, "base64")));
224
+ if (typeof value.local !== "boolean" ||
225
+ typeof value.gateway_required !== "boolean") {
226
+ return blocked();
227
+ }
228
+ return { local: value.local, gateway_required: value.gateway_required };
229
+ },
230
+ async checkProviderRequest(session, path, body, deadline) {
231
+ const revision = state.revision;
232
+ let leaseToRelease;
233
+ let leaseIdentity;
234
+ if (state.disposed) {
235
+ blocked();
236
+ }
237
+ try {
238
+ await waitConfigured(deadline);
239
+ const prepared = await bridge.check({
240
+ profile: "v2.model.generate",
241
+ session_id: session,
242
+ projected_json_b64: Buffer.from(body).toString("base64"),
243
+ route_path: path,
244
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
245
+ }, { deadline });
246
+ const result = prepared.take();
247
+ leaseToRelease = result.route_lease;
248
+ const identity = { generation: result.generation, epoch: bridge.epoch };
249
+ leaseIdentity = identity;
250
+ if (typeof result.local_route !== "boolean" ||
251
+ state.disposed ||
252
+ state.revision !== revision ||
253
+ performance.now() >= deadline ||
254
+ (result.authorization !== "allow" &&
255
+ result.authorization !== "transformed") ||
256
+ (result.decision === "deny" && !result.local_route) ||
257
+ (!result.local_route && result.route_lease === undefined) ||
258
+ (result.local_route && result.route_lease !== undefined)) {
259
+ blocked();
260
+ }
261
+ const bindings = new Map(result.bindings.map(({ token, original }) => [token, original]));
262
+ const publish = bindings.size
263
+ ? state.stage(session, bindings)
264
+ : () => { };
265
+ if (typeof publish === "string") {
266
+ return blocked();
267
+ }
268
+ publish();
269
+ leaseToRelease = undefined;
270
+ return {
271
+ local: result.local_route,
272
+ body: Buffer.from(result.prepared_json_b64, "base64"),
273
+ ...(result.route_lease === undefined
274
+ ? {}
275
+ : {
276
+ routeLease: result.route_lease,
277
+ leaseAction: (action) => routeLeaseAction(session, result.route_lease, action, identity),
278
+ }),
279
+ };
280
+ }
281
+ catch (error) {
282
+ if (leaseToRelease && leaseIdentity) {
283
+ await routeLeaseAction(session, leaseToRelease, "release", leaseIdentity).catch(() => { });
284
+ }
285
+ if (error instanceof OpenCodeGuardError) {
286
+ throw error;
287
+ }
288
+ if (error instanceof ProtocolError) {
289
+ throw new OpenCodeGuardError(error.code === "timeout" ? "timeout" : "unavailable");
290
+ }
291
+ return blocked();
292
+ }
293
+ },
294
+ checkToolArguments: tool,
295
+ async checkToolTexts(input, texts, commit, deadline = performance.now() + timeout + applyReserveMS) {
296
+ const candidate = await tool(input, { texts: [...texts] }, (value) => {
297
+ if (!Array.isArray(value.texts) ||
298
+ value.texts.length !== texts.length ||
299
+ !value.texts.every((text) => typeof text === "string")) {
300
+ blocked();
301
+ }
302
+ commit(value.texts);
303
+ }, deadline, "v2.tool.before");
304
+ return candidate.texts;
305
+ },
306
+ hasRestoration: (session) => state.hasRestoration(session),
307
+ restoreText: restore,
308
+ async observeToolAfter(tool, output) {
309
+ if (state.disposed) {
310
+ return;
311
+ }
312
+ const deadline = performance.now() + timeout + applyReserveMS;
313
+ try {
314
+ await waitConfigured(deadline);
315
+ await bridge.check({
316
+ profile: "tool.after.observe",
317
+ session_id: tool.sessionID,
318
+ call_id: tool.callID,
319
+ tool_name: tool.tool,
320
+ projected_json_b64: Buffer.from(encodeLossless(output)).toString("base64"),
321
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
322
+ }, { deadline });
323
+ }
324
+ catch {
325
+ /* Observation never rolls back an executed action. */
326
+ }
327
+ },
328
+ async demaskResponse(session, response, trace) {
329
+ const bindings = session && !state.disposed ? state.bindings(session) : undefined;
330
+ if (!bindings?.size) {
331
+ trace?.(session ? "no_bindings" : "no_session");
332
+ return response;
333
+ }
334
+ return demaskBody(response, bindings, trace);
335
+ },
336
+ forgetSession: async (session) => state.forgetSession(session),
337
+ async dispose() {
338
+ state.dispose();
339
+ unsubscribe();
340
+ if (!shared) {
341
+ await bridge.dispose();
342
+ }
343
+ },
344
+ };
345
+ }
@@ -0,0 +1,13 @@
1
+ export declare class SessionState {
2
+ #private;
3
+ get disposed(): boolean;
4
+ get revision(): number;
5
+ bindings(session: string): ReadonlyMap<string, string> | undefined;
6
+ hasRestoration(session: string): boolean;
7
+ stage(session: string | null, bindings: ReadonlyMap<string, string>): "bindings_session" | "bindings_conflict" | "bindings_limit" | (() => void);
8
+ retain(session: string | null, bindings: ReadonlyMap<string, string>): "bindings_session" | "bindings_conflict" | "bindings_limit" | undefined;
9
+ clear(): void;
10
+ restoreText(session: string, text: string): string;
11
+ forgetSession(session: string): void;
12
+ dispose(): void;
13
+ }
@@ -0,0 +1,73 @@
1
+ // Owns ephemeral bindings and revision invalidation for one plugin instance.
2
+ export class SessionState {
3
+ #disposed = false;
4
+ #revision = 0;
5
+ #sessions = new Map();
6
+ get disposed() {
7
+ return this.#disposed;
8
+ }
9
+ get revision() {
10
+ return this.#revision;
11
+ }
12
+ bindings(session) {
13
+ return this.#sessions.get(session);
14
+ }
15
+ hasRestoration(session) {
16
+ return !!this.#sessions.get(session)?.size;
17
+ }
18
+ stage(session, bindings) {
19
+ if (!session ||
20
+ (!this.#sessions.has(session) && this.#sessions.size >= 128)) {
21
+ return "bindings_session";
22
+ }
23
+ const next = new Map(this.#sessions.get(session));
24
+ for (const [token, original] of bindings) {
25
+ if (next.has(token) && next.get(token) !== original) {
26
+ return "bindings_conflict";
27
+ }
28
+ next.set(token, original);
29
+ }
30
+ if (next.size > 4096 ||
31
+ [...next].reduce((n, [k, v]) => n + k.length + v.length, 0) > 1 << 20) {
32
+ return "bindings_limit";
33
+ }
34
+ return () => {
35
+ this.#sessions.set(session, next);
36
+ };
37
+ }
38
+ retain(session, bindings) {
39
+ const staged = this.stage(session, bindings);
40
+ if (typeof staged === "string") {
41
+ return staged;
42
+ }
43
+ staged();
44
+ return undefined;
45
+ }
46
+ clear() {
47
+ this.#revision++;
48
+ this.#sessions.clear();
49
+ }
50
+ restoreText(session, text) {
51
+ const bindings = this.#sessions.get(session);
52
+ if (!bindings?.size) {
53
+ return text;
54
+ }
55
+ // One pass: restored plaintext must not be interpreted as another token.
56
+ const pattern = [...bindings.keys()]
57
+ .sort((a, b) => b.length - a.length)
58
+ .map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
59
+ .join("|");
60
+ return text.replace(new RegExp(pattern, "g"), (token) => bindings.get(token));
61
+ }
62
+ forgetSession(session) {
63
+ if (session) {
64
+ this.#revision++;
65
+ this.#sessions.delete(session);
66
+ }
67
+ }
68
+ dispose() {
69
+ this.#disposed = true;
70
+ this.#revision++;
71
+ this.#sessions.clear();
72
+ }
73
+ }
@@ -0,0 +1,9 @@
1
+ export type TextLayoutItem = {
2
+ role: "system" | "user" | "assistant" | "tool";
3
+ kind: "context" | "history" | "current_prompt";
4
+ };
5
+ export declare const layoutField = "text_layout";
6
+ export declare const modelField = "model";
7
+ export declare function modelName(ref: unknown): string | undefined;
8
+ export declare function messageModelName(info: unknown): string | undefined;
9
+ export declare function plainModel(value: unknown): string | undefined;
@@ -0,0 +1,47 @@
1
+ export const layoutField = "text_layout";
2
+ // Name of the source-payload key that carries the model identifier of the
3
+ // request ("provider/model"). It only reaches Guard history; the Go helper
4
+ // validates it and decides whether to send it.
5
+ export const modelField = "model";
6
+ const joinModel = (provider, id) => typeof id === "string" && id
7
+ ? typeof provider === "string" && provider
8
+ ? `${provider}/${id}`
9
+ : id
10
+ : undefined;
11
+ // A v2 model reference ({ providerID, id }). Anything that is not plain strings
12
+ // yields undefined: the model is metadata and never changes a check.
13
+ export function modelName(ref) {
14
+ if (!ref || typeof ref !== "object") {
15
+ return undefined;
16
+ }
17
+ const r = ref;
18
+ return joinModel(r.providerID, r.id);
19
+ }
20
+ // The model a v1 message names. A user message carries `model: { providerID,
21
+ // modelID }`; an assistant message carries `providerID` and `modelID` itself.
22
+ // The message's own `id` is never a model.
23
+ export function messageModelName(info) {
24
+ if (!info || typeof info !== "object") {
25
+ return undefined;
26
+ }
27
+ const r = info;
28
+ const user = r.model && typeof r.model === "object"
29
+ ? r.model
30
+ : undefined;
31
+ return (joinModel(user?.providerID, user?.modelID) ??
32
+ joinModel(r.providerID, r.modelID));
33
+ }
34
+ // A model identifier that is safe to send: 1 to 512 UTF-16 units and no control
35
+ // character. Anything else is dropped; the model is metadata only.
36
+ export function plainModel(value) {
37
+ if (typeof value !== "string" || value.length === 0 || value.length > 512) {
38
+ return undefined;
39
+ }
40
+ for (let i = 0; i < value.length; i++) {
41
+ const code = value.charCodeAt(i);
42
+ if (code < 0x20 || code === 0x7f) {
43
+ return undefined;
44
+ }
45
+ }
46
+ return value;
47
+ }
package/server.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./v2/server.js";
package/server.js ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./v2/server.js";