@capybara-hq/kernel 0.1.0-rc.136 → 0.1.0-rc.138

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 (203) hide show
  1. package/dist/admin/audit-log.service.d.ts +96 -12
  2. package/dist/admin/audit-log.service.js +508 -44
  3. package/dist/admin/audit-targets.d.ts +17 -0
  4. package/dist/admin/audit-targets.js +84 -0
  5. package/dist/admin/audit.controller.d.ts +12 -9
  6. package/dist/admin/audit.controller.js +29 -8
  7. package/dist/admin/audit.schemas.d.ts +20 -4
  8. package/dist/admin/audit.schemas.js +42 -17
  9. package/dist/admin/extensions.controller.d.ts +5 -2
  10. package/dist/admin/extensions.controller.js +10 -1
  11. package/dist/admin/extensions.schemas.d.ts +4 -0
  12. package/dist/admin/extensions.schemas.js +9 -0
  13. package/dist/admin/health.service.d.ts +1 -1
  14. package/dist/admin/health.service.js +3 -3
  15. package/dist/agents/templates.js +3 -10
  16. package/dist/app.d.ts +3 -1
  17. package/dist/app.js +1 -0
  18. package/dist/automations/automations.service.js +4 -5
  19. package/dist/catalog/catalog-content.d.ts +6 -8
  20. package/dist/catalog/catalog-content.js +17 -22
  21. package/dist/catalog/catalog-items.d.ts +5 -10
  22. package/dist/catalog/catalog-items.js +27 -51
  23. package/dist/catalog/catalog-scope.service.d.ts +4 -2
  24. package/dist/catalog/catalog-scope.service.js +109 -145
  25. package/dist/catalog/catalog.module.js +7 -4
  26. package/dist/catalog/catalog.service.d.ts +10 -4
  27. package/dist/catalog/catalog.service.js +52 -10
  28. package/dist/catalog/cli.js +17 -0
  29. package/dist/catalog/component-promotion.js +8 -4
  30. package/dist/catalog/component-scope.service.d.ts +3 -1
  31. package/dist/catalog/component-scope.service.js +101 -140
  32. package/dist/catalog/component-state.d.ts +10 -8
  33. package/dist/catalog/component-state.js +42 -30
  34. package/dist/catalog/dependency-edges.d.ts +25 -0
  35. package/dist/catalog/dependency-edges.js +125 -0
  36. package/dist/catalog/effect-work.d.ts +27 -0
  37. package/dist/catalog/effect-work.js +151 -0
  38. package/dist/catalog/jobs.d.ts +4 -1
  39. package/dist/catalog/jobs.js +14 -4
  40. package/dist/catalog/org-catalog.service.d.ts +5 -1
  41. package/dist/catalog/org-catalog.service.js +101 -106
  42. package/dist/catalog/org-intent.d.ts +45 -0
  43. package/dist/catalog/org-intent.js +205 -0
  44. package/dist/catalog/owned-items.d.ts +6 -2
  45. package/dist/catalog/owned-items.js +27 -32
  46. package/dist/catalog/ownership.d.ts +2 -3
  47. package/dist/catalog/ownership.js +10 -28
  48. package/dist/catalog/platform-components.d.ts +3 -1
  49. package/dist/catalog/platform-components.js +9 -1
  50. package/dist/catalog/plugin-import.d.ts +4 -2
  51. package/dist/catalog/plugin-import.js +22 -21
  52. package/dist/catalog/plugin-install.d.ts +19 -54
  53. package/dist/catalog/plugin-install.js +221 -271
  54. package/dist/catalog/plugin-upgrade.d.ts +10 -5
  55. package/dist/catalog/plugin-upgrade.js +80 -67
  56. package/dist/catalog/request-rules.js +20 -8
  57. package/dist/catalog/scope-orgs.js +2 -7
  58. package/dist/catalog/scope-state.d.ts +6 -6
  59. package/dist/catalog/scope-state.js +24 -43
  60. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  61. package/dist/catalog/scope-sync-workers.js +10 -26
  62. package/dist/catalog/scope-sync.d.ts +19 -116
  63. package/dist/catalog/scope-sync.js +228 -275
  64. package/dist/catalog/scope-writer.d.ts +87 -0
  65. package/dist/catalog/scope-writer.js +239 -0
  66. package/dist/catalog/template-connector-ensure.js +1 -1
  67. package/dist/catalog/unshare.js +9 -43
  68. package/dist/channels/connections.service.js +6 -6
  69. package/dist/channels/supervisor.js +3 -7
  70. package/dist/client/client-access.service.js +2 -12
  71. package/dist/config/schema.d.ts +6 -0
  72. package/dist/config/schema.js +32 -1
  73. package/dist/ctx/create-ctx.d.ts +2 -2
  74. package/dist/ctx/create-ctx.js +2 -60
  75. package/dist/ctx/guard-db.d.ts +6 -0
  76. package/dist/ctx/guard-db.js +55 -0
  77. package/dist/db/extension-handoff-schema.d.ts +1 -1
  78. package/dist/db/extension-handoff-schema.js +48 -10
  79. package/dist/db/extension-schema-transfer.js +5 -2
  80. package/dist/db/kernel-schema.d.ts +32 -6
  81. package/dist/device-access/host-services.d.ts +2 -2
  82. package/dist/device-access/host-services.js +5 -6
  83. package/dist/erasure/org-catalog.js +2 -2
  84. package/dist/erasure/org-rules.js +7 -0
  85. package/dist/extensions/admin-ops.d.ts +10 -6
  86. package/dist/extensions/admin-ops.js +53 -9
  87. package/dist/extensions/admin-view.d.ts +4 -1
  88. package/dist/extensions/admin-view.js +27 -14
  89. package/dist/extensions/bootstrap.d.ts +1 -1
  90. package/dist/extensions/bootstrap.js +6 -4
  91. package/dist/extensions/cli.js +1 -0
  92. package/dist/extensions/effective-config.js +1 -4
  93. package/dist/extensions/enabled.d.ts +183 -29
  94. package/dist/extensions/enabled.js +148 -62
  95. package/dist/extensions/host.d.ts +65 -45
  96. package/dist/extensions/host.js +446 -128
  97. package/dist/extensions/installs.d.ts +9 -0
  98. package/dist/extensions/installs.js +23 -0
  99. package/dist/extensions/isolated/admission.d.ts +10 -0
  100. package/dist/extensions/isolated/admission.js +206 -0
  101. package/dist/extensions/isolated/authorization.d.ts +45 -0
  102. package/dist/extensions/isolated/authorization.js +191 -0
  103. package/dist/extensions/isolated/broker.d.ts +15 -0
  104. package/dist/extensions/isolated/broker.js +471 -0
  105. package/dist/extensions/isolated/child-protocol.d.ts +84 -0
  106. package/dist/extensions/isolated/child-protocol.js +21 -0
  107. package/dist/extensions/isolated/child-registration.d.ts +22 -0
  108. package/dist/extensions/isolated/child-registration.js +152 -0
  109. package/dist/extensions/isolated/child-session.d.ts +6 -0
  110. package/dist/extensions/isolated/child-session.js +343 -0
  111. package/dist/extensions/isolated/child-streams.d.ts +4 -0
  112. package/dist/extensions/isolated/child-streams.js +142 -0
  113. package/dist/extensions/isolated/child.d.ts +1 -0
  114. package/dist/extensions/isolated/child.js +10 -0
  115. package/dist/extensions/isolated/configured-package.d.ts +15 -0
  116. package/dist/extensions/isolated/configured-package.js +73 -0
  117. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  118. package/dist/extensions/isolated/engine-binds.js +82 -0
  119. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  120. package/dist/extensions/isolated/engine-policy.js +75 -0
  121. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  122. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  123. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  124. package/dist/extensions/isolated/engine-proxy.js +408 -0
  125. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  126. package/dist/extensions/isolated/engine-vaults.js +93 -0
  127. package/dist/extensions/isolated/lanes.d.ts +108 -0
  128. package/dist/extensions/isolated/lanes.js +726 -0
  129. package/dist/extensions/isolated/postgres-gate.d.ts +15 -0
  130. package/dist/extensions/isolated/postgres-gate.js +255 -0
  131. package/dist/extensions/isolated/revision.d.ts +32 -0
  132. package/dist/extensions/isolated/revision.js +359 -0
  133. package/dist/extensions/isolated/rpc-frame.d.ts +50 -0
  134. package/dist/extensions/isolated/rpc-frame.js +193 -0
  135. package/dist/extensions/isolated/rpc.d.ts +66 -0
  136. package/dist/extensions/isolated/rpc.js +314 -0
  137. package/dist/extensions/isolated/sandbox.d.ts +39 -0
  138. package/dist/extensions/isolated/sandbox.js +356 -0
  139. package/dist/extensions/isolated/tier.d.ts +6 -0
  140. package/dist/extensions/isolated/tier.js +45 -0
  141. package/dist/extensions/ledger.d.ts +1 -1
  142. package/dist/extensions/lifecycle-topics.d.ts +2 -0
  143. package/dist/extensions/lifecycle-topics.js +2 -0
  144. package/dist/extensions/lifecycle.d.ts +3 -1
  145. package/dist/extensions/lifecycle.js +53 -5
  146. package/dist/extensions/locks.d.ts +2 -0
  147. package/dist/extensions/locks.js +7 -0
  148. package/dist/extensions/org-config.d.ts +17 -27
  149. package/dist/extensions/org-config.js +114 -129
  150. package/dist/extensions/permission-view.d.ts +6 -1
  151. package/dist/extensions/plugin-guides.d.ts +5 -10
  152. package/dist/extensions/plugin-guides.js +18 -37
  153. package/dist/extensions/plugin-icons.d.ts +3 -21
  154. package/dist/extensions/plugin-icons.js +9 -44
  155. package/dist/extensions/plugin-items.d.ts +10 -30
  156. package/dist/extensions/plugin-items.js +32 -73
  157. package/dist/extensions/source-intent.d.ts +14 -0
  158. package/dist/extensions/source-intent.js +77 -0
  159. package/dist/inbox/platform-inbox.service.js +16 -27
  160. package/dist/index.d.ts +2 -1
  161. package/dist/index.js +2 -1
  162. package/dist/infra/database/database.module.js +6 -1
  163. package/dist/infra/database/kernel-db.d.ts +3 -1
  164. package/dist/infra/database/kernel-db.js +4 -0
  165. package/dist/infra/events/kernel-events.d.ts +4 -0
  166. package/dist/infra/outbox/registry.d.ts +3 -36
  167. package/dist/infra/outbox/registry.js +4 -49
  168. package/dist/infra/paging/paged-read.d.ts +56 -0
  169. package/dist/infra/paging/paged-read.js +78 -0
  170. package/dist/infra/queue/queue-names.d.ts +1 -1
  171. package/dist/infra/queue/queue-names.js +1 -1
  172. package/dist/kernel.d.ts +3 -2
  173. package/dist/kernel.js +21 -2
  174. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  175. package/dist/lifecycle/kernel-lifecycle.js +22 -12
  176. package/dist/lifecycle/tokens.d.ts +8 -0
  177. package/dist/lifecycle/tokens.js +2 -0
  178. package/dist/orgs/directory-sync.js +1 -4
  179. package/dist/orgs/org-lock.d.ts +3 -1
  180. package/dist/orgs/org-lock.js +3 -1
  181. package/dist/orgs/orgs.service.d.ts +3 -1
  182. package/dist/orgs/orgs.service.js +15 -8
  183. package/dist/overrides.d.ts +0 -3
  184. package/dist/overrides.js +0 -2
  185. package/dist/platform/ops/admin.ops.js +14 -3
  186. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  187. package/dist/platform/ops/org-plugins.ops.js +5 -2
  188. package/dist/platform/ops/orgs.ops.js +13 -3
  189. package/dist/platform/ops/plugins.ops.js +11 -10
  190. package/dist/setup/setup-checks.service.js +3 -2
  191. package/dist/skills/usable.js +41 -30
  192. package/dist/themes/theme-state.js +3 -3
  193. package/dist/tools/registry.d.ts +2 -2
  194. package/dist/tools/registry.js +7 -3
  195. package/package.json +2 -2
  196. package/src/migrations/0228_extension_org_switches.sql +56 -0
  197. package/src/migrations/0229_catalog_dependency_edges.sql +17 -0
  198. package/src/migrations/0230_audit_filter_idx.sql +18 -0
  199. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  200. package/dist/catalog/install-status.d.ts +0 -6
  201. package/dist/catalog/install-status.js +0 -6
  202. package/dist/catalog/scope-jobs.d.ts +0 -59
  203. package/dist/catalog/scope-jobs.js +0 -78
