@rynx-ai/daemon 0.1.10 → 0.1.11-beta.10

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 (156) hide show
  1. package/bundled-plugins/.rynx-plugin/marketplace.json +10 -0
  2. package/bundled-plugins/plugins/lark/.rynx-plugin/plugin.json +25 -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 +56 -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 +506 -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 +1975 -0
  43. package/bundled-plugins/plugins/lark/dist/runtime.d.ts +13 -0
  44. package/bundled-plugins/plugins/lark/dist/runtime.js +131328 -0
  45. package/bundled-plugins/plugins/lark/dist/settings.d.ts +7 -0
  46. package/bundled-plugins/plugins/lark/dist/settings.js +126971 -0
  47. package/bundled-plugins/plugins/lark/package.json +57 -0
  48. package/bundled-plugins/plugins/lark/ui/assets/index-CGUVAMsv.css +1 -0
  49. package/bundled-plugins/plugins/lark/ui/assets/index-D8Amoe6a.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/agent-file.js +0 -1
  64. package/dist/browser-artifact-management.d.ts +4 -1
  65. package/dist/browser-artifact-management.js +18 -10
  66. package/dist/browser-artifacts.d.ts +1 -0
  67. package/dist/browser-artifacts.js +1 -0
  68. package/dist/bundled-plugins.d.ts +15 -0
  69. package/dist/bundled-plugins.js +134 -0
  70. package/dist/chrome-for-testing-runtime.d.ts +27 -0
  71. package/dist/chrome-for-testing-runtime.js +193 -0
  72. package/dist/chrome-for-testing-store.d.ts +2 -0
  73. package/dist/chrome-for-testing-store.js +9 -0
  74. package/dist/control-deps.d.ts +6 -2
  75. package/dist/control-deps.js +88 -82
  76. package/dist/daemon-server.d.ts +7 -1
  77. package/dist/daemon-server.js +310 -87
  78. package/dist/db.js +181 -124
  79. package/dist/entry-path.d.ts +3 -0
  80. package/dist/entry-path.js +12 -0
  81. package/dist/index-daemon.js +3 -66
  82. package/dist/lifecycle.d.ts +12 -0
  83. package/dist/lifecycle.js +16 -0
  84. package/dist/maintenance-lease.d.ts +39 -0
  85. package/dist/maintenance-lease.js +250 -0
  86. package/dist/migrations/cleanup-legacy-sessions.d.ts +1 -1
  87. package/dist/migrations/cleanup-legacy-sessions.js +33 -15
  88. package/dist/official-plugins.d.ts +2 -0
  89. package/dist/official-plugins.js +2 -0
  90. package/dist/plugin-cli.d.ts +1 -3
  91. package/dist/plugin-cli.js +56 -45
  92. package/dist/plugin-host-leases.d.ts +4 -0
  93. package/dist/plugin-host-leases.js +7 -0
  94. package/dist/plugin-host-rpc.d.ts +73 -6
  95. package/dist/plugin-host-rpc.js +354 -81
  96. package/dist/plugin-installer.d.ts +24 -55
  97. package/dist/plugin-installer.js +258 -412
  98. package/dist/plugin-management-service.d.ts +30 -23
  99. package/dist/plugin-management-service.js +288 -105
  100. package/dist/plugin-marketplace.d.ts +35 -0
  101. package/dist/plugin-marketplace.js +299 -0
  102. package/dist/plugin-package.d.ts +22 -24
  103. package/dist/plugin-package.js +520 -571
  104. package/dist/plugin-skill-context.d.ts +4 -0
  105. package/dist/plugin-skill-context.js +35 -0
  106. package/dist/plugin-store.d.ts +36 -37
  107. package/dist/plugin-store.js +138 -92
  108. package/dist/plugin-supervisor.d.ts +50 -125
  109. package/dist/plugin-supervisor.js +678 -1030
  110. package/dist/pm2.d.ts +11 -2
  111. package/dist/pm2.js +130 -28
  112. package/dist/process.d.ts +12 -0
  113. package/dist/process.js +91 -0
  114. package/dist/runtime-project-store.d.ts +9 -0
  115. package/dist/runtime-project-store.js +83 -0
  116. package/dist/session-fallback-workspace.d.ts +22 -0
  117. package/dist/session-fallback-workspace.js +120 -0
  118. package/dist/session-fork-store.d.ts +41 -0
  119. package/dist/session-fork-store.js +288 -0
  120. package/dist/session-launch-operations.d.ts +23 -2
  121. package/dist/session-launch-operations.js +48 -7
  122. package/dist/session-meta-store.d.ts +12 -9
  123. package/dist/session-meta-store.js +50 -49
  124. package/dist/session-portal-grant-store.d.ts +29 -0
  125. package/dist/session-portal-grant-store.js +84 -0
  126. package/dist/setup-service.d.ts +21 -0
  127. package/dist/setup-service.js +39 -0
  128. package/dist/skills-catalog.d.ts +11 -2
  129. package/dist/skills-catalog.js +307 -7
  130. package/dist/system-dependencies.d.ts +26 -0
  131. package/dist/system-dependencies.js +149 -0
  132. package/package.json +36 -20
  133. package/dist/browser-cli-args.d.ts +0 -20
  134. package/dist/browser-cli-args.js +0 -100
  135. package/dist/channel-store.d.ts +0 -22
  136. package/dist/channel-store.js +0 -65
  137. package/dist/cli.d.ts +0 -2
  138. package/dist/cli.js +0 -732
  139. package/dist/control-client.d.ts +0 -122
  140. package/dist/control-client.js +0 -855
  141. package/dist/control-endpoint.d.ts +0 -14
  142. package/dist/control-endpoint.js +0 -124
  143. package/dist/desktop-browser-host-client.d.ts +0 -35
  144. package/dist/desktop-browser-host-client.js +0 -415
  145. package/dist/instance-store.d.ts +0 -38
  146. package/dist/instance-store.js +0 -85
  147. package/dist/plugin-install-restart.d.ts +0 -13
  148. package/dist/plugin-install-restart.js +0 -24
  149. package/dist/plugin-runtime-control.d.ts +0 -2
  150. package/dist/plugin-runtime-control.js +0 -37
  151. package/dist/registry.d.ts +0 -10
  152. package/dist/registry.js +0 -52
  153. package/dist/setup.d.ts +0 -20
  154. package/dist/setup.js +0 -374
  155. package/dist/update.d.ts +0 -25
  156. package/dist/update.js +0 -133
