@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.
- package/MANUAL-TEST-G.md +167 -0
- package/README.md +334 -2
- package/RELEASE.md +122 -0
- package/bin/darwin-amd64/helper +0 -0
- package/bin/darwin-arm64/helper +0 -0
- package/bin/linux-amd64/helper +0 -0
- package/bin/linux-arm64/helper +0 -0
- package/bin/manifest.json +51 -0
- package/bin/windows-amd64/helper.exe +0 -0
- package/bin/windows-arm64/helper.exe +0 -0
- package/bridge/client.d.ts +55 -0
- package/bridge/client.js +425 -0
- package/bridge/framing.d.ts +19 -0
- package/bridge/framing.js +110 -0
- package/bridge/process.d.ts +38 -0
- package/bridge/process.js +378 -0
- package/bridge/protocol.d.ts +184 -0
- package/bridge/protocol.js +683 -0
- package/connection-catalog.d.ts +69 -0
- package/connection-catalog.js +287 -0
- package/connections-tui.d.ts +11 -0
- package/connections-tui.js +394 -0
- package/demasking.d.ts +2 -0
- package/demasking.js +445 -0
- package/gui-experimental.cjs +33 -0
- package/hook-trace.d.ts +2 -0
- package/hook-trace.js +35 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/licenses/Go-LICENSE +27 -0
- package/messages.d.ts +230 -0
- package/messages.js +231 -0
- package/native/index.d.ts +1 -0
- package/native/index.js +1 -0
- package/native/tui.d.ts +1 -0
- package/native/tui.js +1 -0
- package/package.json +49 -4
- package/plugin-runtime.d.ts +3 -0
- package/plugin-runtime.js +3 -0
- package/plugin-settings.d.ts +77 -0
- package/plugin-settings.js +487 -0
- package/plugin.d.ts +41 -0
- package/plugin.js +10 -0
- package/response-diagnostics.d.ts +13 -0
- package/response-diagnostics.js +142 -0
- package/runtime/attachments.d.ts +4 -0
- package/runtime/attachments.js +19 -0
- package/runtime/errors.d.ts +18 -0
- package/runtime/errors.js +26 -0
- package/runtime/json.d.ts +14 -0
- package/runtime/json.js +243 -0
- package/runtime/limits.d.ts +2 -0
- package/runtime/limits.js +3 -0
- package/runtime/native-edit.d.ts +14 -0
- package/runtime/native-edit.js +73 -0
- package/runtime/runtime.d.ts +43 -0
- package/runtime/runtime.js +345 -0
- package/runtime/session-state.d.ts +13 -0
- package/runtime/session-state.js +73 -0
- package/runtime/text-layout.d.ts +9 -0
- package/runtime/text-layout.js +47 -0
- package/server.d.ts +1 -0
- package/server.js +1 -0
- package/settings-rpc.d.ts +511 -0
- package/settings-rpc.js +197 -0
- package/tui-messages.d.ts +1 -0
- package/tui-messages.js +84 -0
- package/tui.d.ts +17 -0
- package/tui.js +427 -0
- package/v1/hooks.d.ts +81 -0
- package/v1/hooks.js +97 -0
- package/v1/projection.d.ts +32 -0
- package/v1/projection.js +217 -0
- package/v1.d.ts +2 -0
- package/v1.js +2 -0
- package/v2/projection.d.ts +36 -0
- package/v2/projection.js +374 -0
- package/v2/server.d.ts +6 -0
- package/v2/server.js +633 -0
package/RELEASE.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Поставка OpenCode
|
|
2
|
+
|
|
3
|
+
Один npm tarball содержит JS/declarations, шесть CGO=0 Go helpers и
|
|
4
|
+
`bin/manifest.json` с версией, IPC major, target/size и SHA-256 каждого binary.
|
|
5
|
+
Toolchain и compile inputs остаются в private build.json.
|
|
6
|
+
Go и Codex на машине OpenCode не нужны. Install/postinstall scripts отсутствуют.
|
|
7
|
+
Hashes проверяют комплектность байтов, а не доверие к автору пакета.
|
|
8
|
+
|
|
9
|
+
## Migration 0.0.x → 0.1.0
|
|
10
|
+
|
|
11
|
+
| Import | API |
|
|
12
|
+
| --------------------------- | ----------------------------------------------------------- |
|
|
13
|
+
| `@llmguard/opencode` | default native v2 server |
|
|
14
|
+
| `@llmguard/opencode/server` | тот же default server |
|
|
15
|
+
| `@llmguard/opencode/tui` | default TUI |
|
|
16
|
+
| `@llmguard/opencode/rpc` | settingsRPC; `./settings-rpc` остаётся alias |
|
|
17
|
+
| `@llmguard/opencode/plugin` | единственный default function для v1 loader |
|
|
18
|
+
| `@llmguard/opencode/v1` | createOpenCodeHooks, OpenCodeGuardError, type PluginOptions |
|
|
19
|
+
|
|
20
|
+
Root exports GuardClient, Operation, validators и прежний root v1 facade удалены.
|
|
21
|
+
Перенесите программный import createOpenCodeHooks на `@llmguard/opencode/v1`.
|
|
22
|
+
Второй аргумент Checker запрещён, включая явный undefined: это ошибка загрузки.
|
|
23
|
+
Native v1 event names/возвраты сохранены. Внутренние bridge/runtime/core subpaths
|
|
24
|
+
не экспортируются. Тесты policy path используют настоящий helper и mock Guard.
|
|
25
|
+
|
|
26
|
+
Версия вручную меняется только в `package.json`. Номер в
|
|
27
|
+
секции migration описывает прежнюю смену API, а не текущую release identity.
|
|
28
|
+
У helper нет встроенной версии и независимого релиза. Guard `source.adapter_version`
|
|
29
|
+
читается из `package.json` установленного пакета; IPC1 описывает формат сообщений
|
|
30
|
+
и не передаёт версии компонентов. Пакет собирается и обновляется целиком.
|
|
31
|
+
Состояние registry не выводится из локальной сборки.
|
|
32
|
+
Root/test workspaces остаются private. Release package имеет private:false;
|
|
33
|
+
это само по себе ничего не публикует. `UNLICENSED` фиксирует отсутствие выданной
|
|
34
|
+
open-source лицензии проекта; Go runtime license включена отдельно.
|
|
35
|
+
|
|
36
|
+
## Сборка и проверка вне checkout
|
|
37
|
+
|
|
38
|
+
Из корня, с Go 1.27, Node.js 24 и npm 11:
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
npm ci --ignore-scripts
|
|
42
|
+
sh scripts/build-ts.sh && scripts/build.sh --all --output dist/artifacts && go run ./tools/pack pack
|
|
43
|
+
npm exec -- node tests/manual/package-prototype.mjs
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Последняя команда создаёт настоящий npm pack .tgz, устанавливает только его во
|
|
47
|
+
временный каталог offline/ignore-scripts и запускает проверку с пустым PATH,
|
|
48
|
+
изолированным HOME и без LLMGUARD_* environment. Результат acceptance.json и путь
|
|
49
|
+
к tarball печатаются в stdout. Проверяются exports, запрет private subpaths,
|
|
50
|
+
шесть hashes, permissions, helper/IPC handshake, v1/v2 transform/restore/
|
|
51
|
+
deny и fail-closed при отсутствующем helper. Mock Guard слушает только loopback.
|
|
52
|
+
Это не установка/активация в OpenCode. На Windows запускайте именно через
|
|
53
|
+
`npm exec -- node`: npm_execpath позволяет вызвать npm CLI без shell/npm.cmd.
|
|
54
|
+
|
|
55
|
+
Portable ZIP — отдельный convenience artifact: `go run ./tools/pack pack` собирает его вместе с npm tarball из уже
|
|
56
|
+
подготовленных inputs и не компилирует plugin executable или TS.
|
|
57
|
+
Он включает только native v2 graph; v1 программный API поставляется в npm tarball.
|
|
58
|
+
Проверка ZIP: распаковать вне checkout и выполнить `node verify.mjs` в каталоге
|
|
59
|
+
пакета. Никаких запросов к Guard или изменения пользовательских settings.
|
|
60
|
+
|
|
61
|
+
## Требования к будущей native acceptance
|
|
62
|
+
|
|
63
|
+
В `.gitlab-ci.yml` job `check` проверяет исходники и host helper; `build` выполняет cross-build один раз; `verify` тестирует полученные архивы, а публикация запускается вручную из main. Подробности: [PUBLISH.md](PUBLISH.md). Native acceptance на остальных платформах — отдельная будущая работа. Нужны matching native runners:
|
|
64
|
+
|
|
65
|
+
| Job | Native environment |
|
|
66
|
+
| ----------------------------------- | --------------------------------------------------------------- |
|
|
67
|
+
| linux-amd64-glibc | Linux x64 glibc |
|
|
68
|
+
| linux-arm64-glibc | Linux ARM64 glibc |
|
|
69
|
+
| darwin-amd64 | macOS Intel |
|
|
70
|
+
| darwin-arm64 | macOS ARM64 |
|
|
71
|
+
| windows-amd64 | Windows x64 |
|
|
72
|
+
| windows-arm64 | Windows ARM64 с native Node/Go |
|
|
73
|
+
| linux-amd64-musl / linux-arm64-musl | Alpine соответствующей архитектуры, native musl Node 24/Go 1.27 |
|
|
74
|
+
|
|
75
|
+
Каждый job делает checkout, устанавливает **native** Node 24/npm 11 и Go 1.27,
|
|
76
|
+
затем выполняет шаги сборки и `node tests/manual/package-prototype.mjs`. Сохранить .tgz и acceptance.json как artifacts.
|
|
77
|
+
Job считается passed только если platform/arch отчёта совпали с runner и native
|
|
78
|
+
acceptance завершился с exit 0; cross-build на другой ОС этого не заменяет.
|
|
79
|
+
Для musl сохранить `/etc/os-release` и libc identification вместе с отчётом.
|
|
80
|
+
|
|
81
|
+
Это требования к будущей native acceptance, а не включённый CI pipeline.
|
|
82
|
+
Core changes требуют regression всех затронутых Go consumers и обеих TS security
|
|
83
|
+
suites (`scripts/check.sh` каждого репозитория), но не автоматического build/release каждого плагина.
|
|
84
|
+
|
|
85
|
+
## Раздельные фазы и публикация
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
sh scripts/check.sh
|
|
89
|
+
sh scripts/build-package.sh
|
|
90
|
+
sh scripts/verify.sh
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
TS-only staging: `dist/build`. Prebuilt helpers: `dist/artifacts/bin/<os>-<arch>/helper`. Npm tree: `dist/package`;
|
|
94
|
+
tarball: `dist/llmguard-opencode-<version>.tgz`; ZIP: `dist/llmguard-opencode-<version>.zip` (рядом `.sha256`).
|
|
95
|
+
|
|
96
|
+
`packaging-result.json` рядом с outputs содержит product, version, platforms,
|
|
97
|
+
paths и SHA-256 фактических artifacts; hashes деревьев описаны в общем contract.
|
|
98
|
+
Tree hash не является hash будущего npm tarball: publisher должен вычислить
|
|
99
|
+
его отдельно. Этот result описывает outputs упаковщика. Ручная job npm_stage загружает готовый
|
|
100
|
+
tarball в staging npmjs.org. Maintainer подтверждает публикацию с 2FA, затем job release
|
|
101
|
+
проверяет SHA-512 опубликованного пакета и создаёт GitLab Release: [PUBLISH.md](PUBLISH.md).
|
|
102
|
+
Private build.json не попадает в публичный пакет.
|
|
103
|
+
|
|
104
|
+
CI должен проверить SemVer и уникальность относительно опубликованных релизов
|
|
105
|
+
именно OpenCode, но не вычислять/повышать version. Ручная release job поддерживает стабильные версии и npm latest; beta promotion
|
|
106
|
+
не реализован. Build/tests ничего не публикуют и не меняют установку или credentials.
|
|
107
|
+
Релиз OpenCode не выпускает Codex/Claude/Harness. SHA-256 не защищает от замены
|
|
108
|
+
manifest и binary одновременно; publisher и baseline требуют trusted storage.
|
|
109
|
+
|
|
110
|
+
## Если helper не запускается
|
|
111
|
+
|
|
112
|
+
Защищённая операция блокируется; TS fallback, download, compilation или перенос
|
|
113
|
+
binary в обход mount policy отсутствуют. Проверьте соответствие OS/CPU таблице,
|
|
114
|
+
комплектность bin/manifest.json и binary, executable permission и разрешение
|
|
115
|
+
запуска на выбранном filesystem. При noexec выберите разрешённое администратором
|
|
116
|
+
место установки; плагин не делает copy/remount самостоятельно. Read-only package
|
|
117
|
+
не требует записи в собственный каталог. Не отключайте Guard ради запуска.
|
|
118
|
+
|
|
119
|
+
Cross-build есть для всех шести tuples. Native execution текущего артефакта
|
|
120
|
+
подтверждается только его acceptance report; остальные runners и musl остаются
|
|
121
|
+
unverified до исполнения jobs. Реальная приёмка OpenCode с вашим provider/key —
|
|
122
|
+
отдельный этап, не заменяется mock acceptance.
|
|
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.0"
|
|
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 {};
|
package/bridge/client.js
ADDED
|
@@ -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
|
+
}
|