@@ -19,6 +19,7 @@ import { changedPaths, configFields, getPath, secretValues, unreachableSecrets,
19
19
  import { EXTERNAL_CONVERSATIONS_BACKEND } from "../conversations/external/token.js";
20
20
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
21
21
  import { ExtensionEffects } from "../ctx/durable-effects.service.js";
22
+ import { ExtensionEffectKeys } from "../ctx/durable-keys.js";
22
23
  import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
23
24
  import { ConfiguredExtensionDbIdentity, extensionDbIdentity, extensionDbPool, } from "../db/extension-db.js";
24
25
  import { ensureLocalExtensionHandoff } from "../db/extension-handoff-schema.js";
@@ -32,9 +33,10 @@ import { INBOX_ITEMS_BACKEND } from "../inbox/token.js";
32
33
  import { waitWithin } from "../infra/close-within.js";
33
34
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
34
35
  import { KernelDb } from "../infra/database/kernel-db.js";
36
+ import { withOrgScope } from "../infra/database/org-scope.js";
35
37
  import { LockService } from "../infra/lock/lock.service.js";
36
38
  import { KERNEL_LOGGER, KEYRING, REDIS, REDIS_SUBSCRIBER } from "../infra/tokens.js";
37
- import { KERNEL_APP_OPTIONS } from "../lifecycle/tokens.js";
39
+ import { KERNEL_APP_OPTIONS, KERNEL_FIXTURE_TRUST, } from "../lifecycle/tokens.js";
38
40
  import { ModelEmbeddings } from "../models/embeddings.js";
39
41
  import { ModelImages } from "../models/images.js";
40
42
  import { OrgNetworkAllowances } from "../orgs/network-allowances.service.js";
@@ -43,7 +45,7 @@ import { PLUGIN_READS_BACKEND } from "../plugin-reads/token.js";
43
45
  import { DeviceReports } from "../sandbox/device-reports.js";
44
46
  import { ShareLiveness } from "../shares/liveness.js";
45
47
  import { EmbedTokens } from "../ui/embed-token.js";
46
- import { ExtensionApprovals, planApprovals, readSnapshots, withPreApproved, } from "./approvals.js";
48
+ import { ExtensionApprovals, planApprovals, readSnapshots, snapshotCovers, withPreApproved, } from "./approvals.js";
47
49
  import { ExtensionBlobIntegrityError } from "./blobs.js";
48
50
  import { deploymentConfigHash } from "./config-hash.js";
49
51
  import { toIssues } from "./config-issues.js";
@@ -52,6 +54,12 @@ import { EffectiveConfigs } from "./effective-config.js";
52
54
  import { HookRegistry } from "./hooks.js";
53
55
  import { ExtensionInstalls } from "./installs.js";
54
56
  import { ImportTracker, importExtensionModule, ManifestMismatchError, matchesSection, setupInstance, warnUpgrades, } from "./instance.js";
57
+ import { assertIsolatedSection, isolatedDeploymentSchema } from "./isolated/admission.js";
58
+ import { IsolatedInvocationGrants, readIsolatedGrant, } from "./isolated/authorization.js";
59
+ import { readConfiguredExtensionPackage, stageConfiguredExtensionPackage, } from "./isolated/configured-package.js";
60
+ import { IsolatedExtensionQuota } from "./isolated/lanes.js";
61
+ import { isolatedRevision } from "./isolated/revision.js";
62
+ import { sweepExtensionSandboxOrphans } from "./isolated/sandbox.js";
55
63
  import { parseLoadGate } from "./org-levels.js";
56
64
  import { declaredDisplayName, permissionSetOfSection, readMigrationSql } from "./package.js";
57
65
  import { blockingKeys, computePermissionSet, SETUP_CHECK_KEY_PREFIX, UI_VIEW_KEY_PREFIX, } from "./permission-set.js";
@@ -105,15 +113,37 @@ function toFileUrl(spec, resolveFrom) {
105
113
  });
106
114
  }
107
115
  }