@@ -1,1143 +1,791 @@
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
+ services: this.services,
298
+ ...(state.record.pluginId === "workspace"
299
+ && isBuiltInPluginMarketplace(state.record.marketplaceId)
300
+ ? { managedWorkspaceRoot: dataDir }
301
+ : {}),
302
+ emit: async (event) => {
303
+ if (Buffer.byteLength(JSON.stringify(event), "utf8") > MAX_PLUGIN_HOST_EVENT_BYTES) {
304
+ throw new Error("plugin host event exceeds transport budget");
305
+ }
306
+ await runner?.client.emitHostEvent(event.event, event.payload);
307
+ },
308
+ });
309
+ state.hostRpc = hostRpc;
310
+ runner = await this.spawnRunner({
311
+ pluginId: state.record.pluginId,
312
+ pluginVersion: state.record.version,
313
+ installationId: state.record.canonicalId,
314
+ packageRoot: state.record.installPath,
315
+ ...("entry" in runtime
316
+ ? {
317
+ entry: runtime.entry,
318
+ }
319
+ : {
320
+ command: runtime.command,
321
+ args: runtime.args,
322
+ }),
323
+ role: "runtime",
324
+ dataDir,
325
+ cacheDir,
326
+ handleHostCall: (method, params, signal) => hostRpc.call(method, params, signal),
327
+ onStderr: (line) => this.log({
328
+ level: "info",
329
+ event: "plugin-stderr",
330
+ pluginId: state.record.canonicalId,
331
+ message: line,
332
+ }),
333
+ });
334
+ state.runner = runner;
335
+ state.health = runner.initialHealth;
336
+ state.state = healthState(runner.initialHealth);
337
+ state.startedAt = Date.now();
338
+ state.error = undefined;
339
+ setPluginRuntimeState(state.record.canonicalId, state.state);
340
+ this.log({
341
+ level: "info",
342
+ event: "plugin-runtime-started",
343
+ pluginId: state.record.canonicalId,
344
+ });
345
+ this.scheduleHealthPoll(state, runner);
346
+ const generation = state.generation;
347
+ void runner.completion.then((exit) => {
348
+ void this.runSerialized(state.record.canonicalId, () => this.handleExit(state, runner, generation, exit));
349
+ }).catch((error) => {
350
+ void this.runSerialized(state.record.canonicalId, () => this.handleExit(state, runner, generation, {
351
+ code: null,
352
+ signal: null,
353
+ error,
354
+ }));
355
+ });
381
356
  }
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) {
357
+ catch (error) {
395
358
  try {
396
- await runner.client.stopContribution(desired.target);
397
- }
398
- catch (error) {
399
- stopError = error;
359
+ await hostRpc?.dispose();
400
360
  }
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)
361
+ catch (cleanupError) {
362
+ const failure = new AggregateError([error, cleanupError], "plugin runtime startup failed and active-run cleanup was unproven");
363
+ state.runtimeCleanupError = failure;
364
+ this.failState(state, failure);
418
365
  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
366
  }
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);
367
+ state.hostRpc = undefined;
368
+ if (isUnprovenProcessCleanup(error)) {
369
+ state.runtimeCleanupError = error;
370
+ this.failState(state, error);
371
+ return;
488
372
  }
