@rynx-ai/daemon 0.1.11-beta.1 → 0.1.11-beta.3

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 (148) hide show
  1. package/bundled-plugins/.rynx-plugin/marketplace.json +10 -0
  2. package/bundled-plugins/plugins/lark/.rynx-plugin/plugin.json +37 -0
  3. package/bundled-plugins/plugins/lark/dist/cli-mirror/mirror-index.d.ts +48 -0
  4. package/bundled-plugins/plugins/lark/dist/cli-mirror/mirror-index.js +54 -0
  5. package/bundled-plugins/plugins/lark/dist/cli-mirror/rollout-mirror.d.ts +85 -0
  6. package/bundled-plugins/plugins/lark/dist/cli-mirror/rollout-mirror.js +333 -0
  7. package/bundled-plugins/plugins/lark/dist/cli-mirror/rollout-watcher.d.ts +109 -0
  8. package/bundled-plugins/plugins/lark/dist/cli-mirror/rollout-watcher.js +347 -0
  9. package/bundled-plugins/plugins/lark/dist/host-adapters.d.ts +95 -0
  10. package/bundled-plugins/plugins/lark/dist/host-adapters.js +504 -0
  11. package/bundled-plugins/plugins/lark/dist/index.d.ts +7 -0
  12. package/bundled-plugins/plugins/lark/dist/index.js +7 -0
  13. package/bundled-plugins/plugins/lark/dist/lark-card-stream.d.ts +363 -0
  14. package/bundled-plugins/plugins/lark/dist/lark-card-stream.js +1335 -0
  15. package/bundled-plugins/plugins/lark/dist/lark-config-store.d.ts +30 -0
  16. package/bundled-plugins/plugins/lark/dist/lark-config-store.js +135 -0
  17. package/bundled-plugins/plugins/lark/dist/lark-content.d.ts +30 -0
  18. package/bundled-plugins/plugins/lark/dist/lark-content.js +138 -0
  19. package/bundled-plugins/plugins/lark/dist/lark-conversation-directory.d.ts +65 -0
  20. package/bundled-plugins/plugins/lark/dist/lark-conversation-directory.js +106 -0
  21. package/bundled-plugins/plugins/lark/dist/lark-diff-card.d.ts +25 -0
  22. package/bundled-plugins/plugins/lark/dist/lark-diff-card.js +58 -0
  23. package/bundled-plugins/plugins/lark/dist/lark-fork-transcript.d.ts +16 -0
  24. package/bundled-plugins/plugins/lark/dist/lark-fork-transcript.js +141 -0
  25. package/bundled-plugins/plugins/lark/dist/lark-resume-card.d.ts +31 -0
  26. package/bundled-plugins/plugins/lark/dist/lark-resume-card.js +105 -0
  27. package/bundled-plugins/plugins/lark/dist/lark-runtime-state-store.d.ts +18 -0
  28. package/bundled-plugins/plugins/lark/dist/lark-runtime-state-store.js +95 -0
  29. package/bundled-plugins/plugins/lark/dist/lark-sdk/client.d.ts +8 -0
  30. package/bundled-plugins/plugins/lark/dist/lark-sdk/client.js +32 -0
  31. package/bundled-plugins/plugins/lark/dist/lark-sdk/index.d.ts +1 -0
  32. package/bundled-plugins/plugins/lark/dist/lark-sdk/index.js +1 -0
  33. package/bundled-plugins/plugins/lark/dist/lark-sender.d.ts +114 -0
  34. package/bundled-plugins/plugins/lark/dist/lark-sender.js +323 -0
  35. package/bundled-plugins/plugins/lark/dist/lark-session-store.d.ts +13 -0
  36. package/bundled-plugins/plugins/lark/dist/lark-session-store.js +14 -0
  37. package/bundled-plugins/plugins/lark/dist/lark-settings-card.d.ts +55 -0
  38. package/bundled-plugins/plugins/lark/dist/lark-settings-card.js +158 -0
  39. package/bundled-plugins/plugins/lark/dist/lark-setup.d.ts +39 -0
  40. package/bundled-plugins/plugins/lark/dist/lark-setup.js +103 -0
  41. package/bundled-plugins/plugins/lark/dist/lark.d.ts +507 -0
  42. package/bundled-plugins/plugins/lark/dist/lark.js +1977 -0
  43. package/bundled-plugins/plugins/lark/dist/runtime.d.ts +13 -0
  44. package/bundled-plugins/plugins/lark/dist/runtime.js +131313 -0
  45. package/bundled-plugins/plugins/lark/dist/settings.d.ts +7 -0
  46. package/bundled-plugins/plugins/lark/dist/settings.js +126958 -0
  47. package/bundled-plugins/plugins/lark/package.json +57 -0
  48. package/bundled-plugins/plugins/lark/ui/assets/index-B2dhMlMU.css +1 -0
  49. package/bundled-plugins/plugins/lark/ui/assets/index-D9N-AkLX.js +201 -0
  50. package/bundled-plugins/plugins/lark/ui/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  51. package/bundled-plugins/plugins/lark/ui/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  52. package/bundled-plugins/plugins/lark/ui/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  53. package/bundled-plugins/plugins/lark/ui/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  54. package/bundled-plugins/plugins/lark/ui/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  55. package/bundled-plugins/plugins/lark/ui/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  56. package/bundled-plugins/plugins/lark/ui/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  57. package/bundled-plugins/plugins/lark/ui/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  58. package/bundled-plugins/plugins/lark/ui/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  59. package/bundled-plugins/plugins/lark/ui/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  60. package/bundled-plugins/plugins/lark/ui/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  61. package/bundled-plugins/plugins/lark/ui/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  62. package/bundled-plugins/plugins/lark/ui/index.html +13 -0
  63. package/dist/browser-artifact-management.d.ts +4 -1
  64. package/dist/browser-artifact-management.js +18 -10
  65. package/dist/browser-artifacts.d.ts +1 -0
  66. package/dist/browser-artifacts.js +1 -0
  67. package/dist/bundled-plugins.d.ts +15 -0
  68. package/dist/bundled-plugins.js +134 -0
  69. package/dist/chrome-for-testing-runtime.d.ts +27 -0
  70. package/dist/chrome-for-testing-runtime.js +193 -0
  71. package/dist/chrome-for-testing-store.d.ts +2 -0
  72. package/dist/chrome-for-testing-store.js +9 -0
  73. package/dist/control-deps.js +2 -79
  74. package/dist/daemon-server.d.ts +7 -1
  75. package/dist/daemon-server.js +299 -84
  76. package/dist/db.js +147 -124
  77. package/dist/entry-path.d.ts +3 -0
  78. package/dist/entry-path.js +12 -0
  79. package/dist/index-daemon.js +3 -66
  80. package/dist/lifecycle.d.ts +12 -0
  81. package/dist/lifecycle.js +16 -0
  82. package/dist/maintenance-lease.d.ts +39 -0
  83. package/dist/maintenance-lease.js +250 -0
  84. package/dist/migrations/cleanup-legacy-sessions.d.ts +1 -1
  85. package/dist/migrations/cleanup-legacy-sessions.js +33 -15
  86. package/dist/official-plugins.d.ts +2 -0
  87. package/dist/official-plugins.js +2 -0
  88. package/dist/plugin-cli.d.ts +1 -3
  89. package/dist/plugin-cli.js +56 -45
  90. package/dist/plugin-host-leases.d.ts +4 -0
  91. package/dist/plugin-host-leases.js +7 -0
  92. package/dist/plugin-host-rpc.d.ts +60 -4
  93. package/dist/plugin-host-rpc.js +300 -50
  94. package/dist/plugin-installer.d.ts +24 -55
  95. package/dist/plugin-installer.js +258 -412
  96. package/dist/plugin-management-service.d.ts +30 -23
  97. package/dist/plugin-management-service.js +290 -105
  98. package/dist/plugin-marketplace.d.ts +35 -0
  99. package/dist/plugin-marketplace.js +299 -0
  100. package/dist/plugin-package.d.ts +22 -24
  101. package/dist/plugin-package.js +520 -571
  102. package/dist/plugin-skill-context.d.ts +4 -0
  103. package/dist/plugin-skill-context.js +35 -0
  104. package/dist/plugin-store.d.ts +36 -37
  105. package/dist/plugin-store.js +140 -92
  106. package/dist/plugin-supervisor.d.ts +50 -125
  107. package/dist/plugin-supervisor.js +682 -1030
  108. package/dist/pm2.d.ts +11 -2
  109. package/dist/pm2.js +130 -28
  110. package/dist/process.d.ts +12 -0
  111. package/dist/process.js +91 -0
  112. package/dist/runtime-project-store.d.ts +9 -0
  113. package/dist/runtime-project-store.js +83 -0
  114. package/dist/session-fallback-workspace.d.ts +22 -0
  115. package/dist/session-fallback-workspace.js +120 -0
  116. package/dist/session-fork-store.d.ts +41 -0
  117. package/dist/session-fork-store.js +288 -0
  118. package/dist/session-launch-operations.d.ts +23 -2
  119. package/dist/session-launch-operations.js +48 -7
  120. package/dist/session-meta-store.d.ts +7 -9
  121. package/dist/session-meta-store.js +28 -49
  122. package/dist/setup-service.d.ts +20 -0
  123. package/dist/setup-service.js +38 -0
  124. package/package.json +36 -20
  125. package/dist/browser-cli-args.d.ts +0 -20
  126. package/dist/browser-cli-args.js +0 -100
  127. package/dist/channel-store.d.ts +0 -22
  128. package/dist/channel-store.js +0 -65
  129. package/dist/cli.d.ts +0 -2
  130. package/dist/cli.js +0 -732
  131. package/dist/control-client.d.ts +0 -122
  132. package/dist/control-client.js +0 -855
  133. package/dist/control-endpoint.d.ts +0 -14
  134. package/dist/control-endpoint.js +0 -124
  135. package/dist/desktop-browser-host-client.d.ts +0 -35
  136. package/dist/desktop-browser-host-client.js +0 -415
  137. package/dist/instance-store.d.ts +0 -38
  138. package/dist/instance-store.js +0 -85
  139. package/dist/plugin-install-restart.d.ts +0 -13
  140. package/dist/plugin-install-restart.js +0 -24
  141. package/dist/plugin-runtime-control.d.ts +0 -2
  142. package/dist/plugin-runtime-control.js +0 -37
  143. package/dist/registry.d.ts +0 -10
  144. package/dist/registry.js +0 -52
  145. package/dist/setup.d.ts +0 -20
  146. package/dist/setup.js +0 -374
  147. package/dist/update.d.ts +0 -25
  148. package/dist/update.js +0 -133