108
- /** 按顺序导入各 specifier 的插件模块(不排序);同时给出模块所在目录。 */
109
- async function importEntries(specifiers, resolveFrom) {
116
+ /** Read reviewed static packages. Only the test harness supplies executable fixtures directly. */
117
+ async function importEntries(specifiers, resolveFrom, fixtureTrust, maxBytes, cacheDir) {
110
118
  const entries = [];
111
119
  for (const spec of specifiers) {
112
- const url = toFileUrl(spec, resolveFrom);
120
+ if (fixtureTrust) {
121
+ const url = toFileUrl(spec, resolveFrom);
122
+ entries.push({
123
+ manifest: await importExtensionModule(url, spec, resolveFrom),
124
+ dir: dirname(fileURLToPath(url)),
125
+ url,
126
+ });
127
+ continue;
128
+ }
129
+ const snapshot = await readConfiguredExtensionPackage(spec, resolveFrom, maxBytes);
130
+ const { section, sha256, migrationSql, displayName, packageJson } = snapshot.review;
131
+ const staged = cacheDir === undefined
132
+ ? undefined
133
+ : await stageConfiguredExtensionPackage(snapshot, cacheDir);
134
+ const root = staged?.root ?? dirname(fileURLToPath(snapshot.archiveUrl));
113
135
  entries.push({
114
- manifest: await importExtensionModule(url, spec, resolveFrom),
115
- dir: dirname(fileURLToPath(url)),
116
- url,
136
+ manifest: manifestOfSection(section.manifest),
137
+ dir: root,
138
+ url: staged?.entryUrl ?? snapshot.archiveUrl,
139
+ isolated: {
140
+ section,
141
+ root,
142
+ digest: sha256,
143
+ migrationSql,
144
+ ...(displayName && { displayName }),
145
+ ...(typeof packageJson.name === "string" && { npmName: packageJson.name }),
146
+ },
117
147
  });
118
148
  }
119
149
  return entries;
@@ -140,10 +170,13 @@ async function packageNameOf(dir) {
140
170
  }
141
171
  }
142
172
  /** 计算各插件的权限集合(按插件名索引)。 */
143
- async function permissionSets(ordered, dirs) {
173
+ async function permissionSets(ordered, dirs, isolated = new Map()) {
144
174
  const sets = new Map();
145
175
  for (const m of ordered) {
146
- sets.set(m.name, await computePermissionSet(m, dirs.get(m.name)));
176
+ const source = isolated.get(m.name);
177
+ sets.set(m.name, source
178
+ ? permissionSetOfSection(source.section, source.migrationSql ?? (await readMigrationSql(source.root, source.section)))
179
+ : await computePermissionSet(m, dirs.get(m.name)));
147
180
  }
148
181
  return sets;
149
182
  }
@@ -238,7 +271,18 @@ function manifestOfSection(m) {
238
271
  },
239
272
  };
240
273
  }