489
- await delay(Math.min(RUNTIME_STATUS_POLL_MS, remaining));
373
+ removePluginRuntimeLease(dataDir, RUNTIME_LEASE_ID);
374
+ this.failState(state, error);
375
+ this.scheduleRestart(state);
490
376
  }
491
377
  }
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));
378
+ async startSettingsState(state) {
379
+ if (this.disposed)
380
+ throw new Error("plugin supervisor is disposed");
381
+ const cleanupError = blockingCleanupError(state);
382
+ if (cleanupError)
383
+ throw cleanupError;
384
+ if (state.settingsRunner)
385
+ return state.settingsRunner;
386
+ const background = state.record.manifest.settings?.background;
387
+ if (!background) {
388
+ throw new Error(`plugin "${state.record.canonicalId}" has no settings background`);
501
389
  }
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);
390
+ if (!this.services)
391
+ throw new Error("plugin host services are not bound");
392
+ const dataDir = pluginDataDir(state.record.marketplaceId, state.record.pluginId);
393
+ const cacheDir = pluginRuntimeCacheDir(state.record.marketplaceId, state.record.pluginId, state.record.integrity);
533
394
  let runner;
395
+ let hostRpc;
534
396
  try {
397
+ await this.verifyPackage(state.record);
398
+ mkdirSync(dataDir, { recursive: true, mode: 0o700 });
399
+ mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
400
+ writePluginRuntimeLease({
401
+ dataDir,
402
+ pluginId: state.record.pluginId,
403
+ leaseId: SETTINGS_LEASE_ID,
404
+ installPath: state.record.installPath,
405
+ });
406
+ hostRpc = new PluginHostRpc({
407
+ pluginId: state.record.pluginId,
408
+ principalId: state.record.canonicalId,
409
+ daemonInstanceId: this.daemonInstanceId,
410
+ productVersion: this.productVersion,
411
+ cliVersion: this.cliVersion,
412
+ services: this.services,
413
+ ...(state.record.pluginId === "workspace"
414
+ && isBuiltInPluginMarketplace(state.record.marketplaceId)
415
+ ? { managedWorkspaceRoot: dataDir }
416
+ : {}),
417
+ emit: async (event) => {
418
+ if (Buffer.byteLength(JSON.stringify(event), "utf8") > MAX_PLUGIN_HOST_EVENT_BYTES) {
419
+ throw new Error("plugin host event exceeds transport budget");
420
+ }
421
+ await runner?.client.emitHostEvent(event.event, event.payload);
422
+ },
423
+ });
535
424
  runner = await this.spawnRunner({
536
- pluginId,
425
+ pluginId: state.record.pluginId,
426
+ pluginVersion: state.record.version,
427
+ installationId: state.record.canonicalId,
537
428
  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,
429
+ ...("entry" in background
430
+ ? {
431
+ entry: background.entry,
432
+ }
433
+ : {
434
+ command: background.command,
435
+ args: background.args,
436
+ }),
437
+ role: "settings",
438
+ dataDir,
439
+ cacheDir,
440
+ handleHostCall: (method, params, signal) => hostRpc.call(method, params, signal),
441
+ onStderr: (line) => this.log({
442
+ level: "info",
443
+ event: "plugin-stderr",
444
+ pluginId: state.record.canonicalId,
445
+ message: line,
446
+ }),
544
447
  });
545
- assertHandshake(pluginId, state.record.grants, runner.handshake);
448
+ if (!runner.handshake.features.settings) {
449
+ throw new Error(`plugin "${state.record.canonicalId}" does not advertise a settings background`);
450
+ }
451
+ state.settingsRunner = runner;
452
+ state.settingsHostRpc = hostRpc;
453
+ this.log({
454
+ level: "info",
455
+ event: "plugin-settings-started",
456
+ pluginId: state.record.canonicalId,
457
+ });
458
+ void runner.completion.then((exit) => {
459
+ void this.runSerialized(state.record.canonicalId, () => this.handleSettingsExit(state, runner, hostRpc, exit));
460
+ }).catch((error) => {
461
+ void this.runSerialized(state.record.canonicalId, () => this.handleSettingsExit(state, runner, hostRpc, {
462
+ code: null,
463
+ signal: null,
464
+ error,
465
+ }));
466
+ });
467
+ return runner;
546
468
  }
