@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,394 @@
1
+ import { tuiText } from "./tui-messages.js";
2
+ export function registerConnectionsTUI(context, api, locale = process.env.LC_ALL ||
3
+ process.env.LC_MESSAGES ||
4
+ process.env.LANG ||
5
+ "en") {
6
+ const tr = tuiText(locale);
7
+ let open = false, disposed = false;
8
+ let inList = false;
9
+ let selected;
10
+ let draft;
11
+ const notify = (message, variant = "info") => {
12
+ if (!disposed) {
13
+ context.ui.toast.show({ title: "LLMGuard", message, variant });
14
+ }
15
+ };
16
+ async function edit(list, id) {
17
+ if (list.environmentOverride) {
18
+ return;
19
+ }
20
+ const existing = list.items.find((p) => p.id === id);
21
+ if (draft && draft.id !== id) {
22
+ if (!(await context.ui.dialog.confirm({
23
+ title: tr("Отбросить другой черновик?"),
24
+ message: tr("Сохранённые подключения не изменятся."),
25
+ label: { confirm: tr("Отбросить"), cancel: tr("Назад") },
26
+ }))) {
27
+ return;
28
+ }
29
+ }
30
+ if (draft && draft.id !== id) {
31
+ draft = undefined;
32
+ }
33
+ draft ??= {
34
+ ...(existing
35
+ ? {
36
+ id: existing.id,
37
+ name: existing.name,
38
+ baseURL: existing.baseURL,
39
+ projectSID: existing.projectSID,
40
+ allowLoopbackHTTP: existing.allowLoopbackHTTP,
41
+ }
42
+ : { name: "", baseURL: "", projectSID: "", allowLoopbackHTTP: false }),
43
+ revision: list.revision,
44
+ };
45
+ while (!disposed && draft) {
46
+ const pendingField = context.ui.dialog.select({
47
+ title: tr("LLMGuard · Черновик подключения"),
48
+ placeholder: tr("Выберите поле или сохраните"),
49
+ options: [
50
+ {
51
+ title: tr("Название"),
52
+ value: "name",
53
+ description: draft.name || tr("Не задано"),
54
+ },
55
+ {
56
+ title: tr("Сервер"),
57
+ value: "baseURL",
58
+ description: draft.baseURL || tr("Не задан"),
59
+ },
60
+ {
61
+ title: tr("SID проекта"),
62
+ value: "projectSID",
63
+ description: draft.projectSID || tr("Не задан"),
64
+ },
65
+ {
66
+ title: tr("Протокол"),
67
+ value: "protocol",
68
+ description: draft.allowLoopbackHTTP
69
+ ? tr("HTTP разрешён (без TLS)")
70
+ : "HTTPS",
71
+ },
72
+ {
73
+ title: tr("Сохранить"),
74
+ value: "save",
75
+ description: tr("Активное подключение останется прежним"),
76
+ },
77
+ { title: tr("Отбросить черновик…"), value: "discard" },
78
+ ],
79
+ });
80
+ context.ui.dialog.set({ size: "xlarge" });
81
+ const field = await pendingField;
82
+ if (disposed || field === undefined) {
83
+ return;
84
+ }
85
+ if (field === "discard") {
86
+ if (await context.ui.dialog.confirm({
87
+ title: tr("Отбросить черновик?"),
88
+ message: tr("Сохранённые подключения не изменятся."),
89
+ label: { confirm: tr("Отбросить"), cancel: tr("Продолжить") },
90
+ })) {
91
+ draft = undefined;
92
+ }
93
+ continue;
94
+ }
95
+ if (field === "protocol") {
96
+ const mode = await context.ui.dialog.select({
97
+ title: tr("Протокол"),
98
+ current: draft.allowLoopbackHTTP ? "http" : "https",
99
+ options: [
100
+ { title: "HTTPS", value: "https" },
101
+ { title: tr("Разрешить HTTP (без TLS)"), value: "http" },
102
+ ],
103
+ });
104
+ if (mode !== undefined && !disposed) {
105
+ draft.allowLoopbackHTTP = mode === "http";
106
+ }
107
+ }
108
+ else if (field === "name" ||
109
+ field === "baseURL" ||
110
+ field === "projectSID") {
111
+ const value = await context.ui.dialog.prompt({
112
+ title: {
113
+ name: tr("Название"),
114
+ baseURL: tr("Сервер Guard"),
115
+ projectSID: tr("SID проекта"),
116
+ }[field],
117
+ value: draft[field],
118
+ });
119
+ if (value !== undefined && !disposed) {
120
+ draft[field] = value.trim();
121
+ }
122
+ }
123
+ else if (field === "save") {
124
+ if (!draft.name || !draft.baseURL || !draft.projectSID) {
125
+ notify(tr("Заполните название, сервер и SID проекта."), "error");
126
+ continue;
127
+ }
128
+ let token = await context.ui.dialog.prompt({
129
+ title: tr("Ключ Guard"),
130
+ description: tr("Ключ виден при вводе; сохраняется локально на сервере OpenCode. Пусто — сохранить ключ этого подключения. Отмена возвращает к черновику."),
131
+ });
132
+ if (token === undefined || disposed) {
133
+ return;
134
+ }
135
+ try {
136
+ const input = { ...draft, ...(token ? { token } : {}) };
137
+ token = undefined;
138
+ const result = (await api.saveConnection(input));
139
+ // An unknown write result is never retried automatically.
140
+ selected = draft.id ?? result.items.at(-1)?.id;
141
+ draft = undefined;
142
+ notify(tr("Подключение сохранено. Активный проект не изменён."), "success");
143
+ }
144
+ catch {
145
+ notify(tr("Сохранение не подтверждено. Черновик сохранён; обновите список перед повтором."), "error");
146
+ return;
147
+ }
148
+ }
149
+ }
150
+ }
151
+ async function panel() {
152
+ if (open || disposed) {
153
+ return;
154
+ }
155
+ open = true;
156
+ try {
157
+ while (!disposed) {
158
+ let list;
159
+ try {
160
+ list = (await api.connections());
161
+ }
162
+ catch {
163
+ const retry = await context.ui.dialog.confirm({
164
+ title: tr("Список недоступен"),
165
+ message: tr("Состояние подключения неизвестно. Проверьте серверный плагин."),
166
+ label: { confirm: tr("Повторить"), cancel: tr("Закрыть") },
167
+ });
168
+ if (!retry || disposed) {
169
+ return;
170
+ }
171
+ continue;
172
+ }
173
+ if (disposed) {
174
+ return;
175
+ }
176
+ // Reconcile a retained draft only when storage is unchanged; never silently rebase a write.
177
+ let action;
178
+ const trigger = (name, id) => {
179
+ if (id === "__add" && (name === "test" || name === "connect")) {
180
+ return;
181
+ }
182
+ if (action || disposed) {
183
+ return;
184
+ }
185
+ action = { name, ...(id ? { id } : {}) };
186
+ if (id) {
187
+ selected = id;
188
+ }
189
+ context.ui.dialog.clear();
190
+ };
191
+ inList = true;
192
+ const pendingChoice = context.ui.dialog.select({
193
+ title: `LLMGuard · ${list.enabled ? (list.configured ? tr("защита включена") : tr("операции блокируются")) : tr("защита выключена")}${list.environmentOverride ? tr(" · окружение") : ""}`,
194
+ placeholder: tr("Название, сервер или SID"),
195
+ ...((selected ?? list.items.find((p) => p.active)?.id)
196
+ ? { current: selected ?? list.items.find((p) => p.active).id }
197
+ : {}),
198
+ options: [
199
+ ...list.items.map((p) => ({
200
+ title: p.name,
201
+ value: p.id,
202
+ description: `${p.baseURL} · SID ${p.projectSID.slice(0, 8)}…${p.projectSID.slice(-4)}`,
203
+ footer: p.active
204
+ ? tr("Подключён")
205
+ : p.tokenPresent
206
+ ? ""
207
+ : tr("Нужен ключ"),
208
+ })),
209
+ ...(!list.environmentOverride
210
+ ? [{ title: tr("Добавить"), value: "__add", description: "+" }]
211
+ : []),
212
+ ],
213
+ search: (query, options) => options.filter((option) => {
214
+ if (option.value === "__add") {
215
+ return true;
216
+ }
217
+ const p = list.items.find((p) => p.id === option.value);
218
+ return `${p.name} ${p.baseURL} ${p.projectSID}`
219
+ .toLowerCase()
220
+ .includes(query.toLowerCase());
221
+ }),
222
+ actions: [
223
+ ...(!list.environmentOverride && list.items.length
224
+ ? [
225
+ {
226
+ bind: "enter",
227
+ title: tr("Изменить"),
228
+ onTrigger: (id) => trigger(id === "__add" ? "add" : "edit", id),
229
+ },
230
+ ]
231
+ : []),
232
+ ...(!list.environmentOverride
233
+ ? [
234
+ {
235
+ bind: "ctrl+s",
236
+ title: tr("Подключить"),
237
+ onTrigger: (id) => trigger("connect", id),
238
+ },
239
+ ]
240
+ : list.configured && !list.enabled
241
+ ? [
242
+ {
243
+ bind: "ctrl+s",
244
+ title: tr("Включить"),
245
+ selection: "none",
246
+ onTrigger: () => trigger("enable"),
247
+ },
248
+ ]
249
+ : []),
250
+ {
251
+ bind: "ctrl+t",
252
+ title: tr("Проверить"),
253
+ onTrigger: (id) => trigger("test", id),
254
+ },
255
+ ...(!list.environmentOverride
256
+ ? [
257
+ {
258
+ bind: "ctrl+n",
259
+ title: tr("Добавить"),
260
+ selection: "none",
261
+ onTrigger: () => trigger("add"),
262
+ },
263
+ ]
264
+ : []),
265
+ ...(draft
266
+ ? [
267
+ {
268
+ bind: "ctrl+r",
269
+ title: tr("Черновик"),
270
+ selection: "none",
271
+ onTrigger: () => trigger("resume"),
272
+ },
273
+ ]
274
+ : []),
275
+ ...(list.enabled
276
+ ? [
277
+ {
278
+ bind: "ctrl+d",
279
+ title: tr("Отключить…"),
280
+ selection: "none",
281
+ onTrigger: () => trigger("disconnect"),
282
+ },
283
+ ]
284
+ : []),
285
+ ],
286
+ });
287
+ context.ui.dialog.set({ size: "xlarge" });
288
+ const choice = await pendingChoice;
289
+ inList = false;
290
+ if (disposed) {
291
+ return;
292
+ }
293
+ const next = action ??
294
+ (choice === undefined
295
+ ? undefined
296
+ : choice === "__add"
297
+ ? { name: "add" }
298
+ : { name: "edit", id: choice });
299
+ if (!next) {
300
+ return;
301
+ }
302
+ if (next.id) {
303
+ selected = next.id;
304
+ }
305
+ try {
306
+ if (next.name === "add" ||
307
+ next.name === "edit" ||
308
+ next.name === "resume") {
309
+ await edit(list, next.name === "add"
310
+ ? undefined
311
+ : next.name === "resume"
312
+ ? draft?.id
313
+ : next.id);
314
+ }
315
+ else if (next.name === "disconnect") {
316
+ if ((await context.ui.dialog.confirm({
317
+ title: tr("Отключить защиту?"),
318
+ message: tr("Запросы всех сессий этого сервера будут проходить без проверки Guard."),
319
+ label: { confirm: tr("Отключить"), cancel: tr("Отмена") },
320
+ })) &&
321
+ !disposed) {
322
+ await api.setEnabled({ enabled: false });
323
+ notify(tr("Защита выключена."));
324
+ }
325
+ }
326
+ else if (next.name === "enable" && list.environmentOverride) {
327
+ await api.setEnabled({ enabled: true });
328
+ notify(tr("Защита включена."), "success");
329
+ }
330
+ else if (next.id) {
331
+ if (next.name === "connect" && list.environmentOverride) {
332
+ notify(tr("Подключение задано окружением сервера."));
333
+ continue;
334
+ }
335
+ notify(next.name === "connect"
336
+ ? tr("Проверка перед подключением…")
337
+ : tr("Проверка выбранного подключения…"));
338
+ const input = { id: next.id, revision: list.revision };
339
+ const result = (await (next.name === "test"
340
+ ? api.testConnection(input)
341
+ : api.connect(input)));
342
+ notify(result.connected
343
+ ? next.name === "test"
344
+ ? tr("Guard доступен. Активное подключение не изменено.")
345
+ : tr("Подключение применено. Защита включена.")
346
+ : result.code === "key_required"
347
+ ? tr("Нужен ключ: выберите «Изменить», затем «Сохранить».")
348
+ : tr("Проверка не пройдена. Проверьте сервер, SID и ключ."), result.connected ? "success" : "error");
349
+ }
350
+ }
351
+ catch {
352
+ notify(tr("Результат действия неизвестен. Проверьте обновлённый список перед повтором."), "error");
353
+ }
354
+ }
355
+ }
356
+ finally {
357
+ inList = false;
358
+ open = false;
359
+ }
360
+ }
361
+ // The host input also owns Ctrl+N/T. Reuse the native footer commands at
362
+ // a higher priority only while this plugin's connection list is open.
363
+ context.keymap.layer(() => ({
364
+ mode: "modal",
365
+ priority: 1000,
366
+ target: () => context.renderer?.currentFocusedRenderable,
367
+ enabled: () => inList && !disposed,
368
+ commands: context.keymap
369
+ .commands()
370
+ .filter((command) => command.id?.startsWith("plugin.dialog.select.") &&
371
+ typeof command.bind === "string" &&
372
+ command.bind.startsWith("ctrl+"))
373
+ .map((command) => ({ bind: command.bind, run: command.run })),
374
+ }));
375
+ context.keymap.layer(() => ({
376
+ mode: "global",
377
+ commands: [
378
+ {
379
+ id: "llmguard.settings",
380
+ title: tr("LLMGuard: подключения"),
381
+ group: "LLMGuard",
382
+ palette: true,
383
+ slash: { name: "llmguard" },
384
+ run: panel,
385
+ },
386
+ ],
387
+ }));
388
+ return () => {
389
+ disposed = true;
390
+ if (open) {
391
+ context.ui.dialog.clear();
392
+ }
393
+ };
394
+ }
package/demasking.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export type DemaskTrace = (reason: string) => void;
2
+ export declare function demaskBody(response: Response, values: ReadonlyMap<string, string>, trace?: DemaskTrace): Response;