@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
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # LLMGuard для OpenCode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Плагин проверяет текст модельных запросов и вызовы инструментов через LLMGuard.
4
+ Guard определяет, разрешить, замаскировать или заблокировать данные. OpenCode 2
5
+ локально восстанавливает известные маркеры текущей сессии в поддерживаемых JSON
6
+ и SSE-ответах, а в аргументах инструментов — перед проверкой вызова.
7
+
8
+ Маскирование применяется к поддерживаемым текстовым полям. Метаданные, числа и
9
+ неизвестные части проходят без проверки. Если формат ответа вне области
10
+ восстановления, маркеры остаются видимыми. Наблюдение после выполнения инструмента
11
+ не отменяет выполненное действие.
12
+
13
+ В настройках можно включить проверку вложений через Guard file API. Плагин
14
+ применяет разрешённое маскирование к простым текстовым файлам, если их можно
15
+ безопасно заменить. В остальных случаях требование замаскировать вложение
16
+ блокирует запрос.
17
+
18
+ ## Подключение в OpenCode 2
19
+
20
+ 1. Распакуйте ZIP релиза в постоянный каталог. Добавьте абсолютный путь корня
21
+ пакета в массив `plugins` файла `opencode.json` или `opencode.jsonc`.
22
+ Готовый пример находится в `opencode.example.json`. Для удалённого OpenCode
23
+ распакуйте пакет и измените настройки на сервере.
24
+ 2. Перезапустите OpenCode. Откройте `/llmguard` в TUI или **Settings → LLMGuard**
25
+ в Desktop, если его экспериментальный GUI API совместим с SDK 2.2.5.
26
+ 3. Добавьте URL Guard, SID проекта и ключ. HTTPS используется по умолчанию.
27
+ В TUI используйте **Ctrl+N** для добавления, **Ctrl+T** для проверки и
28
+ **Ctrl+S** для подключения и включения защиты. В Desktop используйте
29
+ отдельные кнопки проверки и подключения.
30
+
31
+ Защита включается явно и применяется ко всем сессиям сервера OpenCode.
32
+ Сохранение изменений в каталоге оставляет активное подключение до повторного
33
+ подключения. Ключ хранится в серверном хранилище плагина без шифрования.
34
+ Для отключения защиты используйте действие LLMGuard (**Ctrl+D** в TUI).
35
+ Закрытие TUI, Desktop или отключение расширения GUI оставляет серверную
36
+ настройку активной.
37
+
38
+ ZIP содержит готовые бинарники. Подтверждён запуск helper на Linux x64.
39
+ Нативная приёмка остальных систем, Desktop и реальных SSE-провайдеров
40
+ остаётся отдельной проверкой. Целостность ZIP можно проверить через
41
+ `node verify.mjs` в распакованном каталоге с Node.js 24.
42
+
43
+ ## OpenCode 1 и программный API
44
+
45
+ Для OpenCode 1 используйте npm-поставку `@llmguard/opencode` с legacy entrypoint
46
+ `plugin.js`. В OpenCode 1 настройка `plugin` принимает file URL к entrypoint.
47
+ Конфигурация Guard задаётся через окружение `LLMGUARD_BASE_URL`,
48
+ `LLMGUARD_PROJECT_SID` и `LLMGUARD_TOKEN`.
49
+
50
+ С версии 0.1.0 корневой импорт указывает на сервер OpenCode 2, а
51
+ `createOpenCodeHooks`, `OpenCodeGuardError` и `PluginOptions` доступны из
52
+ `@llmguard/opencode/v1`. `createOpenCodeHooks` принимает только `options`.
53
+ Прежние экспорты внутреннего Guard API удалены. Для v2 доступны subpaths
54
+ `/server`, `/tui` и `/rpc` (`/settings-rpc` остаётся алиасом).
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,51 @@
1
+ {
2
+ "artifacts": [
3
+ {
4
+ "arch": "amd64",
5
+ "bytes": 7655584,
6
+ "file": "bin/linux-amd64/helper",
7
+ "os": "linux",
8
+ "sha256": "1f0c23b53fbe94bbe08d13b95659ad0dedd0af68e3145f2e45c5ffcd1c12d715"
9
+ },
10
+ {
11
+ "arch": "arm64",
12
+ "bytes": 7078048,
13
+ "file": "bin/linux-arm64/helper",
14
+ "os": "linux",
15
+ "sha256": "e0723f6b2196d05fb54b1f13f4b546825e0d6d0ed008a48d4cb8b517cd9f68ee"
16
+ },
17
+ {
18
+ "arch": "amd64",
19
+ "bytes": 7833136,
20
+ "file": "bin/darwin-amd64/helper",
21
+ "os": "darwin",
22
+ "sha256": "2b20501244f7abfbf9c7918fbbd3e6677cf7aecc7db83a2b986d6efbde4761d7"
23
+ },
24
+ {
25
+ "arch": "arm64",
26
+ "bytes": 7250018,
27
+ "file": "bin/darwin-arm64/helper",
28
+ "os": "darwin",
29
+ "sha256": "913021c77f2c1754850af2f38ff4688ff53a6c86378a9c4a44afa0eddd4eb248"
30
+ },
31
+ {
32
+ "arch": "amd64",
33
+ "bytes": 7883776,
34
+ "file": "bin/windows-amd64/helper.exe",
35
+ "os": "windows",
36
+ "sha256": "80e314d419ecdcd95d15ef6c0481604ff724a18100591c1aa75e6e58737714cc"
37
+ },
38
+ {
39
+ "arch": "arm64",
40
+ "bytes": 7150592,
41
+ "file": "bin/windows-arm64/helper.exe",
42
+ "os": "windows",
43
+ "sha256": "fd5f2ec1119f29dc76d71ddb9c303d83f670ef7c43e10dd9dbb7e5d7c0d0c4cf"
44
+ }
45
+ ],
46
+ "cgo_enabled": false,
47
+ "ipc_protocol": 1,
48
+ "package": "@llmguard/opencode",
49
+ "schema_version": 1,
50
+ "version": "0.1.1"
51
+ }
Binary file
Binary file
@@ -0,0 +1,55 @@
1
+ import type { RequestOptions } from "./process.js";
2
+ import type { CheckParams, CheckResult, ConnectionParams, Params, Results } from "./protocol.js";
3
+ export type BridgeState = "starting" | "ready" | "failed" | "restarting" | "disposed";
4
+ type Options = {
5
+ helperURL?: URL;
6
+ onInvalidate?: () => void;
7
+ handshakeTimeoutMS?: number;
8
+ restart?: boolean;
9
+ };
10
+ export declare class PreparedCheck {
11
+ private readonly valid;
12
+ private result;
13
+ readonly authorization: CheckResult["authorization"];
14
+ readonly checkCode: string;
15
+ readonly decision: CheckResult["decision"];
16
+ constructor(result: CheckResult, valid: () => boolean);
17
+ take(): CheckResult;
18
+ }
19
+ export declare class BridgeClient {
20
+ private readonly options;
21
+ private bridgeState;
22
+ private current;
23
+ private boot;
24
+ private generationValue;
25
+ private revision;
26
+ private configuration;
27
+ private readonly restarts;
28
+ private restartTimer;
29
+ private restartWaiter;
30
+ private configTail;
31
+ private disposing;
32
+ private readonly retiring;
33
+ private readonly invalidationListeners;
34
+ constructor(options?: Options);
35
+ get state(): BridgeState;
36
+ get epoch(): string;
37
+ get generation(): number;
38
+ start(): Promise<void>;
39
+ private begin;
40
+ private bootProcess;
41
+ subscribeInvalidation(listener: () => void): () => void;
42
+ private invalidate;
43
+ private failed;
44
+ private scheduleRestart;
45
+ private ready;
46
+ validate(params: ConnectionParams, options?: RequestOptions): Promise<Results["connection.validate"]>;
47
+ configure(params: ConnectionParams, options?: RequestOptions): Promise<number>;
48
+ test(options: RequestOptions): Promise<Results["connection.test"]>;
49
+ attachmentsPolicy(options: RequestOptions): Promise<Results["attachments.policy"]>;
50
+ configureAttachments(params: Params["attachments.configure"], options: RequestOptions): Promise<Results["attachments.configure"]>;
51
+ routeLease(session: string, token: string, action: "renew" | "release", options: RequestOptions): Promise<number>;
52
+ check(params: Omit<CheckParams, "generation" | "budget_ms">, options: RequestOptions): Promise<PreparedCheck>;
53
+ dispose(): Promise<void>;
54
+ }
55
+ export {};
@@ -0,0 +1,425 @@
1
+ import { OpenCodeGuardError } from "../runtime/errors.js";
2
+ import { HelperProcess, helperURL } from "./process.js";
3
+ import { ProtocolError, decodeParams, maxBudgetMS } from "./protocol.js";
4
+ // Prepared data grants no reusable native permission. F1/F2 stage session maps
5
+ // before take(), then check their own snapshot/revision and apply synchronously.
6
+ export class PreparedCheck {
7
+ valid;
8
+ result;
9
+ authorization;
10
+ checkCode;
11
+ decision;
12
+ constructor(result, valid) {
13
+ this.valid = valid;
14
+ this.result = result;
15
+ this.authorization = result.authorization;
16
+ this.checkCode = result.check_code;
17
+ this.decision = result.decision;
18
+ }
19
+ take() {
20
+ const result = this.result;
21
+ this.result = undefined;
22
+ if (!result || !this.valid()) {
23
+ throw new ProtocolError("invalid_state");
24
+ }
25
+ if (result.authorization !== "allow" &&
26
+ result.authorization !== "transformed") {
27
+ const code = result.check_code === "success" && result.decision === "deny"
28
+ ? "guard_denied"
29
+ : result.check_code === "timeout"
30
+ ? "timeout"
31
+ : "unavailable";
32
+ // An attachment stopped the request before or after Guard looked at it.
33
+ // The helper wrote this message itself; it names the attachment by number.
34
+ const attachment = result.authorization === "blocked" &&
35
+ (result.check_code === "attachment_rejected" ||
36
+ result.check_code === "attachment_unavailable") &&
37
+ !!result.block_message;
38
+ const message = attachment ||
39
+ (result.authorization === "blocked" &&
40
+ result.check_code === "success" &&
41
+ result.decision === "deny" &&
42
+ result.reason_code === "rule_blocked" &&
43
+ result.block_message)
44
+ ? result.block_message
45
+ : undefined;
46
+ throw new OpenCodeGuardError(attachment
47
+ ? result.check_code === "attachment_rejected"
48
+ ? "blocked"
49
+ : "unavailable"
50
+ : code, message);
51
+ }
52
+ return result;
53
+ }
54
+ }
55
+ function waiter() {
56
+ let resolve;
57
+ let reject;
58
+ const promise = new Promise((yes, no) => {
59
+ resolve = yes;
60
+ reject = no;
61
+ });
62
+ // Auto-restart is proactive; absence of a caller must not create an unhandled rejection.
63
+ void promise.catch(() => { });
64
+ return { promise, resolve, reject };
65
+ }
66
+ export class BridgeClient {
67
+ options;
68
+ bridgeState = "starting";
69
+ current;
70
+ boot;
71
+ generationValue = 0;
72
+ revision = 0;
73
+ configuration;
74
+ restarts = [];
75
+ restartTimer;
76
+ restartWaiter;
77
+ configTail = Promise.resolve();
78
+ disposing;
79
+ retiring = new Set();
80
+ invalidationListeners = new Set();
81
+ constructor(options = {}) {
82
+ this.options = options;
83
+ }
84
+ get state() {
85
+ return this.bridgeState;
86
+ }
87
+ get epoch() {
88
+ return this.current?.epoch ?? "";
89
+ }
90
+ get generation() {
91
+ return this.generationValue;
92
+ }
93
+ start() {
94
+ if (this.bridgeState === "disposed") {
95
+ return Promise.reject(new ProtocolError("shutting_down"));
96
+ }
97
+ if (this.bridgeState === "ready") {
98
+ return Promise.resolve();
99
+ }
100
+ if (this.restartWaiter) {
101
+ return this.restartWaiter.promise;
102
+ }
103
+ if (this.boot) {
104
+ return this.boot;
105
+ }
106
+ if (this.bridgeState === "failed") {
107
+ return Promise.reject(new ProtocolError("invalid_state"));
108
+ }
109
+ return this.begin();
110
+ }
111
+ begin() {
112
+ this.bridgeState = "starting";
113
+ const attempt = this.bootProcess();
114
+ this.boot = attempt;
115
+ void attempt
116
+ .finally(() => {
117
+ if (this.boot === attempt) {
118
+ this.boot = undefined;
119
+ }
120
+ })
121
+ .catch(() => { });
122
+ return attempt;
123
+ }
124
+ async bootProcess() {
125
+ let transport;
126
+ try {
127
+ transport = new HelperProcess(this.options.helperURL ?? helperURL(), () => {
128
+ if (transport) {
129
+ this.failed(transport);
130
+ }
131
+ });
132
+ this.current = transport;
133
+ await transport.handshake(this.options.handshakeTimeoutMS ?? 5000);
134
+ if (this.current !== transport) {
135
+ throw new ProtocolError("invalid_state");
136
+ }
137
+ if (this.configuration) {
138
+ const configured = await transport.request("connection.configure", this.configuration, { deadline: performance.now() + 5000 });
139
+ if (this.current !== transport) {
140
+ throw new ProtocolError("invalid_state");
141
+ }
142
+ this.generationValue = configured.generation;
143
+ }
144
+ this.bridgeState = "ready";
145
+ }
146
+ catch (error) {
147
+ if (transport && this.current === transport) {
148
+ this.failed(transport);
149
+ }
150
+ else if (!transport && this.bridgeState !== "disposed") {
151
+ this.bridgeState = "failed";
152
+ this.scheduleRestart();
153
+ }
154
+ throw error instanceof ProtocolError
155
+ ? error
156
+ : new ProtocolError("invalid_state");
157
+ }
158
+ }
159
+ subscribeInvalidation(listener) {
160
+ this.invalidationListeners.add(listener);
161
+ return () => {
162
+ this.invalidationListeners.delete(listener);
163
+ };
164
+ }
165
+ invalidate() {
166
+ this.generationValue = 0;
167
+ this.revision++;
168
+ for (const listener of this.invalidationListeners) {
169
+ listener();
170
+ }
171
+ // The runtime callback clears mutable session bindings; no content is sent.
172
+ try {
173
+ this.options.onInvalidate?.();
174
+ }
175
+ catch {
176
+ /* Invalidation never enables protection. */
177
+ }
178
+ }
179
+ failed(transport) {
180
+ if (transport !== this.current || this.bridgeState === "disposed") {
181
+ return;
182
+ }
183
+ this.current = undefined;
184
+ this.invalidate();
185
+ this.bridgeState = "failed";
186
+ const retiring = transport.terminate();
187
+ this.retiring.add(retiring);
188
+ void retiring.finally(() => this.retiring.delete(retiring));
189
+ this.scheduleRestart();
190
+ }
191
+ scheduleRestart() {
192
+ if (this.options.restart === false ||
193
+ this.bridgeState === "disposed" ||
194
+ this.restartTimer) {
195
+ return;
196
+ }
197
+ const now = performance.now();
198
+ while (this.restarts.length && this.restarts[0] <= now - 60_000) {
199
+ this.restarts.shift();
200
+ }
201
+ if (this.restarts.length >= 3) {
202
+ return;
203
+ }
204
+ const delay = [250, 1000, 4000][this.restarts.length];
205
+ this.restarts.push(now);
206
+ this.bridgeState = "restarting";
207
+ const waiting = waiter();
208
+ this.restartWaiter = waiting;
209
+ this.restartTimer = setTimeout(() => {
210
+ this.restartTimer = undefined;
211
+ this.restartWaiter = undefined;
212
+ if (this.bridgeState === "disposed") {
213
+ waiting.reject(new ProtocolError("shutting_down"));
214
+ return;
215
+ }
216
+ void this.begin().then(waiting.resolve, (error) => waiting.reject(error instanceof ProtocolError
217
+ ? error
218
+ : new ProtocolError("invalid_state")));
219
+ }, delay);
220
+ }
221
+ // Startup time belongs to the caller's existing deadline, including when an
222
+ // operation arrives during a restart. Cancelling a waiter does not kill the
223
+ // shared startup needed by other operations.
224
+ async ready(options) {
225
+ options = { ...options };
226
+ if (options.signal?.aborted) {
227
+ throw new ProtocolError("cancelled");
228
+ }
229
+ if (!Number.isFinite(options.deadline) ||
230
+ options.deadline <= performance.now()) {
231
+ throw new ProtocolError("timeout");
232
+ }
233
+ if (options.deadline - performance.now() > maxBudgetMS) {
234
+ throw new ProtocolError("invalid_params");
235
+ }
236
+ await new Promise((resolve, reject) => {
237
+ const abort = () => {
238
+ cleanup();
239
+ reject(new ProtocolError("cancelled"));
240
+ };
241
+ const timer = setTimeout(() => {
242
+ cleanup();
243
+ reject(new ProtocolError("timeout"));
244
+ }, options.deadline - performance.now());
245
+ const cleanup = () => {
246
+ clearTimeout(timer);
247
+ options.signal?.removeEventListener("abort", abort);
248
+ };
249
+ options.signal?.addEventListener("abort", abort, { once: true });
250
+ void this.start().then(() => {
251
+ cleanup();
252
+ resolve();
253
+ }, (error) => {
254
+ cleanup();
255
+ reject(error);
256
+ });
257
+ });
258
+ if (this.bridgeState !== "ready" || !this.current) {
259
+ throw new ProtocolError("invalid_state");
260
+ }
261
+ if (options.signal?.aborted || performance.now() >= options.deadline) {
262
+ throw new ProtocolError(options.signal?.aborted ? "cancelled" : "timeout");
263
+ }
264
+ return this.current;
265
+ }
266
+ async validate(params, options = { deadline: performance.now() + 5000 }) {
267
+ try {
268
+ params = structuredClone(params);
269
+ }
270
+ catch {
271
+ throw new ProtocolError("invalid_params");
272
+ }
273
+ options = { ...options };
274
+ const process = await this.ready(options);
275
+ return process.request("connection.validate", params, options);
276
+ }
277
+ configure(params, options = { deadline: performance.now() + 5000 }) {
278
+ let snapshot;
279
+ try {
280
+ snapshot = structuredClone(params);
281
+ decodeParams("connection.configure", snapshot);
282
+ }
283
+ catch {
284
+ return Promise.reject(new ProtocolError("invalid_params"));
285
+ }
286
+ options = { ...options };
287
+ const configured = this.configTail.then(async () => {
288
+ const process = await this.ready(options);
289
+ // Invalidate already prepared data before crossing the configure await.
290
+ this.invalidate();
291
+ this.configuration = undefined;
292
+ const epoch = process.epoch;
293
+ const result = await process.request("connection.configure", snapshot, options);
294
+ if (this.current !== process ||
295
+ this.bridgeState !== "ready" ||
296
+ process.epoch !== epoch) {
297
+ throw new ProtocolError("invalid_state");
298
+ }
299
+ this.configuration = snapshot;
300
+ this.generationValue = result.generation;
301
+ return result.generation;
302
+ });
303
+ this.configTail = configured.then(() => { }, () => { });
304
+ return configured;
305
+ }
306
+ async test(options) {
307
+ options = { ...options };
308
+ const process = await this.ready(options);
309
+ const generation = this.generationValue;
310
+ if (!generation) {
311
+ throw new ProtocolError("not_configured");
312
+ }
313
+ const revision = this.revision;
314
+ const result = await process.request("connection.test", {
315
+ generation,
316
+ budget_ms: Math.min(maxBudgetMS, Math.max(1, Math.floor(options.deadline - performance.now()))),
317
+ }, options);
318
+ if (this.current !== process ||
319
+ this.revision !== revision ||
320
+ this.generationValue !== generation) {
321
+ throw new ProtocolError("stale_generation");
322
+ }
323
+ return result;
324
+ }
325
+ // The attachment policy in effect. The plugin sends attachment bytes only when
326
+ // inspection is on, so an off policy costs no transfer.
327
+ async attachmentsPolicy(options) {
328
+ options = { ...options };
329
+ const process = await this.ready(options);
330
+ return process.request("attachments.policy", {}, options);
331
+ }
332
+ // Stores the two attachment switches. The helper owns the file; it refuses
333
+ // (invalid_state) while an environment variable decides.
334
+ async configureAttachments(params, options) {
335
+ options = { ...options };
336
+ const process = await this.ready(options);
337
+ return process.request("attachments.configure", params, options);
338
+ }
339
+ async routeLease(session, token, action, options) {
340
+ const started = performance.now();
341
+ const process = this.current;
342
+ if (this.bridgeState !== "ready" || !process) {
343
+ throw new ProtocolError("invalid_state");
344
+ }
345
+ const generation = this.generationValue;
346
+ const revision = this.revision;
347
+ if (!generation) {
348
+ throw new ProtocolError("not_configured");
349
+ }
350
+ const result = await process.request("route.lease", {
351
+ generation,
352
+ session_id: session,
353
+ lease_token: token,
354
+ action,
355
+ budget_ms: Math.max(1, Math.min(5000, Math.floor(options.deadline - performance.now()))),
356
+ }, options);
357
+ if (this.current !== process ||
358
+ this.generationValue !== generation ||
359
+ this.revision !== revision) {
360
+ throw new ProtocolError("stale_generation");
361
+ }
362
+ if (action === "release") {
363
+ return 0;
364
+ }
365
+ // Include startup, IPC queues and response delivery in the conservative budget.
366
+ const remaining = result.valid_for_ms - (performance.now() - started);
367
+ if (remaining <= 0 ||
368
+ options.signal?.aborted ||
369
+ performance.now() >= options.deadline) {
370
+ throw new ProtocolError("timeout");
371
+ }
372
+ return remaining;
373
+ }
374
+ async check(params, options) {
375
+ try {
376
+ params = structuredClone(params);
377
+ }
378
+ catch {
379
+ throw new ProtocolError("invalid_params");
380
+ }
381
+ options = { ...options };
382
+ const process = await this.ready(options);
383
+ const generation = this.generationValue;
384
+ const revision = this.revision;
385
+ const epoch = process.epoch;
386
+ if (!generation) {
387
+ throw new ProtocolError("not_configured");
388
+ }
389
+ const result = await process.request("operation.check", {
390
+ ...params,
391
+ generation,
392
+ budget_ms: Math.min(maxBudgetMS, Math.max(1, Math.floor(options.deadline - performance.now()))),
393
+ }, options);
394
+ const valid = () => this.bridgeState === "ready" &&
395
+ this.current === process &&
396
+ this.revision === revision &&
397
+ this.generationValue === generation &&
398
+ process.epoch === epoch &&
399
+ !options.signal?.aborted &&
400
+ performance.now() < options.deadline;
401
+ if (!valid()) {
402
+ throw new ProtocolError("stale_generation");
403
+ }
404
+ return new PreparedCheck(result, valid);
405
+ }
406
+ dispose() {
407
+ if (this.disposing) {
408
+ return this.disposing;
409
+ }
410
+ this.bridgeState = "disposed";
411
+ this.invalidate();
412
+ this.configuration = undefined;
413
+ clearTimeout(this.restartTimer);
414
+ this.restartTimer = undefined;
415
+ this.restartWaiter?.reject(new ProtocolError("shutting_down"));
416
+ this.restartWaiter = undefined;
417
+ const process = this.current;
418
+ this.current = undefined;
419
+ this.disposing = Promise.all([
420
+ ...this.retiring,
421
+ process?.stop() ?? Promise.resolve(),
422
+ ]).then(() => { });
423
+ return this.disposing;
424
+ }
425
+ }
@@ -0,0 +1,19 @@
1
+ import type { Writable } from "node:stream";
2
+ export declare class FrameDecoder {
3
+ private header;
4
+ private headerUsed;
5
+ private payload;
6
+ private used;
7
+ private broken;
8
+ push(chunk: Uint8Array): Buffer[];
9
+ finish(): void;
10
+ }
11
+ export declare class FrameWriter {
12
+ private readonly stream;
13
+ private queued;
14
+ private broken;
15
+ private tail;
16
+ private readonly onError;
17
+ constructor(stream: Writable);
18
+ write(payload: Uint8Array): Promise<void>;
19
+ }