mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-16 20:11:08 +00:00
* feat(plugins): add sync providers and encrypted sidecar sync
Implement PR 8 of the plugin platform (#2269): namespaced sync Providers
with provider.sync, encrypted-object storage operations, WebDAV through the
shared storage surface, dynamic cloud provider IDs, and non-cascade sidecars
for sync:true plugin settings plus account/CRDT baselines.
Related to #2269
* fix(plugins): wire sync providers and sidecars into production paths
Close PR 8 integration gaps: dynamic plugin provider registry and
getConnectedAdapter createPluginStorage, WebDAV through EncryptedObjectStorage,
cloud payload collect/apply for pluginSidecars, and IPC/preload bridges.
Related to #2269
* fix(plugins): preserve WebDAV auth reuse and resourceId through EOS wrap
encryptedObjectStorageAsCloudAdapter now reports initiallyAuthenticated when
config exists (matching raw WebDAVAdapter) so getConnectedAdapter reuses the
cached instance, and preserves/refreshes resourceId from the backing adapter
instead of always forcing the default object key.
Related to #2269
* fix(plugins): address Codex PR 8 review findings
Carry pluginSidecars through merge/convergent uploads, lazy-connect before
object I/O with revision-aware writes, fail closed on sidecar collect errors,
expose connectPluginProvider, preserve remote timestamps, and drop deleted
installed-plugin settings from collection.
Related to #2269
* fix(plugins): close remaining Codex P1/P2 sync issues
Lazy stream cancel for inline sync reads, must-not-exist conditional writes,
three-way sidecar merge for local resets, validated apply path for settings,
and merge remote sidecars into convergent uploads.
Related to #2269
* fix(plugins): harden sidecar collect/apply and write verification
Preserve last-known sidecars when the host is offline, apply remote
deletions for installed plugins, force convergent upload on sidecar
divergence, verify plugin object writes, and pick plugin providers in
auto-sync startup checks.
Related to #2269
* fix(plugins): close remaining Codex sidecar/sync path gaps
Include sidecars in auto-sync payload and hash, keep explicit empty bundles,
fail apply when host is offline, require getCapabilities, and carry merged
sidecars into convergent local apply/upload decisions.
Related to #2269
* fix(plugins): close Codex P1 sidecar collect/apply/merge gaps
Treat null host responses as unavailable, persist collected settings into
the non-cascade table, retain decoded convergent payloads, use three-way
sidecar merge for deletions, and fail apply only on operational errors.
Also treat non-empty plugin sidecars as meaningful sync data and re-run
auto-sync when plugin contributions change.
Related to #2269
* fix(plugins): close remaining Codex P1 sidecar and provider gaps
Replay offline-cached sidecars before collect, keep explicit empty
sidecar fields after three-way merge, thread sidecars through convergent
conflict/downgrade materialization, keep gated-off plugin providers from
joining sync as connected, and rebind plugin EOS sessions after runtime
replacement.
Related to #2269
* fix(plugins): separate pending remote sidecars from last-known cache
Replay only host-offline remote applies into the DB, keep last-known as
upload fallback, use contribution reset for deleted settings, probe real
plugin host readiness, rebind storage events for plugin providers, clear
plugin bases on reset, and swallow disconnect rejections.
Related to #2269
* fix(plugins): hydrate retained sidecars and gate missing providers
Materialize installed-plugin settings from retained sidecars before
collect pruning, clear sidecars on setting reset, fail closed when
pending remote replay fails, and only restore plugin providers that are
contribution-available. Also initialize dynamic provider counters on
connect.
Related to #2269
* fix(plugins): surface plugin sync providers and preserve conflict sidecars
Collect live sidecars before convergent conflict apply/upload, include
dynamic providers in status and disconnect paths, and list plugin sync
providers in Cloud Sync settings for connect/disconnect.
Related to #2269
* fix(plugins): per-provider sidecar baselines and safer collect/UI
Merge convergent sidecars against each provider's own baseline, keep
retained settings in sidecars without unvalidated plugin_settings writes,
guard isConnectDisabled for never-connected plugins, and fall back plugin
provider labels/icons in the status popup.
Related to #2269
* fix(plugins): correct plugin provider discovery and sidecar reverify
Read nested contribution metadata for sync provider cards, gate empty-config
connects, enforce single-provider disconnect for plugins, and re-verify after
sidecar-only convergent uploads so baselines track the post-write payload.
Related to #2269
* fix(plugins): refresh sync provider availability from live contributions
Replace the contribution-available provider ID set when plugins change so
disabled or uninstalled sync providers leave the auto-sync ready set and
drop to disconnected with config retained.
Related to #2269
* fix(plugins): preserve sidecars in backups, pending queue, and migration
Attach last-known plugin sidecars to protective local vault backups, fail
operationally when pending/last-known storage writes are rejected, carry
sidecars through convergent migration publish, and reject trailing garbage
on encrypted object parse.
Related to #2269
* fix(plugins): abort conflict collect failures and merge migration sidecars
Rethrow operational sidecar collection errors during convergent conflict
resolution, LWW-union all local/provider sidecars during convergent
migration, re-collect last-known after apply, and prefer live host collect
for protective local vault backups.
Related to #2269
* fix(plugins): restore pluginBridge tests, fix import path, union downgrade sidecars
Correct SettingsSyncTab dynamic import path so production builds resolve,
add ipcMain.on to the plugin bridge test double, union all provider
sidecars on convergent downgrade, keep empty last-known resets, and skip
force-delete when contribution reset validation rejects.
Related to #2269
* fix(plugins): abort backup collect failures and honor empty remote wipes
Only fall back to last-known sidecars when the host is unavailable during
protective backups, treat explicit empty remote sidecar bundles as
authoritative wipes, remove lint-blocking anys from harness tests, and
use a stable equal-timestamp sidecar tie-break.
Related to #2269
* fix(plugins): include sidecars in equality, preserve merge base on reconnect
Compare pluginSidecars in cloudSyncPayloadsEqual for migration freshness,
clear plugin merge state only when account/resource changes on reconnect,
cancel accepted sync read streams on failure, and stop re-connecting the
plugin EOS adapter on every I/O.
Related to #2269
* fix(plugins): drop cached adapters on contribution refresh
Invalidate plugin sync adapters when live contributions change so a
restarted runtime gets a fresh connect, take offline any non-disconnected
missing providers, and latch version-change backups only after cancellation
checks pass.
Related to #2269
* fix(plugins): preserve omitted sidecars and hydrate on plugin enable
Treat missing pluginSidecars as legacy/unsupported in three-way merge
(only explicit empty is a wipe), hydrate retained settings when a plugin
enables, and re-enable retained provider configs when contributions return.
Related to #2269
* fix(plugins): keep newer retained sidecars over older stored settings
When collection merges existing sidecars with plugin_settings rows, prefer
the newer updatedAt so a schema-rejected remote value retained only in
the sidecar table is not overwritten by a stale local setting.
Related to #2269
* fix(plugins): seal plugin provider config and clear base on config change
Encrypt opaque plugin provider configuration before persistence, clear
merge state when reconnect configuration changes, and stream sync objects
below a base64-safe inline threshold so control-plane JSON stays in budget.
Related to #2269
* fix(plugins): seal plugin configs by provider id and hydrate before start
Encrypt plugin provider configuration only for non-builtin provider IDs
so field-name collisions cannot skip sealing, hydrate retained sidecars
before plugin enable starts the runtime, and stop tearing down live
adapters on no-op availability refreshes.
Related to #2269
* fix(plugins): seal scalar configs, safe inline reads, stable config fingerprint
Encrypt any non-builtin plugin configuration JSON shape, enforce the
base64-safe inline read cutoff, and compare reconnect configurations with
order-independent fingerprints so merge bases are not cleared spuriously.
Related to #2269
* fix(plugins): thread sync credentials and harden availability checks
Pass SyncConnectPayload.credential through the object-storage and IPC host
path, treat only null/undefined config as missing, and avoid wiping the
plugin provider availability catalog on transient discovery failures.
Related to #2269
* fix(plugins): unblock schema-required sync connect and scalar configs
Add a JSON config dialog for plugin sync providers that declare a
required configurationSchema, reuse retained configs on reconnect, and
treat falsy scalar configs as present in readiness and adapter lookup.
Related to #2269
* fix(plugins): rebind sync adapters on contribution refresh
Drop cached plugin sync adapters when live contributions still include
the provider so replaced runtimes get a fresh connect, and seal falsy
scalar plugin configs with nullish presence checks end-to-end.
Related to #2269
* fix(plugins): apply sidecars under current declared setting scopes
When a plugin update changes a syncable setting scope, write under the
live declaration and drop the obsolete scope row so collection does not
republish duplicates.
Related to #2269
* fix(plugins): seal config envelopes and stabilize provider counters
Use an unambiguous host-owned sealed-config envelope, initialize
dynamic-provider sequence counters before cross-window decrypt, keep
three-way sidecar deletions during convergent migration, and create the
sidecar table for existing schema-1 plugin databases.
Related to #2269
* fix(plugins): avoid mid-sync adapter drops and sidecar resurrection
Keep plugin adapters across setting-only contribution refreshes and
rebind sessions on ensureConnected; stop preserving local-only missing
plugin sidecars when remote already mentions the plugin; compare configs
with nullish semantics across windows; swallow quick-connect failures
after toasting.
Related to #2269
* fix(plugins): restore remoteKeys for installed sidecar resets
Reintroduce the remote key set used when dropping installed-plugin
settings the remote no longer carries so applyFromSync cannot throw
after replacing the sidecar table.
Related to #2269
* fix(plugins): honor conflict policy and re-key scoped sidecars
Pass preferCloud/preferLocal into three-way sidecar merge, use
per-provider baselines on convergent downgrade so local resets are not
resurrected, and re-key applied settings under the current declared
scope coordinates.
Related to #2269
* fix(plugins): keep strategy on final sidecar merge and block dual legacy
Pass preferCloud/preferLocal through the final verified sidecar merge,
avoid auto-reactivating a retained plugin while another legacy provider
is already connected, cache plugin adapters only after initializeSync,
and preserve explicit null configuration values.
Related to #2269
* fix(plugins): strip plugin avatars and protect last-known sidecars
Do not load plugin-supplied avatar URLs in the main renderer, and avoid
overwriting last-known sidecars with an unmerged remote bundle when the
post-apply collect fails or is non-authoritative.
Related to #2269
* fix(plugins): strip top-bar plugin avatars and stop always-rebind
Hide plugin avatar URLs in the sync status popover, drop always-on
rebindSession for plugin adapters, and read convergent mode from the
local config module when deciding whether to auto-reactivate providers.
Related to #2269
* fix(plugins): use window.netcatty for sync IPC and allow null configs
Read plugin sync and sidecar APIs from the production preload global,
and treat an explicit config property (including JSON null) as present
for readiness and adapter lookup.
Related to #2269
* fix(plugins): close residual Codex P2 sync edge cases
Three-way merge sidecars during v2 convergent migration so local
resets are not resurrected, preserve explicit null plugin configs on
adapter rebuild, rebind EOS sessions after I/O failure for replaced
runtimes, and accept the public inlineObjectBytes limit on readObject.
Related to #2269
* fix(plugins): keep inline read cutoff under control-plane budget
Restore the base64-safe inline cutoff so advertised-size reads cannot
overflow the 128 KiB provider JSON envelope; providers near the public
inlineObjectBytes limit must stream.
Related to #2269
* fix(plugins): harden sidecar empty-vault, hydrate LWW, and credential seals
Close remaining Codex/review gaps for PR8: keep empty sidecar shells from
bypassing upload guards, skip startup hydrate when local settings are newer,
seal/validate durable plugin credential refs, and cover schema 1→2 migration.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): rebind plugin sync sessions and keep null configs
Address Codex P2 on 8ae52c54: re-issue connect after runtime replacement,
and treat stored config:null as present in the dashboard reconnect path.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): defer empty sidecar last-known until sync succeeds
Keep prior non-empty last-known across an authoritative empty collect so the
empty-vault guard can still recognize a plugin-only reset, then commit the
empty cache after a successful upload.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): avoid restricted localStorage global in sidecar test
Bind the mock to a local binding so eslint no-restricted-globals stays clean.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): commit applied sidecar cache and reset orphan settings
Prefer merged payload sidecars when updating last-known after sync, and clear
syncable plugin_settings that lack sidecar rows on authoritative remote deletes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): reseal marker-shaped plugin configs instead of skipping
Exact __netcatty_plugin_config_v1 collisions no longer bypass encryption; trusted
host envelopes are unwrapped then resealed, and false collisions are sealed whole.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): keep merged sidecars in last-known after apply collect fails
Return applyFromSync entries from IPC and use them when follow-up collect fails,
so preserved missing-plugin rows are not dropped from the offline upload cache.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): delete stale-scope settings at stored coordinates on reset
After resetSetting against the current declared scope, also remove the row at
the sidecar's stored scope so scope migrations cannot republish remote deletes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): close sync-provider credential, stream, and sidecar gaps
Make SecretRef usable end-to-end via lease-bound network.request, keep
renderer/main transfers abortable and bounded, and stop sidecar
last-known/pending from corrupting backups and conflict apply.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): harden single-provider, secret schema, and conditional conflicts
Keep legacy restart from dual-connecting providers, extract writeOnly schema
secrets into OS storage, and surface conditional-write precondition failures
as conflict UI instead of a generic sync error.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): dedupe sync type imports for lint
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: address Codex review on PR #2713
* fix(plugins): wait for sidecar host before version backup latch
Defer the one-shot upgrade snapshot until the plugin sidecar host is ready (or a short grace), and catch getDataHash failures so pending/baseline paths do not reject unhandled.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): require sidecar grace before version backup
Always wait for contributions/grace tick before the upgrade snapshot, and only latch after a non-cancelled attempt so cleanup cannot suppress retries.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
958 lines
36 KiB
JavaScript
958 lines
36 KiB
JavaScript
import {
|
|
CancellationTokenSource,
|
|
DisposableStore,
|
|
PluginError,
|
|
PLUGIN_ERROR_WIRE_CODES,
|
|
pluginErrorToRpcError,
|
|
} from "@netcatty/plugin-sdk";
|
|
import { createMessagePortStreamEnvelope } from "@netcatty/plugin-contract";
|
|
import { createPluginStreamEndpoint } from "./pluginStreamEndpoint.mjs";
|
|
|
|
let terminalInterceptorTransportPromise;
|
|
|
|
function loadTerminalInterceptorTransport() {
|
|
terminalInterceptorTransportPromise ??= import("../terminalInterceptorTransport.cjs")
|
|
.then((module) => module.default);
|
|
return terminalInterceptorTransportPromise;
|
|
}
|
|
|
|
const RPC_ERRORS = {
|
|
methodNotFound: -32601,
|
|
invalidParams: -32602,
|
|
internal: -32603,
|
|
cancelled: -32001,
|
|
unsupported: -32012,
|
|
};
|
|
|
|
const PLUGIN_ERROR_NAMES_BY_WIRE_CODE = new Map(
|
|
Object.entries(PLUGIN_ERROR_WIRE_CODES).map(([name, code]) => [code, name]),
|
|
);
|
|
|
|
const PROVIDER_KINDS = new Set([
|
|
"terminal.completion",
|
|
"terminal.decoration",
|
|
"terminal.link",
|
|
"terminal.hover",
|
|
"terminal.matcher",
|
|
"terminal.semantic",
|
|
"terminal.prompt",
|
|
"terminal.background",
|
|
"terminal.theme",
|
|
"terminal.interceptor.input",
|
|
"terminal.interceptor.output",
|
|
"connection",
|
|
"authentication",
|
|
"sync",
|
|
"importer",
|
|
]);
|
|
|
|
const CONNECTION_PROVIDER_OPERATIONS = Object.freeze([
|
|
"validateConfiguration",
|
|
"probe",
|
|
"open",
|
|
"resize",
|
|
"signal",
|
|
"reconnect",
|
|
"close",
|
|
"getStatus",
|
|
]);
|
|
const IMPORTER_PROVIDER_OPERATIONS = Object.freeze(["detect", "parse"]);
|
|
const SYNC_PROVIDER_OPERATIONS = Object.freeze([
|
|
"connect",
|
|
"disconnect",
|
|
"getAccount",
|
|
"getCapabilities",
|
|
"readObject",
|
|
"writeObject",
|
|
"deleteObject",
|
|
]);
|
|
const OPERATION_MAP_PROVIDER_KINDS = Object.freeze(new Set(["connection", "importer", "sync"]));
|
|
|
|
function pluginErrorNameFromRpcError(error) {
|
|
if (typeof error?.data?.pluginCode === "string") return error.data.pluginCode;
|
|
if (error?.code === RPC_ERRORS.methodNotFound) return "unsupported";
|
|
if (error?.code === RPC_ERRORS.invalidParams) return "invalid_argument";
|
|
if (error?.code === RPC_ERRORS.internal) return "internal";
|
|
return PLUGIN_ERROR_NAMES_BY_WIRE_CODE.get(error?.code) ?? "unknown";
|
|
}
|
|
|
|
function freezeRuntimeJson(value) {
|
|
const clone = structuredClone(value);
|
|
const freeze = (item) => {
|
|
if (!item || typeof item !== "object" || Object.isFrozen(item)) return item;
|
|
for (const child of Array.isArray(item) ? item : Object.values(item)) freeze(child);
|
|
return Object.freeze(item);
|
|
};
|
|
return freeze(clone);
|
|
}
|
|
|
|
function messageData(value) {
|
|
return value && typeof value === "object" && "data" in value ? value.data : value;
|
|
}
|
|
|
|
function closeTransferredPorts(ports) {
|
|
for (const port of ports ?? []) port?.close?.();
|
|
}
|
|
|
|
function createTransportAdapter(port) {
|
|
const listeners = new Set();
|
|
const handle = (event) => {
|
|
const value = messageData(event);
|
|
for (const listener of listeners) listener(value, event?.ports ?? []);
|
|
};
|
|
if (typeof port.addEventListener === "function") port.addEventListener("message", handle);
|
|
else port.on("message", handle);
|
|
port.start?.();
|
|
return {
|
|
post(message, transfer = []) {
|
|
port.postMessage(message, transfer);
|
|
},
|
|
onMessage(listener) {
|
|
listeners.add(listener);
|
|
return () => listeners.delete(listener);
|
|
},
|
|
close() {
|
|
listeners.clear();
|
|
port.close?.();
|
|
},
|
|
};
|
|
}
|
|
|
|
function makeRpcFailure(id, code, message, data) {
|
|
return {
|
|
jsonrpc: "2.0",
|
|
id,
|
|
error: { code, message, ...(data === undefined ? {} : { data }) },
|
|
};
|
|
}
|
|
|
|
function cancelUnhandledStream(transport, message) {
|
|
const keys = Reflect.ownKeys(message);
|
|
if (keys.some((key) => typeof key !== "string" || (key !== "frame" && key !== "transfer"))) {
|
|
throw new TypeError("Plugin stream envelope contains unknown properties");
|
|
}
|
|
for (const key of keys) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(message, key);
|
|
if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) {
|
|
throw new TypeError("Plugin stream envelope must contain enumerable data properties");
|
|
}
|
|
}
|
|
const envelope = createMessagePortStreamEnvelope(message.frame, message.transfer);
|
|
if (envelope.frame.kind !== "open") {
|
|
throw new Error(`Unknown incoming plugin stream: ${envelope.frame.streamId}`);
|
|
}
|
|
transport.post(createMessagePortStreamEnvelope({
|
|
streamId: envelope.frame.streamId,
|
|
sequence: 1,
|
|
kind: "cancel",
|
|
}));
|
|
}
|
|
|
|
function normalizeError(error) {
|
|
if (error instanceof PluginError) {
|
|
return pluginErrorToRpcError(error);
|
|
}
|
|
return { code: RPC_ERRORS.internal, message: "Plugin operation failed" };
|
|
}
|
|
|
|
function createHostClient(transport) {
|
|
let nextId = 0;
|
|
const pending = new Map();
|
|
function accept(message) {
|
|
if (!message || typeof message !== "object" || !Object.hasOwn(message, "id")) return false;
|
|
if (!Object.hasOwn(message, "result") && !Object.hasOwn(message, "error")) return false;
|
|
const request = pending.get(`${typeof message.id}:${String(message.id)}`);
|
|
if (!request) return false;
|
|
pending.delete(`${typeof message.id}:${String(message.id)}`);
|
|
if (message.error) {
|
|
request.reject(new PluginError(
|
|
pluginErrorNameFromRpcError(message.error),
|
|
message.error.message,
|
|
message.error.data?.details,
|
|
));
|
|
} else request.resolve(message.result);
|
|
return true;
|
|
}
|
|
function request(method, params, options = {}) {
|
|
const id = nextId;
|
|
nextId = nextId === Number.MAX_SAFE_INTEGER ? 0 : nextId + 1;
|
|
return new Promise((resolve, reject) => {
|
|
pending.set(`${typeof id}:${String(id)}`, { resolve, reject });
|
|
transport.post({
|
|
jsonrpc: "2.0",
|
|
id,
|
|
method,
|
|
params,
|
|
...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),
|
|
});
|
|
});
|
|
}
|
|
function notify(method, params) {
|
|
transport.post({ jsonrpc: "2.0", method, params });
|
|
}
|
|
function close() {
|
|
const error = new PluginError("unavailable", "Plugin host disconnected");
|
|
for (const request of pending.values()) request.reject(error);
|
|
pending.clear();
|
|
}
|
|
return { accept, request, notify, close };
|
|
}
|
|
|
|
function assertStorageKey(key) {
|
|
if (typeof key !== "string" || key.length < 1 || key.length > 256 || key.includes("\0")) {
|
|
throw new PluginError("invalid_argument", "Plugin storage key is invalid");
|
|
}
|
|
return key;
|
|
}
|
|
|
|
function assertCredentialRef(credential) {
|
|
if (
|
|
!credential
|
|
|| typeof credential !== "object"
|
|
|| (credential.kind !== "secret" && credential.kind !== "credential")
|
|
|| typeof credential.id !== "string"
|
|
|| credential.id.length < 16
|
|
|| credential.id.length > 256
|
|
) throw new PluginError("invalid_argument", "Credential reference is invalid");
|
|
if (
|
|
credential.kind === "secret"
|
|
&& (
|
|
typeof credential.key !== "string"
|
|
|| credential.key.length < 1
|
|
|| credential.key.length > 256
|
|
|| credential.key.includes("\0")
|
|
)
|
|
) throw new PluginError("invalid_argument", "Credential reference is invalid");
|
|
return credential.kind === "secret"
|
|
? { kind: "secret", id: credential.id, key: credential.key }
|
|
: { kind: "credential", id: credential.id };
|
|
}
|
|
|
|
function forwardedDeadline(value, maximum) {
|
|
return Number.isSafeInteger(value) && value >= 1 && value <= maximum ? value : undefined;
|
|
}
|
|
|
|
function assertCompanionId(companionId) {
|
|
if (typeof companionId !== "string" || companionId.length < 5 || companionId.length > 192) {
|
|
throw new PluginError("invalid_argument", "Companion ID is invalid");
|
|
}
|
|
return companionId;
|
|
}
|
|
|
|
function assertOwnedContributionId(pluginId, id, label) {
|
|
if (typeof id !== "string" || !id.startsWith(`${pluginId}.`) || id.length > 256) {
|
|
throw new PluginError("invalid_argument", `${label} ID is invalid`);
|
|
}
|
|
return id;
|
|
}
|
|
|
|
function assertProviderKind(kind) {
|
|
if (!PROVIDER_KINDS.has(kind)) {
|
|
throw new PluginError("invalid_argument", "Plugin Provider kind is invalid");
|
|
}
|
|
return kind;
|
|
}
|
|
|
|
function operationMapLabel(kind) {
|
|
if (kind === "connection") return "Connection";
|
|
if (kind === "importer") return "Importer";
|
|
if (kind === "sync") return "Sync";
|
|
return kind;
|
|
}
|
|
|
|
function operationsForProviderKind(kind) {
|
|
if (kind === "connection") return CONNECTION_PROVIDER_OPERATIONS;
|
|
if (kind === "importer") return IMPORTER_PROVIDER_OPERATIONS;
|
|
if (kind === "sync") return SYNC_PROVIDER_OPERATIONS;
|
|
return null;
|
|
}
|
|
|
|
function normalizeProviderHandler(kind, handler) {
|
|
if (!OPERATION_MAP_PROVIDER_KINDS.has(kind)) {
|
|
if (typeof handler !== "function") {
|
|
throw new PluginError("invalid_argument", "Plugin Provider handler must be a function");
|
|
}
|
|
return handler;
|
|
}
|
|
const label = operationMapLabel(kind);
|
|
if (!handler || typeof handler !== "object" || Array.isArray(handler)) {
|
|
throw new PluginError("invalid_argument", `${label} Provider handler must be an operation map`);
|
|
}
|
|
const normalized = {};
|
|
const operations = operationsForProviderKind(kind);
|
|
for (const operation of operations) {
|
|
if (typeof handler[operation] !== "function") {
|
|
throw new PluginError("invalid_argument", `${label} Provider handler is missing operation: ${operation}`);
|
|
}
|
|
normalized[operation] = handler[operation].bind(handler);
|
|
}
|
|
return Object.freeze(normalized);
|
|
}
|
|
|
|
function assertOwnedContextKey(pluginId, key) {
|
|
const prefix = `${pluginId}.`;
|
|
const suffix = typeof key === "string" && key.startsWith(prefix)
|
|
? key.slice(prefix.length)
|
|
: "";
|
|
if (!/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,255}$/u.test(suffix)
|
|
|| key.length > 256) {
|
|
throw new PluginError("invalid_argument", "Plugin Context Key ID is invalid");
|
|
}
|
|
return key;
|
|
}
|
|
|
|
function normalizeRuntimeEnvironment(value) {
|
|
const source = value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
const sourceTokens = source.themeTokens && typeof source.themeTokens === "object"
|
|
&& !Array.isArray(source.themeTokens)
|
|
? source.themeTokens
|
|
: {};
|
|
const themeTokens = Object.freeze(Object.fromEntries(
|
|
Object.entries(sourceTokens).filter(([key, token]) => key.length > 0 && typeof token === "string"),
|
|
));
|
|
return Object.freeze({
|
|
locale: typeof source.locale === "string" ? source.locale : "en",
|
|
theme: typeof source.theme === "string" ? source.theme : "system",
|
|
reducedMotion: source.reducedMotion === true,
|
|
highContrast: source.highContrast === true,
|
|
themeTokens,
|
|
});
|
|
}
|
|
|
|
function createEmitter() {
|
|
const listeners = new Set();
|
|
return {
|
|
event(listener) {
|
|
if (typeof listener !== "function") throw new PluginError("invalid_argument", "Plugin event listener must be a function");
|
|
listeners.add(listener);
|
|
return Object.freeze({ dispose: () => listeners.delete(listener) });
|
|
},
|
|
fire(value) {
|
|
for (const listener of [...listeners]) {
|
|
try { listener(value); } catch {}
|
|
}
|
|
},
|
|
clear() { listeners.clear(); },
|
|
};
|
|
}
|
|
|
|
function createPluginContext(config, client, runtimeApi) {
|
|
const subscriptions = new DisposableStore();
|
|
const storage = {
|
|
get: (key) => client.request("storage.get", { key: assertStorageKey(key) })
|
|
.then((result) => result?.found ? result.value : undefined),
|
|
set: (key, value) => client.request("storage.set", { key: assertStorageKey(key), value })
|
|
.then(() => undefined),
|
|
delete: (key) => client.request("storage.delete", { key: assertStorageKey(key) })
|
|
.then(() => undefined),
|
|
keys: () => client.request("storage.keys", {}).then((result) => result?.keys ?? []),
|
|
};
|
|
const secrets = {
|
|
get: (key) => client.request("secrets.get", { key: assertStorageKey(key) })
|
|
.then((result) => result?.found ? result.secret : undefined),
|
|
set: (key, value) => client.request("secrets.set", {
|
|
key: assertStorageKey(key),
|
|
value,
|
|
}).then((result) => result.secret),
|
|
delete: (key) => client.request("secrets.delete", { key: assertStorageKey(key) })
|
|
.then(() => undefined),
|
|
};
|
|
const credentials = {
|
|
createLease: (secret, options) => client.request("credentials.createLease", {
|
|
secret: assertCredentialRef(secret),
|
|
operationId: options?.operationId,
|
|
purpose: options?.purpose,
|
|
...(options?.ttlMs === undefined ? {} : { ttlMs: options.ttlMs }),
|
|
}),
|
|
};
|
|
const network = {
|
|
request: (request) => client.request("network.request", request, {
|
|
deadlineMs: forwardedDeadline(request?.timeoutMs, 300_000),
|
|
}),
|
|
};
|
|
const filesystem = {
|
|
readFile: (filePath, options = {}) => client.request("filesystem.readFile", {
|
|
path: filePath,
|
|
...options,
|
|
}).then((result) => result.data),
|
|
writeFile: (filePath, data, options = {}) => client.request("filesystem.writeFile", {
|
|
path: filePath,
|
|
data,
|
|
...options,
|
|
}).then(() => undefined),
|
|
stat: (filePath) => client.request("filesystem.stat", { path: filePath }),
|
|
readDirectory: (directoryPath) => client.request("filesystem.readDirectory", { path: directoryPath })
|
|
.then((result) => result.entries),
|
|
};
|
|
const companions = {
|
|
start: async (companionId) => {
|
|
const result = await client.request("companion.start", {
|
|
companionId: assertCompanionId(companionId),
|
|
});
|
|
let stopped = false;
|
|
let stopPromise = null;
|
|
const stop = () => {
|
|
if (stopped) return Promise.resolve();
|
|
if (stopPromise) return stopPromise;
|
|
stopPromise = client.request("companion.stop", { handleId: result.handleId })
|
|
.then(() => { stopped = true; })
|
|
.finally(() => { stopPromise = null; });
|
|
return stopPromise;
|
|
};
|
|
return Object.freeze({
|
|
id: result.handleId,
|
|
request: (method, params, options = {}) => client.request(
|
|
"companion.request",
|
|
{
|
|
handleId: result.handleId,
|
|
method,
|
|
...(params === undefined ? {} : { params }),
|
|
...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
|
|
...(options.credentialLeases === undefined ? {} : {
|
|
credentialLeases: options.credentialLeases,
|
|
operationId: options.operationId,
|
|
}),
|
|
},
|
|
{ deadlineMs: forwardedDeadline(options.timeoutMs, 60_000) },
|
|
),
|
|
stop,
|
|
dispose() { void stop().catch(() => {}); },
|
|
});
|
|
},
|
|
};
|
|
const streams = {
|
|
acceptReadable: (streamId) => runtimeApi.streams.acceptReadable(streamId),
|
|
openWritable: (streamId, options = {}) => runtimeApi.streams.openWritable(
|
|
streamId,
|
|
options.windowBytes,
|
|
),
|
|
};
|
|
const settings = {
|
|
get: (settingId, options = {}) => client.request("settings.get", {
|
|
settingId: assertOwnedContributionId(config.pluginId, settingId, "Plugin setting"),
|
|
...(options.scopeId === undefined ? {} : { scopeId: options.scopeId }),
|
|
}).then((result) => result?.found ? result.value : undefined),
|
|
update: (settingId, value, options = {}) => client.request("settings.update", {
|
|
settingId: assertOwnedContributionId(config.pluginId, settingId, "Plugin setting"),
|
|
value,
|
|
...(options.scopeId === undefined ? {} : { scopeId: options.scopeId }),
|
|
}).then((result) => result ?? { restartRequired: false }),
|
|
onDidChange: runtimeApi.settingsChanged.event,
|
|
};
|
|
const commands = {
|
|
registerCommand(commandId, handler) {
|
|
const id = assertOwnedContributionId(config.pluginId, commandId, "Plugin command");
|
|
if (typeof handler !== "function") throw new PluginError("invalid_argument", "Plugin command handler must be a function");
|
|
if (runtimeApi.commandHandlers.has(id)) throw new PluginError("already_exists", `Plugin command is already registered: ${id}`);
|
|
runtimeApi.commandHandlers.set(id, handler);
|
|
return Object.freeze({
|
|
dispose() {
|
|
if (runtimeApi.commandHandlers.get(id) === handler) {
|
|
runtimeApi.commandHandlers.delete(id);
|
|
}
|
|
},
|
|
});
|
|
},
|
|
executeCommand: (commandId, args) => client.request("commands.execute", {
|
|
command: assertOwnedContributionId(config.pluginId, commandId, "Plugin command"),
|
|
...(args === undefined ? {} : { args }),
|
|
}),
|
|
};
|
|
const contextKeys = {
|
|
set: (key, value) => client.request("contextKeys.set", {
|
|
key: assertOwnedContextKey(config.pluginId, key),
|
|
value,
|
|
}).then(() => undefined),
|
|
};
|
|
const views = {
|
|
onDidReceiveMessage(viewId, listener) {
|
|
const id = assertOwnedContributionId(config.pluginId, viewId, "Plugin view");
|
|
let emitter = runtimeApi.viewMessages.get(id);
|
|
if (!emitter) {
|
|
emitter = createEmitter();
|
|
runtimeApi.viewMessages.set(id, emitter);
|
|
}
|
|
return emitter.event(listener);
|
|
},
|
|
postMessage: (viewId, message) => client.notify("views.postMessage", {
|
|
viewId: assertOwnedContributionId(config.pluginId, viewId, "Plugin view"),
|
|
message,
|
|
}),
|
|
getState: (viewId, scopeId) => client.request("views.getState", {
|
|
viewId: assertOwnedContributionId(config.pluginId, viewId, "Plugin view"),
|
|
scopeId,
|
|
}).then((result) => result?.state),
|
|
setState: (viewId, scopeId, state) => client.request("views.setState", {
|
|
viewId: assertOwnedContributionId(config.pluginId, viewId, "Plugin view"),
|
|
scopeId,
|
|
state,
|
|
}).then(() => undefined),
|
|
};
|
|
const providers = {
|
|
register(providerId, kind, handler) {
|
|
const id = assertOwnedContributionId(config.pluginId, providerId, "Plugin Provider");
|
|
const normalizedKind = assertProviderKind(kind);
|
|
const normalizedHandler = normalizeProviderHandler(normalizedKind, handler);
|
|
if (runtimeApi.providerHandlers.has(id)) {
|
|
throw new PluginError("already_exists", `Plugin Provider is already registered: ${id}`);
|
|
}
|
|
const registration = Object.freeze({ kind: normalizedKind, handler: normalizedHandler });
|
|
runtimeApi.providerHandlers.set(id, registration);
|
|
return Object.freeze({
|
|
dispose() {
|
|
if (runtimeApi.providerHandlers.get(id) === registration) {
|
|
runtimeApi.providerHandlers.delete(id);
|
|
}
|
|
},
|
|
});
|
|
},
|
|
};
|
|
const terminals = {
|
|
onDidChange: runtimeApi.terminalEvents.event,
|
|
};
|
|
const environment = {
|
|
get locale() { return runtimeApi.environment.locale ?? "en"; },
|
|
get theme() { return runtimeApi.environment.theme ?? "system"; },
|
|
get reducedMotion() { return runtimeApi.environment.reducedMotion === true; },
|
|
get highContrast() { return runtimeApi.environment.highContrast === true; },
|
|
get themeTokens() { return runtimeApi.environment.themeTokens; },
|
|
onDidChange: runtimeApi.environmentChanged.event,
|
|
};
|
|
const logger = Object.fromEntries(["debug", "info", "warn", "error"].map((level) => [
|
|
level,
|
|
(message, fields) => client.notify("log.write", {
|
|
level,
|
|
message: String(message).slice(0, 2_048),
|
|
...(fields === undefined ? {} : { fields }),
|
|
}),
|
|
]));
|
|
return {
|
|
pluginId: config.pluginId,
|
|
netcattyVersion: config.netcattyVersion,
|
|
apiVersion: config.apiVersion,
|
|
enabledFeatures: new Set(config.enabledFeatures),
|
|
subscriptions,
|
|
storage,
|
|
settings,
|
|
commands,
|
|
contextKeys,
|
|
views,
|
|
providers,
|
|
terminals,
|
|
environment,
|
|
secrets,
|
|
credentials,
|
|
network,
|
|
filesystem,
|
|
companions,
|
|
streams,
|
|
logger,
|
|
};
|
|
}
|
|
|
|
export async function startPluginRuntime({
|
|
port,
|
|
config,
|
|
loadPlugin,
|
|
loadTerminalInterceptorTransport: loadTerminalInterceptorTransportForRuntime = loadTerminalInterceptorTransport,
|
|
}) {
|
|
const transport = createTransportAdapter(port);
|
|
const client = createHostClient(transport);
|
|
const cancellation = new Map();
|
|
let plugin;
|
|
let context;
|
|
let activated = false;
|
|
let deactivated = false;
|
|
const runtimeApi = {
|
|
commandHandlers: new Map(),
|
|
providerHandlers: new Map(),
|
|
settingsChanged: createEmitter(),
|
|
environmentChanged: createEmitter(),
|
|
terminalEvents: createEmitter(),
|
|
environment: normalizeRuntimeEnvironment(config.environment),
|
|
viewMessages: new Map(),
|
|
terminalInterceptorPorts: new Set(),
|
|
streams: null,
|
|
};
|
|
runtimeApi.streams = createPluginStreamEndpoint(transport);
|
|
const pluginModule = await loadPlugin(config.entryUrl);
|
|
plugin = pluginModule?.default;
|
|
if (!plugin || typeof plugin.activate !== "function") {
|
|
throw new Error("Plugin entrypoint must default-export a plugin with activate(context)");
|
|
}
|
|
|
|
async function handleRequest(message, cancellationToken, ports = []) {
|
|
const isTerminalAttachment = message.method === "plugin.terminal.interceptor.attach";
|
|
if (!isTerminalAttachment) closeTransferredPorts(ports);
|
|
if (message.method === "plugin.initialize") {
|
|
if (context) throw new PluginError("failed_precondition", "Plugin is already initialized");
|
|
context = createPluginContext(config, client, runtimeApi);
|
|
return {
|
|
pluginId: config.pluginId,
|
|
pluginVersion: config.pluginVersion,
|
|
apiVersion: config.apiVersion,
|
|
enabledFeatures: [...config.enabledFeatures],
|
|
};
|
|
}
|
|
if (message.method === "plugin.activate") {
|
|
if (!context) throw new PluginError("failed_precondition", "Plugin must be initialized first");
|
|
if (!activated) {
|
|
if (message.params?.environment && typeof message.params.environment === "object"
|
|
&& !Array.isArray(message.params.environment)) {
|
|
runtimeApi.environment = normalizeRuntimeEnvironment(message.params.environment);
|
|
}
|
|
const disposable = await plugin.activate(context);
|
|
if (disposable && typeof disposable.dispose === "function") context.subscriptions.add(disposable);
|
|
activated = true;
|
|
}
|
|
return null;
|
|
}
|
|
if (message.method === "plugin.deactivate") {
|
|
if (!deactivated) {
|
|
deactivated = true;
|
|
await plugin.deactivate?.();
|
|
context?.subscriptions.dispose();
|
|
}
|
|
return null;
|
|
}
|
|
if (message.method === "plugin.terminal.interceptor.attach") {
|
|
if (ports.length !== 1) {
|
|
closeTransferredPorts(ports);
|
|
throw new PluginError("invalid_argument", "Terminal interceptor attachment requires exactly one port");
|
|
}
|
|
try {
|
|
await attachTerminalInterceptor(message.params, ports, cancellationToken);
|
|
return { accepted: true };
|
|
} catch (error) {
|
|
closeTransferredPorts(ports);
|
|
throw error;
|
|
}
|
|
}
|
|
if (message.method === "plugin.command.execute") {
|
|
if (!activated || !context) throw new PluginError("failed_precondition", "Plugin is not activated");
|
|
const command = assertOwnedContributionId(config.pluginId, message.params?.command, "Plugin command");
|
|
const handler = runtimeApi.commandHandlers.get(command);
|
|
if (!handler) throw new PluginError("failed_precondition", `Plugin command has no registered handler: ${command}`);
|
|
return await handler(message.params?.args, message.params?.invocation);
|
|
}
|
|
if (message.method === "provider.invoke") {
|
|
if (!activated || !context) throw new PluginError("failed_precondition", "Plugin is not activated");
|
|
const providerId = assertOwnedContributionId(config.pluginId, message.params?.providerId, "Plugin Provider");
|
|
const kind = assertProviderKind(message.params?.kind);
|
|
const registration = runtimeApi.providerHandlers.get(providerId);
|
|
if (!registration) {
|
|
throw new PluginError("failed_precondition", `Plugin Provider has no registered handler: ${providerId}`);
|
|
}
|
|
if (registration.kind !== kind) {
|
|
throw new PluginError("failed_precondition", `Plugin Provider kind changed: ${providerId}`);
|
|
}
|
|
const requestId = message.params?.requestId;
|
|
if (typeof requestId !== "string" || requestId.length < 1 || requestId.length > 128) {
|
|
throw new PluginError("invalid_argument", "Plugin Provider request ID is invalid");
|
|
}
|
|
const operation = message.params?.operation;
|
|
if (typeof operation !== "string" || operation.length < 1 || operation.length > 128) {
|
|
throw new PluginError("invalid_argument", "Plugin Provider operation is invalid");
|
|
}
|
|
const deadlineMs = message.params?.deadlineMs;
|
|
if (deadlineMs != null && (!Number.isInteger(deadlineMs) || deadlineMs < 1 || deadlineMs > 300_000)) {
|
|
throw new PluginError("invalid_argument", "Plugin Provider deadline is invalid");
|
|
}
|
|
const payload = message.params?.payload === undefined
|
|
? undefined
|
|
: freezeRuntimeJson(message.params.payload);
|
|
const connectionOpen = kind === "connection" && operation === "open";
|
|
const importerParse = kind === "importer" && operation === "parse";
|
|
const syncReadStream = kind === "sync" && operation === "readObject" && typeof payload?.outputStreamId === "string";
|
|
const syncWriteStream = kind === "sync" && operation === "writeObject" && typeof payload?.inputStreamId === "string";
|
|
const streamed = connectionOpen || importerParse || syncReadStream || syncWriteStream;
|
|
let input;
|
|
let output;
|
|
let cancelStreams;
|
|
if (streamed) {
|
|
const inputStreamId = payload?.inputStreamId;
|
|
const outputStreamId = payload?.outputStreamId;
|
|
const windowBytes = payload?.windowBytes;
|
|
if (connectionOpen || importerParse) {
|
|
if (typeof inputStreamId !== "string" || typeof outputStreamId !== "string") {
|
|
throw new PluginError("invalid_argument", "Streamed Provider invocation requires input and output stream IDs");
|
|
}
|
|
} else if (syncReadStream && typeof outputStreamId !== "string") {
|
|
throw new PluginError("invalid_argument", "Sync readObject stream requires an output stream ID");
|
|
} else if (syncWriteStream && typeof inputStreamId !== "string") {
|
|
throw new PluginError("invalid_argument", "Sync writeObject stream requires an input stream ID");
|
|
}
|
|
if (typeof inputStreamId === "string") {
|
|
input = runtimeApi.streams.acceptReadable(inputStreamId);
|
|
// Prevent a cancelled request from creating an unhandled rejected
|
|
// promise when the Provider never awaited its input stream.
|
|
void input.catch(() => {});
|
|
}
|
|
if (typeof outputStreamId === "string") {
|
|
try {
|
|
output = await runtimeApi.streams.openWritable(outputStreamId, windowBytes);
|
|
} catch (error) {
|
|
if (typeof inputStreamId === "string") {
|
|
runtimeApi.streams.rejectReadable(inputStreamId, error);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
cancelStreams = () => {
|
|
const error = new PluginError("cancelled", "Streamed Provider invocation was cancelled");
|
|
if (typeof inputStreamId === "string") {
|
|
runtimeApi.streams.rejectReadable(inputStreamId, error);
|
|
void input?.then((stream) => stream.cancel(), () => {});
|
|
}
|
|
output?.cancel?.();
|
|
};
|
|
}
|
|
const cancellationDisposable = cancelStreams
|
|
? cancellationToken.onCancellationRequested(cancelStreams)
|
|
: null;
|
|
const invocation = Object.freeze({
|
|
providerId,
|
|
kind,
|
|
operation,
|
|
requestId,
|
|
payload,
|
|
deadlineMs,
|
|
cancellationToken,
|
|
...(input !== undefined ? { input } : {}),
|
|
...(output !== undefined ? { output } : {}),
|
|
});
|
|
try {
|
|
const handler = OPERATION_MAP_PROVIDER_KINDS.has(registration.kind)
|
|
? registration.handler[operation]
|
|
: registration.handler;
|
|
if (typeof handler !== "function") {
|
|
throw new PluginError("invalid_argument", `${kind} Provider operation is not implemented: ${operation}`);
|
|
}
|
|
const result = await handler(invocation);
|
|
if (cancellationToken.isCancellationRequested) {
|
|
return { requestId, status: "cancelled" };
|
|
}
|
|
// Sync readObject may return inline base64 or found:false while the host
|
|
// still opened an output stream for large-object fallback — release it.
|
|
if (syncReadStream && output && !(result && result.streamed === true)) {
|
|
try { output.cancel?.(); } catch { /* best-effort */ }
|
|
}
|
|
return { requestId, status: "ok", result: result === undefined ? null : result };
|
|
} catch (error) {
|
|
cancelStreams?.();
|
|
if (cancellationToken.isCancellationRequested) {
|
|
return { requestId, status: "cancelled" };
|
|
}
|
|
const rpcError = normalizeError(error);
|
|
return {
|
|
requestId,
|
|
status: "failed",
|
|
error: { code: rpcError.code, message: rpcError.message, ...(rpcError.data === undefined ? {} : { data: rpcError.data }) },
|
|
};
|
|
} finally {
|
|
cancellationDisposable?.dispose();
|
|
if (streamed && cancellationToken.isCancellationRequested) cancelStreams();
|
|
}
|
|
}
|
|
throw new PluginError("unsupported", `Unsupported host method: ${message.method}`);
|
|
}
|
|
|
|
function handleNotification(message) {
|
|
if (message.method === "plugin.settings.changed") {
|
|
runtimeApi.settingsChanged.fire(message.params);
|
|
return true;
|
|
}
|
|
if (message.method === "plugin.environment.changed") {
|
|
runtimeApi.environment = normalizeRuntimeEnvironment(message.params);
|
|
runtimeApi.environmentChanged.fire(runtimeApi.environment);
|
|
return true;
|
|
}
|
|
if (message.method === "plugin.view.message") {
|
|
const viewId = assertOwnedContributionId(config.pluginId, message.params?.viewId, "Plugin view");
|
|
runtimeApi.viewMessages.get(viewId)?.fire(message.params?.message);
|
|
return true;
|
|
}
|
|
if (message.method === "plugin.terminal.event") {
|
|
runtimeApi.terminalEvents.fire(freezeRuntimeJson(message.params));
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
const attachTerminalInterceptor = async (message, ports, cancellationToken) => {
|
|
const descriptor = message?.descriptor;
|
|
const providerId = assertOwnedContributionId(config.pluginId, descriptor?.providerId, "Terminal interceptor");
|
|
const direction = descriptor?.direction;
|
|
const kind = direction === "input" ? "terminal.interceptor.input"
|
|
: direction === "output" ? "terminal.interceptor.output" : null;
|
|
const sessionId = descriptor?.session?.sessionId;
|
|
if (!kind || typeof sessionId !== "string" || sessionId.length < 1 || sessionId.length > 256) {
|
|
throw new PluginError("invalid_argument", "Terminal interceptor descriptor is invalid");
|
|
}
|
|
const registration = runtimeApi.providerHandlers.get(providerId);
|
|
const interceptorPort = ports?.[0];
|
|
if (!activated || registration?.kind !== kind || !interceptorPort?.postMessage) {
|
|
interceptorPort?.close?.();
|
|
throw new PluginError("failed_precondition", "Terminal interceptor provider is not registered");
|
|
}
|
|
runtimeApi.terminalInterceptorPorts.add(interceptorPort);
|
|
let attached = false;
|
|
try {
|
|
const {
|
|
TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES,
|
|
createTerminalInterceptorEnvelope,
|
|
} = await loadTerminalInterceptorTransportForRuntime();
|
|
if (cancellationToken?.isCancellationRequested
|
|
|| deactivated
|
|
|| !activated
|
|
|| !runtimeApi.terminalInterceptorPorts.has(interceptorPort)
|
|
|| runtimeApi.providerHandlers.get(providerId) !== registration) {
|
|
throw new PluginError("failed_precondition", "Terminal interceptor attachment was cancelled or became stale");
|
|
}
|
|
const handleChunk = (event) => {
|
|
let envelope;
|
|
try {
|
|
const message = messageData(event);
|
|
envelope = createTerminalInterceptorEnvelope(message?.frame, message?.transfer);
|
|
} catch {
|
|
interceptorPort.close?.();
|
|
return;
|
|
}
|
|
const chunk = envelope.frame;
|
|
if (chunk?.type === "netcatty:terminal-interceptor:ready") return;
|
|
if (chunk.type !== "netcatty:terminal-interceptor:chunk"
|
|
|| chunk.direction !== direction) {
|
|
interceptorPort.close?.();
|
|
return;
|
|
}
|
|
const invocation = Object.freeze({
|
|
providerId,
|
|
kind,
|
|
direction,
|
|
sequence: chunk.sequence,
|
|
session: freezeRuntimeJson(descriptor.session),
|
|
data: new Uint8Array(envelope.transfer),
|
|
});
|
|
// Resolve the registration for every chunk so disposal/re-registration
|
|
// cannot keep a captured stale handler alive. Starting from a resolved
|
|
// promise also converts synchronous handler throws into the ordinary
|
|
// failed response path instead of tearing down the utility runtime.
|
|
void Promise.resolve().then(() => {
|
|
const currentRegistration = runtimeApi.providerHandlers.get(providerId);
|
|
if (currentRegistration?.kind !== kind) {
|
|
throw new PluginError("failed_precondition", "Terminal interceptor provider is no longer registered");
|
|
}
|
|
return currentRegistration.handler(invocation);
|
|
}).then(
|
|
(result) => {
|
|
let bytes;
|
|
if (result instanceof Uint8Array) bytes = result;
|
|
else if (result instanceof ArrayBuffer) bytes = new Uint8Array(result);
|
|
else throw new PluginError("data_loss", "Terminal interceptor must return Uint8Array or ArrayBuffer");
|
|
if (bytes.byteLength > TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES) {
|
|
throw new PluginError("resource_exhausted", "Terminal interceptor result is too large");
|
|
}
|
|
const copy = new Uint8Array(bytes.byteLength);
|
|
copy.set(bytes);
|
|
const resultEnvelope = createTerminalInterceptorEnvelope({
|
|
type: "netcatty:terminal-interceptor:result",
|
|
sequence: chunk.sequence,
|
|
status: "ok",
|
|
creditBytes: chunk.byteLength,
|
|
byteLength: copy.byteLength,
|
|
}, copy.buffer);
|
|
interceptorPort.postMessage(resultEnvelope, [copy.buffer]);
|
|
},
|
|
() => interceptorPort.postMessage(createTerminalInterceptorEnvelope({
|
|
type: "netcatty:terminal-interceptor:result",
|
|
sequence: chunk.sequence,
|
|
status: "failed",
|
|
})),
|
|
).catch(() => interceptorPort.close?.());
|
|
};
|
|
if (typeof interceptorPort.addEventListener === "function") {
|
|
interceptorPort.addEventListener("message", handleChunk);
|
|
} else {
|
|
interceptorPort.on("message", handleChunk);
|
|
}
|
|
interceptorPort.start?.();
|
|
interceptorPort.on?.("close", () => runtimeApi.terminalInterceptorPorts.delete(interceptorPort));
|
|
attached = true;
|
|
} finally {
|
|
if (!attached) {
|
|
runtimeApi.terminalInterceptorPorts.delete(interceptorPort);
|
|
interceptorPort.close?.();
|
|
}
|
|
}
|
|
};
|
|
|
|
const dispose = transport.onMessage((message, ports) => {
|
|
if (message && typeof message === "object" && Object.hasOwn(message, "frame")) {
|
|
for (const port of ports) port?.close?.();
|
|
try {
|
|
if (!runtimeApi.streams.accept(message)) cancelUnhandledStream(transport, message);
|
|
}
|
|
catch { transport.close(); }
|
|
return;
|
|
}
|
|
if (client.accept(message)) {
|
|
for (const port of ports) port?.close?.();
|
|
return;
|
|
}
|
|
if (!message || message.jsonrpc !== "2.0") {
|
|
for (const port of ports) port?.close?.();
|
|
return;
|
|
}
|
|
if (message.method === "$/cancelRequest") {
|
|
for (const port of ports) port?.close?.();
|
|
cancellation.get(message.params?.cancellationId)?.cancel();
|
|
return;
|
|
}
|
|
if (!Object.hasOwn(message, "id")) {
|
|
for (const port of ports) port?.close?.();
|
|
try { handleNotification(message); } catch { transport.close(); }
|
|
return;
|
|
}
|
|
const cancellationId = message.cancellationId;
|
|
const source = new CancellationTokenSource();
|
|
if (cancellationId) cancellation.set(cancellationId, source);
|
|
void handleRequest(message, source.token, ports).then(
|
|
(result) => transport.post({
|
|
jsonrpc: "2.0",
|
|
id: message.id,
|
|
result: result === undefined ? null : result,
|
|
}),
|
|
(error) => {
|
|
const rpcError = normalizeError(error);
|
|
transport.post(makeRpcFailure(message.id, rpcError.code, rpcError.message, rpcError.data));
|
|
},
|
|
).finally(() => {
|
|
if (cancellationId) cancellation.delete(cancellationId);
|
|
source.dispose();
|
|
});
|
|
});
|
|
|
|
return {
|
|
async dispose() {
|
|
dispose();
|
|
client.close();
|
|
for (const source of cancellation.values()) source.cancel();
|
|
runtimeApi.commandHandlers.clear();
|
|
runtimeApi.providerHandlers.clear();
|
|
runtimeApi.settingsChanged.clear();
|
|
runtimeApi.environmentChanged.clear();
|
|
runtimeApi.terminalEvents.clear();
|
|
for (const interceptorPort of runtimeApi.terminalInterceptorPorts) interceptorPort.close?.();
|
|
runtimeApi.terminalInterceptorPorts.clear();
|
|
runtimeApi.streams.close();
|
|
for (const emitter of runtimeApi.viewMessages.values()) emitter.clear();
|
|
cancellation.clear();
|
|
if (!deactivated) {
|
|
await plugin.deactivate?.();
|
|
context?.subscriptions.dispose();
|
|
}
|
|
transport.close();
|
|
},
|
|
};
|
|
}
|