241
- /** 插件宿主:解析、校验配置、迁移、setup,并登记插件提供的能力与路由。 */
274
+ function isolatedManifestOf(section) {
275
+ const manifest = manifestOfSection(section.manifest);
276
+ const schema = section.configSchemas?.deployment;
277
+ const checked = {
278
+ ...manifest,
279
+ ...(schema && { config: { deployment: isolatedDeploymentSchema(schema) } }),
280
+ ...(section.migrations && { migrations: packagePath(section.migrations) }),
281
+ };
282
+ assertSecretsReachable(checked);
283
+ return checked;
284
+ }
285
+ /** Resolves extensions and their configuration, runs migrations and registers capabilities. */
242
286
  let ExtensionHost = class ExtensionHost {
243
287
  registry;
244
288
  installs;
@@ -246,7 +290,10 @@ let ExtensionHost = class ExtensionHost {
246
290
  status;
247
291
  config;
248
292
  log;
293
+ options;
249
294
  effective;
295
+ allowances;
296
+ modules;
250
297
  dbIdentity;
251
298
  /**
252
299
  * Only resolves extensions and runs migrations in dependency order: no deployment config check, no
@@ -260,8 +307,9 @@ let ExtensionHost = class ExtensionHost {
260
307
  */
261
308
  static async migrateOnly(specifiers, opts) {
262
309
  const from = resolvePath(opts.resolveFrom ?? process.cwd());
263
- const entries = await importEntries(specifiers, from);
310
+ const entries = await importEntries(specifiers, from, opts[KERNEL_FIXTURE_TRUST] !== undefined, opts.maxPackageBytes, opts.packageCacheDir ?? join(from, ".capybara", "plugins"));
264
311
  const dirs = new Map(entries.map((e) => [e.manifest.name, e.dir]));
312
+ const isolation = new Map(entries.flatMap((e) => (e.isolated ? [[e.manifest.name, e.isolated]] : [])));
265
313
  const ordered = resolveExtensions(entries.map((e) => e.manifest), SDK_VERSION);
266
314
  for (const manifest of ordered)
267
315
  assertSecretsReachable(manifest);
@@ -271,7 +319,7 @@ let ExtensionHost = class ExtensionHost {
271
319
  }
272
320
  let toMigrate = ordered;
273
321
  if (!opts.autoApprove && ordered.length > 0) {
274
- const sets = await permissionSets(ordered, dirs);
322
+ const sets = await permissionSets(ordered, dirs, isolation);
275
323
  const raw = createDb(opts.dbUrl, 1, () => { }, { connectTimeoutMs: opts.connectTimeoutMs });
276
324
  let decisions;
277
325
  try {
@@ -288,20 +336,26 @@ let ExtensionHost = class ExtensionHost {
288
336
  }
289
337
  const out = [];
290
338
  for (const manifest of toMigrate) {
291
- const r = await migratePlugin(identity.resolve(manifest.name), manifest, migrationsDirOf(manifest, dirs.get(manifest.name)), opts.connectTimeoutMs);
339
+ const name = manifest.name;
340
+ const target = identity.resolve(name);
341
+ const source = isolation.get(name);
342
+ if (source) {
343
+ assertIsolatedSection(source.section);
344
+ if (!target.dedicated) {
345
+ throw new Error("Isolated extension migrations require the dedicated login");
346
+ }
347
+ }
348
+ const r = await migratePlugin(target, source ? isolatedManifestOf(source.section) : manifest, source?.section.migrations
349
+ ? join(source.root, packagePath(source.section.migrations))
350
+ : migrationsDirOf(manifest, dirs.get(name)), opts.connectTimeoutMs, source ? AbortSignal.timeout(opts.migrationTimeoutMs ?? 300_000) : undefined);
292
351
  if (r)
293
352
  out.push({ plugin: manifest.name, ...r });
294
353
  }
295
354
  return out;
296
355
  }
297
- /**
298
- * The names of the config-declared extensions (`specifiers`, the startup config `extensions`
299
- * list): imports their modules only (the same modules `load()` imports next, from Node's module
300
- * cache). The kernel passes them to the bootstrap step before loading, so a bootstrap entry of
301
- * the same name is kept and gets no install record (config wins, C15).
302
- */
356
+ /** Reads configured package identities for bootstrap without starting extension code. */
303
357
  static async declaredNames(specifiers, opts = {}) {
304
- const entries = await importEntries(specifiers, resolvePath(opts.resolveFrom ?? process.cwd()));
358
+ const entries = await importEntries(specifiers, resolvePath(opts.resolveFrom ?? process.cwd()), opts[KERNEL_FIXTURE_TRUST] !== undefined, opts.maxPackageBytes);
305
359
  return new Set(entries.map((e) => e.manifest.name));
306
360
  }
307
361
  /**
@@ -310,21 +364,35 @@ let ExtensionHost = class ExtensionHost {
310
364
  */
311
365
  static async inspect(specifiers, opts = {}) {
312
366
  const from = resolvePath(opts.resolveFrom ?? process.cwd());
313
- const entries = await importEntries(specifiers, from);
367
+ const entries = await importEntries(specifiers, from, opts[KERNEL_FIXTURE_TRUST] !== undefined, opts.maxPackageBytes);
314
368
  const dirs = new Map(entries.map((e) => [e.manifest.name, e.dir]));
369
+ const isolation = new Map(entries.flatMap((e) => (e.isolated ? [[e.manifest.name, e.isolated]] : [])));
315
370
  const ordered = resolveExtensions(entries.map((e) => e.manifest), SDK_VERSION);
316
371
  for (const manifest of ordered)
317
372
  assertSecretsReachable(manifest);
318
- const sets = await permissionSets(ordered, dirs);
373
+ const sets = await permissionSets(ordered, dirs, isolation);
319
374
  const out = [];
320
375
  for (const manifest of ordered) {
321
376
  const dir = dirs.get(manifest.name);
377
+ const source = isolation.get(manifest.name);
378
+ let inspected = manifest;
379
+ if (source) {
380
+ try {
381
+ inspected = isolatedManifestOf(source.section);
382
+ }
383
+ catch {
384
+ // The static permission review remains available for an inadmissible config schema.
385
+ }
386
+ }
322
387
  out.push({
323
388
  source: "config",
324
- manifest,
389
+ ...(source && { isolated: true }),
390
+ manifest: inspected,
325
391
  dir,
326
392
  permissions: sets.get(manifest.name),
327
- displayName: (await declaredDisplayName(dir, manifest.name)).displayName ?? null,
393
+ displayName: source
394
+ ? (source.displayName ?? null)
395
+ : ((await declaredDisplayName(dir, manifest.name)).displayName ?? null),
328
396
  });
329
397
  }
330
398
  return out;
@@ -333,6 +401,12 @@ let ExtensionHost = class ExtensionHost {
333
401
  * M-1: plugin → mount points where deployment state expects `policy` hooks. A per-replica copy of PG
334
402
  * deployment state (like the registry), rebuilt on every load / converge, never written elsewhere.
335
403
  */
404
+ declaredIsolation = new Map();
405
+ quota = new Map();
406
+ isolatedAuthority = new WeakMap();
407
+ isolatedLanes = new WeakMap();
408
+ isolatedGrants = new IsolatedInvocationGrants();
409
+ executionTier = new Map();
336
410
  policyExpected = new Map();
337
411
  /**
338
412
  * Runs the hooks of this process's active plugin instances (resolved from the registry on every
@@ -468,7 +542,10 @@ let ExtensionHost = class ExtensionHost {
468
542
  this.status = status;
469
543
  this.config = config;
470
544
  this.log = log;
545
+ this.options = options;
471
546
  this.effective = effective;
547
+ this.allowances = allowances;
548
+ this.modules = modules;
472
549
  this.dbIdentity = dbIdentity;
473
550
  const c = config.get();
474
551
  this.hooks = new HookRegistry({
@@ -650,7 +727,26 @@ let ExtensionHost = class ExtensionHost {
650
727
  this.didLoad = true;
651
728
  const p = Array.isArray(plan) ? { config: plan } : plan;
652
729
  this.installLoader = p.installs;
653
- const entries = await importEntries(p.config ?? [], this.resolveFrom);
730
+ const isolation = this.config.get().extensionHost.isolation;
731
+ if (isolation) {
732
+ await sweepExtensionSandboxOrphans(isolation.engineUrl).catch(() => {
733
+ this.log.error("Could not sweep exited isolated extension sandboxes");
734
+ });
735
+ }
736
+ const entries = await importEntries(p.config ?? [], this.resolveFrom, this.options[KERNEL_FIXTURE_TRUST] !== undefined, this.config.get().packages.maxBytes, this.config.get().extensionHost.dir);
737
+ for (const { manifest, isolated } of entries) {
738
+ if (!isolated)
739
+ continue;
740
+ try {
741
+ assertIsolatedSection(isolated.section);
742
+ }
743
+ catch (cause) {
744
+ throw new Error(`Configured extension ${manifest.name} was refused: ${errMsg(cause)}`, {
745
+ cause,
746
+ });
747
+ }
748
+ this.declaredIsolation.set(manifest.name, isolated);
749
+ }
654
750
  await this.claimNames(entries);
655
751
  await this.noteDisplayNames(entries);
656
752
  const dirs = new Map(entries.map((e) => [e.manifest.name, e.dir]));
@@ -661,11 +757,11 @@ let ExtensionHost = class ExtensionHost {
661
757
  : { ready: entries.map((e) => e.manifest), deferred: [] };
662
758
  const ordered = resolveExtensions(ready, SDK_VERSION);
663
759
  for (const e of entries)
664
- this.sources.set(e.manifest.name, { source: "config", sha256: null });
760
+ this.sources.set(e.manifest.name, { source: "config", sha256: e.isolated?.digest ?? null });
665
761
  this.registry.declare(entries.map((e) => e.manifest.name));
666
762
  for (const e of entries)
667
763
  assertSecretsReachable(e.manifest);
668
- const sets = await permissionSets(ordered, dirs);
764
+ const sets = await permissionSets(ordered, dirs, this.declaredIsolation);
669
765
  this.noteDeclared(ordered, sets);
670
766
  const approvals = this.approvals;
671
767
  if (this.autoApprove) {
@@ -679,9 +775,10 @@ let ExtensionHost = class ExtensionHost {
679
775
  await this.activate(approvals, {
680
776
  manifest,
681
777
  source: this.sourceOf(manifest.name),
682
- sha256: null,
778
+ isolated: this.declaredIsolation.get(manifest.name),
779
+ sha256: this.declaredIsolation.get(manifest.name)?.digest ?? null,
683
780
  entryUrl: urls.get(manifest.name),
684
- migrationsDir: migrationsDirOf(manifest, dirs.get(manifest.name)),
781
+ migrationsDir: this.declaredMigrationDirectory(manifest, dirs),
685
782
  set: sets.get(manifest.name),
686
783
  decision: this.blockedByUnloaded(manifest, decisions.get(manifest.name)),
687
784
  fatal: true,
@@ -695,9 +792,8 @@ let ExtensionHost = class ExtensionHost {
695
792
  desired = await p.installs.desired();
696
793
  }
697
794
  catch (e) {
698
- this.log.error("cannot read extension install records; installed extensions are not loaded", {
699
- err: e,
700
- });
795
+ this.log.error("Cannot load the authoritative extension policy inventory", { err: e });
796
+ throw new Error("Extension policy inventory is unavailable during startup", { cause: e });
701
797
  }
702
798
  if (desired) {
703
799
  // Packages kept in PG first: the object store serving the others may be one of them (a
@@ -713,7 +809,7 @@ let ExtensionHost = class ExtensionHost {
713
809
  if (deferred.length > 0) {
714
810
  await this.loadDeferred(deferred, dirs, urls, snapshots, approvals, installProviders);
715
811
  }
716
- await this.refreshPolicyExpectations(p.installs ? desired : []);
812
+ await this.refreshPolicyExpectations(desired ?? []);
717
813
  const orphans = Object.keys(this.extensionConfig).filter((k) => !this.sources.has(k));
718
814
  if (orphans.length > 0) {
719
815
  this.log.warn("extensionConfig has keys for extensions that are not loaded", {
@@ -747,7 +843,7 @@ let ExtensionHost = class ExtensionHost {
747
843
  async claimNames(entries) {
748
844
  const rows = [];
749
845
  for (const e of entries) {
750
- const pkg = await packageNameOf(e.dir);
846
+ const pkg = e.isolated?.npmName ?? (await packageNameOf(e.dir));
751
847
  if (pkg === undefined) {
752
848
  this.log.warn("plugin module has no package.json name; its plugin name is not claimed", {
753
849
  plugin: e.manifest.name,
@@ -824,18 +920,19 @@ let ExtensionHost = class ExtensionHost {
824
920
  if (values.length > 0)
825
921
  this.log.addSecrets(values);
826
922
  }
923
+ tierOf(loader, revision, verifyBytes) {
924
+ const fixtures = this.options[KERNEL_FIXTURE_TRUST];
925
+ if (fixtures === true || fixtures?.installDigests.includes(revision.sha256)) {
926
+ return Promise.resolve("trusted");
927
+ }
928
+ return loader.tier?.(revision, verifyBytes) ?? Promise.resolve("isolated");
929
+ }
827
930
  /**
828
- * 安装记录收敛到 PG 期望状态(启动第 3 步与运行中的 {@link converge} 共用,C16);`desired` 为期望启用的记录。
829
- * 1. 不再期望启用的(停用 / 卸载):卸下(排空在途调用),未加载但写过状态行的标为 unloaded;
830
- * 2. 期望启用、本副本已在目标包上的:不动;
831
- * 3. 其余:准备候选(同步 → 按静态清单与迁移 SQL 算权限集合;失败记 failed:`sync_failed` / `sha_mismatch`),
832
- * 与生效的插件一起按依赖拓扑序逐个处理:权限闸门(新增权限待批准 → pending / approval,旧实例照常)、
833
- * 必需能力(此刻没有生效的提供方 → pending / dependency)、导入模块并核对静态清单(`import_failed` /
834
- * `manifest_mismatch`;闸门放行之前不导入)、部署配置、
835
- * 持锁迁移(busy → pending / migration)、setup,成功后登记新实例(先加载新、再撤销旧:旧实例在后台排空后撤销);
836
- * 任何一步失败旧实例保留,记 failed(`migration_failed` / `setup_failed`)。
837
- * 4. 运行中(非启动):对变了的能力做依赖方连锁(本轮刚加载的除外),此前因依赖卸下的插件随之补回。
838
- * 返回启用的安装记录在静态清单里声明提供的能力(启动第 4 步据此判断待定还是缺提供方)。
931
+ * Reconciles enabled installs from PostgreSQL at startup and during convergence. It removes
932
+ * withdrawn revisions, verifies the tier, and prepares replacements in dependency order.
933
+ * Permission or dependency waits keep the same-tier serving revision. Import, migration and
934
+ * setup failures report the stage that failed. Successful replacements drain the old instance
935
+ * and changed providers trigger dependency reconciliation.
839
936
  */
840
937
  async applyInstalls(loader, desired, startup,
841
938
  /**
@@ -847,13 +944,32 @@ let ExtensionHost = class ExtensionHost {
847
944
  const declared = this.declared();
848
945
  const installProviders = new Map();
849
946
  const wanted = new Map();
947
+ const tiers = new Map();
948
+ const rejected = new Map();
949
+ for (const d of electAmong) {
950
+ if (declared.has(d.name))
951
+ continue;
952
+ try {
953
+ const tier = await this.tierOf(loader, d, false);
954
+ if (tier === "refused") {
955
+ rejected.set(d.name, "The extension revision did not pass trust admission");
956
+ continue;
957
+ }
958
+ if (tier === "isolated")
959
+ assertIsolatedSection(d.section);
960
+ tiers.set(d.name, tier);
961
+ }
962
+ catch (error) {
963
+ rejected.set(d.name, errMsg(error));
964
+ }
965
+ }
850
966
  // Single-provider election: of the enabled install records providing one single-provider
851
967
  // extension point, only the earliest enabled is loaded (desired() order: enabled_at, install
852
968
  // time, name). Decided from PG alone, never from what loaded here, so every replica and every
853
969
  // restart picks the same one. Two enabled providers only remain from before a second enable
854
970
  // was refused; the others are pending / conflict until the super admin disables one. A loser
855
971
  // provides nothing (left out of `installProviders`, so `blockedBy` never names it).
856
- const { losers } = electSingleProviders(electAmong.filter((d) => !declared.has(d.name)));
972
+ const { losers } = electSingleProviders(electAmong.filter((d) => tiers.has(d.name)));
857
973
  for (const d of desired) {
858
974
  const taken = declared.get(d.name);
859
975
  if (taken) {
@@ -865,7 +981,7 @@ let ExtensionHost = class ExtensionHost {
865
981
  }
866
982
  continue;
867
983
  }
868
- if (losers.has(d.name))
984
+ if (losers.has(d.name) || !tiers.has(d.name))
869
985
  continue;
870
986
  wanted.set(d.name, d);
871
987
  // 按审阅过的静态清单(不论随后加载成败)
@@ -874,9 +990,15 @@ let ExtensionHost = class ExtensionHost {
874
990
  }
875
991
  }
876
992
  this.installProvides = installProviders;
993
+ for (const name of this.unloadedForDependency) {
994
+ if (this.specs.get(name)?.source !== "install" || wanted.has(name))
995
+ continue;
996
+ this.unloadedForDependency.delete(name);
997
+ this.specs.delete(name);
998
+ }
877
999
  const drainMs = this.drainMs();
878
1000
  const changed = [];
879
- // 1. 不再期望启用:卸下;未加载但写过状态行的标为 unloaded
1001
+ // Unload withdrawn instances and clear stale serving status.
880
1002
  for (const inst of this.registry.all()) {
881
1003
  if (inst.source !== "install" || wanted.has(inst.name))
882
1004
  continue;
@@ -900,13 +1022,54 @@ let ExtensionHost = class ExtensionHost {
900
1022
  detail: null,
901
1023
  });
902
1024
  }
903
- // 2 / 3. 需要换包或尚未加载的:准备候选
1025
+ for (const d of desired) {
1026
+ const detail = rejected.get(d.name);
1027
+ if (detail)
1028
+ await this.writeStatus({
1029
+ plugin: d.name,
1030
+ version: d.version,
1031
+ sha256: d.sha256,
1032
+ source: "install",
1033
+ state: "failed",
1034
+ reason: "import_failed",
1035
+ detail,
1036
+ });
1037
+ }
904
1038
  const candidates = [];
905
1039
  for (const d of wanted.values()) {
906
1040
  if (this.closed)
907
1041
  throw new Error(CLOSED_DURING_LOAD);
908
- if (this.registry.current(d.name)?.sha256 === d.sha256)
1042
+ const tier = tiers.get(d.name);
1043
+ const current = this.registry.current(d.name);
1044
+ if (current && this.executionTier.get(d.name) !== tier) {
1045
+ const removed = await this.doUnload(d.name, drainMs, null);
1046
+ if (removed)
1047
+ changed.push(...removed.manifest.provides);
1048
+ }
1049
+ else if (current?.sha256 === d.sha256) {
909
1050
  continue;
1051
+ }
1052
+ if (tier === "trusted") {
1053
+ let verified = "refused";
1054
+ try {
1055
+ verified = await this.tierOf(loader, d, true);
1056
+ }
1057
+ catch {
1058
+ this.log.warn("Extension revision integrity could not be verified", { plugin: d.name });
1059
+ }
1060
+ if (verified !== "trusted") {
1061
+ await this.writeStatus({
1062
+ plugin: d.name,
1063
+ version: d.version,
1064
+ sha256: d.sha256,
1065
+ source: "install",
1066
+ state: "failed",
1067
+ reason: "sha_mismatch",
1068
+ detail: "The trusted extension package did not match its verified integrity",
1069
+ });
1070
+ continue;
1071
+ }
1072
+ }
910
1073
  const c = await this.prepare(loader, d);
911
1074
  if (c)
912
1075
  candidates.push(c);
@@ -998,8 +1161,10 @@ let ExtensionHost = class ExtensionHost {
998
1161
  continue;
999
1162
  if (this.closed)
1000
1163
  throw new Error(CLOSED_DURING_LOAD);
1164
+ const isolated = tiers.get(m.name) === "isolated";
1001
1165
  const a = {
1002
1166
  manifest: c.manifest,
1167
+ ...(isolated && { isolated: { root: c.root, section: c.d.section } }),
1003
1168
  source: "install",
1004
1169
  optionalBootstrap: c.d.source === "bootstrap" && !c.d.required,
1005
1170
  sha256: c.d.sha256,
@@ -1009,13 +1174,14 @@ let ExtensionHost = class ExtensionHost {
1009
1174
  decision: { plugin: m.name, action: "pending" },
1010
1175
  fatal: false,
1011
1176
  migrate: () => loader.migrate(c.d, c.migrationsDir, this.abort.signal),
1012
- importModule: () => this.importInstalled(c),
1177
+ ...(!isolated && { importModule: () => this.importInstalled(c) }),
1013
1178
  };
1014
1179
  a.decision = this.decidePending(m.name, a, snapshots, installProviders);
1015
1180
  const old = this.registry.current(m.name);
1016
1181
  // 安装记录不受信任:启动时 setup 同样限时(I3),挂住的 setup 不卡住内核启动;配置声明的启动时不限
1017
1182
  const inst = await this.activate(approvals, a, this.reloadSetupTimeoutMs());
1018
1183
  if (inst) {
1184
+ this.executionTier.set(m.name, isolated ? "isolated" : "trusted");
1019
1185
  activated.add(m.name);
1020
1186
  changed.push(...inst.manifest.provides, ...(old?.manifest.provides ?? []));
1021
1187
  }
@@ -1158,7 +1324,7 @@ let ExtensionHost = class ExtensionHost {
1158
1324
  else
1159
1325
  this.pendingPlugins.push(p);
1160
1326
  }
1161
- /** 从待定清单里去掉。 */
1327
+ /** Removes an extension from the pending list. */
1162
1328
  dropPending(plugin) {
1163
1329
  const at = this.pendingPlugins.findIndex((x) => x.plugin === plugin);
1164
1330
  if (at >= 0)
@@ -1171,12 +1337,21 @@ let ExtensionHost = class ExtensionHost {
1171
1337
  * 与「配置声明插件依赖待批准的配置声明插件」一致,内核照常启动;
1172
1338
  * - 缺的能力没有任何提供方 → 与此前一样抛错(内核启动失败)。
1173
1339
  */
1340
+ declaredMigrationDirectory(manifest, dirs) {
1341
+ const source = this.declaredIsolation.get(manifest.name);
1342
+ if (source) {
1343
+ return source.section.migrations
1344
+ ? join(source.root, packagePath(source.section.migrations))
1345
+ : undefined;
1346
+ }
1347
+ return migrationsDirOf(manifest, dirs.get(manifest.name));
1348
+ }
1174
1349
  async loadDeferred(deferred, dirs, urls, snapshots, approvals, installProviders) {
1175
1350
  if (this.closed)
1176
1351
  throw new Error(CLOSED_DURING_LOAD);
1177
1352
  const loaded = this.registry.all();
1178
1353
  const { ready, deferred: blocked } = splitDeferred([...loaded.map((i) => i.manifest), ...deferred], new Set(deferred.map((m) => m.name)));
1179
- const deferredSets = await permissionSets(deferred, dirs);
1354
+ const deferredSets = await permissionSets(deferred, dirs, this.declaredIsolation);
1180
1355
  this.noteDeclared(deferred, deferredSets);
1181
1356
  const sets = new Map([...loaded.map((i) => [i.name, i.permissions]), ...deferredSets]);
1182
1357
  const blockedProvides = new Set(blocked.flatMap((m) => m.provides));
@@ -1201,9 +1376,10 @@ let ExtensionHost = class ExtensionHost {
1201
1376
  await this.activate(approvals, {
1202
1377
  manifest: m,
1203
1378
  source: "config",
1204
- sha256: null,
1379
+ isolated: this.declaredIsolation.get(m.name),
1380
+ sha256: this.declaredIsolation.get(m.name)?.digest ?? null,
1205
1381
  entryUrl: urls.get(m.name),
1206
- migrationsDir: migrationsDirOf(m, dirs.get(m.name)),
1382
+ migrationsDir: this.declaredMigrationDirectory(m, dirs),
1207
1383
  set: sets.get(m.name),
1208
1384
  decision: {
1209
1385
  plugin: m.name,
@@ -1232,9 +1408,10 @@ let ExtensionHost = class ExtensionHost {
1232
1408
  await this.activate(approvals, {
1233
1409
  manifest,
1234
1410
  source: "config",
1235
- sha256: null,
1411
+ isolated: this.declaredIsolation.get(manifest.name),
1412
+ sha256: this.declaredIsolation.get(manifest.name)?.digest ?? null,
1236
1413
  entryUrl: urls.get(manifest.name),
1237
- migrationsDir: migrationsDirOf(manifest, dirs.get(manifest.name)),
1414
+ migrationsDir: this.declaredMigrationDirectory(manifest, dirs),
1238
1415
  set: sets.get(manifest.name),
1239
1416
  // 同一批里的提供方可能刚记为待配置:依赖方改为待定,不让启动失败
1240
1417
  decision: this.blockedByUnloaded(manifest, decisions.get(manifest.name)),
@@ -1319,22 +1496,31 @@ let ExtensionHost = class ExtensionHost {
1319
1496
  }
1320
1497
  }
1321
1498
  /**
1322
- * 加载一个插件:权限闸门结论、部署配置、迁移、setup、登记。`fatal` 时(配置声明)出错直接抛;
1323
- * 否则(安装记录)记 failed 后返回。部署配置不合法时(任何来源)只记 pending(reason config),不抛(C10)。
1324
- * 已有同名实例时(升级):新实例登记后旧实例才撤销(后台排空在途调用);新实例没加载成时旧实例保持不变。
1325
- * 返回新登记的实例(没有加载时返回 undefined)。
1499
+ * Admit a reviewed revision, resolve deployment config, migrate, and register it. Ineligible
1500
+ * config leaves the extension pending. A same-tier replacement keeps the previous instance
1501
+ * available until the new instance registers. Tier transitions drain before replacement.
1326
1502
  */
1327
1503
  async activate(approvals, a, setupTimeoutMs) {
1328
1504
  const { decision } = a;
1329
1505
  let manifest = a.manifest;
1330
1506
  const name = manifest.name;
1331
1507
  const base = { plugin: name, version: manifest.version, sha256: a.sha256, source: a.source };
1332
- const failSoft = async (reason, e) => {
1508
+ // Install records are reconciled from PostgreSQL, while declarations need a local retry.
1509
+ const retryLater = () => {
1510
+ if (a.source !== "install")
1511
+ this.pendingActivations.set(name, a);
1512
+ };
1513
+ const failSoft = async (reason, e, refusedDeclaration = false) => {
1333
1514
  this.logFailure(name, a.sha256, reason, e, { version: manifest.version });
1334
1515
  await this.writeStatus({ ...base, state: "failed", reason, detail: errMsg(e) });
1516
+ if (a.fatal && a.isolated && refusedDeclaration) {
1517
+ throw new Error(`Configured extension ${name} was refused: ${errMsg(e)}`, { cause: e });
1518
+ }
1519
+ if (a.isolated)
1520
+ retryLater();
1335
1521
  return undefined;
1336
1522
  };
1337
- // 安装记录:闸门放行之后才导入真实模块(I1:批准之前不执行插件代码);待批准时只有静态清单,不读部署配置
1523
+ // Approved trusted installs may import here. Pending installs use only their static manifest.
1338
1524
  if (a.importModule && decision.action !== "pending") {
1339
1525
  try {
1340
1526
  manifest = await a.importModule();
@@ -1345,13 +1531,17 @@ let ExtensionHost = class ExtensionHost {
1345
1531
  return failSoft(e instanceof ManifestMismatchError ? "manifest_mismatch" : "import_failed", e);
1346
1532
  }
1347
1533
  }
1534
+ if (a.isolated && decision.action !== "pending") {
1535
+ try {
1536
+ assertIsolatedSection(a.isolated.section);
1537
+ manifest = isolatedManifestOf(a.isolated.section);
1538
+ }
1539
+ catch (error) {
1540
+ return failSoft("import_failed", error, true);
1541
+ }
1542
+ }
1348
1543
  const schema = manifest.config?.deployment;
1349
- // 安装记录每次 converge 都按 PG 重新判定,不进 pendingActivations
1350
- const retryLater = () => {
1351
- if (a.source !== "install")
1352
- this.pendingActivations.set(name, a);
1353
- };
1354
- const readConfig = !(a.importModule && decision.action === "pending");
1544
+ const readConfig = !((a.importModule || a.isolated) && decision.action === "pending");
1355
1545
  let raw;
1356
1546
  try {
1357
1547
  if (readConfig)
@@ -1450,10 +1640,29 @@ let ExtensionHost = class ExtensionHost {
1450
1640
  }
1451
1641
  if (this.closed)
1452
1642
  throw new Error(CLOSED_DURING_LOAD);
1453
- // 安装记录:一个副本持锁迁移(C16),别的副本正在迁移时待定、旧实例照常;配置声明:按 schema 锁直接迁移
1643
+ // The isolated runner must be available before an isolated revision can migrate or activate.
1644
+ if (a.isolated && !this.config.get().extensionHost.isolation) {
1645
+ return failSoft("setup_failed", new Error("The isolated extension supervisor is not configured"), true);
1646
+ }
1647
+ if (a.isolated) {
1648
+ try {
1649
+ const identity = this.dbIdentity.resolve(name);
1650
+ if (!identity.dedicated) {
1651
+ throw new Error("Isolated extension migrations require the dedicated login");
1652
+ }
1653
+ }
1654
+ catch {
1655
+ return failSoft("migration_failed", new Error("The isolated extension has no dedicated database identity"));
1656
+ }
1657
+ }
1454
1658
  const migrating = a.migrate
1455
1659
  ? a.migrate()
1456
- : migratePlugin(this.dbIdentity.resolve(name), manifest, a.migrationsDir, this.deps.connectTimeoutMs, this.abort.signal);
1660
+ : migratePlugin(this.dbIdentity.resolve(name), manifest, a.migrationsDir, this.deps.connectTimeoutMs, a.isolated
1661
+ ? AbortSignal.any([
1662
+ this.abort.signal,
1663
+ AbortSignal.timeout(this.config.get().extensionHost.migrationTimeoutSeconds * 1000),
1664
+ ])
1665
+ : this.abort.signal);
1457
1666
  this.migrating = migrating;
1458
1667
  try {
1459
1668
  if ((await migrating) === "busy") {
@@ -1469,7 +1678,7 @@ let ExtensionHost = class ExtensionHost {
1469
1678
  catch (e) {
1470
1679
  if (this.closed)
1471
1680
  throw new Error(CLOSED_DURING_LOAD, { cause: e });
1472
- if (a.fatal)
1681
+ if (a.fatal && !a.isolated)
1473
1682
  throw e;
1474
1683
  return failSoft("migration_failed", e);
1475
1684
  }
@@ -1480,6 +1689,7 @@ let ExtensionHost = class ExtensionHost {
1480
1689
  throw new Error(CLOSED_DURING_LOAD);
1481
1690
  const spec = {
1482
1691
  manifest,
1692
+ isolated: a.isolated,
1483
1693
  entryUrl: a.entryUrl,
1484
1694
  source: a.source,
1485
1695
  sha256: a.sha256,
@@ -1494,7 +1704,7 @@ let ExtensionHost = class ExtensionHost {
1494
1704
  catch (e) {
1495
1705
  if (this.closed)
1496
1706
  throw new Error(CLOSED_DURING_LOAD, { cause: e });
1497
- if (a.fatal)
1707
+ if (a.fatal && !a.isolated)
1498
1708
  throw e;
1499
1709
  return failSoft("setup_failed", e);
1500
1710
  }
@@ -1510,6 +1720,8 @@ let ExtensionHost = class ExtensionHost {
1510
1720
  this.declaredActivations.set(name, a);
1511
1721
  this.unloadedForDependency.delete(name);
1512
1722
  const old = this.registry.activate(inst);
1723
+ if (old)
1724
+ this.isolatedAuthority.get(old)?.abort();
1513
1725
  this.loggedFailures.delete(name);
1514
1726
  await this.writeStatus({
1515
1727
  ...base,
@@ -1574,66 +1786,47 @@ let ExtensionHost = class ExtensionHost {
1574
1786
  activatePending() {
1575
1787
  return this.serial(() => this.activatePendingNow());
1576
1788
  }
1789
+ revokeIsolatedInvocations(scope) {
1790
+ this.isolatedGrants.revoke(scope);
1791
+ for (const instance of this.registry.all()) {
1792
+ if (scope.plugin !== undefined && scope.plugin !== instance.name)
1793
+ continue;
1794
+ this.isolatedLanes.get(instance)?.revokeOrg(scope.orgId);
1795
+ }
1796
+ }
1797
+ refreshIsolatedOrgIntent(orgId) {
1798
+ return this.isolatedGrants.refreshOrgIntent(orgId);
1799
+ }
1800
+ revalidateIsolatedInvocations() {
1801
+ return this.isolatedGrants.revalidate();
1802
+ }
1577
1803
  /**
1578
- * 本副本收敛到部署的期望状态(T14 reconcile 的一步,与 unload / reload 串行):
1579
- * 1. 待定的配置声明插件(批准后、或运行中加载失败的)按此刻的快照与生效的提供方重试;
1580
- * 2. 安装记录按 PG 期望状态收敛(见 {@link applyInstalls}:停用 / 卸载的卸下,换包的先加载新再撤销旧,
1581
- * 失败的每次重试),之后做依赖方连锁;
1582
- * 3. 再试一次第 1 步(安装记录提供的能力可能放行了依赖它的配置声明插件)。
1583
- * 读不到安装记录时只做第 1 步并抛错(调用方记日志,下一个周期再来)。
1804
+ * Publish approved policy expectations before doing work that might leave a handler temporarily
1805
+ * unavailable. Re-read after activation, which may have persisted new permission approvals.
1584
1806
  */
1585
1807
  converge() {
1586
1808
  return this.serial(async () => {
1587
- await this.activatePendingNow();
1588
1809
  const loader = this.installLoader;
1589
- if (!loader)
1590
- return;
1591
- const desired = await loader.desired();
1592
- // N-2: drop plugins no longer desired before applyInstalls unloads them (the drain can take
1593
- // extensionHost.drainSeconds; meanwhile a disabled policy plugin must not fail calls closed).
1594
- // Shrink only: plugins that are newly expected are added after they had their chance to load.
1595
- await this.refreshPolicyExpectations(desired, { shrinkOnly: true });
1596
- await this.applyInstalls(loader, desired, false);
1597
- if (this.pendingActivations.size > 0)
1598
- await this.activatePendingNow();
1810
+ const desired = (await loader?.desired()) ?? [];
1811
+ await this.refreshPolicyExpectations(desired);
1812
+ await this.activatePendingNow();
1813
+ if (loader) {
1814
+ await this.applyInstalls(loader, desired, false);
1815
+ if (this.pendingActivations.size > 0)
1816
+ await this.activatePendingNow();
1817
+ }
1599
1818
  await this.refreshPolicyExpectations(desired);
1600
1819
  });
1601
1820
  }
1602
- /**
1603
- * Refreshes {@link policyExpected} from deployment state (M-1):
1604
- * config-declared plugins and enabled installs (`desired`) from their approved permission snapshot.
1605
- * `desired` undefined (install records unreadable) keeps the previous install entries.
1606
- * `shrinkOnly`: only remove entries (a plugin no longer desired or approved), never add new ones.
1607
- */
1608
- async refreshPolicyExpectations(desired, opts = {}) {
1821
+ /** Policy expectations follow approval and deployment state for every execution tier. */
1822
+ async refreshPolicyExpectations(desired) {
1609
1823
  const snapshots = await this.approvals.all();
1824
+ const names = new Set([...this.declaredInfo.keys(), ...desired.map(({ name }) => name)]);
1610
1825
  const next = new Map();
1611
- const add = (name, set) => {
1612
- const mounts = set?.permissions?.policyHooks ?? [];
1826
+ for (const name of names) {
1827
+ const mounts = snapshots.get(name)?.permissions.permissions.policyHooks ?? [];
1613
1828
  if (mounts.length > 0)
1614
1829
  next.set(name, [...mounts]);
1615
- };
1616
- for (const name of this.declaredInfo.keys()) {
1617
- add(name, snapshots.get(name)?.permissions);
1618
- }
1619
- const declared = this.declared();
1620
- if (desired === undefined) {
1621
- for (const [name, mounts] of this.policyExpected) {
1622
- if (!this.declaredInfo.has(name))
1623
- next.set(name, mounts);
1624
- }
1625
- }
1626
- else {
1627
- for (const d of desired) {
1628
- if (!declared.has(d.name))
1629
- add(d.name, snapshots.get(d.name)?.permissions);
1630
- }
1631
- }
1632
- if (opts.shrinkOnly) {
1633
- for (const name of [...next.keys()]) {
1634
- if (!this.policyExpected.has(name))
1635
- next.delete(name);
1636
- }
1637
1830
  }
1638
1831
  this.policyExpected = next;
1639
1832
  }
@@ -1781,7 +1974,7 @@ let ExtensionHost = class ExtensionHost {
1781
1974
  return this.registry.declared();
1782
1975
  }
1783
1976
  /**
1784
- * Extensions enabled in the org: `extension_org_configs.enabled` plus every always-on extension
1977
+ * Extensions enabled in the org: the org intent projection
1785
1978
  * (required bootstrap plugins, builtin plugins' extensions; see `enabled.ts`); queried every
1786
1979
  * time, not cached.
1787
1980
  * Cost (M-4): hooks call this on every run, so one PG query per model attempt and per tool call.
@@ -1794,7 +1987,7 @@ let ExtensionHost = class ExtensionHost {
1794
1987
  /**
1795
1988
  * The access behind an extension's `ctx.extensionPoints`: only active instances in the registry
1796
1989
  * (dependencies load in topological order, so the depended-on are ready first); org enablement is
1797
- * read from `extension_org_configs` every time, not cached. Resolved live on every call: once a
1990
+ * read from PostgreSQL every time, not cached. Resolved live on every call: once a
1798
1991
  * provider is revoked it is no longer returned.
1799
1992
  */
1800
1993
  extensionPointAccess = {
@@ -1817,23 +2010,120 @@ let ExtensionHost = class ExtensionHost {
1817
2010
  };
1818
2011
  }
1819
2012
  /**
1820
- * 按加载参数建一个新实例(setup 期间的 ctx 记在 `settingUp`,close() 时立即关闭)。
1821
- * `timeoutMs`(运行中重新加载):setup 超时或宿主被关闭时关闭这个 ctx 并抛错;迟到完成的实例随即撤销。
1822
- * 配置声明的插件启动时不设时限(见 {@link load})。
2013
+ * Build a new generation. Track its context during setup so shutdown can close it immediately.
2014
+ * A reload deadline closes incomplete setup and any late instance that reaches registration.
1823
2015
  */
1824
2016
  async setup(spec, timeoutMs) {
1825
2017
  if (this.imports.record(spec.manifest.name, spec.entryUrl)) {
1826
2018
  warnUpgrades(this.log, this.imports);
1827
2019
  }
1828
2020
  let ctx;
2021
+ let active;
2022
+ let lanes;
2023
+ const authority = spec.isolated ? new AbortController() : undefined;
1829
2024
  const name = spec.manifest.name;
1830
2025
  const identity = this.dbIdentity.resolve(name);
1831
2026
  const extensionDb = extensionDbPool(identity, name, this.config.get().db, (err) => this.log.warn("extension database pool error", { plugin: name, err }));
1832
2027
  const p = (async () => {
2028
+ let manifest = spec.manifest;
2029
+ if (spec.isolated && authority) {
2030
+ const isolation = this.config.get().extensionHost.isolation;
2031
+ if (!isolation)
2032
+ throw new Error("The isolated extension supervisor is not configured");
2033
+ let quota = this.quota.get(name);
2034
+ if (!quota) {
2035
+ quota = new IsolatedExtensionQuota();
2036
+ this.quota.set(name, quota);
2037
+ }
2038
+ const modules = this.modules;
2039
+ const db = kernelDb(this.deps.db);
2040
+ const current = () => active !== undefined &&
2041
+ !authority.signal.aborted &&
2042
+ !this.closed &&
2043
+ this.registry.current(name) === active;
2044
+ const authorize = (orgId) => {
2045
+ if (!current())
2046
+ return Promise.resolve(undefined);
2047
+ const scope = orgId === undefined ? { plugin: name } : { plugin: name, orgId };
2048
+ const check = async () => current() &&
2049
+ (await readIsolatedGrant(db, {
2050
+ plugin: name,
2051
+ installedSha: spec.source === "install" ? spec.sha256 : undefined,
2052
+ permissions: spec.permissions,
2053
+ orgId,
2054
+ })) &&
2055
+ current();
2056
+ return this.isolatedGrants.issue(scope, () => (orgId === undefined ? check() : withOrgScope(orgId, check)), () => lanes?.revokeOrg(orgId), authority.signal);
2057
+ };
2058
+ const declared = spec.manifest.permissions?.network ?? [];
2059
+ manifest = await isolatedRevision({
2060
+ manifest,
2061
+ revision: spec.sha256 ?? spec.entryUrl,
2062
+ section: spec.isolated.section,
2063
+ identity,
2064
+ sandbox: {
2065
+ engineUrl: isolation.engineUrl,
2066
+ image: isolation.image,
2067
+ postgresSocket: isolation.postgresSocket,
2068
+ packageRoot: spec.isolated.root,
2069
+ },
2070
+ socketDir: isolation.socketDir,
2071
+ runtimeUrl: this.config.get().db.url,
2072
+ signal: AbortSignal.any([this.abort.signal, authority.signal]),
2073
+ quota,
2074
+ onLanes: (value) => {
2075
+ lanes = value;
2076
+ },
2077
+ onCrash: (retryAfterMs) => {
2078
+ this.log.warn("Isolated extension sandbox exited unexpectedly", {
2079
+ plugin: name,
2080
+ retryAfterMs,
2081
+ });
2082
+ void this.status
2083
+ .note(name, `Isolated sandbox crashed. Retry is delayed by ${retryAfterMs} ms.`)
2084
+ .catch(() => { });
2085
+ },
2086
+ cleanupFault: () => {
2087
+ this.log.error("Isolated extension sandbox removal could not be confirmed", {
2088
+ plugin: name,
2089
+ });
2090
+ void this.status
2091
+ .note(name, "Isolated sandbox cleanup could not be confirmed")
2092
+ .catch(() => { });
2093
+ },
2094
+ rls: this.config.get().db.rls,
2095
+ roles: this.config.get().roles,
2096
+ effective: (orgId) => this.effective.get(orgId, name),
2097
+ authorize,
2098
+ broker: {
2099
+ plugin: name,
2100
+ current,
2101
+ effects: () => {
2102
+ if (!modules)
2103
+ throw new Error("Extension effects are unavailable");
2104
+ return modules.get(ExtensionEffects, { strict: false });
2105
+ },
2106
+ keys: () => {
2107
+ if (!modules)
2108
+ throw new Error("Extension effect keys are unavailable");
2109
+ return modules.get(ExtensionEffectKeys, { strict: false });
2110
+ },
2111
+ network: async (url, orgId) => {
2112
+ const approved = (value) => value === url.hostname || value === url.origin;
2113
+ if (declared.some(approved))
2114
+ return true;
2115
+ if (orgId === undefined)
2116
+ return false;
2117
+ const policy = await this.allowances.policyFor(orgId);
2118
+ return (policy.trustedOrigins.some(approved) || policy.allowPrivateHosts.some(approved));
2119
+ },
2120
+ },
2121
+ });
2122
+ }
1833
2123
  if (!identity.separate) {
1834
2124
  await ensureLocalExtensionHandoff(this.deps.db, this.deps.dbUrl, pluginSchemaName(name), this.deps.connectTimeoutMs);
1835
2125
  }
1836
- return setupInstance(this.loadDeps, spec.manifest, {
2126
+ active = await setupInstance(this.loadDeps, manifest, {
1837
2127
  entryUrl: spec.entryUrl,
1838
2128
  source: spec.source,
1839
2129
  sha256: spec.sha256,
@@ -1848,7 +2138,13 @@ let ExtensionHost = class ExtensionHost {
1848
2138
  this.settingUp = c;
1849
2139
  },
1850
2140
  });
2141
+ if (authority)
2142
+ this.isolatedAuthority.set(active, authority);
2143
+ if (lanes)
2144
+ this.isolatedLanes.set(active, lanes);
2145
+ return active;
1851
2146
  })().catch(async (error) => {
2147
+ authority?.abort();
1852
2148
  if (!ctx)
1853
2149
  await extensionDb.destroy();
1854
2150
  throw error;
@@ -2313,6 +2609,7 @@ let ExtensionHost = class ExtensionHost {
2313
2609
  const inst = this.registry.deactivate(plugin);
2314
2610
  if (!inst)
2315
2611
  return undefined;
2612
+ this.isolatedAuthority.get(inst)?.abort();
2316
2613
  if (reason === "dependency")
2317
2614
  this.unloadedForDependency.add(plugin);
2318
2615
  else
@@ -2330,6 +2627,22 @@ let ExtensionHost = class ExtensionHost {
2330
2627
  this.log.info("plugin unloaded", { plugin, generation: inst.generation, reason });
2331
2628
  return inst;
2332
2629
  }
2630
+ async assertCurrentInstall(spec) {
2631
+ const name = spec.manifest.name;
2632
+ const loader = this.installLoader;
2633
+ const revision = loader && (await loader.desired()).find((d) => d.name === name);
2634
+ if (!loader || !revision || revision.sha256 !== spec.sha256) {
2635
+ throw new Error("The cached extension revision is no longer desired");
2636
+ }
2637
+ const tier = await this.tierOf(loader, revision, true);
2638
+ if (tier !== (spec.isolated ? "isolated" : "trusted")) {
2639
+ throw new Error("The cached extension revision no longer passes trust admission");
2640
+ }
2641
+ const snapshots = await this.approvals.all();
2642
+ if (!snapshotCovers(snapshots.get(name), spec.permissions)) {
2643
+ throw new Error("The cached extension revision no longer has its approved permissions");
2644
+ }
2645
+ }
2333
2646
  /** 新建实例并原子替换、撤销旧实例(不做连锁)。 */
2334
2647
  async doReload(plugin, drainMs) {
2335
2648
  if (this.closed)
@@ -2337,6 +2650,8 @@ let ExtensionHost = class ExtensionHost {
2337
2650
  const spec = this.specs.get(plugin);
2338
2651
  if (!spec)
2339
2652
  throw new Error(`plugin ${plugin} has never been loaded in this process`);
2653
+ if (spec.source === "install")
2654
+ await this.assertCurrentInstall(spec);
2340
2655
  const available = new Set(this.registry
2341
2656
  .all()
2342
2657
  .filter((i) => i.name !== plugin)
@@ -2352,6 +2667,8 @@ let ExtensionHost = class ExtensionHost {
2352
2667
  }
2353
2668
  this.unloadedForDependency.delete(plugin);
2354
2669
  const old = this.registry.activate(inst);
2670
+ if (old)
2671
+ this.isolatedAuthority.get(old)?.abort();
2355
2672
  await this.writeStatus({
2356
2673
  plugin,
2357
2674
  version: inst.version,
@@ -2475,6 +2792,7 @@ let ExtensionHost = class ExtensionHost {
2475
2792
  async close(opts = {}) {
2476
2793
  this.closed = true;
2477
2794
  this.abort.abort();
2795
+ this.revokeIsolatedInvocations({});
2478
2796
  await this.migrating?.catch(() => { });
2479
2797
  const lifecycleWaitMs = opts.lifecycleWaitMs ?? CLOSE_LIFECYCLE_WAIT_MS;
2480
2798
  await waitWithin(this.lifecycle.catch(() => { }), lifecycleWaitMs);