@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
package/demasking.js ADDED
@@ -0,0 +1,445 @@
1
+ import { encodeLossless, parseLossless } from "./runtime/json.js";
2
+ import { createResponseDiagnostics } from "./response-diagnostics.js";
3
+ import { maxResponseBytes } from "./runtime/limits.js";
4
+ // Bounded streaming restoration of provider-bound responses, following the
5
+ // model proxy: only exact server-issued tokens for this session are restored,
6
+ // restored plaintext is never re-interpreted as another token, and a marker
7
+ // that may be incomplete across chunks is held back. A response that cannot be
8
+ // recognized as JSON/SSE passes through unchanged with its markers visible.
9
+ // Resource-limit failures after streaming begins terminate the body.
10
+ const encoder = new TextEncoder();
11
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
12
+ // Tokens start with '<' and contain no further '<' or line breaks, so only the
13
+ // final '<' can start an incomplete token. Replacement happens on the decoded
14
+ // chunk before the restored plaintext is emitted, so it is never re-scanned.
15
+ const holdbackIndex = (text, tokens) => {
16
+ const index = text.lastIndexOf("<");
17
+ if (index < 0) {
18
+ return text.length;
19
+ }
20
+ const suffix = text.slice(index);
21
+ for (const token of tokens) {
22
+ if (suffix.length < token.length && token.startsWith(suffix)) {
23
+ return index;
24
+ }
25
+ }
26
+ return text.length;
27
+ };
28
+ // Fetch runtimes decompress response bodies transparently while keeping the
29
+ // content-encoding header, so the header cannot decide. A body is demasked
30
+ // only when it starts like the expected JSON or SSE text; compressed magic
31
+ // bytes, binary and unknown starts pass through unchanged.
32
+ const textLeads = new Set([
33
+ 0x20,
34
+ 0x09,
35
+ 0x0a,
36
+ 0x0d, // whitespace
37
+ 0x7b,
38
+ 0x5b, // '{', '['
39
+ 0x3a, // ':' SSE comment
40
+ 0x64,
41
+ 0x65,
42
+ 0x69,
43
+ 0x72, // 'data:', 'event:', 'id:', 'retry:'
44
+ ]);
45
+ const isTextStart = (buffer) => {
46
+ let offset = 0;
47
+ if (buffer.length >= 3 &&
48
+ buffer[0] === 0xef &&
49
+ buffer[1] === 0xbb &&
50
+ buffer[2] === 0xbf) {
51
+ offset = 3;
52
+ }
53
+ if (offset >= buffer.length) {
54
+ return buffer.length > 0;
55
+ }
56
+ return textLeads.has(buffer[offset]);
57
+ };
58
+ export function demaskBody(response, values, trace) {
59
+ try {
60
+ if (response.status !== 200 || !response.body || !values.size) {
61
+ trace?.(`status=${response.status} body=${!!response.body}`);
62
+ return response;
63
+ }
64
+ const mediaType = response.headers
65
+ .get("content-type")
66
+ ?.split(";")[0]
67
+ ?.trim()
68
+ .toLowerCase();
69
+ if (mediaType !== "application/json" && mediaType !== "text/event-stream") {
70
+ trace?.(`media=${mediaType ?? "none"}`);
71
+ return response;
72
+ }
73
+ // Snapshot bindings: a later Guard check must not change an open response.
74
+ const bindings = new Map(values);
75
+ const tokens = [...bindings.keys()];
76
+ const pattern = new RegExp(tokens.map(escapeRegExp).join("|"), "g");
77
+ let growth = 0;
78
+ let replaced = 0;
79
+ const restore = (text) => text.replace(pattern, (token) => {
80
+ const original = bindings.get(token);
81
+ growth += Math.max(0, Buffer.byteLength(original) - Buffer.byteLength(token));
82
+ if (growth > maxResponseBytes) {
83
+ throw new Error("LLMGuard: restoration limit exceeded");
84
+ }
85
+ replaced++;
86
+ return original;
87
+ });
88
+ const before = trace ? createResponseDiagnostics() : undefined;
89
+ const after = trace ? createResponseDiagnostics() : undefined;
90
+ let reported = false;
91
+ const report = () => {
92
+ if (!reported && trace && before && after) {
93
+ reported = true;
94
+ before.report(after, trace);
95
+ }
96
+ };
97
+ const sse = createEventRestorer(tokens, restore);
98
+ let raw = Buffer.alloc(0);
99
+ let mode = "undecided";
100
+ const emit = (controller, text) => {
101
+ if (text) {
102
+ controller.enqueue(encoder.encode(text));
103
+ }
104
+ };
105
+ const process = (controller, final = false) => {
106
+ if (mediaType === "application/json") {
107
+ if (!final) {
108
+ return;
109
+ }
110
+ // Replace decoded JSON string values, preserving keys and numeric tokens.
111
+ const source = raw.toString("utf8");
112
+ before?.json(source);
113
+ const restored = restoreJSON(source, restore);
114
+ after?.json(restored);
115
+ emit(controller, restored);
116
+ raw = Buffer.alloc(0);
117
+ return;
118
+ }
119
+ // Frame boundaries, unlike network chunks, are semantic boundaries. Delta
120
+ // fields keep their own marker tail across frames and interleaved outputs.
121
+ while (raw.length) {
122
+ const text = raw.toString("utf8");
123
+ const boundary = /\r\n\r\n|\n\n|\r\r/.exec(text);
124
+ if (!boundary) {
125
+ break;
126
+ }
127
+ const end = boundary.index + boundary[0].length;
128
+ const frame = text.slice(0, end);
129
+ raw = raw.subarray(Buffer.byteLength(frame));
130
+ before?.frame(frame);
131
+ const restored = sse.frame(frame);
132
+ after?.frame(restored);
133
+ emit(controller, restored);
134
+ if (before?.ended()) {
135
+ report();
136
+ }
137
+ }
138
+ if (final) {
139
+ if (raw.length) {
140
+ const source = raw.toString("utf8");
141
+ before?.frame(source);
142
+ const restored = sse.frame(source);
143
+ after?.frame(restored);
144
+ emit(controller, restored);
145
+ }
146
+ const tail = sse.finish();
147
+ after?.frame(tail);
148
+ emit(controller, tail);
149
+ raw = Buffer.alloc(0);
150
+ }
151
+ };
152
+ const stream = response.body.pipeThrough(new TransformStream({
153
+ transform(chunk, controller) {
154
+ if (mode === "passthrough") {
155
+ controller.enqueue(chunk);
156
+ return;
157
+ }
158
+ raw = Buffer.concat([raw, chunk]);
159
+ if (mode === "undecided") {
160
+ if (raw.length < 3 && raw[0] === 0xef) {
161
+ return;
162
+ }
163
+ if (!isTextStart(raw)) {
164
+ trace?.("binary_body");
165
+ controller.enqueue(raw);
166
+ raw = Buffer.alloc(0);
167
+ mode = "passthrough";
168
+ return;
169
+ }
170
+ mode = "text";
171
+ }
172
+ if (raw.length > maxResponseBytes) {
173
+ throw new Error("LLMGuard: restoration limit exceeded");
174
+ }
175
+ process(controller);
176
+ },
177
+ flush(controller) {
178
+ if (mode === "passthrough") {
179
+ return;
180
+ }
181
+ process(controller, true);
182
+ trace?.(replaced ? `demasked=${replaced}` : "no_token_in_body");
183
+ report();
184
+ },
185
+ }));
186
+ const headers = new Headers(response.headers);
187
+ for (const header of ["content-length", "content-md5", "digest", "etag"]) {
188
+ headers.delete(header);
189
+ }
190
+ headers.set("cache-control", "no-store");
191
+ return new Response(stream, {
192
+ status: response.status,
193
+ statusText: response.statusText,
194
+ headers,
195
+ });
196
+ }
197
+ catch (error) {
198
+ // Setup failures keep the original body. Stream errors propagate to the
199
+ // reader; already emitted bytes cannot be rolled back.
200
+ trace?.(`failed=${error instanceof Error && error.message.startsWith("LLMGuard") ? "limit" : "error"}`);
201
+ return response;
202
+ }
203
+ }
204
+ // Keep the wire representation of numbers and object keys untouched.
205
+ function restoreJSON(source, restore) {
206
+ try {
207
+ parseLossless(encoder.encode(source.replace(/^\uFEFF/, "")));
208
+ }
209
+ catch {
210
+ return source;
211
+ }
212
+ return source.replace(/"(?:[^"\\]|\\.)*"/g, (literal, offset) => {
213
+ if (/^\s*:/.test(source.slice(offset + literal.length))) {
214
+ return literal;
215
+ }
216
+ // Encoded tool arguments need a second JSON escaping layer. Leave these
217
+ // strings masked; execute.before restores their parsed string leaves.
218
+ if (/"(?:arguments|partial_json)"\s*:\s*$/.test(source.slice(0, offset))) {
219
+ return literal;
220
+ }
221
+ const text = JSON.parse(literal);
222
+ const restored = restore(text);
223
+ return restored === text ? literal : JSON.stringify(restored);
224
+ });
225
+ }
226
+ const eventObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
227
+ function createEventRestorer(tokens, restore) {
228
+ const pending = new Map();
229
+ const finish = (prefix = "") => {
230
+ let output = "";
231
+ for (const [key, state] of pending) {
232
+ if (!key.startsWith(prefix)) {
233
+ continue;
234
+ }
235
+ output += state.emit(state.tail);
236
+ pending.delete(key);
237
+ }
238
+ return output;
239
+ };
240
+ const identity = (value) => Buffer.from(encodeLossless(value ?? null)).toString();
241
+ const frame = (wire) => {
242
+ const lines = wire.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
243
+ const data = lines
244
+ .filter((line) => line.startsWith("data:"))
245
+ .map((line) => line.slice(5).replace(/^ /, ""))
246
+ .join("\n");
247
+ if (data === "[DONE]") {
248
+ return finish() + wire;
249
+ }
250
+ if (!data) {
251
+ return wire;
252
+ }
253
+ let obj;
254
+ try {
255
+ obj = parseLossless(encoder.encode(data));
256
+ }
257
+ catch {
258
+ return wire;
259
+ }
260
+ if (!eventObject(obj)) {
261
+ return wire;
262
+ }
263
+ const root = obj;
264
+ let flushed = "";
265
+ const restoreFrame = () => {
266
+ const restored = restoreJSON(data, restore);
267
+ if (restored === data) {
268
+ return wire;
269
+ }
270
+ if (wire.includes(data)) {
271
+ return wire.replace(data, () => restored);
272
+ }
273
+ return `data: ${restored}\n\n`;
274
+ };
275
+ const delta = (key, holder, field) => {
276
+ if (typeof holder[field] !== "string") {
277
+ return;
278
+ }
279
+ const text = (pending.get(key)?.tail ?? "") + holder[field];
280
+ const at = holdbackIndex(text, tokens);
281
+ holder[field] = restore(text.slice(0, at));
282
+ if (at < text.length) {
283
+ if (!pending.has(key) && pending.size >= 4096) {
284
+ throw new Error("LLMGuard: restoration limit exceeded");
285
+ }
286
+ // Capture serialized state after all fields have been processed below.
287
+ pending.set(key, {
288
+ tail: text.slice(at),
289
+ bytes: Buffer.byteLength(wire),
290
+ emit: (tail) => {
291
+ // Synthetic tail events contain only the pending text field. Do
292
+ // not replay tool calls, other choices, usage or reasoning deltas.
293
+ if (Array.isArray(root.choices)) {
294
+ const choice = root.choices.find((value) => eventObject(value) && value.delta === holder);
295
+ const snapshot = {
296
+ ...root,
297
+ choices: [
298
+ {
299
+ index: choice.index,
300
+ delta: { [field]: tail },
301
+ finish_reason: null,
302
+ },
303
+ ],
304
+ };
305
+ delete snapshot.usage;
306
+ return render(snapshot);
307
+ }
308
+ if (Array.isArray(root.candidates)) {
309
+ const candidate = root.candidates.find((value) => eventObject(value) &&
310
+ eventObject(value.content) &&
311
+ Array.isArray(value.content.parts) &&
312
+ value.content.parts.includes(holder));
313
+ const content = candidate.content;
314
+ return render({
315
+ ...root,
316
+ candidates: [
317
+ {
318
+ index: candidate.index,
319
+ content: { role: content.role, parts: [{ [field]: tail }] },
320
+ finishReason: null,
321
+ },
322
+ ],
323
+ });
324
+ }
325
+ if (root.type === "content_block_delta") {
326
+ return render({
327
+ ...root,
328
+ delta: { type: holder.type, [field]: tail },
329
+ });
330
+ }
331
+ return render({ ...root, [field]: tail });
332
+ },
333
+ });
334
+ let retained = 0;
335
+ for (const state of pending.values()) {
336
+ retained += state.bytes;
337
+ }
338
+ if (retained > maxResponseBytes) {
339
+ throw new Error("LLMGuard: restoration limit exceeded");
340
+ }
341
+ }
342
+ else {
343
+ pending.delete(key);
344
+ }
345
+ };
346
+ const render = (value = root) => {
347
+ const encoded = Buffer.from(encodeLossless(value)).toString();
348
+ // Retain event/id/retry fields; collapse multi-line data to one JSON line.
349
+ let added = false;
350
+ return lines
351
+ .map((line) => {
352
+ if (!line.startsWith("data:")) {
353
+ return line;
354
+ }
355
+ if (added) {
356
+ return null;
357
+ }
358
+ added = true;
359
+ return `data: ${encoded}`;
360
+ })
361
+ .filter((line) => line !== null)
362
+ .join(wire.includes("\r\n") ? "\r\n" : "\n");
363
+ };
364
+ let recognized = false;
365
+ // OpenAI Chat Completions. Choices and reasoning/content are independent.
366
+ if (Array.isArray(root.choices)) {
367
+ recognized = true;
368
+ for (const choice of root.choices) {
369
+ if (!eventObject(choice)) {
370
+ continue;
371
+ }
372
+ const prefix = `chat:${identity(root.id)}:${identity(choice.index)}:`;
373
+ if (eventObject(choice.delta)) {
374
+ for (const field of ["content", "reasoning_content", "reasoning"]) {
375
+ delta(prefix + field, choice.delta, field);
376
+ }
377
+ // Arguments are JSON encoded inside JSON. Restoring arbitrary slices
378
+ // here would require a second JSON escaping layer; execute.before
379
+ // restores validated string leaves before tools run instead.
380
+ }
381
+ if (choice.finish_reason != null) {
382
+ flushed += finish(prefix);
383
+ }
384
+ }
385
+ }
386
+ // Gemini streams carry text deltas inside candidate content parts.
387
+ if (Array.isArray(root.candidates)) {
388
+ recognized = true;
389
+ for (const candidate of root.candidates) {
390
+ if (!eventObject(candidate) || !eventObject(candidate.content)) {
391
+ continue;
392
+ }
393
+ const prefix = `gemini:${identity(candidate.index)}:`;
394
+ if (Array.isArray(candidate.content.parts)) {
395
+ candidate.content.parts.forEach((part, index) => {
396
+ if (eventObject(part)) {
397
+ delta(`${prefix}${identity(index)}:text`, part, "text");
398
+ }
399
+ });
400
+ }
401
+ if (candidate.finishReason != null) {
402
+ flushed += finish(prefix);
403
+ }
404
+ }
405
+ }
406
+ // Anthropic Messages: text and thinking have independent block indices.
407
+ if (root.type === "content_block_delta" && eventObject(root.delta)) {
408
+ recognized = true;
409
+ for (const field of ["text", "thinking"]) {
410
+ delta(`anthropic:${identity(root.index)}:${field}`, root.delta, field);
411
+ }
412
+ }
413
+ else if (root.type === "content_block_stop") {
414
+ recognized = true;
415
+ flushed += finish(`anthropic:${identity(root.index)}:`);
416
+ }
417
+ else if (root.type === "message_stop") {
418
+ recognized = true;
419
+ flushed += finish();
420
+ }
421
+ // OpenAI Responses: don't mix output items or content/summary parts.
422
+ if (typeof root.type === "string" &&
423
+ /^response\.(output_text|reasoning_text|reasoning_summary_text)\.delta$/.test(root.type)) {
424
+ recognized = true;
425
+ delta(`responses:${identity(root.item_id)}:${identity(root.output_index)}:${identity(root.content_index ?? root.summary_index)}:${root.type}`, root, "delta");
426
+ }
427
+ else if (["response.completed", "response.incomplete", "response.failed"].includes(String(root.type))) {
428
+ flushed += finish();
429
+ return flushed + restoreFrame();
430
+ }
431
+ else if (typeof root.type === "string" &&
432
+ /^response\..+\.done$/.test(root.type)) {
433
+ // A done event carries a full snapshot. Flush incomplete delta prefixes
434
+ // first, then restore the snapshot independently.
435
+ const prefix = `responses:${identity(root.item_id)}:${identity(root.output_index)}:`;
436
+ const textDone = /^response\.(output_text|reasoning_text|reasoning_summary_text)\.done$/.test(root.type);
437
+ flushed += finish(textDone
438
+ ? `${prefix}${identity(root.content_index ?? root.summary_index)}:${root.type.replace(/\.done$/, ".delta")}`
439
+ : prefix);
440
+ return flushed + restoreFrame();
441
+ }
442
+ return flushed + (recognized ? render() : restoreFrame());
443
+ };
444
+ return { frame, finish };
445
+ }
@@ -0,0 +1,33 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("solid-js/web"),ie=require("@opencode/plugin/gui"),r=require("solid-js"),ze={en:{filesTitle:"Attachments",filesInspect:"Inspect files and images",filesOff:"Off",filesOn:"On",filesUninspectable:"When a file cannot be inspected",filesBlock:"Block",filesAllow:"Let through",filesNote:"If a file fails inspection or a rule matches its text, the request is rejected; otherwise the provider gets the original.",filesAllowNote:"Unsupported types, links and file ids go to the provider without inspection. Service failures and rule matches still stop the request.",filesEnv:"Set by LLMGUARD_FILE_INSPECTION and LLMGUARD_FILE_UNINSPECTABLE; settings do not change it.",filesDamaged:"The settings file is damaged: strict mode is in effect. Choose values to replace it.",filesSavedOn:"Attachment inspection is on. It applies to the next request.",filesSavedOff:"Attachment inspection is off. Files pass as before.",catalogTitle:"Connections",catalogAdd:"Add connection",catalogSearch:"Search connections",catalogSearchPlaceholder:"Name, server or SID",catalogNoResults:"No connections found",catalogEmpty:"Add your first connection",catalogNew:"New connection",catalogName:"Name",catalogServer:"Server",catalogSave:"Save",catalogCancel:"Cancel",catalogConnect:"Connect",catalogDisconnect:"Disconnect",catalogCheck:"Check",catalogRetry:"Retry",catalogActive:"Connected",catalogKeyAvailable:"Key available",catalogKeyRequired:"Key required",catalogKeepKey:"Leave blank to keep this connection’s key",catalogEnterKey:"Enter a project key",catalogDiscardConfirm:"Discard the unsaved changes? Saved connections will stay unchanged.",catalogDisconnectConfirm:"Disconnect protection for all sessions on this server? Requests will pass without Guard checks.",catalogDiscard:"Discard changes",catalogContinue:"Continue editing",catalogDisconnected:"Protection disconnected",catalogConflict:"The connection list changed. Cancel the draft and review the latest saved settings.",catalogOutcomeUnknown:"Action outcome unknown. Review the list before retrying. Your draft has been kept; re-enter the key if needed.",catalogSaved:"Connection saved. Active route unchanged.",catalogConnected:"Connected to {{name}}. Protection enabled.",catalogChecked:"{{name}} is reachable · test decision: {{decision}}. Active route unchanged.",catalogRoute:"Route: {{name}}",catalogNone:"not configured",statusFailed:"Status unavailable. Check the server plugin and refresh. Your input has been kept.",unsavedChanges:"Unapplied changes",discardChanges:"Discard changes",saveDraftHint:"Saving applies this connection and turns protection off. You can enable it again above.",activeDraftHint:"Protection uses the saved settings. Your changes have not been applied yet.",inactiveDraftHint:"Apply or discard your changes before enabling protection.",keyDraftHint:"The new key has not been applied. Select Set key to replace the current key and turn protection off.",testDraftHint:"This check uses the saved connection and key. Apply or discard your changes first.",connectionSaved:"Connection saved. Check the connection before enabling protection.",keySaved:"Key applied. Check the connection before enabling protection.",settings:"LLMGuard: settings and status",actionFailed:"Action failed. Check the connection and server plugin availability.",protection:"Protection",protectionDescription:"Check requests and tools across all sessions on this server.",statusUnavailable:"Status unavailable",loading:"Loading…",enabled:"Protection enabled",blocked:"Operations blocked",disabled:"Protection disabled",requests:"Request checks",noConnection:"Cannot reach the server plugin. Refresh the status.",loadingStatus:"Retrieving server plugin status.",checksDescription:"Guard checks selected text fields before they are sent.",blockedDescription:"Protection is enabled but the connection is not ready. Configure the connection and key; operations remain blocked until then.",disabledDescription:"Requests pass without Guard checks. Configure the connection and enable protection.",enable:"Enable protection",connection:"Connection",connectionDescription:"Guard address and LLMGuard project. Saving changes disables protection until you enable it again.",noData:"No data",environment:"From environment",connectionSet:"Connection configured",setupRequired:"Setup required",connectionEnvironment:"Connection is configured by the server environment",urlExample:"For example, https://guard.example.com",projectSID:"Project SID",transport:"Connection protocol",transportDescription:"For Guard without TLS; HTTPS is required by default",allowHTTP:"Allow HTTP",accessKey:"Access key",keyDescription:"The key is sent to the server plugin and is not written to chat. Replacing the key disables protection.",keySet:"Key configured",keyMissing:"Key not configured",guardKey:"Guard key",serverEnvironment:"server environment",untilRestart:"saved locally",keyStorage:"The key is saved locally on the OpenCode server",catalogRestoreKey:"Enter the key and save to enable Connect and Check.",catalogSaveKey:"Save the key first, then connect or check this profile.",connectionTest:"Connection test",testDescription:"Sends only fixed test text. Session content is not sent.",available:"Guard is available",testFailed:"Test failed",checking:"Checking…",notChecked:"Connection not tested",testingConnection:"Testing the connection to Guard…",timeout:"The test timed out. Guard did not respond in time.",guardTestFailed:"Guard test failed. Check the address, key and server availability.",testError:"Could not run the test. Check server plugin availability.",testing:"Testing…",testConnection:"Test connection",testHint:"No test has been run yet. Configure the connection and key, then click “Test connection”.",intro:"One connection and shared protection for all OpenCode projects and sessions.",saveConnection:"Save connection",setKey:"Set key",refreshStatus:"Refresh status",keySource:"Key configured: {{source}}. A new key disables protection.",testDecision:"Guard is available. Decision for the test text: {{decision}}."},ru:{filesTitle:"Вложения",filesInspect:"Проверять файлы и изображения",filesOff:"Выключена",filesOn:"Включена",filesUninspectable:"Если файл нельзя проверить",filesBlock:"Блокировать",filesAllow:"Пропускать",filesNote:"Если файл не прошёл проверку или правило сработало на его тексте, запрос отклоняется; иначе провайдер получает оригинал.",filesAllowNote:"Неподдерживаемые типы, ссылки и идентификаторы файлов уходят провайдеру без проверки. Сбои проверки и срабатывания правил запрос всё равно останавливают.",filesEnv:"Задано переменными LLMGUARD_FILE_INSPECTION и LLMGUARD_FILE_UNINSPECTABLE; настройки их не меняют.",filesDamaged:"Файл настроек повреждён: действует строгий режим. Выберите значения, чтобы заменить его.",filesSavedOn:"Проверка вложений включена. Она применится к следующему запросу.",filesSavedOff:"Проверка вложений выключена. Файлы проходят как раньше.",catalogTitle:"Подключения",catalogAdd:"Добавить подключение",catalogSearch:"Поиск подключений",catalogSearchPlaceholder:"Название, сервер или SID",catalogNoResults:"Ничего не найдено",catalogEmpty:"Добавьте первое подключение",catalogNew:"Новое подключение",catalogName:"Название",catalogServer:"Сервер",catalogSave:"Сохранить",catalogCancel:"Отмена",catalogConnect:"Подключить",catalogDisconnect:"Отключить",catalogCheck:"Проверить",catalogRetry:"Повторить",catalogActive:"Подключён",catalogKeyAvailable:"Ключ доступен",catalogKeyRequired:"Нужен ключ",catalogKeepKey:"Пусто — оставить ключ этого подключения",catalogEnterKey:"Введите ключ проекта",catalogDiscardConfirm:"Отбросить несохранённые изменения? Сохранённые подключения останутся прежними.",catalogDisconnectConfirm:"Отключить защиту для всех сессий этого сервера? Запросы будут проходить без проверки Guard.",catalogDiscard:"Отбросить изменения",catalogContinue:"Продолжить редактирование",catalogDisconnected:"Защита отключена",catalogConflict:"Список подключений изменился. Отмените черновик и проверьте актуальные сохранённые настройки.",catalogOutcomeUnknown:"Результат действия неизвестен. Проверьте список перед повтором. Черновик сохранён; при необходимости введите ключ заново.",catalogSaved:"Подключение сохранено. Активный маршрут не изменён.",catalogConnected:"Подключено: {{name}}. Защита включена.",catalogChecked:"{{name}} доступен · решение теста: {{decision}}. Активный маршрут не изменён.",catalogRoute:"Маршрут: {{name}}",catalogNone:"не задан",statusFailed:"Статус недоступен. Проверьте серверный плагин и обновите статус. Введённые данные сохранены в форме.",unsavedChanges:"Есть неприменённые изменения",discardChanges:"Отменить изменения",saveDraftHint:"Сохранение применит подключение и выключит защиту. Включить её снова можно выше.",activeDraftHint:"Защита использует сохранённые настройки. Изменения в форме ещё не применены.",inactiveDraftHint:"Примените или отмените изменения перед включением защиты.",keyDraftHint:"Новый ключ ещё не применён. Нажмите «Задать ключ», чтобы заменить текущий ключ и выключить защиту.",testDraftHint:"Проверка использует сохранённое подключение и ключ. Сначала примените или отмените изменения.",connectionSaved:"Подключение сохранено. Проверьте связь перед включением защиты.",keySaved:"Ключ применён. Проверьте связь перед включением защиты.",settings:"LLMGuard: настройки и статус",actionFailed:"Не удалось выполнить действие. Проверьте подключение и доступность серверного плагина.",protection:"Защита",protectionDescription:"Проверка запросов и инструментов во всех сессиях этого сервера.",statusUnavailable:"Статус недоступен",loading:"Загрузка…",enabled:"Защита включена",blocked:"Операции заблокированы",disabled:"Защита выключена",requests:"Проверка запросов",noConnection:"Нет связи с серверным плагином. Обновите статус.",loadingStatus:"Получаем состояние серверного плагина.",checksDescription:"Выбранные текстовые поля проверяются Guard перед отправкой.",blockedDescription:"Защита включена, но подключение не готово. Настройте подключение и ключ: до этого операции блокируются.",disabledDescription:"Запросы проходят без проверки Guard. Настройте подключение и включите защиту.",enable:"Включить защиту",connection:"Подключение",connectionDescription:"Адрес Guard и проект LLMGuard. Сохранение изменений выключает защиту до повторного включения.",noData:"Нет данных",environment:"Из окружения",connectionSet:"Подключение задано",setupRequired:"Требуется настройка",connectionEnvironment:"Подключение задано окружением сервера",urlExample:"Например, https://guard.example.com",projectSID:"SID проекта",transport:"Протокол подключения",transportDescription:"Для Guard без TLS; по умолчанию требуется HTTPS",allowHTTP:"Разрешить HTTP",accessKey:"Ключ доступа",keyDescription:"Ключ передаётся серверному плагину и не записывается в чат. Замена ключа выключает защиту.",keySet:"Ключ задан",keyMissing:"Ключ не задан",guardKey:"Ключ Guard",serverEnvironment:"окружение сервера",untilRestart:"сохранён локально",keyStorage:"Ключ сохранён локально на сервере OpenCode",catalogRestoreKey:"Введите ключ и сохраните, чтобы подключиться или проверить.",catalogSaveKey:"Сначала сохраните ключ, затем подключите или проверьте профиль.",connectionTest:"Проверка связи",testDescription:"Отправляет только фиксированный тестовый текст. Содержимое сессий не передаётся.",available:"Guard доступен",testFailed:"Проверка не пройдена",checking:"Проверяем…",notChecked:"Связь не проверена",testingConnection:"Проверка подключения к Guard…",timeout:"Время проверки истекло. Guard не ответил вовремя.",guardTestFailed:"Проверка Guard не прошла. Проверьте адрес, ключ и доступность сервера.",testError:"Не удалось выполнить проверку. Проверьте доступность серверного плагина.",testing:"Проверка…",testConnection:"Проверить связь",testHint:"Проверка ещё не выполнялась. После настройки подключения и ключа нажмите «Проверить связь».",intro:"Одно подключение и общая защита для всех проектов и сессий OpenCode.",saveConnection:"Сохранить подключение",setKey:"Задать ключ",refreshStatus:"Обновить статус",keySource:"Ключ задан: {{source}}. Новый ключ выключает защиту.",testDecision:"Guard доступен. Решение для тестового текста: {{decision}}."}},M={type:"object",additionalProperties:!1},Y={type:"object",properties:{baseURL:{type:"string",maxLength:2048},projectSID:{type:"string",maxLength:36},allowLoopbackHTTP:{type:"boolean"},configured:{type:"boolean"},enabled:{type:"boolean"},tokenPresent:{type:"boolean"},environmentOverride:{type:"boolean"},tokenSource:{type:"string",enum:["environment","session","missing"]}},required:["baseURL","projectSID","allowLoopbackHTTP","configured","enabled","tokenPresent","environmentOverride","tokenSource"],additionalProperties:!1},_e={baseURL:{type:"string",maxLength:2048},projectSID:{type:"string",maxLength:36},allowLoopbackHTTP:{type:"boolean"}},xe={type:"object",additionalProperties:!1,properties:{configured:{type:"boolean"},activeLabel:{type:"string"},revision:{type:"integer",minimum:0},enabled:{type:"boolean"},environmentOverride:{type:"boolean"},items:{type:"array",maxItems:100,items:{type:"object",additionalProperties:!1,properties:{..._e,id:{type:"string"},name:{type:"string"},tokenPresent:{type:"boolean"},tokenHint:{type:"string",maxLength:7},active:{type:"boolean"}},required:["baseURL","projectSID","allowLoopbackHTTP","id","name","tokenPresent","active"]}}},required:["revision","enabled","configured","activeLabel","environmentOverride","items"]},De={type:"object",additionalProperties:!1,properties:{id:{type:"string",maxLength:64},revision:{type:"integer",minimum:0}},required:["id","revision"]},Le={type:"object",properties:{inspect:{type:"boolean"},allowUninspectable:{type:"boolean"},source:{type:"string",enum:["default","file","env"]},damaged:{type:"boolean"}},required:["inspect","allowUninspectable","source","damaged"],additionalProperties:!1},Te={type:"object",additionalProperties:!1,properties:{connected:{type:"boolean"},code:{type:"string",maxLength:64},decision:{enum:["allow","deny","transform",null]}},required:["connected","code","decision"]},Ge={id:"llmguard.settings",methods:{connections:{input:M,output:xe},saveConnection:{input:{type:"object",additionalProperties:!1,properties:{..._e,revision:{type:"integer",minimum:0},id:{type:"string",maxLength:64},name:{type:"string",minLength:1,maxLength:100},token:{type:"string",maxLength:4096}},required:["revision","name","baseURL","projectSID","allowLoopbackHTTP"]},output:xe},testConnection:{input:De,output:Te},connect:{input:De,output:Te},status:{input:M,output:Y},setEnabled:{input:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"],additionalProperties:!1},output:Y},save:{input:{type:"object",properties:{baseURL:{type:"string",maxLength:2048},projectSID:{type:"string",maxLength:36},allowLoopbackHTTP:{type:"boolean"}},required:["baseURL","projectSID","allowLoopbackHTTP"],additionalProperties:!1},output:Y},setKey:{input:{type:"object",properties:{token:{type:"string",minLength:1,maxLength:4096}},required:["token"],additionalProperties:!1},output:Y},files:{input:M,output:Le},setFiles:{input:{type:"object",properties:{inspect:{type:"boolean"},allowUninspectable:{type:"boolean"}},required:["inspect","allowUninspectable"],additionalProperties:!1},output:Le},test:{input:M,output:{type:"object",properties:{connected:{type:"boolean"},code:{type:"string",maxLength:64},decision:{enum:["allow","deny","transform",null]}},required:["connected","code","decision"],additionalProperties:!1}}},events:{}};var qe=e.template("<div class=ocguard-confirm role=alert><p class=ocguard-note></p><div class=ocguard-actions>"),W=e.template("<p class=ocguard-note>"),Be=e.template('<p class="ocguard-note ocguard-error"role=alert>'),Fe=e.template("<div class=ocguard-actions>"),Me=e.template('<div class="ocguard-confirm ocguard-confirm-local"role=alert><p class=ocguard-note></p><div class=ocguard-actions>'),Ye=e.template('<p class="ocguard-note ocguard-error">'),We=e.template("<div class=ocguard-files><h3 class=ocguard-files-title></h3><div class=ocguard-field><span class=ocguard-field-label></span><div class=ocguard-actions></div></div><div class=ocguard-field><span class=ocguard-field-label></span><div class=ocguard-actions>"),Je=e.template("<span>"),Qe=e.template(`<section class=ocguard aria-label=LLMGuard><style>
2
+ .ocguard{container:ocguard / inline-size;max-width:920px;width:100%;box-sizing:border-box;margin:0 auto;padding:28px;color:var(--text-base);font:inherit}
3
+ .ocguard *{box-sizing:border-box;min-width:0}
4
+ .ocguard-header{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:24px}
5
+ .ocguard h2{font-size:18px;font-weight:500;margin:0}
6
+ .ocguard-search{margin-bottom:24px}
7
+ .ocguard-columns{display:grid;grid-template-columns:minmax(200px,.75fr) minmax(300px,1.25fr);gap:32px}
8
+ .ocguard-list{display:grid;align-content:start;gap:8px;max-height:420px;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:thin}
9
+ .ocguard .ocguard-item{display:block;width:100%;height:auto;padding:16px;text-align:left;border-radius:8px;white-space:normal}
10
+ .ocguard .ocguard-item[aria-pressed=true]{background:var(--surface-raised-base);box-shadow:inset 0 0 0 1px var(--border-base)}
11
+ .ocguard-item-title{display:flex;justify-content:space-between;align-items:baseline;gap:8px;margin-bottom:5px}
12
+ .ocguard-item-name{overflow-wrap:anywhere;font-weight:500}
13
+ .ocguard-active{color:var(--text-success, var(--text-base));font-size:11px;flex-shrink:0}
14
+ .ocguard-meta{display:block;font-size:12px;line-height:1.6;color:var(--text-weak);overflow-wrap:anywhere}
15
+ .ocguard-sid{font-family:var(--font-family-mono,monospace)}
16
+ .ocguard-editor{padding-left:32px;border-left:1px solid var(--border-base);display:grid;align-content:start;gap:20px}
17
+ .ocguard-editor-title{font-size:14px;font-weight:500;overflow-wrap:anywhere}
18
+ .ocguard-field{display:grid;gap:8px}
19
+ .ocguard .ocguard-input{width:100%;max-width:none}
20
+ .ocguard .ocguard-input input{width:100%;max-width:none}
21
+ .ocguard-field-label{font-size:12px;color:var(--text-weak)}
22
+ .ocguard-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding-top:8px}
23
+ .ocguard-note{font-size:12px;color:var(--text-weak);line-height:1.5;overflow-wrap:anywhere;margin:0}
24
+ .ocguard-confirm{padding:14px 0;margin-bottom:16px;border-bottom:1px solid var(--border-base);display:grid;gap:12px}
25
+ .ocguard-confirm-local{margin:0;border:0;padding:0}
26
+ .ocguard-files{margin-top:28px;padding-top:20px;border-top:1px solid var(--border-base);display:grid;gap:16px}
27
+ .ocguard-files-title{font-size:14px;font-weight:500;margin:0}
28
+ .ocguard-footer{margin-top:28px;padding-top:20px;border-top:1px solid var(--border-base);display:flex;align-items:center;justify-content:space-between;gap:16px}
29
+ .ocguard-footer-text{display:grid;gap:4px;overflow-wrap:anywhere}
30
+ .ocguard-error{color:var(--text-danger, var(--text-base))}
31
+ @container ocguard (max-width:620px){.ocguard-list{max-height:260px}.ocguard-columns{grid-template-columns:minmax(0,1fr);gap:20px}.ocguard-editor{padding:20px 0 0;border-left:0;border-top:1px solid var(--border-base)}}
32
+ @media(max-width:440px){.ocguard{padding:16px}}
33
+ </style><header class=ocguard-header><h2></h2></header><div class=ocguard-search></div><div class=ocguard-columns><nav class=ocguard-list></nav><div class=ocguard-editor><div class=ocguard-editor-title></div><div class=ocguard-field><span class=ocguard-field-label aria-hidden=true></span></div><div class=ocguard-field><span class=ocguard-field-label aria-hidden=true></span></div><div class=ocguard-field><span class=ocguard-field-label aria-hidden=true></span></div><div class=ocguard-field><span class=ocguard-field-label aria-hidden=true></span></div><p class=ocguard-note role=status></p></div></div><footer class=ocguard-footer><div class=ocguard-footer-text aria-live=polite><span></span><span class=ocguard-note>`),Ve=e.template("<span class=ocguard-active>"),Xe=e.template("<span class=ocguard-item-title><span class=ocguard-item-name>"),$e=e.template("<span class=ocguard-meta>"),Ze=e.template('<span class="ocguard-meta ocguard-sid">SID <!>…');function et(L){const a=L.ctx,c=a.ui,[l,oe]=r.createSignal(),[f,J]=r.createSignal(!1),[u,N]=r.createSignal(),[re,se]=r.createSignal(),[I,O]=r.createSignal(""),[le,Pe]=r.createSignal(""),[d,ce]=r.createSignal(""),[T,R]=r.createSignal(),[g,z]=r.createSignal(),[A,de]=r.createSignal(!1),[p,Q]=r.createSignal(),ue=new AbortController;let v=!1,V=!1,U;const w=a.client.rpc(Ge),x=(t=1e4)=>({signal:AbortSignal.any([ue.signal,AbortSignal.timeout(t)])}),b=()=>l()?.items.find(t=>t.id===u()?.id),$=()=>{const t=u(),i=re();return!!t&&(!!I()||!i||t.name.trim()!==i.name||t.baseURL.trim()!==i.baseURL||t.projectSID.trim()!==i.projectSID||t.allowLoopbackHTTP!==i.allowLoopbackHTTP)},G=()=>!!u()&&u().revision!==l()?.revision,k=()=>f()&&!d()&&!g()&&!l()?.environmentOverride,ge=()=>{const t=le().trim().toLowerCase();return l()?.items.filter(i=>`${i.name} ${i.baseURL} ${i.projectSID}`.toLowerCase().includes(t))??[]},Ie=()=>!!b()&&ge().some(t=>t.id===b().id),X=()=>f()&&!d()&&!g()&&!$()&&!G()&&!A()&&Ie()&&!!b()?.tokenPresent,pe=()=>k()&&$()&&!G()&&!A()&&!!u()?.name.trim()&&!!u()?.baseURL.trim()&&!!u()?.projectSID.trim()&&(!!u()?.id||!!I().trim()),H=()=>f()&&!d()&&!g()&&p()?.source!=="env";function q(t,i){H()&&K("files",async()=>(Q(await w.setFiles({inspect:t,allowUninspectable:i},x())),{key:t?"filesSavedOn":"filesSavedOff"}))}const fe=()=>T()?a.t(T().key,T().params):"",Re=t=>({id:t.id,name:t.name,baseURL:t.baseURL,projectSID:t.projectSID,allowLoopbackHTTP:t.allowLoopbackHTTP,revision:l().revision});function j(t){const i=t?Re(t):{name:"",baseURL:"",projectSID:"",allowLoopbackHTTP:!1,revision:l()?.revision??0};N(i),se({...i}),O(""),de(!1),R(void 0)}function Z(t,i){k()&&N(m=>m&&{...m,[t]:i})}async function E(){return U||(U=(async()=>{try{const t=await w.connections({},x());if(v)return;const i=b(),m=$()||A();oe(t),J(!0);try{const s=await w.files({},x());v||Q(s)}catch{Q(void 0)}if(!V)V=!0,j(t.items.find(s=>s.active)??t.items[0]);else if(!m&&u()?.id){const s=t.items.find(_=>_.id===u().id),S=i&&s&&(i.baseURL!==s.baseURL||i.projectSID!==s.projectSID||i.tokenPresent!==s.tokenPresent||i.tokenHint!==s.tokenHint||i.allowLoopbackHTTP!==s.allowLoopbackHTTP)?void 0:T();j(s??t.items.find(_=>_.active)??t.items[0]),R(S)}else!m&&u()&&(N(s=>s&&{...s,revision:t.revision}),se(s=>s&&{...s,revision:t.revision}));T()?.key==="statusFailed"&&R(void 0)}catch{v||(J(!1),R({key:"statusFailed",error:!0}))}finally{U=void 0}})(),U)}function B(t){if(!(d()||!f()||g())&&!(t.kind==="select"&&t.id===u()?.id)){if(t.kind==="disconnect"||$()||A()){z(t);return}me(t)}}function me(t){t.kind==="select"?j(l()?.items.find(i=>i.id===t.id)):t.kind==="new"?j():t.kind==="reset"&&j(b())}async function he(){const t=g();!t||d()||!f()||(z(void 0),t.kind==="disconnect"?await K("disconnect",async()=>(await w.setEnabled({enabled:!1},x()),{key:"catalogDisconnected"})):me(t))}async function K(t,i){if(!(d()||v)){ce(t);try{if(await U,!f()||v)return;const m=await i();if(v||(await E(),v))return;f()&&R(m)}catch{v||(t!=="check"&&(de(!0),J(!1)),await E(),v||R({key:t==="check"?"testError":"catalogOutcomeUnknown",error:!0}))}finally{v||ce("")}}}function Ue(){if(!pe())return;const t={...u(),...I()?{token:I()}:{}};O(""),K("save",async()=>{if(t.revision!==l()?.revision)return{key:"catalogConflict",error:!0};const i=await w.saveConnection(t,x());if(v)return{key:"catalogSaved"};const m=t.id??i.items.find(s=>!l()?.items.some(C=>C.id===s.id))?.id;return oe(i),j(i.items.find(s=>s.id===m)),{key:"catalogSaved"}})}function ve(t=!1){if(!X()||t&&l()?.environmentOverride)return;const i=b().id,m=b().name;K(t?"connect":"check",async()=>{const s=l();if(!s||u()?.id!==i||$()||G())return{key:"catalogConflict",error:!0};const C={id:i,revision:s.revision},S=await(t?w.connect(C,x(19e4)):w.testConnection(C,x(19e4)));return S.connected?{key:t?"catalogConnected":"catalogChecked",params:{name:m,decision:S.decision??"—"}}:{key:S.code==="key_required"?"catalogKeyRequired":S.code==="timeout"?"timeout":"guardTestFailed",error:!0}})}return r.onMount(()=>{E();const t=setInterval(()=>{!d()&&!g()&&E()},5e3);r.onCleanup(()=>clearInterval(t))}),r.onCleanup(()=>{v=!0,ue.abort(),O("")}),(()=>{var t=Qe(),i=t.firstChild,m=i.nextSibling,s=m.firstChild,C=m.nextSibling,S=C.nextSibling,_=S.firstChild,P=_.nextSibling,be=P.firstChild,F=be.nextSibling,je=F.firstChild,ee=F.nextSibling,Ae=ee.firstChild,te=ee.nextSibling,He=te.firstChild,ne=te.nextSibling,Ee=ne.firstChild,Ke=ne.nextSibling,ae=S.nextSibling,ye=ae.firstChild,ke=ye.firstChild,Ne=ke.nextSibling;return e.insert(s,()=>a.t("catalogTitle")),e.insert(m,e.createComponent(c.Button,{variant:"ghost",size:"normal",get disabled(){return!k()},onClick:()=>B({kind:"new"}),get children(){return a.t("catalogAdd")}}),null),e.insert(t,e.createComponent(r.Show,{get when(){return e.memo(()=>!!g())()&&g()?.kind!=="disconnect"},get children(){var n=qe(),o=n.firstChild,h=o.nextSibling;return e.insert(o,()=>a.t(g()?.kind==="disconnect"?"catalogDisconnectConfirm":"catalogDiscardConfirm")),e.insert(h,e.createComponent(c.Button,{variant:"contrast",size:"normal",get disabled(){return!!d()||!f()},onClick:()=>{he()},get children(){return a.t(g()?.kind==="disconnect"?"catalogDisconnect":"catalogDiscard")}}),null),e.insert(h,e.createComponent(c.Button,{variant:"ghost",size:"normal",get disabled(){return!!d()},onClick:()=>z(void 0),get children(){return a.t(g()?.kind==="disconnect"?"catalogCancel":"catalogContinue")}}),null),n}}),C),e.insert(C,e.createComponent(c.TextInput,{class:"ocguard-input",size:"large",get label(){return a.t("catalogSearch")},get placeholder(){return a.t("catalogSearchPlaceholder")},get value(){return le()},get disabled(){return!!d()||!!g()},onInput:Pe})),e.insert(_,e.createComponent(r.For,{get each(){return ge()},get fallback(){return(()=>{var n=W();return e.insert(n,()=>a.t(V?l()?.items.length?"catalogNoResults":"catalogEmpty":"loading")),n})()},children:n=>e.createComponent(c.Button,{variant:"ghost",class:"ocguard-item",get"aria-label"(){return n.name},get"aria-pressed"(){return u()?.id===n.id},get disabled(){return!!d()||!f()||!!g()},onClick:()=>B({kind:"select",id:n.id}),get children(){return[(()=>{var o=Xe(),h=o.firstChild;return e.insert(h,()=>n.name),e.insert(o,e.createComponent(r.Show,{get when(){return n.active},get children(){var y=Ve();return e.insert(y,()=>a.t("catalogActive")),y}}),null),o})(),(()=>{var o=$e();return e.insert(o,()=>n.baseURL.replace(/^https?:\/\//,"")),o})(),(()=>{var o=Ze(),h=o.firstChild,y=h.nextSibling;return y.nextSibling,e.insert(o,()=>n.projectSID.slice(0,8),y),e.insert(o,()=>n.projectSID.slice(-4),null),o})(),(()=>{var o=$e();return e.insert(o,()=>a.t(n.tokenPresent?"catalogKeyAvailable":"catalogKeyRequired")),o})()]}})})),e.insert(be,(()=>{var n=e.memo(()=>!!u()?.id);return()=>n()?re()?.name:a.t("catalogNew")})()),e.insert(P,e.createComponent(r.Show,{get when(){return l()?.environmentOverride},get children(){var n=W();return e.insert(n,()=>a.t("connectionEnvironment")),n}}),F),e.insert(je,()=>a.t("catalogName")),e.insert(F,e.createComponent(c.TextInput,{class:"ocguard-input",size:"large",get label(){return a.t("catalogName")},get value(){return u()?.name??""},get disabled(){return!k()},onInput:n=>Z("name",n)}),null),e.insert(Ae,()=>a.t("catalogServer")),e.insert(ee,e.createComponent(c.TextInput,{class:"ocguard-input",size:"large",get label(){return a.t("catalogServer")},type:"url",get value(){return u()?.baseURL??""},get disabled(){return!k()},onInput:n=>Z("baseURL",n)}),null),e.insert(He,()=>a.t("projectSID")),e.insert(te,e.createComponent(c.TextInput,{class:"ocguard-input",size:"large",get label(){return a.t("projectSID")},get value(){return u()?.projectSID??""},get disabled(){return!k()},onInput:n=>Z("projectSID",n)}),null),e.insert(Ee,()=>a.t("guardKey")),e.insert(ne,e.createComponent(c.TextInput,{class:"ocguard-input",size:"large",get label(){return a.t("guardKey")},type:"password",get placeholder(){return e.memo(()=>!!b()?.tokenPresent)()?b()?.tokenHint??"••••":a.t("catalogEnterKey")},get value(){return I()},get disabled(){return!k()},onInput:n=>{k()&&O(n)}}),null),e.insert(Ke,()=>a.t(I().trim()?"catalogSaveKey":b()?.tokenPresent?"keyStorage":"catalogRestoreKey")),e.insert(P,e.createComponent(c.Switch,{get label(){return a.t("allowHTTP")},get checked(){return u()?.allowLoopbackHTTP??!1},get disabled(){return!k()},onChange:n=>{k()&&N(o=>o&&{...o,allowLoopbackHTTP:n})}}),null),e.insert(P,e.createComponent(r.Show,{get when(){return e.memo(()=>!!G())()&&$()},get children(){var n=Be();return e.insert(n,()=>a.t("catalogConflict")),n}}),null),e.insert(P,e.createComponent(r.Show,{get when(){return g()?.kind!=="disconnect"},get children(){var n=Fe();return e.insert(n,e.createComponent(c.Button,{variant:"neutral",size:"normal",get busy(){return d()==="save"},get disabled(){return!pe()},onClick:Ue,get children(){return a.t("catalogSave")}}),null),e.insert(n,e.createComponent(r.Show,{get when(){return $()||A()},get children(){return e.createComponent(c.Button,{variant:"ghost",size:"normal",get disabled(){return!!d()||!f()},onClick:()=>B({kind:"reset"}),get children(){return a.t("catalogCancel")}})}}),null),e.insert(n,e.createComponent(c.Button,{variant:"contrast",size:"normal",get busy(){return d()==="connect"},get disabled(){return!X()||!!l()?.environmentOverride||!!b()?.active&&!!l()?.enabled&&!!l()?.configured},onClick:()=>ve(!0),get children(){return a.t(b()?.active&&l()?.enabled&&l()?.configured?"catalogActive":"catalogConnect")}}),null),e.insert(n,e.createComponent(r.Show,{get when(){return l()?.enabled},get children(){return e.createComponent(c.Button,{variant:"ghost",size:"normal",get disabled(){return!!d()||!f()||!!g()},onClick:()=>B({kind:"disconnect"}),get children(){return a.t("catalogDisconnect")}})}}),null),n}}),null),e.insert(P,e.createComponent(r.Show,{get when(){return g()?.kind==="disconnect"},get children(){var n=Me(),o=n.firstChild,h=o.nextSibling;return e.insert(o,()=>a.t(g()?.kind==="disconnect"?"catalogDisconnectConfirm":"catalogDiscardConfirm")),e.insert(h,e.createComponent(c.Button,{variant:"contrast",size:"normal",get disabled(){return!!d()||!f()},onClick:()=>{he()},get children(){return a.t(g()?.kind==="disconnect"?"catalogDisconnect":"catalogDiscard")}}),null),e.insert(h,e.createComponent(c.Button,{variant:"ghost",size:"normal",get disabled(){return!!d()},onClick:()=>z(void 0),get children(){return a.t(g()?.kind==="disconnect"?"catalogCancel":"catalogContinue")}}),null),n}}),null),e.insert(P,e.createComponent(r.Show,{get when(){return e.memo(()=>!!l()?.environmentOverride)()&&!l()?.enabled},get children(){return e.createComponent(c.Button,{variant:"contrast",size:"normal",get disabled(){return!!d()||!f()||!l()?.configured},onClick:()=>{K("enable",async()=>(await w.setEnabled({enabled:!0},x()),{key:"enabled"}))},get children(){return a.t("enable")}})}}),null),e.insert(t,e.createComponent(r.Show,{get when(){return p()},get children(){var n=We(),o=n.firstChild,h=o.nextSibling,y=h.firstChild,Ce=y.nextSibling,Oe=h.nextSibling,Se=Oe.firstChild,we=Se.nextSibling;return e.insert(o,()=>a.t("filesTitle")),e.insert(y,()=>a.t("filesInspect")),e.insert(Ce,e.createComponent(c.Button,{get variant(){return p().inspect?"ghost":"contrast"},size:"normal",get disabled(){return!H()},onClick:()=>q(!1,p().allowUninspectable),get children(){return`${p().inspect?"":"✓ "}${a.t("filesOff")}`}}),null),e.insert(Ce,e.createComponent(c.Button,{get variant(){return p().inspect?"contrast":"ghost"},size:"normal",get disabled(){return!H()},onClick:()=>q(!0,p().allowUninspectable),get children(){return`${p().inspect?"✓ ":""}${a.t("filesOn")}`}}),null),e.insert(Se,()=>a.t("filesUninspectable")),e.insert(we,e.createComponent(c.Button,{get variant(){return p().allowUninspectable?"ghost":"contrast"},size:"normal",get disabled(){return!H()},onClick:()=>q(p().inspect,!1),get children(){return`${p().allowUninspectable?"":"✓ "}${a.t("filesBlock")}`}}),null),e.insert(we,e.createComponent(c.Button,{get variant(){return p().allowUninspectable?"contrast":"ghost"},size:"normal",get disabled(){return!H()},onClick:()=>q(p().inspect,!0),get children(){return`${p().allowUninspectable?"✓ ":""}${a.t("filesAllow")}`}}),null),e.insert(n,e.createComponent(r.Show,{get when(){return p().source==="env"},get children(){var D=W();return e.insert(D,()=>a.t("filesEnv")),D}}),null),e.insert(n,e.createComponent(r.Show,{get when(){return p().damaged},get children(){var D=Ye();return e.insert(D,()=>a.t("filesDamaged")),D}}),null),e.insert(n,e.createComponent(r.Show,{get when(){return p().inspect},get children(){var D=W();return e.insert(D,()=>a.t(p().allowUninspectable?"filesAllowNote":"filesNote")),D}}),null),n}}),ae),e.insert(ke,()=>a.t("catalogRoute",{name:l()?.activeLabel||a.t("catalogNone")})),e.insert(Ne,()=>a.t(f()?l()?.enabled?l()?.configured?"enabled":"blocked":"disabled":"statusUnavailable")),e.insert(ye,e.createComponent(r.Show,{get when(){return fe()},get children(){var n=Je();return e.insert(n,fe),e.effect(o=>{var h=T()?.error?"alert":"status",y=`ocguard-note${T()?.error?" ocguard-error":""}`;return h!==o.e&&e.setAttribute(n,"role",o.e=h),y!==o.t&&e.className(n,o.t=y),o},{e:void 0,t:void 0}),n}}),null),e.insert(ae,e.createComponent(c.Button,{variant:"ghost",size:"normal",get busy(){return d()==="check"},get disabled(){return!!d()||!!g()||f()&&!X()},onClick:()=>{f()?ve():E()},get children(){return a.t(f()?d()==="check"?"testing":"catalogCheck":"catalogRetry")}}),null),e.effect(()=>e.setAttribute(_,"aria-label",a.t("catalogTitle"))),t})()}const tt=ie.Plugin.define({i18n:ze,setup(L){L.add(ie.SettingsPage,{id:"llmguard",title:"LLMGuard",render:()=>e.createComponent(et,{ctx:L})}),L.add(ie.Command,{id:"settings",get title(){return L.t("settings")},run:()=>L.layout.settings("llmguard")})}});exports.default=tt;
@@ -0,0 +1,2 @@
1
+ export type HookTrace = (reason: string) => void;
2
+ export declare function createHookTracer(): HookTrace;
package/hook-trace.js ADDED
@@ -0,0 +1,35 @@
1
+ import { appendFileSync, renameSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ // Diagnostics for hook activity: timestamps, hook kind and a short reason code
5
+ // only. Never message content, credentials or response bodies. Everything is
6
+ // bounded to one small local file that rotates, and every failure of the tracer
7
+ // itself is swallowed so tracing can never affect guarding.
8
+ const maxTraceBytes = 256 * 1024;
9
+ const tracePath = () => {
10
+ const override = process.env["LLMGUARD_TRACE_FILE"];
11
+ if (override) {
12
+ return override;
13
+ }
14
+ const data = process.env["XDG_DATA_HOME"] || join(homedir(), ".local/share");
15
+ return join(data, "opencode/log/llmguard-hooks.log");
16
+ };
17
+ export function createHookTracer() {
18
+ return (reason) => {
19
+ try {
20
+ const file = tracePath();
21
+ try {
22
+ if (statSync(file).size > maxTraceBytes) {
23
+ renameSync(file, `${file}.1`);
24
+ }
25
+ }
26
+ catch {
27
+ /* Missing file is fine; the first append creates it. */
28
+ }
29
+ appendFileSync(file, `${new Date().toISOString()} ${reason}\n`);
30
+ }
31
+ catch {
32
+ /* Tracing is best-effort diagnostics only. */
33
+ }
34
+ };
35
+ }
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./server.js";
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./server.js";
@@ -0,0 +1,27 @@
1
+ Copyright 2009 The Go Authors.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ * Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+ * Redistributions in binary form must reproduce the above
10
+ copyright notice, this list of conditions and the following disclaimer
11
+ in the documentation and/or other materials provided with the
12
+ distribution.
13
+ * Neither the name of Google LLC nor the names of its
14
+ contributors may be used to endorse or promote products derived from
15
+ this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.