@@ -1,1143 +1,795 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import path from "node:path";
3
- import { resolveAllowedRoots, rynxHome, } from "@rynx-ai/core";
4
- import { PLUGIN_RUNNER_API_VERSION, spawnPluginRunner, } from "@rynx-ai/plugin-runner";
5
- import { normalizePluginConfig, } from "@rynx-ai/plugin-sdk";
2
+ import { mkdirSync } from "node:fs";
3
+ import { removePluginRuntimeLease, writePluginRuntimeLease, } from "@rynx-ai/plugin-sdk";
4
+ import { spawnPluginRunner, } from "@rynx-ai/plugin-runner";
6
5
  import { MAX_PLUGIN_HOST_EVENT_BYTES, PluginHostRpc, } from "./plugin-host-rpc.js";
6
+ import { pluginDataDir, pluginRuntimeCacheDir, } from "./plugin-installer.js";
7
+ import { PLUGIN_HOST_RUNTIME_LEASE_IDS } from "./plugin-host-leases.js";
8
+ import { isBuiltInPluginMarketplace } from "./plugin-marketplace.js";
9
+ import { validatePluginPackageSnapshot } from "./plugin-package.js";
10
+ import { setPluginRuntimeState, } from "./plugin-store.js";
7
11
  const DEFAULT_RESTART_BASE_MS = 1_000;
8
12
  const MAX_RESTART_DELAY_MS = 30_000;
9
- const DEFAULT_STABLE_RESET_MS = 60_000;
10
- const MAX_HOST_EVENT_QUEUE_ITEMS = 64;
11
- const MAX_HOST_EVENT_QUEUE_BYTES = 8 * 1024 * 1024;
12
- const MAX_STDERR_LINE_BYTES = 64 * 1024;
13
- const MAX_STATUS_ERROR_BYTES = 16 * 1024;
14
- const DEFAULT_READY_TIMEOUT_MS = 15_000;
15
- const MAX_READY_TIMEOUT_MS = 60_000;
16
- const RUNTIME_STATUS_POLL_MS = 50;
17
- const TARGET_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
13
+ const STABLE_RESET_MS = 60_000;
14
+ const DEFAULT_HEALTH_POLL_MS = 30_000;
15
+ const [RUNTIME_LEASE_ID, SETTINGS_LEASE_ID] = PLUGIN_HOST_RUNTIME_LEASE_IDS;
18
16
  /**
19
- * Owns isolated plugin child processes and projects their static chat-channel
20
- * declarations onto trusted host-side ChannelManager handles.
21
- *
22
- * There is at most one resident child per enabled plugin. Chat-channel
23
- * instances are independent desired-state entries inside that child, so
24
- * stopping the final channel does not tear down the plugin runtime itself.
17
+ * Supervises exactly one language-neutral runtime process per enabled plugin.
18
+ * It has no channel-instance API and never interprets plugin-owned state.
25
19
  */