547
469
  catch (error) {
548
- eventQueue.close(error);
549
- stderr.flush();
550
- await runner?.close().catch(() => undefined);
551
- await host.dispose();
470
+ const cleanupErrors = [];
471
+ if (runner) {
472
+ try {
473
+ await runner.close();
474
+ }
475
+ catch (cleanupError) {
476
+ state.settingsRunner = runner;
477
+ cleanupErrors.push(cleanupError);
478
+ }
479
+ }
480
+ try {
481
+ await hostRpc?.dispose();
482
+ }
483
+ catch (cleanupError) {
484
+ state.settingsHostRpc = hostRpc;
485
+ cleanupErrors.push(cleanupError);
486
+ }
487
+ if (cleanupErrors.length > 0) {
488
+ const failure = new AggregateError([error, ...cleanupErrors], "plugin settings startup failed and cleanup was unproven");
489
+ state.settingsCleanupError = failure;
490
+ throw failure;
491
+ }
492
+ if (isUnprovenProcessCleanup(error)) {
493
+ state.settingsCleanupError = error;
494
+ throw error;
495
+ }
496
+ removePluginRuntimeLease(dataDir, SETTINGS_LEASE_ID);
552
497
  throw error;
553
498
  }
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");
499
+ }
500
+ async stopSettingsState(state) {
501
+ const runner = state.settingsRunner;
502
+ const hostRpc = state.settingsHostRpc;
503
+ if (state.settingsCleanupError && !runner && !hostRpc) {
504
+ throw state.settingsCleanupError;
560
505
  }
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;
506
+ const errors = [];
507
+ if (runner) {
508
+ try {
509
+ await runner.close();
510
+ if (state.settingsRunner === runner)
511
+ state.settingsRunner = undefined;
512
+ }
513
+ catch (error) {
514
+ errors.push(error);
515
+ }
516
+ }
517
+ if (hostRpc) {
518
+ try {
519
+ await hostRpc.dispose();
520
+ if (state.settingsHostRpc === hostRpc)
521
+ state.settingsHostRpc = undefined;
522
+ }
523
+ catch (error) {
524
+ errors.push(error);
525
+ }
526
+ }
527
+ if (errors.length > 0) {
528
+ const failure = cleanupFailure(errors, "plugin settings cleanup was unproven");
529
+ state.settingsCleanupError = failure;
530
+ throw failure;
531
+ }
532
+ state.settingsCleanupError = undefined;
533
+ removePluginRuntimeLease(pluginDataDir(state.record.marketplaceId, state.record.pluginId), SETTINGS_LEASE_ID);
591
534
  }
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({
535
+ async handleSettingsExit(state, runner, hostRpc, exit) {
536
+ if (state.settingsRunner !== runner)
537
+ return;
538
+ try {
539
+ await runner.terminateTree();
540
+ }
541
+ catch (error) {
542
+ state.settingsCleanupError = error;
543
+ this.log({
605
544
  level: "error",
606
- event: "plugin.runner.exit_handler_failed",
607
- pluginId: state.record.manifest.id,
608
- message: messageOf(transitionError),
545
+ event: "plugin-settings-exited",
546
+ pluginId: state.record.canonicalId,
547
+ message: error instanceof Error ? error.message : String(error),
609
548
  });
610
- }).catch(() => undefined);
611
- }
612
- async runnerExited(state, runner, host, generation, outcome, error) {
613
- if (state.runner !== runner || state.generation !== generation)
614
549
  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
550
  }
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;
551
+ state.settingsRunner = undefined;
673
552
  try {
674
- runner = await this.ensureRunner(state);
553
+ await hostRpc.dispose();
554
+ if (state.settingsHostRpc === hostRpc)
555
+ state.settingsHostRpc = undefined;
675
556
  }
676
557
  catch (error) {
677
- this.writeLog({
558
+ state.settingsCleanupError = error;
559
+ this.log({
678
560
  level: "error",
679
- event: "plugin.runner.restart_failed",
680
- pluginId: state.record.manifest.id,
681
- message: messageOf(error),
561
+ event: "plugin-settings-exited",
562
+ pluginId: state.record.canonicalId,
563
+ message: error instanceof Error ? error.message : String(error),
682
564
  });
683
565
  return;
684
566
  }
685
- await this.refreshRuntimeStatus(state);
686
- await this.restoreDesiredContributions(state, runner);
567
+ state.settingsCleanupError = undefined;
568
+ removePluginRuntimeLease(pluginDataDir(state.record.marketplaceId, state.record.pluginId), SETTINGS_LEASE_ID);
569
+ if (!this.disposed) {
570
+ this.log({
571
+ level: "warn",
572
+ event: "plugin-settings-exited",
573
+ pluginId: state.record.canonicalId,
574
+ message: exit.error instanceof Error
575
+ ? exit.error.message
576
+ : `settings background exited with code ${exit.code ?? "null"}${exit.signal ? ` (${exit.signal})` : ""}`,
577
+ });
578
+ }
687
579
  }
688
- async restoreDesiredContributions(state, runner) {
689
- for (const desired of [...state.desired.values()]) {
580
+ async stopState(state) {
581
+ state.stopping = true;
582
+ if (state.restartTimer)
583
+ clearTimeout(state.restartTimer);
584
+ state.restartTimer = undefined;
585
+ if (state.healthTimer)
586
+ clearTimeout(state.healthTimer);
587
+ state.healthTimer = undefined;
588
+ const runner = state.runner;
589
+ const hostRpc = state.hostRpc;
590
+ if (state.runtimeCleanupError && !runner && !hostRpc) {
591
+ throw state.runtimeCleanupError;
592
+ }
593
+ const errors = [];
594
+ if (runner) {
690
595
  try {
691
- await this.startDesiredOnRunner(state, desired, runner);
692
- await this.refreshContributionStatus(state, desired);
596
+ await runner.close();
597
+ if (state.runner === runner)
598
+ state.runner = undefined;
693
599
  }
694
600
  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
- });
601
+ errors.push(error);
701
602
  }
702
603
  }
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) {
604
+ if (hostRpc) {
716
605
  try {
717
- await runner.close();
606
+ await hostRpc.dispose();
607
+ if (state.hostRpc === hostRpc)
608
+ state.hostRpc = undefined;
718
609
  }
719
610
  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
- });
611
+ errors.push(error);
726
612
  }