26
20
  export class PluginSupervisor {
27
21
  states = new Map();
28
- services;
22
+ queues = new Map();
29
23
  spawnRunner;
30
- logger;
24
+ log;
25
+ daemonInstanceId;
26
+ productVersion;
27
+ cliVersion;
31
28
  restartBaseMs;
32
29
  restartMaxMs;
33
- stableResetMs;
34
- daemonInstanceId;
35
- runtimeOperations = new Map();
30
+ healthPollMs;
31
+ verifyPackage;
32
+ services;
36
33
  disposed = false;
37
- constructor(plugins, options) {
34
+ disposePromise;
35
+ constructor(records, options = {}) {
38
36
  this.services = options.services;
39
37
  this.spawnRunner = options.spawnRunner ?? spawnPluginRunner;
40
- this.logger = options.log;
41
- this.restartBaseMs = Math.min(positiveDelay(options.restartBaseMs, DEFAULT_RESTART_BASE_MS), MAX_RESTART_DELAY_MS);
42
- this.restartMaxMs = Math.max(this.restartBaseMs, Math.min(positiveDelay(options.restartMaxMs, MAX_RESTART_DELAY_MS), MAX_RESTART_DELAY_MS));
43
- this.stableResetMs = positiveDelay(options.stableResetMs, DEFAULT_STABLE_RESET_MS);
44
- this.daemonInstanceId = options.daemonInstanceId?.trim() || randomUUID();
45
- for (const record of plugins) {
46
- validateRecord(record);
47
- if (this.states.has(record.manifest.id)) {
48
- throw new Error(`duplicate runnable plugin id: ${record.manifest.id}`);
49
- }
50
- this.states.set(record.manifest.id, createPluginState(record));
51
- }
38
+ this.log = options.log ?? (() => { });
39
+ this.daemonInstanceId = options.daemonInstanceId ?? randomUUID();
40
+ this.productVersion = options.productVersion ?? "development";
41
+ this.cliVersion = options.cliVersion ?? "development";
42
+ this.restartBaseMs = options.restartBaseMs ?? DEFAULT_RESTART_BASE_MS;
43
+ this.restartMaxMs = Math.min(options.restartMaxMs ?? MAX_RESTART_DELAY_MS, MAX_RESTART_DELAY_MS);
44
+ this.healthPollMs = options.healthPollMs ?? DEFAULT_HEALTH_POLL_MS;
45
+ this.verifyPackage = options.verifyPackage ?? verifyInstalledPackage;
46
+ if (!Number.isSafeInteger(this.healthPollMs) || this.healthPollMs <= 0) {
47
+ throw new Error("plugin health poll interval must be a positive safe integer");
48
+ }
49
+ for (const record of records)
50
+ this.upsertState(record);
52
51
  }
53
- /** Static channel catalog. Calling this never loads or executes plugin code. */
54
- createChannelTypeDescriptors() {
55
- const descriptors = [];
56
- for (const state of this.states.values()) {
57
- for (const contribution of state.record.manifest.contributions?.chatChannels ?? []) {
58
- descriptors.push(this.channelDescriptor(state, contribution));
59
- }
60
- }
61
- return descriptors;
62
- }
63
- /** Bind the trusted host once, after the server composition root constructs it. */
64
52
  bindHostServices(services) {
65
- this.assertOpen();
66
53
  if (this.services)
67
54
  throw new Error("plugin host services are already bound");
68
55
  this.services = services;
69
- return this;
70
56
  }
71
- /** Cached, non-blocking runner/contribution health for the generic control API. */
72
- statusSnapshot() {
73
- const plugins = [];
74
- for (const state of this.states.values()) {
75
- if (state.runner)
76
- void this.refreshRuntimeStatus(state).catch(() => undefined);
77
- for (const desired of state.desired.values()) {
78
- if (state.runner && desired.startedGeneration === state.generation) {
79
- void this.refreshContributionStatus(state, desired).catch(() => undefined);
80
- }
81
- }
82
- const contributions = [...state.desired.values()].map((desired) => ({
83
- key: desired.key,
84
- target: { ...desired.target },
85
- desired: true,
86
- ...(desired.startedGeneration === undefined
87
- ? {}
88
- : { generation: desired.startedGeneration }),
89
- failureCount: desired.failureCount,
90
- status: { ...desired.status },
91
- }));
92
- plugins.push({
93
- pluginId: state.record.manifest.id,
94
- runner: {
95
- state: runnerSnapshotState(state, this.disposed),
96
- generation: state.generation,
97
- failureCount: state.failureCount,
98
- ...(state.lastRunnerError ? { lastError: state.lastRunnerError } : {}),
99
- },
100
- runtimeStatus: { ...state.runtimeStatus },
101
- contributions,
102
- });
103
- }
104
- return { capturedAt: new Date().toISOString(), plugins };
105
- }
106
- /** Start one resident runner for every enabled runtime plugin. */
107
57
  async startPluginRuntimes() {
108
- this.assertReady();
109
- await Promise.all([...this.states.values()].map(async (state) => {
110
- try {
111
- await this.ensureRunner(state);
112
- await this.refreshRuntimeStatus(state);
58
+ const starts = [...this.states.values()].map((state) => this.runSerialized(state.record.canonicalId, () => this.startState(state)));
59
+ await Promise.allSettled(starts);
60
+ }
61
+ async ensurePluginRuntime(record) {
62
+ return await this.runSerialized(record.canonicalId, async () => {
63
+ const state = this.upsertState(record);
64
+ if (!record.enabled) {
65
+ await this.stopState(state);
66
+ return "stopped";
113
67
  }
114
- catch (error) {
115
- this.writeLog({
116
- level: "error",
117
- event: "plugin.runner.start_failed",
118
- pluginId: state.record.manifest.id,
119
- message: messageOf(error),
120
- });
68
+ if (!record.manifest.runtime) {
69
+ state.state = "absent";
70
+ setPluginRuntimeState(record.canonicalId, "absent");
71
+ return "absent";
121
72
  }
122
- }));
73
+ if (!state.runner)
74
+ await this.startState(state);
75
+ return state.state;
76
+ });
123
77
  }
124
- /**
125
- * Atomically replace or add one plugin runtime, preserving its live chat
126
- * desired state. Concurrent reloads of the same plugin are applied in call
127
- * order; other plugins continue running independently.
128
- */
129
- reloadPluginRuntime(record, { readyTimeoutMs } = {}) {
130
- this.assertReady();
131
- validateRecord(record);
132
- const pluginId = record.manifest.id;
133
- return this.enqueueRuntimeOperation(pluginId, () => this.performPluginRuntimeReload(record, createRuntimeReadyDeadline(boundedReadyTimeout(readyTimeoutMs))));
78
+ /** Strict cutover: stop current generation, then start the supplied generation. */
79
+ async reloadPluginRuntime(record) {
80
+ return await this.runSerialized(record.canonicalId, async () => {
81
+ const state = this.upsertState(record);
82
+ await this.stopState(state);
83
+ await this.stopSettingsState(state);
84
+ state.record = record;
85
+ state.stopping = false;
86
+ if (!record.enabled || !record.manifest.runtime) {
87
+ state.state = record.manifest.runtime ? "stopped" : "absent";
88
+ setPluginRuntimeState(record.canonicalId, state.state);
89
+ return state.state;
90
+ }
91
+ await this.startState(state);
92
+ return state.state;
93
+ });
134
94
  }
135
- /**
136
- * Make one enabled plugin runtime ready without replacing an already healthy
137
- * runner. This is the idempotent operation plugin CLIs use when their durable
138
- * configuration has not changed.
139
- */
140
- ensurePluginRuntime(record, { readyTimeoutMs } = {}) {
141
- this.assertReady();
142
- validateRecord(record);
143
- const pluginId = record.manifest.id;
144
- return this.enqueueRuntimeOperation(pluginId, () => this.performPluginRuntimeEnsure(record, createRuntimeReadyDeadline(boundedReadyTimeout(readyTimeoutMs))));
95
+ async stopPluginRuntime(identity) {
96
+ await this.runSerialized(identity, async () => {
97
+ const state = this.states.get(identity);
98
+ if (state)
99
+ await this.stopState(state);
100
+ });
145
101
  }
146
- enqueueRuntimeOperation(pluginId, execute) {
147
- const preceding = this.runtimeOperations.get(pluginId);
148
- const operation = (preceding ? preceding.catch(() => undefined) : Promise.resolve())
149
- .then(execute);
150
- this.runtimeOperations.set(pluginId, operation);
151
- void operation.finally(() => {
152
- if (this.runtimeOperations.get(pluginId) === operation) {
153
- this.runtimeOperations.delete(pluginId);
102
+ async changeEnabled(record, enabled, mutateRegistry) {
103
+ return await this.runSerialized(record.canonicalId, async () => {
104
+ const state = this.upsertState(record);
105
+ if (!enabled) {
106
+ await this.stopState(state);
107
+ let updated;
108
+ try {
109
+ updated = mutateRegistry();
110
+ }
111
+ catch (error) {
112
+ state.stopping = false;
113
+ if (state.record.enabled)
114
+ await this.startState(state);
115
+ throw error;
116
+ }
117
+ state.record = updated;
118
+ return state.state;
154
119
  }
155
- }).catch(() => undefined);
156
- return operation;
120
+ const updated = mutateRegistry();
121
+ state.record = updated;
122
+ state.stopping = false;
123
+ await this.startState(state);
124
+ return state.state;
125
+ });
157
126
  }
158
- async performPluginRuntimeEnsure(record, deadline) {
159
- this.assertReady();
160
- const state = this.states.get(record.manifest.id);
161
- if (!state || !sameRuntimeRecord(state.record, record)) {
162
- return this.performPluginRuntimeReload(record, deadline);
163
- }
164
- if (!state.runner) {
165
- return this.performPluginRuntimeReload(record, deadline);
166
- }
167
- const status = await this.refreshRuntimeStatus(state, deadline);
168
- if (status.state === "unconfigured" ||
169
- status.state === "failed" ||
170
- status.state === "stopped") {
171
- return this.performPluginRuntimeReload(record, deadline);
172
- }
173
- // A starting or degraded runtime may be recovering its own transport. Do
174
- // not destroy it (and any active task leases) merely because the user ran
175
- // the same connect command twice; wait for its bounded readiness result.
176
- return this.waitForRuntimeReady(state, deadline);
127
+ async cutoverInstallation(identity, commitRegistry) {
128
+ return await this.runSerialized(identity, async () => {
129
+ const current = this.states.get(identity);
130
+ if (current) {
131
+ await this.stopState(current);
132
+ await this.stopSettingsState(current);
133
+ }
134
+ let installed;
135
+ try {
136
+ installed = await commitRegistry();
137
+ }
138
+ catch (error) {
139
+ if (current) {
140
+ current.stopping = false;
141
+ if (current.record.enabled)
142
+ await this.startState(current);
143
+ }
144
+ throw error;
145
+ }
146
+ const state = this.upsertState(installed);
147
+ state.record = installed;
148
+ state.stopping = false;
149
+ if (installed.enabled)
150
+ await this.startState(state);
151
+ return state.state;
152
+ });
177
153
  }
178
- async performPluginRuntimeReload(record, deadline) {
179
- this.assertReady();
180
- const pluginId = record.manifest.id;
181
- let state = this.states.get(pluginId);
182
- if (!state) {
183
- state = createPluginState(record);
184
- this.states.set(pluginId, state);
185
- }
186
- else {
187
- await this.joinExitTransition(state);
188
- const spawning = state.spawnPromise;
189
- this.cancelRestart(state);
190
- await this.closeRunner(state);
191
- await spawning?.catch(() => undefined);
192
- // A runner that was already spawning may have bound after the first
193
- // close. Close once more before switching the immutable package record.
194
- await this.closeRunner(state);
195
- this.cancelRestart(state);
196
- state.record = record;
197
- state.failureCount = 0;
198
- state.lastRunnerError = undefined;
199
- state.runtimeStatusRefresh = undefined;
200
- for (const desired of state.desired.values()) {
201
- desired.startedGeneration = undefined;
202
- desired.status = { state: "starting", connected: false, lastError: null };
203
- state.channelStatus.set(desired.key, {
204
- ...(state.channelStatus.get(desired.key) ?? {}),
205
- connected: false,
206
- lastError: null,
207
- });
154
+ async uninstallInstallation(identity, removeRegistry) {
155
+ return await this.runSerialized(identity, async () => {
156
+ const state = this.states.get(identity);
157
+ if (state) {
158
+ await this.stopState(state);
159
+ await this.stopSettingsState(state);
208
160
  }
209
- }
210
- state.runtimeStatus = { state: "starting", connected: false, lastError: null };
211
- try {
212
- const runner = await this.ensureRunner(state);
213
- await this.restoreDesiredContributions(state, runner);
214
- }
215
- catch {
216
- // ensureRunner already cached the failure and scheduled resident backoff.
217
- // The bounded readiness loop remains authoritative and can observe a
218
- // successful retry before the caller's timeout expires.
219
- }
220
- return this.waitForRuntimeReady(state, deadline);
161
+ let removed;
162
+ try {
163
+ removed = await removeRegistry();
164
+ }
165
+ catch (error) {
166
+ if (state) {
167
+ state.stopping = false;
168
+ if (state.record.enabled)
169
+ await this.startState(state);
170
+ }
171
+ throw error;
172
+ }
173
+ if (!removed && state) {
174
+ state.stopping = false;
175
+ if (state.record.enabled)
176
+ await this.startState(state);
177
+ }
178
+ if (removed)
179
+ this.states.delete(identity);
180
+ return removed;
181
+ });
221
182
  }
222
- /** Permanently stop all children and cancel every pending automatic restart. */
223
- async dispose() {
224
- if (this.disposed)
225
- return;
226
- this.disposed = true;
227
- const closes = [];
228
- for (const state of this.states.values()) {
229
- state.desired.clear();
230
- for (const [key, status] of state.channelStatus) {
231
- state.channelStatus.set(key, { ...status, connected: false });
183
+ async settingsCall(identity, expectedGeneration, method, params, options = {}) {
184
+ return await this.runSerialized(identity, async () => {
185
+ const state = this.states.get(identity);
186
+ if (!state)
187
+ throw new Error(`plugin "${identity}" is not installed`);
188
+ if (state.record.integrity !== expectedGeneration) {
189
+ throw new Error("plugin settings UI generation is stale");
232
190
  }
233
- this.cancelRestart(state);
234
- clearTimer(state.stableTimer);
235
- state.stableTimer = undefined;
236
- state.runtimeStatus = { state: "stopping", connected: false };
237
- closes.push(this.disposeState(state));
238
- }
239
- await Promise.all(closes);
240
- for (const state of this.states.values()) {
241
- state.runtimeStatus = { state: "stopped", connected: false };
242
- }
191
+ const runner = await this.startSettingsState(state);
192
+ if (!runner.handshake.features.settings) {
193
+ throw new Error(`plugin "${identity}" does not advertise a settings background`);
194
+ }
195
+ const result = await runner.client.settingsCall(method, params, options);
196
+ await state.runner?.client.emitHostEvent("plugin.settings.changed", {
197
+ method,
198
+ ...(params === undefined ? {} : { params }),
199
+ }).catch(() => undefined);
200
+ return result;
201
+ });
243
202
  }
244
- channelDescriptor(state, contribution) {
245
- return {
246
- type: contribution.type,
247
- factory: (context) => this.createRemoteChannel(state, contribution, context),
248
- ...(contribution.configSchema ? { configSchema: contribution.configSchema } : {}),
249
- ...(contribution.authorize
250
- ? {
251
- authorize: (emit, signal, context) => this.authorize(state, contribution, emit, signal, context),
252
- }
253
- : {}),
254
- };
203
+ supportsSettings(identity) {
204
+ return Boolean(this.states.get(identity)?.record.manifest.settings);
255
205
  }
256
- createRemoteChannel(state, contribution, context) {
257
- const instanceId = context.instanceId ?? contribution.type;
258
- if (!TARGET_ID_PATTERN.test(instanceId)) {
259
- throw new Error(`invalid plugin channel instance id: ${instanceId}`);
260
- }
261
- const key = channelKey(contribution.type, instanceId);
262
- const target = {
263
- kind: "chat-channel",
264
- contributionId: contribution.type,
265
- instanceId,
266
- };
267
- const request = {
268
- ...target,
269
- config: normalizeChatChannelConfig(contribution, context.options),
270
- ...(context.defaultAgent ? { defaultAgent: context.defaultAgent } : {}),
271
- executionDefaults: {
272
- runtime: context.config.AGENT_RUNTIME,
273
- ...(context.config.RYNX_DEFAULT_AGENT
274
- ? { defaultAgent: context.config.RYNX_DEFAULT_AGENT }
275
- : {}),
276
- allowedRoots: resolveAllowedRoots(context.config),
277
- },
278
- };
206
+ statusSnapshot() {
279
207
  return {
280
- id: contribution.type,
281
- start: async () => {
282
- this.assertReady();
283
- const existing = state.desired.get(key);
284
- const desired = existing ?? this.rememberDesired(state, { key, request, target });
285
- if (existing && !sameStartRequest(existing.request, request)) {
286
- throw new Error(`plugin channel instance is already started with different config: ${instanceId}`);
287
- }
288
- await this.ensureDesiredStarted(state, desired);
289
- },
290
- stop: async () => {
291
- const desired = state.desired.get(key);
292
- if (!desired) {
293
- state.channelStatus.set(key, { connected: false, lastError: null });
294
- return;
295
- }
296
- await this.stopDesired(state, desired);
297
- },
298
- getStatus: () => {
299
- const cached = state.channelStatus.get(key) ?? {
300
- connected: false,
301
- lastError: null,
302
- lastEventAt: null,
303
- };
304
- const desired = state.desired.get(key);
305
- if (desired)
306
- void this.refreshContributionStatus(state, desired).catch(() => undefined);
307
- return { ...cached };
308
- },
208
+ plugins: [...this.states.values()].map((state) => ({
209
+ pluginId: state.record.canonicalId,
210
+ generation: state.generation,
211
+ state: state.state,
212
+ ...(state.health ? { health: structuredClone(state.health) } : {}),
213
+ ...(state.error ? { error: state.error } : {}),
214
+ settings: Boolean(state.record.manifest.settings),
215
+ })),
309
216
  };
310
217
  }
311
- async authorize(state, contribution, emit, signal, context) {
312
- this.assertReady();
313
- const runner = await this.ensureRunner(state);
314
- return runner.client.authorize({
315
- kind: "chat-channel",
316
- contributionId: contribution.type,
317
- ...(context?.instanceId ? { instanceId: context.instanceId } : {}),
318
- config: clonePluginConfig(context?.config),
319
- }, (material) => emit(material), { signal });
320
- }
321
- rememberDesired(state, input) {
322
- const desired = {
323
- ...input,
324
- status: { state: "stopped" },
325
- failureCount: 0,
218
+ async dispose() {
219
+ if (this.disposePromise)
220
+ return this.disposePromise;
221
+ this.disposed = true;
222
+ const attempt = (async () => {
223
+ const stopped = await Promise.allSettled([...this.states.values()].map((state) => this.runSerialized(state.record.canonicalId, async () => {
224
+ await this.stopState(state);
225
+ await this.stopSettingsState(state);
226
+ })));
227
+ const failures = stopped
228
+ .filter((result) => result.status === "rejected")
229
+ .map((result) => result.reason);
230
+ if (failures.length > 0) {
231
+ throw new AggregateError(failures, "plugin supervisor could not stop every runtime");
232
+ }
233
+ })();
234
+ this.disposePromise = attempt;
235
+ void attempt.catch(() => {
236
+ if (this.disposePromise === attempt)
237
+ this.disposePromise = undefined;
238
+ });
239
+ return attempt;
240
+ }
241
+ upsertState(record) {
242
+ const current = this.states.get(record.canonicalId);
243
+ if (current) {
244
+ if (!current.runner && !current.settingsRunner)
245
+ current.record = record;
246
+ return current;
247
+ }
248
+ const state = {
249
+ record,
250
+ state: record.manifest.runtime ? "stopped" : "absent",
251
+ generation: 0,
252
+ restartFailures: 0,
253
+ stopping: false,
326
254
  };
327
- state.desired.set(desired.key, desired);
328
- if (desired.target.kind === "chat-channel") {
329
- state.channelStatus.set(desired.key, { connected: false, lastError: null });
330
- }
331
- return desired;
332
- }
333
- async ensureDesiredStarted(state, desired) {
334
- const runner = await this.ensureRunner(state);
335
- if (state.desired.get(desired.key) !== desired) {
255
+ this.states.set(record.canonicalId, state);
256
+ return state;
257
+ }
258
+ async startState(state) {
259
+ if (this.disposed
260
+ || state.runner
261
+ || blockingCleanupError(state)
262
+ || !state.record.enabled)
336
263
  return;
337
- }
338
- await this.startDesiredOnRunner(state, desired, runner);
339
- await this.refreshContributionStatus(state, desired);
340
- }
341
- async startDesiredOnRunner(state, desired, runner) {
342
- const generation = state.generation;
343
- if (desired.startedGeneration === generation)
344
- return;
345
- if (desired.starting && desired.startingGeneration === generation) {
346
- await desired.starting;
264
+ const runtime = state.record.manifest.runtime;
265
+ if (!runtime) {
266
+ state.state = "absent";
267
+ setPluginRuntimeState(state.record.canonicalId, "absent");
347
268
  return;
348
269
  }
349
- desired.status = { state: "starting" };
350
- const operation = runner.client.startContribution(desired.request).then(() => {
351
- if (state.runner === runner && state.desired.get(desired.key) === desired) {
352
- desired.startedGeneration = generation;
353
- desired.failureCount = 0;
354
- desired.status = {
355
- state: "running",
356
- connected: false,
357
- lastError: null,
358
- };
359
- state.channelStatus.set(desired.key, {
360
- ...(state.channelStatus.get(desired.key) ?? {}),
361
- connected: state.channelStatus.get(desired.key)?.connected ?? false,
362
- lastError: null,
363
- });
364
- }
365
- }, (error) => {
366
- if (state.runner === runner && state.desired.get(desired.key) === desired) {
367
- this.markContributionFailed(state, desired, error);
368
- }
369
- throw error;
370
- });
371
- desired.starting = operation;
372
- desired.startingGeneration = generation;
270
+ if (!this.services)
271
+ throw new Error("plugin host services are not bound");
272
+ state.stopping = false;
273
+ state.state = "starting";
274
+ state.error = undefined;
275
+ state.generation += 1;
276
+ setPluginRuntimeState(state.record.canonicalId, "starting");
277
+ const dataDir = pluginDataDir(state.record.marketplaceId, state.record.pluginId);
278
+ const cacheDir = pluginRuntimeCacheDir(state.record.marketplaceId, state.record.pluginId, state.record.integrity);
279
+ let runner;
280
+ let hostRpc;
373
281
  try {
374
- await operation;
375
- }
376
- finally {
377
- if (desired.starting === operation) {
378
- desired.starting = undefined;
379
- desired.startingGeneration = undefined;
380
- }
282
+ await this.verifyPackage(state.record);
283
+ mkdirSync(dataDir, { recursive: true, mode: 0o700 });
284
+ mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
285
+ writePluginRuntimeLease({
286
+ dataDir,
287
+ pluginId: state.record.pluginId,
288
+ leaseId: RUNTIME_LEASE_ID,
289
+ installPath: state.record.installPath,
290
+ });
291
+ hostRpc = new PluginHostRpc({
292
+ pluginId: state.record.pluginId,
293
+ principalId: state.record.canonicalId,
294
+ daemonInstanceId: this.daemonInstanceId,
295
+ productVersion: this.productVersion,
296
+ cliVersion: this.cliVersion,
297
+ capabilities: state.record.manifest.capabilities,
298
+ services: this.services,
299
+ ...(state.record.pluginId === "workspace"
300
+ && isBuiltInPluginMarketplace(state.record.marketplaceId)
301
+ ? { managedWorkspaceRoot: dataDir }
302
+ : {}),
303
+ emit: async (event) => {
304
+ if (Buffer.byteLength(JSON.stringify(event), "utf8") > MAX_PLUGIN_HOST_EVENT_BYTES) {
305
+ throw new Error("plugin host event exceeds transport budget");
306
+ }
307
+ await runner?.client.emitHostEvent(event.event, event.payload);
308
+ },
309
+ });
310
+ state.hostRpc = hostRpc;
311
+ runner = await this.spawnRunner({
312
+ pluginId: state.record.pluginId,
313
+ pluginVersion: state.record.version,
314
+ installationId: state.record.canonicalId,
315
+ packageRoot: state.record.installPath,
316
+ ...("entry" in runtime
317
+ ? {
318
+ entry: runtime.entry,
319
+ }
320
+ : {
321
+ command: runtime.command,
322
+ args: runtime.args,
323
+ }),
324
+ role: "runtime",
325
+ dataDir,
326
+ cacheDir,
327
+ capabilities: state.record.manifest.capabilities,
328
+ handleHostCall: (method, params, signal) => hostRpc.call(method, params, signal),
329
+ onStderr: (line) => this.log({
330
+ level: "info",
331
+ event: "plugin-stderr",
332
+ pluginId: state.record.canonicalId,
333
+ message: line,
334
+ }),
335
+ });
336
+ state.runner = runner;
337
+ state.health = runner.initialHealth;
338
+ state.state = healthState(runner.initialHealth);
339
+ state.startedAt = Date.now();
340
+ state.error = undefined;
341
+ setPluginRuntimeState(state.record.canonicalId, state.state);
342
+ this.log({
343
+ level: "info",
344
+ event: "plugin-runtime-started",
345
+ pluginId: state.record.canonicalId,
346
+ });
347
+ this.scheduleHealthPoll(state, runner);
348
+ const generation = state.generation;
349
+ void runner.completion.then((exit) => {
350
+ void this.runSerialized(state.record.canonicalId, () => this.handleExit(state, runner, generation, exit));
351
+ }).catch((error) => {
352
+ void this.runSerialized(state.record.canonicalId, () => this.handleExit(state, runner, generation, {
353
+ code: null,
354
+ signal: null,
355
+ error,
356
+ }));
357
+ });
381
358
  }
382
- }
383
- async stopDesired(state, desired) {
384
- if (state.desired.get(desired.key) !== desired)
385
- return;
386
- state.desired.delete(desired.key);
387
- state.channelStatus.set(desired.key, {
388
- connected: false,
389
- lastError: null,
390
- lastEventAt: state.channelStatus.get(desired.key)?.lastEventAt ?? null,
391
- });
392
- let stopError;
393
- const runner = state.runner;
394
- if (runner) {
359
+ catch (error) {
395
360
  try {
396
- await runner.client.stopContribution(desired.target);
397
- }
398
- catch (error) {
399
- stopError = error;
361
+ await hostRpc?.dispose();
400
362
  }
401
- }
402
- if (stopError)
403
- throw stopError;
404
- }
405
- async refreshContributionStatus(state, desired) {
406
- if (desired.statusRefresh)
407
- return desired.statusRefresh;
408
- const runner = state.runner;
409
- if (!runner || desired.startedGeneration !== state.generation)
410
- return;
411
- const refresh = runner.client.status(desired.target).then((status) => {
412
- if (state.runner !== runner || state.desired.get(desired.key) !== desired)
413
- return;
414
- desired.status = boundedContributionStatus(status);
415
- state.channelStatus.set(desired.key, statusToChannelStatus(desired.status));
416
- }, (error) => {
417
- if (state.runner !== runner || state.desired.get(desired.key) !== desired)
363
+ catch (cleanupError) {
364
+ const failure = new AggregateError([error, cleanupError], "plugin runtime startup failed and active-run cleanup was unproven");
365
+ state.runtimeCleanupError = failure;
366
+ this.failState(state, failure);
418
367
  return;
419
- desired.status = {
420
- state: "degraded",
421
- connected: false,
422
- lastError: messageOf(error),
423
- };
424
- state.channelStatus.set(desired.key, {
425
- ...(state.channelStatus.get(desired.key) ?? {}),
426
- connected: false,
427
- lastError: messageOf(error),
428
- });
429
- });
430
- desired.statusRefresh = refresh;
431
- try {
432
- await refresh;
433
- }
434
- finally {
435
- if (desired.statusRefresh === refresh)
436
- desired.statusRefresh = undefined;
437
- }
438
- }
439
- async refreshRuntimeStatus(state, deadline) {
440
- if (deadline && deadline.expiresAt - Date.now() <= 0) {
441
- throw this.runtimeReadyTimeoutError(state, deadline.timeoutMs);
442
- }
443
- const runner = state.runner;
444
- if (!runner)
445
- return state.runtimeStatus;
446
- let refresh = state.runtimeStatusRefresh;
447
- if (!refresh) {
448
- refresh = runner.client.runtimeStatus().then((status) => {
449
- if (state.runner !== runner)
450
- return state.runtimeStatus;
451
- state.runtimeStatus = boundedRuntimeStatus(status);
452
- return state.runtimeStatus;
453
- }, (error) => {
454
- if (state.runner !== runner)
455
- return state.runtimeStatus;
456
- state.runtimeStatus = {
457
- state: "degraded",
458
- connected: false,
459
- lastError: messageOf(error),
460
- };
461
- return state.runtimeStatus;
462
- });
463
- state.runtimeStatusRefresh = refresh;
464
- void refresh.finally(() => {
465
- if (state.runtimeStatusRefresh === refresh)
466
- state.runtimeStatusRefresh = undefined;
467
- }).catch(() => undefined);
468
- }
469
- return deadline
470
- ? await settleBeforeDeadline(refresh, deadline.expiresAt, () => this.runtimeReadyTimeoutError(state, deadline.timeoutMs))
471
- : await refresh;
472
- }
473
- async waitForRuntimeReady(state, deadline) {
474
- while (true) {
475
- this.assertOpen();
476
- const remainingBeforeRefresh = deadline.expiresAt - Date.now();
477
- if (remainingBeforeRefresh <= 0) {
478
- throw this.runtimeReadyTimeoutError(state, deadline.timeoutMs);
479
368
  }
480
- const status = state.runner
481
- ? await this.refreshRuntimeStatus(state, deadline)
482
- : state.runtimeStatus;
483
- if (status.state === "running" && status.connected !== false)
484
- return { ...status };
485
- const remaining = deadline.expiresAt - Date.now();
486
- if (remaining <= 0) {
487
- throw this.runtimeReadyTimeoutError(state, deadline.timeoutMs);
369
+ state.hostRpc = undefined;
370
+ if (isUnprovenProcessCleanup(error)) {
371
+ state.runtimeCleanupError = error;
372
+ this.failState(state, error);
373
+ return;
488
374
  }
489
- await delay(Math.min(RUNTIME_STATUS_POLL_MS, remaining));
375
+ removePluginRuntimeLease(dataDir, RUNTIME_LEASE_ID);
376
+ this.failState(state, error);
377
+ this.scheduleRestart(state);
490
378
  }
491
379
  }
492
- runtimeReadyTimeoutError(state, timeoutMs) {
493
- const status = state.runtimeStatus;
494
- const detail = status.lastError ? `: ${status.lastError}` : ` (state=${status.state})`;
495
- return new Error(`plugin runtime "${state.record.manifest.id}" did not become ready within ${timeoutMs}ms${detail}`);
496
- }
497
- ensureRunner(state) {
498
- this.assertReady();
499
- if (state.exitTransition) {
500
- return this.joinExitTransition(state).then(() => this.ensureRunner(state));
380
+ async startSettingsState(state) {
381
+ if (this.disposed)
382
+ throw new Error("plugin supervisor is disposed");
383
+ const cleanupError = blockingCleanupError(state);
384
+ if (cleanupError)
385
+ throw cleanupError;
386
+ if (state.settingsRunner)
387
+ return state.settingsRunner;
388
+ const background = state.record.manifest.settings?.background;
389
+ if (!background) {
390
+ throw new Error(`plugin "${state.record.canonicalId}" has no settings background`);
501
391
  }
502
- if (state.runner)
503
- return Promise.resolve(state.runner);
504
- if (state.spawnPromise)
505
- return state.spawnPromise;
506
- state.runtimeStatus = { state: "starting", connected: false, lastError: null };
507
- const spawn = this.spawnAndBind(state).catch((error) => {
508
- if (!this.disposed) {
509
- state.failureCount += 1;
510
- this.markRunnerUnavailable(state, `plugin runner failed to start: ${messageOf(error)}`);
511
- this.scheduleRestart(state);
512
- }
513
- throw error;
514
- });
515
- state.spawnPromise = spawn;
516
- void spawn.finally(() => {
517
- if (state.spawnPromise === spawn)
518
- state.spawnPromise = undefined;
519
- }).catch(() => undefined);
520
- return spawn;
521
- }
522
- async spawnAndBind(state) {
523
- const pluginId = state.record.manifest.id;
524
- const eventQueue = new BoundedHostEventQueue();
525
- const host = new PluginHostRpc({
526
- pluginId,
527
- daemonInstanceId: this.daemonInstanceId,
528
- grants: state.record.grants,
529
- services: this.requireHostServices(),
530
- emit: (event) => eventQueue.enqueue(event),
531
- });
532
- const stderr = this.stderrSink(pluginId);
392
+ if (!this.services)
393
+ throw new Error("plugin host services are not bound");
394
+ const dataDir = pluginDataDir(state.record.marketplaceId, state.record.pluginId);
395
+ const cacheDir = pluginRuntimeCacheDir(state.record.marketplaceId, state.record.pluginId, state.record.integrity);
533
396
  let runner;
397
+ let hostRpc;
534
398
  try {
399
+ await this.verifyPackage(state.record);
400
+ mkdirSync(dataDir, { recursive: true, mode: 0o700 });
401
+ mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
402
+ writePluginRuntimeLease({
403
+ dataDir,
404
+ pluginId: state.record.pluginId,
405
+ leaseId: SETTINGS_LEASE_ID,
406
+ installPath: state.record.installPath,
407
+ });
408
+ hostRpc = new PluginHostRpc({
409
+ pluginId: state.record.pluginId,
410
+ principalId: state.record.canonicalId,
411
+ daemonInstanceId: this.daemonInstanceId,
412
+ productVersion: this.productVersion,
413
+ cliVersion: this.cliVersion,
414
+ capabilities: state.record.manifest.capabilities,
415
+ services: this.services,
416
+ ...(state.record.pluginId === "workspace"
417
+ && isBuiltInPluginMarketplace(state.record.marketplaceId)
418
+ ? { managedWorkspaceRoot: dataDir }
419
+ : {}),
420
+ emit: async (event) => {
421
+ if (Buffer.byteLength(JSON.stringify(event), "utf8") > MAX_PLUGIN_HOST_EVENT_BYTES) {
422
+ throw new Error("plugin host event exceeds transport budget");
423
+ }
424
+ await runner?.client.emitHostEvent(event.event, event.payload);
425
+ },
426
+ });
535
427
  runner = await this.spawnRunner({
536
- pluginId,
428
+ pluginId: state.record.pluginId,
429
+ pluginVersion: state.record.version,
430
+ installationId: state.record.canonicalId,
537
431
  packageRoot: state.record.installPath,
538
- runtimeEntry: path.resolve(state.record.installPath, state.record.manifest.runtimeEntry),
539
- dataDir: path.join(rynxHome(), "plugin-data", pluginId),
540
- config: {},
541
- grantedCapabilities: [...state.record.grants],
542
- handleHostCall: (method, params) => host.call(method, params),
543
- onStderr: stderr.write,
432
+ ...("entry" in background
433
+ ? {
434
+ entry: background.entry,
435
+ }
436
+ : {
437
+ command: background.command,
438
+ args: background.args,
439
+ }),
440
+ role: "settings",
441
+ dataDir,
442
+ cacheDir,
443
+ capabilities: state.record.manifest.capabilities,
444
+ handleHostCall: (method, params, signal) => hostRpc.call(method, params, signal),
445
+ onStderr: (line) => this.log({
446
+ level: "info",
447
+ event: "plugin-stderr",
448
+ pluginId: state.record.canonicalId,
449
+ message: line,
450
+ }),
544
451
  });
545
- assertHandshake(pluginId, state.record.grants, runner.handshake);
452
+ if (!runner.handshake.features.settings) {
453
+ throw new Error(`plugin "${state.record.canonicalId}" does not advertise a settings background`);
454
+ }
455
+ state.settingsRunner = runner;
456
+ state.settingsHostRpc = hostRpc;
457
+ this.log({
458
+ level: "info",
459
+ event: "plugin-settings-started",
460
+ pluginId: state.record.canonicalId,
461
+ });
462
+ void runner.completion.then((exit) => {
463
+ void this.runSerialized(state.record.canonicalId, () => this.handleSettingsExit(state, runner, hostRpc, exit));
464
+ }).catch((error) => {
465
+ void this.runSerialized(state.record.canonicalId, () => this.handleSettingsExit(state, runner, hostRpc, {
466
+ code: null,
467
+ signal: null,
468
+ error,
469
+ }));
470
+ });
471
+ return runner;
546
472
  }
547
473
  catch (error) {
548
- eventQueue.close(error);
549
- stderr.flush();
550
- await runner?.close().catch(() => undefined);
551
- await host.dispose();
474
+ const cleanupErrors = [];
475
+ if (runner) {
476
+ try {
477
+ await runner.close();
478
+ }
479
+ catch (cleanupError) {
480
+ state.settingsRunner = runner;
481
+ cleanupErrors.push(cleanupError);
482
+ }
483
+ }
484
+ try {
485
+ await hostRpc?.dispose();
486
+ }
487
+ catch (cleanupError) {
488
+ state.settingsHostRpc = hostRpc;
489
+ cleanupErrors.push(cleanupError);
490
+ }
491
+ if (cleanupErrors.length > 0) {
492
+ const failure = new AggregateError([error, ...cleanupErrors], "plugin settings startup failed and cleanup was unproven");
493
+ state.settingsCleanupError = failure;
494
+ throw failure;
495
+ }
496
+ if (isUnprovenProcessCleanup(error)) {
497
+ state.settingsCleanupError = error;
498
+ throw error;
499
+ }
500
+ removePluginRuntimeLease(dataDir, SETTINGS_LEASE_ID);
552
501
  throw error;
553
502
  }
554
- if (this.disposed) {
555
- eventQueue.close(new Error("plugin supervisor is disposed"));
556
- stderr.flush();
557
- await runner.close().catch(() => undefined);
558
- await host.dispose();
559
- throw new Error("plugin supervisor is disposed");
503
+ }
504
+ async stopSettingsState(state) {
505
+ const runner = state.settingsRunner;
506
+ const hostRpc = state.settingsHostRpc;
507
+ if (state.settingsCleanupError && !runner && !hostRpc) {
508
+ throw state.settingsCleanupError;
560
509
  }
561
- eventQueue.bind(runner.client);
562
- state.runner = runner;
563
- state.host = host;
564
- state.eventQueue = eventQueue;
565
- state.lastRunnerError = undefined;
566
- state.generation += 1;
567
- const generation = state.generation;
568
- clearTimer(state.stableTimer);
569
- state.stableTimer = setTimeout(() => {
570
- if (state.runner === runner)
571
- state.failureCount = 0;
572
- }, this.stableResetMs);
573
- state.stableTimer.unref?.();
574
- void runner.completion.then((outcome) => {
575
- eventQueue.close(new Error("plugin runner exited"));
576
- stderr.flush();
577
- this.trackRunnerExit(state, runner, host, generation, outcome);
578
- }, (error) => {
579
- eventQueue.close(error);
580
- stderr.flush();
581
- this.trackRunnerExit(state, runner, host, generation, undefined, error);
582
- }).catch((error) => {
583
- this.writeLog({
584
- level: "error",
585
- event: "plugin.runner.exit_handler_failed",
586
- pluginId,
587
- message: messageOf(error),
588
- });
589
- });
590
- return runner;
510
+ const errors = [];
511
+ if (runner) {
512
+ try {
513
+ await runner.close();
514
+ if (state.settingsRunner === runner)
515
+ state.settingsRunner = undefined;
516
+ }
517
+ catch (error) {
518
+ errors.push(error);
519
+ }
520
+ }
521
+ if (hostRpc) {
522
+ try {
523
+ await hostRpc.dispose();
524
+ if (state.settingsHostRpc === hostRpc)
525
+ state.settingsHostRpc = undefined;
526
+ }
527
+ catch (error) {
528
+ errors.push(error);
529
+ }
530
+ }
531
+ if (errors.length > 0) {
532
+ const failure = cleanupFailure(errors, "plugin settings cleanup was unproven");
533
+ state.settingsCleanupError = failure;
534
+ throw failure;
535
+ }
536
+ state.settingsCleanupError = undefined;
537
+ removePluginRuntimeLease(pluginDataDir(state.record.marketplaceId, state.record.pluginId), SETTINGS_LEASE_ID);
591
538
  }
592
- trackRunnerExit(state, runner, host, generation, outcome, error) {
593
- const preceding = state.exitTransition;
594
- const transition = (preceding
595
- ? preceding.catch(() => undefined)
596
- : Promise.resolve()).then(() => this.runnerExited(state, runner, host, generation, outcome, error));
597
- state.exitTransition = transition;
598
- void transition.then(() => {
599
- if (state.exitTransition === transition)
600
- state.exitTransition = undefined;
601
- }, (transitionError) => {
602
- if (state.exitTransition === transition)
603
- state.exitTransition = undefined;
604
- this.writeLog({
539
+ async handleSettingsExit(state, runner, hostRpc, exit) {
540
+ if (state.settingsRunner !== runner)
541
+ return;
542
+ try {
543
+ await runner.terminateTree();
544
+ }
545
+ catch (error) {
546
+ state.settingsCleanupError = error;
547
+ this.log({
605
548
  level: "error",
606
- event: "plugin.runner.exit_handler_failed",
607
- pluginId: state.record.manifest.id,
608
- message: messageOf(transitionError),
549
+ event: "plugin-settings-exited",
550
+ pluginId: state.record.canonicalId,
551
+ message: error instanceof Error ? error.message : String(error),
609
552
  });
610
- }).catch(() => undefined);
611
- }
612
- async runnerExited(state, runner, host, generation, outcome, error) {
613
- if (state.runner !== runner || state.generation !== generation)
614
553
  return;
615
- state.runner = undefined;
616
- if (state.host === host)
617
- state.host = undefined;
618
- state.eventQueue?.close(error ?? new Error("plugin runner exited"));
619
- state.eventQueue = undefined;
620
- state.runtimeStatusRefresh = undefined;
621
- clearTimer(state.stableTimer);
622
- state.stableTimer = undefined;
623
- await host.dispose();
624
- // Reload, explicit start, and dispose all join this transition. Keep the
625
- // generation guard as a final defence against any future call path that
626
- // can bind a successor without waiting for the old host cleanup.
627
- if (this.disposed || state.runner || state.generation !== generation)
628
- return;
629
- const message = error
630
- ? messageOf(error)
631
- : `plugin runner exited (code=${String(outcome?.code)}, signal=${String(outcome?.signal)})`;
632
- this.markRunnerUnavailable(state, message);
633
- this.writeLog({
634
- level: outcome?.code === 0 && !error ? "warn" : "error",
635
- event: "plugin.runner.exited",
636
- pluginId: state.record.manifest.id,
637
- message,
638
- code: outcome?.code,
639
- signal: outcome?.signal,
640
- });
641
- state.failureCount += 1;
642
- this.scheduleRestart(state);
643
- }
644
- async joinExitTransition(state) {
645
- while (state.exitTransition) {
646
- const transition = state.exitTransition;
647
- await transition.catch(() => undefined);
648
- if (state.exitTransition === transition)
649
- state.exitTransition = undefined;
650
554
  }
651
- }
652
- scheduleRestart(state) {
653
- if (this.disposed || state.restartTimer)
654
- return;
655
- const exponent = Math.min(Math.max(state.failureCount - 1, 0), 30);
656
- const delayMs = Math.min(this.restartMaxMs, this.restartBaseMs * 2 ** exponent);
657
- this.writeLog({
658
- level: "warn",
659
- event: "plugin.runner.restart_scheduled",
660
- pluginId: state.record.manifest.id,
661
- delayMs,
662
- });
663
- state.restartTimer = setTimeout(() => {
664
- state.restartTimer = undefined;
665
- void this.restart(state);
666
- }, delayMs);
667
- state.restartTimer.unref?.();
668
- }
669
- async restart(state) {
670
- if (this.disposed)
671
- return;
672
- let runner;
555
+ state.settingsRunner = undefined;
673
556
  try {
674
- runner = await this.ensureRunner(state);
557
+ await hostRpc.dispose();
558
+ if (state.settingsHostRpc === hostRpc)
559
+ state.settingsHostRpc = undefined;
675
560
  }
676
561
  catch (error) {
677
- this.writeLog({
562
+ state.settingsCleanupError = error;
563
+ this.log({
678
564
  level: "error",
679
- event: "plugin.runner.restart_failed",
680
- pluginId: state.record.manifest.id,
681
- message: messageOf(error),
565
+ event: "plugin-settings-exited",
566
+ pluginId: state.record.canonicalId,
567
+ message: error instanceof Error ? error.message : String(error),
682
568
  });
683
569
  return;
684
570
  }
685
- await this.refreshRuntimeStatus(state);
686
- await this.restoreDesiredContributions(state, runner);
571
+ state.settingsCleanupError = undefined;
572
+ removePluginRuntimeLease(pluginDataDir(state.record.marketplaceId, state.record.pluginId), SETTINGS_LEASE_ID);
573
+ if (!this.disposed) {
574
+ this.log({
575
+ level: "warn",
576
+ event: "plugin-settings-exited",
577
+ pluginId: state.record.canonicalId,
578
+ message: exit.error instanceof Error
579
+ ? exit.error.message
580
+ : `settings background exited with code ${exit.code ?? "null"}${exit.signal ? ` (${exit.signal})` : ""}`,
581
+ });
582
+ }
687
583
  }
688
- async restoreDesiredContributions(state, runner) {
689
- for (const desired of [...state.desired.values()]) {
584
+ async stopState(state) {
585
+ state.stopping = true;
586
+ if (state.restartTimer)
587
+ clearTimeout(state.restartTimer);
588
+ state.restartTimer = undefined;
589
+ if (state.healthTimer)
590
+ clearTimeout(state.healthTimer);
591
+ state.healthTimer = undefined;
592
+ const runner = state.runner;
593
+ const hostRpc = state.hostRpc;
594
+ if (state.runtimeCleanupError && !runner && !hostRpc) {
595
+ throw state.runtimeCleanupError;
596
+ }
597
+ const errors = [];
598
+ if (runner) {
690
599
  try {
691
- await this.startDesiredOnRunner(state, desired, runner);
692
- await this.refreshContributionStatus(state, desired);
600
+ await runner.close();
601
+ if (state.runner === runner)
602
+ state.runner = undefined;
693
603
  }
694
604
  catch (error) {
695
- this.writeLog({
696
- level: "error",
697
- event: "plugin.contribution.restore_failed",
698
- pluginId: state.record.manifest.id,
699
- message: messageOf(error),
700
- });
605
+ errors.push(error);
701
606
  }
702
607
  }
703
- }
704
- async closeRunner(state) {
705
- const runner = state.runner;
706
- const host = state.host;
707
- const eventQueue = state.eventQueue;
708
- state.runner = undefined;
709
- state.host = undefined;
710
- state.eventQueue = undefined;
711
- state.runtimeStatusRefresh = undefined;
712
- eventQueue?.close(new Error("plugin runner is closing"));
713
- clearTimer(state.stableTimer);
714
- state.stableTimer = undefined;
715
- if (runner) {
608
+ if (hostRpc) {
716
609
  try {
717
- await runner.close();
610
+ await hostRpc.dispose();
611
+ if (state.hostRpc === hostRpc)
612
+ state.hostRpc = undefined;
718
613
  }
719
614
  catch (error) {
720
- this.writeLog({
721
- level: "warn",
722
- event: "plugin.runner.close_failed",
723
- pluginId: state.record.manifest.id,
724
- message: messageOf(error),
725
- });
615
+ errors.push(error);
726
616
  }
727
617
  }
728
- await host?.dispose();
729
- }
730
- async disposeState(state) {
731
- await this.joinExitTransition(state);
732
- const spawning = state.spawnPromise;
733
- await this.closeRunner(state);
734
- await spawning?.catch(() => undefined);
735
- // A spawn can bind between the first close and the disposed check inside
736
- // spawnAndBind. A final idempotent close makes dispose a true join point.
737
- await this.closeRunner(state);
738
- await this.joinExitTransition(state);
739
- }
740
- cancelRestart(state) {
741
- clearTimer(state.restartTimer);
742
- state.restartTimer = undefined;
743
- }
744
- markRunnerUnavailable(state, message) {
745
- state.lastRunnerError = message;
746
- state.runtimeStatus = {
747
- state: "failed",
748
- connected: false,
749
- lastError: message,
750
- };
751
- for (const desired of state.desired.values()) {
752
- desired.startedGeneration = undefined;
753
- desired.status = {
754
- state: "failed",
755
- connected: false,
756
- lastError: message,
757
- };
758
- state.channelStatus.set(desired.key, {
759
- ...(state.channelStatus.get(desired.key) ?? {}),
760
- connected: false,
761
- lastError: message,
762
- });
618
+ if (errors.length > 0) {
619
+ const failure = cleanupFailure(errors, "plugin runtime cleanup was unproven");
620
+ state.runtimeCleanupError = failure;
621
+ this.failState(state, failure);
622
+ throw failure;
763
623
  }
624
+ state.runtimeCleanupError = undefined;
625
+ removePluginRuntimeLease(pluginDataDir(state.record.marketplaceId, state.record.pluginId), RUNTIME_LEASE_ID);
626
+ state.health = undefined;
627
+ state.error = undefined;
628
+ state.state = state.record.manifest.runtime ? "stopped" : "absent";
629
+ setPluginRuntimeState(state.record.canonicalId, state.state);
764
630
  }
765
- markContributionFailed(state, desired, error) {
766
- desired.startedGeneration = undefined;
767
- desired.failureCount += 1;
768
- desired.status = {
769
- state: "failed",
770
- connected: false,
771
- lastError: messageOf(error),
772
- };
773
- state.channelStatus.set(desired.key, {
774
- ...(state.channelStatus.get(desired.key) ?? {}),
775
- connected: false,
776
- lastError: messageOf(error),
777
- });
778
- }
779
- stderrSink(pluginId) {
780
- let buffered = "";
781
- const continuation = " …[continued]";
782
- const contentLimit = MAX_STDERR_LINE_BYTES - Buffer.byteLength(continuation, "utf8");
783
- const emitLine = (line) => {
784
- const message = line.trimEnd();
785
- if (!message)
786
- return;
787
- this.writeLog({
788
- level: "warn",
789
- event: "plugin.runner.stderr",
790
- pluginId,
791
- message,
792
- });
793
- };
794
- const appendSegment = (segment) => {
795
- let remaining = segment;
796
- while (remaining.length > 0) {
797
- const bufferedBytes = Buffer.byteLength(buffered, "utf8");
798
- const budget = Math.max(1, contentLimit - bufferedBytes);
799
- const [prefix, rest] = splitUtf8AtMost(remaining, budget);
800
- if (!prefix && rest) {
801
- if (buffered) {
802
- emitLine(`${buffered}${continuation}`);
803
- buffered = "";
804
- continue;
805
- }
806
- // `contentLimit` is much larger than a single UTF-8 code point, so
807
- // this branch is defensive only.
808
- const first = String.fromCodePoint(remaining.codePointAt(0));
809
- buffered = first;
810
- remaining = remaining.slice(first.length);
811
- continue;
812
- }
813
- buffered += prefix;
814
- remaining = rest;
815
- if (remaining.length > 0 || Buffer.byteLength(buffered, "utf8") >= contentLimit) {
816
- emitLine(`${buffered}${continuation}`);
817
- buffered = "";
818
- }
819
- }
820
- };
821
- return {
822
- write: (chunk) => {
823
- let offset = 0;
824
- while (offset < chunk.length) {
825
- const newline = chunk.indexOf("\n", offset);
826
- if (newline < 0) {
827
- appendSegment(chunk.slice(offset));
828
- return;
829
- }
830
- appendSegment(chunk.slice(offset, newline));
831
- emitLine(buffered);
832
- buffered = "";
833
- offset = newline + 1;
834
- }
835
- },
836
- flush: () => {
837
- if (buffered)
838
- emitLine(buffered);
839
- buffered = "";
840
- },
841
- };
842
- }
843
- writeLog(entry) {
844
- if (this.logger) {
845
- this.logger(entry);
631
+ async handleExit(state, runner, generation, exit) {
632
+ if (state.runner !== runner || state.generation !== generation)
846
633
  return;
847
- }
848
- console.error(JSON.stringify({ timestamp: new Date().toISOString(), ...entry }));
849
- }
850
- assertOpen() {
851
- if (this.disposed)
852
- throw new Error("plugin supervisor is disposed");
853
- }
854
- assertReady() {
855
- this.assertOpen();
856
- this.requireHostServices();
857
- }
858
- requireHostServices() {
859
- if (!this.services)
860
- throw new Error("plugin host services are not bound");
861
- return this.services;
862
- }
863
- }
864
- /** A single-writer queue: bounded buffering plus an awaitable delivery ack. */
865
- class BoundedHostEventQueue {
866
- items = [];
867
- client;
868
- queuedBytes = 0;
869
- draining = false;
870
- closed = false;
871
- closeError;
872
- bind(client) {
873
- if (this.client)
874
- throw new Error("plugin host event queue is already bound");
875
- if (this.closed)
876
- throw this.closeError ?? new Error("plugin host event queue is closed");
877
- this.client = client;
878
- void this.drain();
879
- }
880
- enqueue(event) {
881
- if (this.closed) {
882
- return Promise.reject(this.closeError ?? new Error("plugin host event queue is closed"));
883
- }
884
- let bytes;
634
+ if (state.healthTimer)
635
+ clearTimeout(state.healthTimer);
636
+ state.healthTimer = undefined;
885
637
  try {
886
- bytes = Buffer.byteLength(JSON.stringify(event), "utf8");
638
+ await runner.terminateTree();
887
639
  }
888
- catch {
889
- return Promise.reject(new Error("plugin host event must be JSON serializable"));
640
+ catch (error) {
641
+ state.runtimeCleanupError = error;
642
+ this.failState(state, error);
643
+ return;
890
644
  }
891
- if (bytes > MAX_PLUGIN_HOST_EVENT_BYTES) {
892
- return Promise.reject(new Error("plugin host event exceeds the bounded event budget"));
645
+ state.runner = undefined;
646
+ try {
647
+ await state.hostRpc?.dispose();
648
+ state.hostRpc = undefined;
893
649
  }
894
- if (this.items.length + (this.draining ? 1 : 0) >= MAX_HOST_EVENT_QUEUE_ITEMS ||
895
- this.queuedBytes + bytes > MAX_HOST_EVENT_QUEUE_BYTES) {
896
- return Promise.reject(new Error("plugin host event queue is full"));
650
+ catch (error) {
651
+ state.runtimeCleanupError = error;
652
+ if (!state.stopping && !this.disposed)
653
+ this.failState(state, error);
654
+ return;
897
655
  }
898
- const promise = new Promise((resolve, reject) => {
899
- this.items.push({ event, bytes, resolve, reject });
900
- this.queuedBytes += bytes;
656
+ state.runtimeCleanupError = undefined;
657
+ removePluginRuntimeLease(pluginDataDir(state.record.marketplaceId, state.record.pluginId), RUNTIME_LEASE_ID);
658
+ if (state.stopping || this.disposed)
659
+ return;
660
+ const stable = state.startedAt && Date.now() - state.startedAt >= STABLE_RESET_MS;
661
+ if (stable)
662
+ state.restartFailures = 0;
663
+ this.failState(state, exit.error ?? new Error(`runtime exited with code ${exit.code ?? "null"}${exit.signal ? ` (${exit.signal})` : ""}`));
664
+ this.scheduleRestart(state);
665
+ }
666
+ failState(state, error) {
667
+ state.restartFailures += 1;
668
+ state.health = undefined;
669
+ state.state = "failed";
670
+ state.error = error instanceof Error ? error.message : String(error);
671
+ setPluginRuntimeState(state.record.canonicalId, "failed", state.error);
672
+ this.log({
673
+ level: "error",
674
+ event: "plugin-runtime-failed",
675
+ pluginId: state.record.canonicalId,
676
+ message: state.error,
901
677
  });
902
- void this.drain();
903
- return promise;
904
678
  }
905
- close(error) {
906
- if (this.closed)
679
+ scheduleRestart(state) {
680
+ if (this.disposed || state.stopping || !state.record.enabled || state.restartTimer)
907
681
  return;
908
- this.closed = true;
909
- this.closeError = error instanceof Error
910
- ? error
911
- : new Error(error === undefined ? "plugin host event queue is closed" : String(error));
912
- for (const item of this.items.splice(0)) {
913
- this.queuedBytes -= item.bytes;
914
- item.reject(this.closeError);
915
- }
682
+ const delayMs = Math.min(this.restartMaxMs, this.restartBaseMs * 2 ** Math.max(0, state.restartFailures - 1));
683
+ state.restartTimer = setTimeout(() => {
684
+ state.restartTimer = undefined;
685
+ void this.runSerialized(state.record.canonicalId, () => this.startState(state));
686
+ }, delayMs);
687
+ state.restartTimer.unref?.();
688
+ this.log({
689
+ level: "warn",
690
+ event: "plugin-runtime-restart-scheduled",
691
+ pluginId: state.record.canonicalId,
692
+ delayMs,
693
+ });
916
694
  }
917
- async drain() {
918
- if (this.draining || this.closed || !this.client)
695
+ scheduleHealthPoll(state, runner) {
696
+ if (this.disposed || state.stopping || state.runner !== runner || state.healthTimer)
919
697
  return;
920
- this.draining = true;
921
- try {
922
- while (!this.closed && this.client && this.items.length > 0) {
923
- const item = this.items.shift();
698
+ state.healthTimer = setTimeout(() => {
699
+ state.healthTimer = undefined;
700
+ void this.runSerialized(state.record.canonicalId, async () => {
701
+ if (state.runner !== runner || state.stopping || this.disposed)
702
+ return;
924
703
  try {
925
- await this.client.emitHostEvent(item.event.event, item.event.payload);
926
- item.resolve();
704
+ await this.refreshHealth(state);
705
+ this.scheduleHealthPoll(state, runner);
927
706
  }
928
707
  catch (error) {
929
- const failure = error instanceof Error ? error : new Error(String(error));
930
- item.reject(failure);
931
- this.queuedBytes -= item.bytes;
932
- this.close(failure);
933
- return;
708
+ await this.failRunningState(state, runner, error);
934
709
  }
935
- this.queuedBytes -= item.bytes;
936
- }
710
+ });
711
+ }, this.healthPollMs);
712
+ state.healthTimer.unref?.();
713
+ }
714
+ async refreshHealth(state) {
715
+ const runner = state.runner;
716
+ if (!runner) {
717
+ throw new Error(`plugin runtime "${state.record.canonicalId}" is not running`);
937
718
  }
938
- finally {
939
- this.draining = false;
940
- if (!this.closed && this.client && this.items.length > 0)
941
- void this.drain();
719
+ const health = await runner.client.health();
720
+ if (state.runner !== runner)
721
+ return;
722
+ const nextState = healthState(health);
723
+ const changed = state.state !== nextState ||
724
+ state.error !== undefined ||
725
+ JSON.stringify(state.health) !== JSON.stringify(health);
726
+ state.health = health;
727
+ state.state = nextState;
728
+ state.error = undefined;
729
+ if (changed)
730
+ setPluginRuntimeState(state.record.canonicalId, state.state);
731
+ }
732
+ async failRunningState(state, runner, error) {
733
+ if (state.runner !== runner)
734
+ return;
735
+ if (state.healthTimer)
736
+ clearTimeout(state.healthTimer);
737
+ state.healthTimer = undefined;
738
+ try {
739
+ await runner.close();
942
740
  }
943
- }
944
- }
945
- /** Convenience export for composition roots that only need the static catalog. */
946
- export function createChannelTypeDescriptors(supervisor) {
947
- return supervisor.createChannelTypeDescriptors();
948
- }
949
- function createPluginState(record) {
950
- return {
951
- record,
952
- desired: new Map(),
953
- channelStatus: new Map(),
954
- generation: 0,
955
- failureCount: 0,
956
- runtimeStatus: { state: "stopped", connected: false },
957
- };
958
- }
959
- function validateRecord(record) {
960
- if (record.name !== record.manifest.id) {
961
- throw new Error(`runnable plugin id mismatch: ${record.name} != ${record.manifest.id}`);
962
- }
963
- if (!record.enabled) {
964
- throw new Error(`plugin ${record.manifest.id} is disabled`);
965
- }
966
- const requested = new Set(record.manifest.requestedCapabilities);
967
- for (const grant of record.grants) {
968
- if (!requested.has(grant)) {
969
- throw new Error(`plugin ${record.manifest.id} was granted an unrequested capability: ${grant}`);
741
+ catch (cleanupError) {
742
+ state.runtimeCleanupError = cleanupError;
743
+ this.failState(state, cleanupError);
744
+ return;
970
745
  }
746
+ state.runner = undefined;
747
+ try {
748
+ await state.hostRpc?.dispose();
749
+ state.hostRpc = undefined;
750
+ }
751
+ catch (cleanupError) {
752
+ state.runtimeCleanupError = cleanupError;
753
+ if (!state.stopping && !this.disposed)
754
+ this.failState(state, cleanupError);
755
+ return;
756
+ }
757
+ state.runtimeCleanupError = undefined;
758
+ removePluginRuntimeLease(pluginDataDir(state.record.marketplaceId, state.record.pluginId), RUNTIME_LEASE_ID);
759
+ if (state.stopping || this.disposed)
760
+ return;
761
+ this.failState(state, error);
762
+ this.scheduleRestart(state);
971
763
  }
972
- }
973
- function sameRuntimeRecord(left, right) {
974
- return left.installPath === right.installPath &&
975
- left.integrity === right.integrity &&
976
- JSON.stringify(left.manifest) === JSON.stringify(right.manifest) &&
977
- JSON.stringify(left.grants) === JSON.stringify(right.grants);
978
- }
979
- function assertHandshake(pluginId, grants, handshake) {
980
- if (handshake.pluginId !== pluginId) {
981
- throw new Error(`plugin runner identity mismatch: ${handshake.pluginId} != ${pluginId}`);
982
- }
983
- if (handshake.apiVersion !== PLUGIN_RUNNER_API_VERSION) {
984
- throw new Error(`plugin runner API mismatch: ${handshake.apiVersion} != ${PLUGIN_RUNNER_API_VERSION}`);
985
- }
986
- if (handshake.grantedCapabilities.length !== grants.length ||
987
- handshake.grantedCapabilities.some((capability, index) => capability !== grants[index])) {
988
- throw new Error(`plugin runner capability handshake mismatch: ${pluginId}`);
989
- }
990
- }
991
- function statusToChannelStatus(status) {
992
- return {
993
- connected: status.connected ?? status.state === "running",
994
- lastError: status.lastError ?? null,
995
- lastEventAt: status.lastEventAt ?? null,
996
- };
997
- }
998
- function boundedContributionStatus(status) {
999
- return {
1000
- ...status,
1001
- ...(typeof status.lastError === "string"
1002
- ? { lastError: boundedText(status.lastError, MAX_STATUS_ERROR_BYTES) }
1003
- : {}),
1004
- ...(typeof status.lastEventAt === "string"
1005
- ? { lastEventAt: boundedText(status.lastEventAt, 256) }
1006
- : {}),
1007
- };
1008
- }
1009
- function boundedRuntimeStatus(status) {
1010
- return {
1011
- ...status,
1012
- ...(typeof status.lastError === "string"
1013
- ? { lastError: boundedText(status.lastError, MAX_STATUS_ERROR_BYTES) }
1014
- : {}),
1015
- ...(typeof status.lastEventAt === "string"
1016
- ? { lastEventAt: boundedText(status.lastEventAt, 256) }
1017
- : {}),
1018
- };
1019
- }
1020
- function channelKey(contributionId, instanceId) {
1021
- return `channel:${contributionId}:${instanceId}`;
1022
- }
1023
- function positiveDelay(value, fallback) {
1024
- return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback;
1025
- }
1026
- function boundedReadyTimeout(value) {
1027
- if (value === undefined)
1028
- return DEFAULT_READY_TIMEOUT_MS;
1029
- if (!Number.isFinite(value) || value < 0) {
1030
- throw new Error("plugin runtime ready timeout must be a non-negative finite number");
1031
- }
1032
- return Math.min(value, MAX_READY_TIMEOUT_MS);
1033
- }
1034
- function createRuntimeReadyDeadline(timeoutMs) {
1035
- return { timeoutMs, expiresAt: Date.now() + timeoutMs };
1036
- }
1037
- function settleBeforeDeadline(promise, expiresAt, timeoutError) {
1038
- const remaining = expiresAt - Date.now();
1039
- if (remaining <= 0)
1040
- return Promise.reject(timeoutError());
1041
- return new Promise((resolve, reject) => {
1042
- const timer = setTimeout(() => reject(timeoutError()), remaining);
1043
- promise.then((value) => {
1044
- clearTimeout(timer);
1045
- resolve(value);
1046
- }, (error) => {
1047
- clearTimeout(timer);
1048
- reject(error);
1049
- });
1050
- });
1051
- }
1052
- function delay(milliseconds) {
1053
- return new Promise((resolve) => setTimeout(resolve, milliseconds));
1054
- }
1055
- function clearTimer(timer) {
1056
- if (timer)
1057
- clearTimeout(timer);
1058
- }
1059
- function runnerSnapshotState(state, disposed) {
1060
- if (state.runner)
1061
- return "running";
1062
- if (state.spawnPromise)
1063
- return "starting";
1064
- if (state.restartTimer)
1065
- return "backoff";
1066
- if (state.lastRunnerError && !disposed)
1067
- return "failed";
1068
- return "stopped";
1069
- }
1070
- function splitUtf8AtMost(value, maxBytes) {
1071
- if (Buffer.byteLength(value, "utf8") <= maxBytes)
1072
- return [value, ""];
1073
- let low = 0;
1074
- let high = value.length;
1075
- while (low < high) {
1076
- const middle = Math.ceil((low + high) / 2);
1077
- if (Buffer.byteLength(value.slice(0, middle), "utf8") <= maxBytes)
1078
- low = middle;
1079
- else
1080
- high = middle - 1;
764
+ runSerialized(identity, operation) {
765
+ const previous = this.queues.get(identity) ?? Promise.resolve();
766
+ const current = previous.catch(() => undefined).then(operation);
767
+ this.queues.set(identity, current);
768
+ void current.finally(() => {
769
+ if (this.queues.get(identity) === current)
770
+ this.queues.delete(identity);
771
+ }).catch(() => undefined);
772
+ return current;
1081
773
  }
1082
- if (low > 0 && low < value.length && isHighSurrogate(value.charCodeAt(low - 1)))
1083
- low -= 1;
1084
- return [value.slice(0, low), value.slice(low)];
1085
- }
1086
- function isHighSurrogate(value) {
1087
- return value >= 0xd800 && value <= 0xdbff;
1088
774
  }
1089
- function messageOf(error) {
1090
- return boundedText(error instanceof Error ? error.message : String(error), MAX_STATUS_ERROR_BYTES);
775
+ function cleanupFailure(errors, message) {
776
+ return errors.length === 1 ? errors[0] : new AggregateError(errors, message);
1091
777
  }
1092
- function boundedText(value, maxBytes) {
1093
- if (Buffer.byteLength(value, "utf8") <= maxBytes)
1094
- return value;
1095
- const marker = "…[truncated]";
1096
- const budget = maxBytes - Buffer.byteLength(marker, "utf8");
1097
- const [prefix] = splitUtf8AtMost(value, Math.max(1, budget));
1098
- return `${prefix}${marker}`;
778
+ function blockingCleanupError(state) {
779
+ return state.runtimeCleanupError ?? state.settingsCleanupError;
1099
780
  }
1100
- function sameStartRequest(left, right) {
1101
- return JSON.stringify(left) === JSON.stringify(right);
781
+ function isUnprovenProcessCleanup(error) {
782
+ return Boolean(error
783
+ && typeof error === "object"
784
+ && "code" in error
785
+ && error.code === "PROCESS_TREE_STUCK");
1102
786
  }
1103
- function clonePluginConfig(value) {
1104
- if (!value)
1105
- return {};
1106
- return cloneJsonValue(value, "options", new WeakSet());
787
+ function healthState(health) {
788
+ return health.state;
1107
789
  }
1108
- function normalizeChatChannelConfig(contribution, value) {
1109
- const config = clonePluginConfig(value);
1110
- const schema = contribution.configSchema ?? [];
1111
- return schema.length > 0 ? normalizePluginConfig(schema, config) : config;
1112
- }
1113
- function cloneJsonValue(value, pathLabel, ancestors) {
1114
- if (value === null || typeof value === "string" || typeof value === "boolean")
1115
- return value;
1116
- if (typeof value === "number") {
1117
- if (!Number.isFinite(value))
1118
- throw new Error(`${pathLabel} must contain finite numbers`);
1119
- return value;
1120
- }
1121
- if (typeof value !== "object") {
1122
- throw new Error(`${pathLabel} must contain only JSON values`);
1123
- }
1124
- if (ancestors.has(value))
1125
- throw new Error(`${pathLabel} must not be cyclic`);
1126
- ancestors.add(value);
1127
- try {
1128
- if (Array.isArray(value)) {
1129
- return value.map((item, index) => cloneJsonValue(item, `${pathLabel}[${index}]`, ancestors));
1130
- }
1131
- if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
1132
- throw new Error(`${pathLabel} must contain only plain objects`);
1133
- }
1134
- const output = {};
1135
- for (const [key, item] of Object.entries(value)) {
1136
- output[key] = cloneJsonValue(item, `${pathLabel}.${key}`, ancestors);
1137
- }
1138
- return output;
1139
- }
1140
- finally {
1141
- ancestors.delete(value);
790
+ async function verifyInstalledPackage(record) {
791
+ const integrity = await validatePluginPackageSnapshot(record.installPath);
792
+ if (integrity !== record.integrity) {
793
+ throw new Error(`plugin package integrity changed for "${record.canonicalId}"`);
1142
794
  }
1143
795
  }