727
613
  }
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
- });
614
+ if (errors.length > 0) {
615
+ const failure = cleanupFailure(errors, "plugin runtime cleanup was unproven");
616
+ state.runtimeCleanupError = failure;
617
+ this.failState(state, failure);
618
+ throw failure;
763
619
  }
620
+ state.runtimeCleanupError = undefined;
621
+ removePluginRuntimeLease(pluginDataDir(state.record.marketplaceId, state.record.pluginId), RUNTIME_LEASE_ID);
622
+ state.health = undefined;
623
+ state.error = undefined;
624
+ state.state = state.record.manifest.runtime ? "stopped" : "absent";
625
+ setPluginRuntimeState(state.record.canonicalId, state.state);
764
626
  }
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);
627
+ async handleExit(state, runner, generation, exit) {
628
+ if (state.runner !== runner || state.generation !== generation)
846
629
  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;
630
+ if (state.healthTimer)
631
+ clearTimeout(state.healthTimer);
632
+ state.healthTimer = undefined;
885
633
  try {
886
- bytes = Buffer.byteLength(JSON.stringify(event), "utf8");
634
+ await runner.terminateTree();
887
635
  }
888
- catch {
889
- return Promise.reject(new Error("plugin host event must be JSON serializable"));
636
+ catch (error) {
637
+ state.runtimeCleanupError = error;
638
+ this.failState(state, error);
639
+ return;
890
640
  }
891
- if (bytes > MAX_PLUGIN_HOST_EVENT_BYTES) {
892
- return Promise.reject(new Error("plugin host event exceeds the bounded event budget"));
641
+ state.runner = undefined;
642
+ try {
643
+ await state.hostRpc?.dispose();
644
+ state.hostRpc = undefined;
893
645
  }
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"));
646
+ catch (error) {
647
+ state.runtimeCleanupError = error;
648
+ if (!state.stopping && !this.disposed)
649
+ this.failState(state, error);
650
+ return;
897
651
  }
898
- const promise = new Promise((resolve, reject) => {
899
- this.items.push({ event, bytes, resolve, reject });
900
- this.queuedBytes += bytes;
652
+ state.runtimeCleanupError = undefined;
653
+ removePluginRuntimeLease(pluginDataDir(state.record.marketplaceId, state.record.pluginId), RUNTIME_LEASE_ID);
654
+ if (state.stopping || this.disposed)
655
+ return;
656
+ const stable = state.startedAt && Date.now() - state.startedAt >= STABLE_RESET_MS;
657
+ if (stable)
658
+ state.restartFailures = 0;
659
+ this.failState(state, exit.error ?? new Error(`runtime exited with code ${exit.code ?? "null"}${exit.signal ? ` (${exit.signal})` : ""}`));
660
+ this.scheduleRestart(state);
661
+ }
662
+ failState(state, error) {
663
+ state.restartFailures += 1;
664
+ state.health = undefined;
665
+ state.state = "failed";
666
+ state.error = error instanceof Error ? error.message : String(error);
667
+ setPluginRuntimeState(state.record.canonicalId, "failed", state.error);
668
+ this.log({
669
+ level: "error",
670
+ event: "plugin-runtime-failed",
671
+ pluginId: state.record.canonicalId,
672
+ message: state.error,
901
673
  });
902
- void this.drain();
903
- return promise;
904
674
  }
905
- close(error) {
906
- if (this.closed)
675
+ scheduleRestart(state) {
676
+ if (this.disposed || state.stopping || !state.record.enabled || state.restartTimer)
907
677
  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
- }
678
+ const delayMs = Math.min(this.restartMaxMs, this.restartBaseMs * 2 ** Math.max(0, state.restartFailures - 1));
679
+ state.restartTimer = setTimeout(() => {
680
+ state.restartTimer = undefined;
681
+ void this.runSerialized(state.record.canonicalId, () => this.startState(state));
682
+ }, delayMs);
683
+ state.restartTimer.unref?.();
684
+ this.log({
685
+ level: "warn",
686
+ event: "plugin-runtime-restart-scheduled",
687
+ pluginId: state.record.canonicalId,
688
+ delayMs,
689
+ });
916
690
  }
917
- async drain() {
918
- if (this.draining || this.closed || !this.client)
691
+ scheduleHealthPoll(state, runner) {
692
+ if (this.disposed || state.stopping || state.runner !== runner || state.healthTimer)
919
693
  return;
920
- this.draining = true;
921
- try {
922
- while (!this.closed && this.client && this.items.length > 0) {
923
- const item = this.items.shift();
694
+ state.healthTimer = setTimeout(() => {
695
+ state.healthTimer = undefined;
696
+ void this.runSerialized(state.record.canonicalId, async () => {
697
+ if (state.runner !== runner || state.stopping || this.disposed)
698
+ return;
924
699
  try {
925
- await this.client.emitHostEvent(item.event.event, item.event.payload);
926
- item.resolve();
700
+ await this.refreshHealth(state);
701
+ this.scheduleHealthPoll(state, runner);
927
702
  }
928
703
  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;
704
+ await this.failRunningState(state, runner, error);
934
705
  }
935
- this.queuedBytes -= item.bytes;
936
- }
706
+ });
707
+ }, this.healthPollMs);
708
+ state.healthTimer.unref?.();
709
+ }
710
+ async refreshHealth(state) {
711
+ const runner = state.runner;
712
+ if (!runner) {
713
+ throw new Error(`plugin runtime "${state.record.canonicalId}" is not running`);
937
714
  }
938
- finally {
939
- this.draining = false;
940
- if (!this.closed && this.client && this.items.length > 0)
941
- void this.drain();
715
+ const health = await runner.client.health();
716
+ if (state.runner !== runner)
717
+ return;
718
+ const nextState = healthState(health);
719
+ const changed = state.state !== nextState ||
720
+ state.error !== undefined ||
721
+ JSON.stringify(state.health) !== JSON.stringify(health);
722
+ state.health = health;
723
+ state.state = nextState;
724
+ state.error = undefined;
725
+ if (changed)
726
+ setPluginRuntimeState(state.record.canonicalId, state.state);
727
+ }
728
+ async failRunningState(state, runner, error) {
729
+ if (state.runner !== runner)
730
+ return;
731
+ if (state.healthTimer)
732
+ clearTimeout(state.healthTimer);
733
+ state.healthTimer = undefined;
734
+ try {
735
+ await runner.close();
942
736
  }
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}`);
737
+ catch (cleanupError) {
738
+ state.runtimeCleanupError = cleanupError;
739
+ this.failState(state, cleanupError);
740
+ return;
970
741
  }
742
+ state.runner = undefined;
743
+ try {
744
+ await state.hostRpc?.dispose();
745
+ state.hostRpc = undefined;
746
+ }
747
+ catch (cleanupError) {
748
+ state.runtimeCleanupError = cleanupError;
749
+ if (!state.stopping && !this.disposed)
750
+ this.failState(state, cleanupError);
751
+ return;
752
+ }
753
+ state.runtimeCleanupError = undefined;
754
+ removePluginRuntimeLease(pluginDataDir(state.record.marketplaceId, state.record.pluginId), RUNTIME_LEASE_ID);
755
+ if (state.stopping || this.disposed)
756
+ return;
757
+ this.failState(state, error);
758
+ this.scheduleRestart(state);
971
759
  }
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;
760
+ runSerialized(identity, operation) {
761
+ const previous = this.queues.get(identity) ?? Promise.resolve();
762
+ const current = previous.catch(() => undefined).then(operation);
763
+ this.queues.set(identity, current);
764
+ void current.finally(() => {
765
+ if (this.queues.get(identity) === current)
766
+ this.queues.delete(identity);
767
+ }).catch(() => undefined);
768
+ return current;
1081
769
  }
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
770
  }
1089
- function messageOf(error) {
1090
- return boundedText(error instanceof Error ? error.message : String(error), MAX_STATUS_ERROR_BYTES);
771
+ function cleanupFailure(errors, message) {
772
+ return errors.length === 1 ? errors[0] : new AggregateError(errors, message);
1091
773
  }
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}`;
774
+ function blockingCleanupError(state) {
775
+ return state.runtimeCleanupError ?? state.settingsCleanupError;
1099
776
  }
1100
- function sameStartRequest(left, right) {
1101
- return JSON.stringify(left) === JSON.stringify(right);
777
+ function isUnprovenProcessCleanup(error) {
778
+ return Boolean(error
779
+ && typeof error === "object"
780
+ && "code" in error
781
+ && error.code === "PROCESS_TREE_STUCK");
1102
782
  }
1103
- function clonePluginConfig(value) {
1104
- if (!value)
1105
- return {};
1106
- return cloneJsonValue(value, "options", new WeakSet());
783
+ function healthState(health) {
784
+ return health.state;
1107
785
  }
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);
786
+ async function verifyInstalledPackage(record) {
787
+ const integrity = await validatePluginPackageSnapshot(record.installPath);
788
+ if (integrity !== record.integrity) {
789
+ throw new Error(`plugin package integrity changed for "${record.canonicalId}"`);
1142
790
  }
1143
791
  }