@capybara-hq/kernel 0.1.0-rc.135 → 0.1.0-rc.137

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 (242) hide show
  1. package/dist/admin/admin.module.js +3 -0
  2. package/dist/admin/audit-log.service.d.ts +96 -12
  3. package/dist/admin/audit-log.service.js +508 -44
  4. package/dist/admin/audit-targets.d.ts +17 -0
  5. package/dist/admin/audit-targets.js +84 -0
  6. package/dist/admin/audit.controller.d.ts +12 -9
  7. package/dist/admin/audit.controller.js +29 -8
  8. package/dist/admin/audit.schemas.d.ts +20 -4
  9. package/dist/admin/audit.schemas.js +42 -17
  10. package/dist/admin/health.service.d.ts +2 -2
  11. package/dist/admin/health.service.js +6 -2
  12. package/dist/agents/templates.js +3 -10
  13. package/dist/app.d.ts +3 -1
  14. package/dist/app.js +1 -0
  15. package/dist/automations/automations.service.js +4 -5
  16. package/dist/catalog/catalog-content.d.ts +1 -1
  17. package/dist/catalog/catalog-content.js +17 -22
  18. package/dist/catalog/catalog-items.d.ts +5 -10
  19. package/dist/catalog/catalog-items.js +27 -51
  20. package/dist/catalog/catalog-scope.service.d.ts +4 -2
  21. package/dist/catalog/catalog-scope.service.js +105 -141
  22. package/dist/catalog/catalog.module.js +2 -0
  23. package/dist/catalog/catalog.service.d.ts +3 -3
  24. package/dist/catalog/catalog.service.js +33 -8
  25. package/dist/catalog/cli.js +17 -0
  26. package/dist/catalog/component-promotion.js +8 -4
  27. package/dist/catalog/component-scope.service.d.ts +3 -1
  28. package/dist/catalog/component-scope.service.js +101 -140
  29. package/dist/catalog/component-state.d.ts +10 -8
  30. package/dist/catalog/component-state.js +42 -30
  31. package/dist/catalog/dependency-edges.d.ts +25 -0
  32. package/dist/catalog/dependency-edges.js +125 -0
  33. package/dist/catalog/install-status.d.ts +2 -3
  34. package/dist/catalog/install-status.js +2 -3
  35. package/dist/catalog/marketplaces.service.d.ts +1 -1
  36. package/dist/catalog/org-catalog.service.d.ts +3 -1
  37. package/dist/catalog/org-catalog.service.js +33 -94
  38. package/dist/catalog/org-intent.d.ts +43 -0
  39. package/dist/catalog/org-intent.js +184 -0
  40. package/dist/catalog/owned-items.d.ts +1 -1
  41. package/dist/catalog/owned-items.js +9 -29
  42. package/dist/catalog/ownership.d.ts +2 -3
  43. package/dist/catalog/ownership.js +10 -28
  44. package/dist/catalog/platform-components.d.ts +3 -1
  45. package/dist/catalog/platform-components.js +9 -1
  46. package/dist/catalog/plugin-import.js +12 -16
  47. package/dist/catalog/plugin-install.d.ts +3 -4
  48. package/dist/catalog/plugin-install.js +25 -49
  49. package/dist/catalog/plugin-upgrade.d.ts +2 -2
  50. package/dist/catalog/plugin-upgrade.js +18 -34
  51. package/dist/catalog/request-rules.js +20 -8
  52. package/dist/catalog/scope-orgs.js +2 -7
  53. package/dist/catalog/scope-state.d.ts +6 -6
  54. package/dist/catalog/scope-state.js +24 -43
  55. package/dist/catalog/scope-sync.d.ts +0 -2
  56. package/dist/catalog/scope-sync.js +11 -39
  57. package/dist/catalog/scope-writer.d.ts +78 -0
  58. package/dist/catalog/scope-writer.js +181 -0
  59. package/dist/catalog/unshare.js +8 -41
  60. package/dist/channels/connections.service.js +6 -6
  61. package/dist/channels/supervisor.js +3 -7
  62. package/dist/client/client-access.service.js +2 -12
  63. package/dist/config/schema.d.ts +6 -0
  64. package/dist/config/schema.js +29 -1
  65. package/dist/conversations/access.d.ts +15 -7
  66. package/dist/conversations/access.js +59 -10
  67. package/dist/conversations/conversation-agent.d.ts +18 -0
  68. package/dist/conversations/conversation-agent.js +23 -0
  69. package/dist/conversations/conversation-ref.d.ts +3 -2
  70. package/dist/conversations/conversation-ref.js +6 -1
  71. package/dist/conversations/conversations.controller.d.ts +28 -5
  72. package/dist/conversations/conversations.controller.js +99 -10
  73. package/dist/conversations/conversations.module.js +10 -0
  74. package/dist/conversations/conversations.schemas.d.ts +6 -0
  75. package/dist/conversations/conversations.schemas.js +15 -0
  76. package/dist/conversations/conversations.service.d.ts +125 -21
  77. package/dist/conversations/conversations.service.js +260 -90
  78. package/dist/conversations/event-log.d.ts +9 -1
  79. package/dist/conversations/event-log.js +2 -0
  80. package/dist/conversations/events.d.ts +57 -0
  81. package/dist/conversations/events.js +73 -1
  82. package/dist/conversations/external/external-calls.d.ts +75 -0
  83. package/dist/conversations/external/external-calls.js +91 -0
  84. package/dist/conversations/external/external-calls.processor.d.ts +45 -0
  85. package/dist/conversations/external/external-calls.processor.js +144 -0
  86. package/dist/conversations/external/external-conversations.service.d.ts +266 -0
  87. package/dist/conversations/external/external-conversations.service.js +1138 -0
  88. package/dist/conversations/external/external.schemas.d.ts +63 -0
  89. package/dist/conversations/external/external.schemas.js +52 -0
  90. package/dist/conversations/external/token.d.ts +6 -0
  91. package/dist/conversations/external/token.js +6 -0
  92. package/dist/conversations/permission-profile-store.d.ts +4 -1
  93. package/dist/conversations/permission-profiles.controller.d.ts +33 -9
  94. package/dist/conversations/permission-profiles.controller.js +86 -6
  95. package/dist/conversations/prompt-suggestions.js +2 -1
  96. package/dist/conversations/queue.js +2 -1
  97. package/dist/conversations/titles.js +4 -3
  98. package/dist/ctx/create-ctx.d.ts +9 -2
  99. package/dist/ctx/create-ctx.js +47 -62
  100. package/dist/ctx/guard-db.d.ts +6 -0
  101. package/dist/ctx/guard-db.js +55 -0
  102. package/dist/db/extension-handoff-schema.d.ts +1 -1
  103. package/dist/db/extension-handoff-schema.js +48 -10
  104. package/dist/db/extension-schema-transfer.js +5 -2
  105. package/dist/db/kernel-schema.d.ts +42 -5
  106. package/dist/device-access/host-services.d.ts +2 -2
  107. package/dist/device-access/host-services.js +8 -8
  108. package/dist/device-access/person-handles.d.ts +16 -7
  109. package/dist/device-access/person-handles.js +14 -9
  110. package/dist/devices/conversation-devices.d.ts +5 -0
  111. package/dist/devices/conversation-devices.js +16 -0
  112. package/dist/erasure/org-catalog.js +2 -2
  113. package/dist/erasure/org-rules.js +5 -0
  114. package/dist/errors.d.ts +34 -0
  115. package/dist/errors.js +34 -0
  116. package/dist/evals/snapshot.js +3 -1
  117. package/dist/evals/trajectory.service.d.ts +2 -2
  118. package/dist/evals/trajectory.service.js +11 -7
  119. package/dist/extensions/admin-ops.d.ts +9 -5
  120. package/dist/extensions/admin-ops.js +52 -8
  121. package/dist/extensions/admin-view.js +1 -4
  122. package/dist/extensions/bootstrap.js +4 -1
  123. package/dist/extensions/cli.js +1 -0
  124. package/dist/extensions/effective-config.js +1 -4
  125. package/dist/extensions/enabled.d.ts +23 -29
  126. package/dist/extensions/enabled.js +141 -62
  127. package/dist/extensions/extensions.module.js +3 -0
  128. package/dist/extensions/host.d.ts +71 -45
  129. package/dist/extensions/host.js +454 -128
  130. package/dist/extensions/installs.d.ts +9 -0
  131. package/dist/extensions/installs.js +23 -0
  132. package/dist/extensions/isolated/admission.d.ts +10 -0
  133. package/dist/extensions/isolated/admission.js +206 -0
  134. package/dist/extensions/isolated/authorization.d.ts +37 -0
  135. package/dist/extensions/isolated/authorization.js +146 -0
  136. package/dist/extensions/isolated/broker.d.ts +15 -0
  137. package/dist/extensions/isolated/broker.js +452 -0
  138. package/dist/extensions/isolated/child-protocol.d.ts +84 -0
  139. package/dist/extensions/isolated/child-protocol.js +21 -0
  140. package/dist/extensions/isolated/child-registration.d.ts +22 -0
  141. package/dist/extensions/isolated/child-registration.js +152 -0
  142. package/dist/extensions/isolated/child-session.d.ts +6 -0
  143. package/dist/extensions/isolated/child-session.js +343 -0
  144. package/dist/extensions/isolated/child-streams.d.ts +4 -0
  145. package/dist/extensions/isolated/child-streams.js +142 -0
  146. package/dist/extensions/isolated/child.d.ts +1 -0
  147. package/dist/extensions/isolated/child.js +10 -0
  148. package/dist/extensions/isolated/configured-package.d.ts +15 -0
  149. package/dist/extensions/isolated/configured-package.js +73 -0
  150. package/dist/extensions/isolated/lanes.d.ts +100 -0
  151. package/dist/extensions/isolated/lanes.js +699 -0
  152. package/dist/extensions/isolated/postgres-gate.d.ts +14 -0
  153. package/dist/extensions/isolated/postgres-gate.js +255 -0
  154. package/dist/extensions/isolated/revision.d.ts +32 -0
  155. package/dist/extensions/isolated/revision.js +358 -0
  156. package/dist/extensions/isolated/rpc-frame.d.ts +50 -0
  157. package/dist/extensions/isolated/rpc-frame.js +193 -0
  158. package/dist/extensions/isolated/rpc.d.ts +66 -0
  159. package/dist/extensions/isolated/rpc.js +314 -0
  160. package/dist/extensions/isolated/sandbox.d.ts +35 -0
  161. package/dist/extensions/isolated/sandbox.js +372 -0
  162. package/dist/extensions/isolated/tier.d.ts +6 -0
  163. package/dist/extensions/isolated/tier.js +45 -0
  164. package/dist/extensions/ledger.d.ts +1 -1
  165. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  166. package/dist/extensions/lifecycle-topics.js +1 -0
  167. package/dist/extensions/lifecycle.d.ts +3 -1
  168. package/dist/extensions/lifecycle.js +32 -5
  169. package/dist/extensions/locks.d.ts +2 -0
  170. package/dist/extensions/locks.js +7 -0
  171. package/dist/extensions/org-config.d.ts +17 -27
  172. package/dist/extensions/org-config.js +114 -129
  173. package/dist/extensions/permission-view.d.ts +3 -1
  174. package/dist/extensions/permission-view.js +4 -1
  175. package/dist/extensions/plugin-guides.d.ts +5 -10
  176. package/dist/extensions/plugin-guides.js +18 -37
  177. package/dist/extensions/plugin-icons.d.ts +3 -21
  178. package/dist/extensions/plugin-icons.js +9 -44
  179. package/dist/extensions/plugin-items.d.ts +10 -30
  180. package/dist/extensions/plugin-items.js +32 -73
  181. package/dist/extensions/point-defaults.d.ts +13 -21
  182. package/dist/extensions/point-defaults.js +32 -72
  183. package/dist/extensions/point-serving.d.ts +56 -0
  184. package/dist/extensions/point-serving.js +120 -0
  185. package/dist/extensions/source-intent.d.ts +14 -0
  186. package/dist/extensions/source-intent.js +77 -0
  187. package/dist/inbox/inbox-items.service.d.ts +11 -0
  188. package/dist/inbox/inbox-items.service.js +39 -0
  189. package/dist/index.d.ts +2 -1
  190. package/dist/index.js +2 -1
  191. package/dist/infra/database/database.module.js +6 -1
  192. package/dist/infra/database/kernel-db.d.ts +3 -1
  193. package/dist/infra/database/kernel-db.js +4 -0
  194. package/dist/infra/outbox/registry.d.ts +70 -0
  195. package/dist/infra/outbox/registry.js +44 -0
  196. package/dist/infra/paging/paged-read.d.ts +56 -0
  197. package/dist/infra/paging/paged-read.js +78 -0
  198. package/dist/infra/queue/queue-names.d.ts +1 -1
  199. package/dist/infra/queue/queue-names.js +1 -0
  200. package/dist/kernel.d.ts +3 -2
  201. package/dist/kernel.js +21 -2
  202. package/dist/kernel.module.js +4 -0
  203. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  204. package/dist/lifecycle/kernel-lifecycle.js +22 -12
  205. package/dist/lifecycle/tokens.d.ts +8 -0
  206. package/dist/lifecycle/tokens.js +2 -0
  207. package/dist/orgs/directory-sync.js +1 -4
  208. package/dist/platform/exclusions.js +10 -0
  209. package/dist/platform/ops/admin.ops.js +14 -3
  210. package/dist/platform/ops/conversations.ops.d.ts +8 -1
  211. package/dist/platform/ops/conversations.ops.js +52 -14
  212. package/dist/platform/ops/orgs.ops.js +13 -3
  213. package/dist/plugin-reads/plugin-reads.service.js +4 -1
  214. package/dist/push/recipients.js +5 -2
  215. package/dist/retention/worker.js +2 -1
  216. package/dist/roles/worker-role.d.ts +3 -1
  217. package/dist/roles/worker-role.js +8 -2
  218. package/dist/roles/worker.module.js +3 -0
  219. package/dist/runtime/context/build.js +8 -0
  220. package/dist/runtime/context/compaction.js +7 -0
  221. package/dist/runtime/idle-arm.js +3 -1
  222. package/dist/runtime/idle-compaction.js +2 -1
  223. package/dist/runtime/run-finish.js +2 -1
  224. package/dist/runtime/run-jobs.js +2 -1
  225. package/dist/runtime/run-queue.js +4 -2
  226. package/dist/runtime/run-worker.js +5 -2
  227. package/dist/runtime/stream.js +10 -0
  228. package/dist/runtime/usage-report.js +2 -1
  229. package/dist/runtime/waits.js +2 -1
  230. package/dist/setup/setup-checks.service.js +3 -2
  231. package/dist/skills/usable.js +41 -30
  232. package/dist/themes/theme-state.js +3 -3
  233. package/dist/tools/approvals.service.js +6 -2
  234. package/dist/tools/builtins/skill-load.js +3 -2
  235. package/dist/tools/registry.d.ts +1 -1
  236. package/dist/tools/registry.js +1 -1
  237. package/dist/tools/tool-watch.service.js +3 -1
  238. package/package.json +3 -3
  239. package/src/migrations/0227_external_conversations.sql +33 -0
  240. package/src/migrations/0228_extension_org_switches.sql +56 -0
  241. package/src/migrations/0229_catalog_dependency_edges.sql +17 -0
  242. package/src/migrations/0230_audit_filter_idx.sql +18 -0
@@ -16,8 +16,10 @@ import { Inject, Injectable, Optional } from "@nestjs/common";
16
16
  import { ModuleRef } from "@nestjs/core";
17
17
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
18
18
  import { changedPaths, configFields, getPath, secretValues, unreachableSecrets, } from "../config/fields.js";
19
+ import { EXTERNAL_CONVERSATIONS_BACKEND } from "../conversations/external/token.js";
19
20
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
20
21
  import { ExtensionEffects } from "../ctx/durable-effects.service.js";
22
+ import { ExtensionEffectKeys } from "../ctx/durable-keys.js";
21
23
  import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
22
24
  import { ConfiguredExtensionDbIdentity, extensionDbIdentity, extensionDbPool, } from "../db/extension-db.js";
23
25
  import { ensureLocalExtensionHandoff } from "../db/extension-handoff-schema.js";
@@ -31,9 +33,10 @@ import { INBOX_ITEMS_BACKEND } from "../inbox/token.js";
31
33
  import { waitWithin } from "../infra/close-within.js";
32
34
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
33
35
  import { KernelDb } from "../infra/database/kernel-db.js";
36
+ import { withOrgScope } from "../infra/database/org-scope.js";
34
37
  import { LockService } from "../infra/lock/lock.service.js";
35
38
  import { KERNEL_LOGGER, KEYRING, REDIS, REDIS_SUBSCRIBER } from "../infra/tokens.js";
36
- import { KERNEL_APP_OPTIONS } from "../lifecycle/tokens.js";
39
+ import { KERNEL_APP_OPTIONS, KERNEL_FIXTURE_TRUST, } from "../lifecycle/tokens.js";
37
40
  import { ModelEmbeddings } from "../models/embeddings.js";
38
41
  import { ModelImages } from "../models/images.js";
39
42
  import { OrgNetworkAllowances } from "../orgs/network-allowances.service.js";
@@ -42,7 +45,7 @@ import { PLUGIN_READS_BACKEND } from "../plugin-reads/token.js";
42
45
  import { DeviceReports } from "../sandbox/device-reports.js";
43
46
  import { ShareLiveness } from "../shares/liveness.js";
44
47
  import { EmbedTokens } from "../ui/embed-token.js";
45
- import { ExtensionApprovals, planApprovals, readSnapshots, withPreApproved, } from "./approvals.js";
48
+ import { ExtensionApprovals, planApprovals, readSnapshots, snapshotCovers, withPreApproved, } from "./approvals.js";
46
49
  import { ExtensionBlobIntegrityError } from "./blobs.js";
47
50
  import { deploymentConfigHash } from "./config-hash.js";
48
51
  import { toIssues } from "./config-issues.js";
@@ -51,6 +54,12 @@ import { EffectiveConfigs } from "./effective-config.js";
51
54
  import { HookRegistry } from "./hooks.js";
52
55
  import { ExtensionInstalls } from "./installs.js";
53
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";
54
63
  import { parseLoadGate } from "./org-levels.js";
55
64
  import { declaredDisplayName, permissionSetOfSection, readMigrationSql } from "./package.js";
56
65
  import { blockingKeys, computePermissionSet, SETUP_CHECK_KEY_PREFIX, UI_VIEW_KEY_PREFIX, } from "./permission-set.js";
@@ -104,15 +113,37 @@ function toFileUrl(spec, resolveFrom) {
104
113
  });
105
114
  }
106
115
  }
107
- /** 按顺序导入各 specifier 的插件模块(不排序);同时给出模块所在目录。 */
108
- 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) {
109
118
  const entries = [];
110
119
  for (const spec of specifiers) {
111
- 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));
112
135
  entries.push({
113
- manifest: await importExtensionModule(url, spec, resolveFrom),
114
- dir: dirname(fileURLToPath(url)),
115
- 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
+ },
116
147
  });
117
148
  }
118
149
  return entries;
@@ -139,10 +170,13 @@ async function packageNameOf(dir) {
139
170
  }
140
171
  }
141
172
  /** 计算各插件的权限集合(按插件名索引)。 */
142
- async function permissionSets(ordered, dirs) {
173
+ async function permissionSets(ordered, dirs, isolated = new Map()) {
143
174
  const sets = new Map();
144
175
  for (const m of ordered) {
145
- 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)));
146
180
  }
147
181
  return sets;
148
182
  }
@@ -237,7 +271,18 @@ function manifestOfSection(m) {
237
271
  },
238
272
  };
239
273
  }
240
- /** 插件宿主:解析、校验配置、迁移、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. */
241
286
  let ExtensionHost = class ExtensionHost {
242
287
  registry;
243
288
  installs;
@@ -245,7 +290,10 @@ let ExtensionHost = class ExtensionHost {
245
290
  status;
246
291
  config;
247
292
  log;
293
+ options;
248
294
  effective;
295
+ allowances;
296
+ modules;
249
297
  dbIdentity;
250
298
  /**
251
299
  * Only resolves extensions and runs migrations in dependency order: no deployment config check, no
@@ -259,8 +307,9 @@ let ExtensionHost = class ExtensionHost {
259
307
  */
260
308
  static async migrateOnly(specifiers, opts) {
261
309
  const from = resolvePath(opts.resolveFrom ?? process.cwd());
262
- 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"));
263
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]] : [])));
264
313
  const ordered = resolveExtensions(entries.map((e) => e.manifest), SDK_VERSION);
265
314
  for (const manifest of ordered)
266
315
  assertSecretsReachable(manifest);
@@ -270,7 +319,7 @@ let ExtensionHost = class ExtensionHost {
270
319
  }
271
320
  let toMigrate = ordered;
272
321
  if (!opts.autoApprove && ordered.length > 0) {
273
- const sets = await permissionSets(ordered, dirs);
322
+ const sets = await permissionSets(ordered, dirs, isolation);
274
323
  const raw = createDb(opts.dbUrl, 1, () => { }, { connectTimeoutMs: opts.connectTimeoutMs });
275
324
  let decisions;
276
325
  try {
@@ -287,20 +336,26 @@ let ExtensionHost = class ExtensionHost {
287
336
  }
288
337
  const out = [];
289
338
  for (const manifest of toMigrate) {
290
- 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);
291
351
  if (r)
292
352
  out.push({ plugin: manifest.name, ...r });
293
353
  }
294
354
  return out;
295
355
  }
296
- /**
297
- * The names of the config-declared extensions (`specifiers`, the startup config `extensions`
298
- * list): imports their modules only (the same modules `load()` imports next, from Node's module
299
- * cache). The kernel passes them to the bootstrap step before loading, so a bootstrap entry of
300
- * the same name is kept and gets no install record (config wins, C15).
301
- */
356
+ /** Reads configured package identities for bootstrap without starting extension code. */
302
357
  static async declaredNames(specifiers, opts = {}) {
303
- 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);
304
359
  return new Set(entries.map((e) => e.manifest.name));
305
360
  }
306
361
  /**
@@ -309,21 +364,35 @@ let ExtensionHost = class ExtensionHost {
309
364
  */
310
365
  static async inspect(specifiers, opts = {}) {
311
366
  const from = resolvePath(opts.resolveFrom ?? process.cwd());
312
- const entries = await importEntries(specifiers, from);
367
+ const entries = await importEntries(specifiers, from, opts[KERNEL_FIXTURE_TRUST] !== undefined, opts.maxPackageBytes);
313
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]] : [])));
314
370
  const ordered = resolveExtensions(entries.map((e) => e.manifest), SDK_VERSION);
315
371
  for (const manifest of ordered)
316
372
  assertSecretsReachable(manifest);
317
- const sets = await permissionSets(ordered, dirs);
373
+ const sets = await permissionSets(ordered, dirs, isolation);
318
374
  const out = [];
319
375
  for (const manifest of ordered) {
320
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
+ }
321
387
  out.push({
322
388
  source: "config",
323
- manifest,
389
+ ...(source && { isolated: true }),
390
+ manifest: inspected,
324
391
  dir,
325
392
  permissions: sets.get(manifest.name),
326
- displayName: (await declaredDisplayName(dir, manifest.name)).displayName ?? null,
393
+ displayName: source
394
+ ? (source.displayName ?? null)
395
+ : ((await declaredDisplayName(dir, manifest.name)).displayName ?? null),
327
396
  });
328
397
  }
329
398
  return out;
@@ -332,6 +401,12 @@ let ExtensionHost = class ExtensionHost {
332
401
  * M-1: plugin → mount points where deployment state expects `policy` hooks. A per-replica copy of PG
333
402
  * deployment state (like the registry), rebuilt on every load / converge, never written elsewhere.
334
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();
335
410
  policyExpected = new Map();
336
411
  /**
337
412
  * Runs the hooks of this process's active plugin instances (resolved from the registry on every
@@ -454,6 +529,8 @@ let ExtensionHost = class ExtensionHost {
454
529
  * `TriggerEventsService` (`ctx.triggers`, {@link TRIGGER_EVENTS_BACKEND}) and
455
530
  * `InboxItemsService` (`ctx.inbox`, {@link INBOX_ITEMS_BACKEND}) and `PluginReadsService`
456
531
  * (`ctx.agents`, `ctx.conversations`, `ctx.people`, {@link PLUGIN_READS_BACKEND}) and
532
+ * `ExternalConversationsService` (`ctx.conversations`' external methods,
533
+ * {@link EXTERNAL_CONVERSATIONS_BACKEND}) and
457
534
  * `ServiceEvents` (`ctx.devices.serviceEvent`, {@link SERVICE_EVENTS_BACKEND}) likewise.
458
535
  */
459
536
  modules,
@@ -465,7 +542,10 @@ let ExtensionHost = class ExtensionHost {
465
542
  this.status = status;
466
543
  this.config = config;
467
544
  this.log = log;
545
+ this.options = options;
468
546
  this.effective = effective;
547
+ this.allowances = allowances;
548
+ this.modules = modules;
469
549
  this.dbIdentity = dbIdentity;
470
550
  const c = config.get();
471
551
  this.hooks = new HookRegistry({
@@ -542,6 +622,14 @@ let ExtensionHost = class ExtensionHost {
542
622
  return undefined;
543
623
  }
544
624
  },
625
+ externalConversations: () => {
626
+ try {
627
+ return modules?.get(EXTERNAL_CONVERSATIONS_BACKEND, { strict: false });
628
+ }
629
+ catch {
630
+ return undefined;
631
+ }
632
+ },
545
633
  locks,
546
634
  runWorkers: c.roles.includes("worker"),
547
635
  log,
@@ -639,7 +727,26 @@ let ExtensionHost = class ExtensionHost {
639
727
  this.didLoad = true;
640
728
  const p = Array.isArray(plan) ? { config: plan } : plan;
641
729
  this.installLoader = p.installs;
642
- const entries = await importEntries(p.config ?? [], this.resolveFrom);
730
+ const isolation = this.config.get().extensionHost.isolation;
731
+ if (isolation) {
732
+ await sweepExtensionSandboxOrphans(isolation.dockerSocket).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
+ }
643
750
  await this.claimNames(entries);
644
751
  await this.noteDisplayNames(entries);
645
752
  const dirs = new Map(entries.map((e) => [e.manifest.name, e.dir]));
@@ -650,11 +757,11 @@ let ExtensionHost = class ExtensionHost {
650
757
  : { ready: entries.map((e) => e.manifest), deferred: [] };
651
758
  const ordered = resolveExtensions(ready, SDK_VERSION);
652
759
  for (const e of entries)
653
- this.sources.set(e.manifest.name, { source: "config", sha256: null });
760
+ this.sources.set(e.manifest.name, { source: "config", sha256: e.isolated?.digest ?? null });
654
761
  this.registry.declare(entries.map((e) => e.manifest.name));
655
762
  for (const e of entries)
656
763
  assertSecretsReachable(e.manifest);
657
- const sets = await permissionSets(ordered, dirs);
764
+ const sets = await permissionSets(ordered, dirs, this.declaredIsolation);
658
765
  this.noteDeclared(ordered, sets);
659
766
  const approvals = this.approvals;
660
767
  if (this.autoApprove) {
@@ -668,9 +775,10 @@ let ExtensionHost = class ExtensionHost {
668
775
  await this.activate(approvals, {
669
776
  manifest,
670
777
  source: this.sourceOf(manifest.name),
671
- sha256: null,
778
+ isolated: this.declaredIsolation.get(manifest.name),
779
+ sha256: this.declaredIsolation.get(manifest.name)?.digest ?? null,
672
780
  entryUrl: urls.get(manifest.name),
673
- migrationsDir: migrationsDirOf(manifest, dirs.get(manifest.name)),
781
+ migrationsDir: this.declaredMigrationDirectory(manifest, dirs),
674
782
  set: sets.get(manifest.name),
675
783
  decision: this.blockedByUnloaded(manifest, decisions.get(manifest.name)),
676
784
  fatal: true,
@@ -684,9 +792,8 @@ let ExtensionHost = class ExtensionHost {
684
792
  desired = await p.installs.desired();
685
793
  }
686
794
  catch (e) {
687
- this.log.error("cannot read extension install records; installed extensions are not loaded", {
688
- err: e,
689
- });
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 });
690
797
  }
691
798
  if (desired) {
692
799
  // Packages kept in PG first: the object store serving the others may be one of them (a
@@ -702,7 +809,7 @@ let ExtensionHost = class ExtensionHost {
702
809
  if (deferred.length > 0) {
703
810
  await this.loadDeferred(deferred, dirs, urls, snapshots, approvals, installProviders);
704
811
  }
705
- await this.refreshPolicyExpectations(p.installs ? desired : []);
812
+ await this.refreshPolicyExpectations(desired ?? []);
706
813
  const orphans = Object.keys(this.extensionConfig).filter((k) => !this.sources.has(k));
707
814
  if (orphans.length > 0) {
708
815
  this.log.warn("extensionConfig has keys for extensions that are not loaded", {
@@ -736,7 +843,7 @@ let ExtensionHost = class ExtensionHost {
736
843
  async claimNames(entries) {
737
844
  const rows = [];
738
845
  for (const e of entries) {
739
- const pkg = await packageNameOf(e.dir);
846
+ const pkg = e.isolated?.npmName ?? (await packageNameOf(e.dir));
740
847
  if (pkg === undefined) {
741
848
  this.log.warn("plugin module has no package.json name; its plugin name is not claimed", {
742
849
  plugin: e.manifest.name,
@@ -813,18 +920,19 @@ let ExtensionHost = class ExtensionHost {
813
920
  if (values.length > 0)
814
921
  this.log.addSecrets(values);
815
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
+ }
816
930
  /**
817
- * 安装记录收敛到 PG 期望状态(启动第 3 步与运行中的 {@link converge} 共用,C16);`desired` 为期望启用的记录。
818
- * 1. 不再期望启用的(停用 / 卸载):卸下(排空在途调用),未加载但写过状态行的标为 unloaded;
819
- * 2. 期望启用、本副本已在目标包上的:不动;
820
- * 3. 其余:准备候选(同步 → 按静态清单与迁移 SQL 算权限集合;失败记 failed:`sync_failed` / `sha_mismatch`),
821
- * 与生效的插件一起按依赖拓扑序逐个处理:权限闸门(新增权限待批准 → pending / approval,旧实例照常)、
822
- * 必需能力(此刻没有生效的提供方 → pending / dependency)、导入模块并核对静态清单(`import_failed` /
823
- * `manifest_mismatch`;闸门放行之前不导入)、部署配置、
824
- * 持锁迁移(busy → pending / migration)、setup,成功后登记新实例(先加载新、再撤销旧:旧实例在后台排空后撤销);
825
- * 任何一步失败旧实例保留,记 failed(`migration_failed` / `setup_failed`)。
826
- * 4. 运行中(非启动):对变了的能力做依赖方连锁(本轮刚加载的除外),此前因依赖卸下的插件随之补回。
827
- * 返回启用的安装记录在静态清单里声明提供的能力(启动第 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.
828
936
  */
829
937
  async applyInstalls(loader, desired, startup,
830
938
  /**
@@ -836,13 +944,32 @@ let ExtensionHost = class ExtensionHost {
836
944
  const declared = this.declared();
837
945
  const installProviders = new Map();
838
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
+ }
839
966
  // Single-provider election: of the enabled install records providing one single-provider
840
967
  // extension point, only the earliest enabled is loaded (desired() order: enabled_at, install
841
968
  // time, name). Decided from PG alone, never from what loaded here, so every replica and every
842
969
  // restart picks the same one. Two enabled providers only remain from before a second enable
843
970
  // was refused; the others are pending / conflict until the super admin disables one. A loser
844
971
  // provides nothing (left out of `installProviders`, so `blockedBy` never names it).
845
- const { losers } = electSingleProviders(electAmong.filter((d) => !declared.has(d.name)));
972
+ const { losers } = electSingleProviders(electAmong.filter((d) => tiers.has(d.name)));
846
973
  for (const d of desired) {
847
974
  const taken = declared.get(d.name);
848
975
  if (taken) {
@@ -854,7 +981,7 @@ let ExtensionHost = class ExtensionHost {
854
981
  }
855
982
  continue;
856
983
  }
857
- if (losers.has(d.name))
984
+ if (losers.has(d.name) || !tiers.has(d.name))
858
985
  continue;
859
986
  wanted.set(d.name, d);
860
987
  // 按审阅过的静态清单(不论随后加载成败)
@@ -863,9 +990,15 @@ let ExtensionHost = class ExtensionHost {
863
990
  }
864
991
  }
865
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
+ }
866
999
  const drainMs = this.drainMs();
867
1000
  const changed = [];
868
- // 1. 不再期望启用:卸下;未加载但写过状态行的标为 unloaded
1001
+ // Unload withdrawn instances and clear stale serving status.
869
1002
  for (const inst of this.registry.all()) {
870
1003
  if (inst.source !== "install" || wanted.has(inst.name))
871
1004
  continue;
@@ -889,13 +1022,54 @@ let ExtensionHost = class ExtensionHost {
889
1022
  detail: null,
890
1023
  });
891
1024
  }
892
- // 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
+ }
893
1038
  const candidates = [];
894
1039
  for (const d of wanted.values()) {
895
1040
  if (this.closed)
896
1041
  throw new Error(CLOSED_DURING_LOAD);
897
- 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) {
898
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
+ }
899
1073
  const c = await this.prepare(loader, d);
900
1074
  if (c)
901
1075
  candidates.push(c);
@@ -987,8 +1161,10 @@ let ExtensionHost = class ExtensionHost {
987
1161
  continue;
988
1162
  if (this.closed)
989
1163
  throw new Error(CLOSED_DURING_LOAD);
1164
+ const isolated = tiers.get(m.name) === "isolated";
990
1165
  const a = {
991
1166
  manifest: c.manifest,
1167
+ ...(isolated && { isolated: { root: c.root, section: c.d.section } }),
992
1168
  source: "install",
993
1169
  optionalBootstrap: c.d.source === "bootstrap" && !c.d.required,
994
1170
  sha256: c.d.sha256,
@@ -998,13 +1174,14 @@ let ExtensionHost = class ExtensionHost {
998
1174
  decision: { plugin: m.name, action: "pending" },
999
1175
  fatal: false,
1000
1176
  migrate: () => loader.migrate(c.d, c.migrationsDir, this.abort.signal),
1001
- importModule: () => this.importInstalled(c),
1177
+ ...(!isolated && { importModule: () => this.importInstalled(c) }),
1002
1178
  };
1003
1179
  a.decision = this.decidePending(m.name, a, snapshots, installProviders);
1004
1180
  const old = this.registry.current(m.name);
1005
1181
  // 安装记录不受信任:启动时 setup 同样限时(I3),挂住的 setup 不卡住内核启动;配置声明的启动时不限
1006
1182
  const inst = await this.activate(approvals, a, this.reloadSetupTimeoutMs());
1007
1183
  if (inst) {
1184
+ this.executionTier.set(m.name, isolated ? "isolated" : "trusted");
1008
1185
  activated.add(m.name);
1009
1186
  changed.push(...inst.manifest.provides, ...(old?.manifest.provides ?? []));
1010
1187
  }
@@ -1147,7 +1324,7 @@ let ExtensionHost = class ExtensionHost {
1147
1324
  else
1148
1325
  this.pendingPlugins.push(p);
1149
1326
  }
1150
- /** 从待定清单里去掉。 */
1327
+ /** Removes an extension from the pending list. */
1151
1328
  dropPending(plugin) {
1152
1329
  const at = this.pendingPlugins.findIndex((x) => x.plugin === plugin);
1153
1330
  if (at >= 0)
@@ -1160,12 +1337,21 @@ let ExtensionHost = class ExtensionHost {
1160
1337
  * 与「配置声明插件依赖待批准的配置声明插件」一致,内核照常启动;
1161
1338
  * - 缺的能力没有任何提供方 → 与此前一样抛错(内核启动失败)。
1162
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
+ }
1163
1349
  async loadDeferred(deferred, dirs, urls, snapshots, approvals, installProviders) {
1164
1350
  if (this.closed)
1165
1351
  throw new Error(CLOSED_DURING_LOAD);
1166
1352
  const loaded = this.registry.all();
1167
1353
  const { ready, deferred: blocked } = splitDeferred([...loaded.map((i) => i.manifest), ...deferred], new Set(deferred.map((m) => m.name)));
1168
- const deferredSets = await permissionSets(deferred, dirs);
1354
+ const deferredSets = await permissionSets(deferred, dirs, this.declaredIsolation);
1169
1355
  this.noteDeclared(deferred, deferredSets);
1170
1356
  const sets = new Map([...loaded.map((i) => [i.name, i.permissions]), ...deferredSets]);
1171
1357
  const blockedProvides = new Set(blocked.flatMap((m) => m.provides));
@@ -1190,9 +1376,10 @@ let ExtensionHost = class ExtensionHost {
1190
1376
  await this.activate(approvals, {
1191
1377
  manifest: m,
1192
1378
  source: "config",
1193
- sha256: null,
1379
+ isolated: this.declaredIsolation.get(m.name),
1380
+ sha256: this.declaredIsolation.get(m.name)?.digest ?? null,
1194
1381
  entryUrl: urls.get(m.name),
1195
- migrationsDir: migrationsDirOf(m, dirs.get(m.name)),
1382
+ migrationsDir: this.declaredMigrationDirectory(m, dirs),
1196
1383
  set: sets.get(m.name),
1197
1384
  decision: {
1198
1385
  plugin: m.name,
@@ -1221,9 +1408,10 @@ let ExtensionHost = class ExtensionHost {
1221
1408
  await this.activate(approvals, {
1222
1409
  manifest,
1223
1410
  source: "config",
1224
- sha256: null,
1411
+ isolated: this.declaredIsolation.get(manifest.name),
1412
+ sha256: this.declaredIsolation.get(manifest.name)?.digest ?? null,
1225
1413
  entryUrl: urls.get(manifest.name),
1226
- migrationsDir: migrationsDirOf(manifest, dirs.get(manifest.name)),
1414
+ migrationsDir: this.declaredMigrationDirectory(manifest, dirs),
1227
1415
  set: sets.get(manifest.name),
1228
1416
  // 同一批里的提供方可能刚记为待配置:依赖方改为待定,不让启动失败
1229
1417
  decision: this.blockedByUnloaded(manifest, decisions.get(manifest.name)),
@@ -1308,22 +1496,31 @@ let ExtensionHost = class ExtensionHost {
1308
1496
  }
1309
1497
  }
1310
1498
  /**
1311
- * 加载一个插件:权限闸门结论、部署配置、迁移、setup、登记。`fatal` 时(配置声明)出错直接抛;
1312
- * 否则(安装记录)记 failed 后返回。部署配置不合法时(任何来源)只记 pending(reason config),不抛(C10)。
1313
- * 已有同名实例时(升级):新实例登记后旧实例才撤销(后台排空在途调用);新实例没加载成时旧实例保持不变。
1314
- * 返回新登记的实例(没有加载时返回 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.
1315
1502
  */
1316
1503
  async activate(approvals, a, setupTimeoutMs) {
1317
1504
  const { decision } = a;
1318
1505
  let manifest = a.manifest;
1319
1506
  const name = manifest.name;
1320
1507
  const base = { plugin: name, version: manifest.version, sha256: a.sha256, source: a.source };
1321
- 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) => {
1322
1514
  this.logFailure(name, a.sha256, reason, e, { version: manifest.version });
1323
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();
1324
1521
  return undefined;
1325
1522
  };
1326
- // 安装记录:闸门放行之后才导入真实模块(I1:批准之前不执行插件代码);待批准时只有静态清单,不读部署配置
1523
+ // Approved trusted installs may import here. Pending installs use only their static manifest.
1327
1524
  if (a.importModule && decision.action !== "pending") {
1328
1525
  try {
1329
1526
  manifest = await a.importModule();
@@ -1334,13 +1531,17 @@ let ExtensionHost = class ExtensionHost {
1334
1531
  return failSoft(e instanceof ManifestMismatchError ? "manifest_mismatch" : "import_failed", e);
1335
1532
  }
1336
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
+ }
1337
1543
  const schema = manifest.config?.deployment;
1338
- // 安装记录每次 converge 都按 PG 重新判定,不进 pendingActivations
1339
- const retryLater = () => {
1340
- if (a.source !== "install")
1341
- this.pendingActivations.set(name, a);
1342
- };
1343
- const readConfig = !(a.importModule && decision.action === "pending");
1544
+ const readConfig = !((a.importModule || a.isolated) && decision.action === "pending");
1344
1545
  let raw;
1345
1546
  try {
1346
1547
  if (readConfig)
@@ -1439,10 +1640,29 @@ let ExtensionHost = class ExtensionHost {
1439
1640
  }
1440
1641
  if (this.closed)
1441
1642
  throw new Error(CLOSED_DURING_LOAD);
1442
- // 安装记录:一个副本持锁迁移(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
+ }
1443
1658
  const migrating = a.migrate
1444
1659
  ? a.migrate()
1445
- : 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);
1446
1666
  this.migrating = migrating;
1447
1667
  try {
1448
1668
  if ((await migrating) === "busy") {
@@ -1458,7 +1678,7 @@ let ExtensionHost = class ExtensionHost {
1458
1678
  catch (e) {
1459
1679
  if (this.closed)
1460
1680
  throw new Error(CLOSED_DURING_LOAD, { cause: e });
1461
- if (a.fatal)
1681
+ if (a.fatal && !a.isolated)
1462
1682
  throw e;
1463
1683
  return failSoft("migration_failed", e);
1464
1684
  }
@@ -1469,6 +1689,7 @@ let ExtensionHost = class ExtensionHost {
1469
1689
  throw new Error(CLOSED_DURING_LOAD);
1470
1690
  const spec = {
1471
1691
  manifest,
1692
+ isolated: a.isolated,
1472
1693
  entryUrl: a.entryUrl,
1473
1694
  source: a.source,
1474
1695
  sha256: a.sha256,
@@ -1483,7 +1704,7 @@ let ExtensionHost = class ExtensionHost {
1483
1704
  catch (e) {
1484
1705
  if (this.closed)
1485
1706
  throw new Error(CLOSED_DURING_LOAD, { cause: e });
1486
- if (a.fatal)
1707
+ if (a.fatal && !a.isolated)
1487
1708
  throw e;
1488
1709
  return failSoft("setup_failed", e);
1489
1710
  }
@@ -1499,6 +1720,8 @@ let ExtensionHost = class ExtensionHost {
1499
1720
  this.declaredActivations.set(name, a);
1500
1721
  this.unloadedForDependency.delete(name);
1501
1722
  const old = this.registry.activate(inst);
1723
+ if (old)
1724
+ this.isolatedAuthority.get(old)?.abort();
1502
1725
  this.loggedFailures.delete(name);
1503
1726
  await this.writeStatus({
1504
1727
  ...base,
@@ -1563,66 +1786,44 @@ let ExtensionHost = class ExtensionHost {
1563
1786
  activatePending() {
1564
1787
  return this.serial(() => this.activatePendingNow());
1565
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
+ revalidateIsolatedInvocations() {
1798
+ return this.isolatedGrants.revalidate();
1799
+ }
1566
1800
  /**
1567
- * 本副本收敛到部署的期望状态(T14 reconcile 的一步,与 unload / reload 串行):
1568
- * 1. 待定的配置声明插件(批准后、或运行中加载失败的)按此刻的快照与生效的提供方重试;
1569
- * 2. 安装记录按 PG 期望状态收敛(见 {@link applyInstalls}:停用 / 卸载的卸下,换包的先加载新再撤销旧,
1570
- * 失败的每次重试),之后做依赖方连锁;
1571
- * 3. 再试一次第 1 步(安装记录提供的能力可能放行了依赖它的配置声明插件)。
1572
- * 读不到安装记录时只做第 1 步并抛错(调用方记日志,下一个周期再来)。
1801
+ * Publish approved policy expectations before doing work that might leave a handler temporarily
1802
+ * unavailable. Re-read after activation, which may have persisted new permission approvals.
1573
1803
  */
1574
1804
  converge() {
1575
1805
  return this.serial(async () => {
1576
- await this.activatePendingNow();
1577
1806
  const loader = this.installLoader;
1578
- if (!loader)
1579
- return;
1580
- const desired = await loader.desired();
1581
- // N-2: drop plugins no longer desired before applyInstalls unloads them (the drain can take
1582
- // extensionHost.drainSeconds; meanwhile a disabled policy plugin must not fail calls closed).
1583
- // Shrink only: plugins that are newly expected are added after they had their chance to load.
1584
- await this.refreshPolicyExpectations(desired, { shrinkOnly: true });
1585
- await this.applyInstalls(loader, desired, false);
1586
- if (this.pendingActivations.size > 0)
1587
- await this.activatePendingNow();
1807
+ const desired = (await loader?.desired()) ?? [];
1808
+ await this.refreshPolicyExpectations(desired);
1809
+ await this.activatePendingNow();
1810
+ if (loader) {
1811
+ await this.applyInstalls(loader, desired, false);
1812
+ if (this.pendingActivations.size > 0)
1813
+ await this.activatePendingNow();
1814
+ }
1588
1815
  await this.refreshPolicyExpectations(desired);
1589
1816
  });
1590
1817
  }
1591
- /**
1592
- * Refreshes {@link policyExpected} from deployment state (M-1):
1593
- * config-declared plugins and enabled installs (`desired`) from their approved permission snapshot.
1594
- * `desired` undefined (install records unreadable) keeps the previous install entries.
1595
- * `shrinkOnly`: only remove entries (a plugin no longer desired or approved), never add new ones.
1596
- */
1597
- async refreshPolicyExpectations(desired, opts = {}) {
1818
+ /** Policy expectations follow approval and deployment state for every execution tier. */
1819
+ async refreshPolicyExpectations(desired) {
1598
1820
  const snapshots = await this.approvals.all();
1821
+ const names = new Set([...this.declaredInfo.keys(), ...desired.map(({ name }) => name)]);
1599
1822
  const next = new Map();
1600
- const add = (name, set) => {
1601
- const mounts = set?.permissions?.policyHooks ?? [];
1823
+ for (const name of names) {
1824
+ const mounts = snapshots.get(name)?.permissions.permissions.policyHooks ?? [];
1602
1825
  if (mounts.length > 0)
1603
1826
  next.set(name, [...mounts]);
1604
- };
1605
- for (const name of this.declaredInfo.keys()) {
1606
- add(name, snapshots.get(name)?.permissions);
1607
- }
1608
- const declared = this.declared();
1609
- if (desired === undefined) {
1610
- for (const [name, mounts] of this.policyExpected) {
1611
- if (!this.declaredInfo.has(name))
1612
- next.set(name, mounts);
1613
- }
1614
- }
1615
- else {
1616
- for (const d of desired) {
1617
- if (!declared.has(d.name))
1618
- add(d.name, snapshots.get(d.name)?.permissions);
1619
- }
1620
- }
1621
- if (opts.shrinkOnly) {
1622
- for (const name of [...next.keys()]) {
1623
- if (!this.policyExpected.has(name))
1624
- next.delete(name);
1625
- }
1626
1827
  }
1627
1828
  this.policyExpected = next;
1628
1829
  }
@@ -1770,7 +1971,7 @@ let ExtensionHost = class ExtensionHost {
1770
1971
  return this.registry.declared();
1771
1972
  }
1772
1973
  /**
1773
- * Extensions enabled in the org: `extension_org_configs.enabled` plus every always-on extension
1974
+ * Extensions enabled in the org: the org intent projection
1774
1975
  * (required bootstrap plugins, builtin plugins' extensions; see `enabled.ts`); queried every
1775
1976
  * time, not cached.
1776
1977
  * Cost (M-4): hooks call this on every run, so one PG query per model attempt and per tool call.
@@ -1783,7 +1984,7 @@ let ExtensionHost = class ExtensionHost {
1783
1984
  /**
1784
1985
  * The access behind an extension's `ctx.extensionPoints`: only active instances in the registry
1785
1986
  * (dependencies load in topological order, so the depended-on are ready first); org enablement is
1786
- * read from `extension_org_configs` every time, not cached. Resolved live on every call: once a
1987
+ * read from PostgreSQL every time, not cached. Resolved live on every call: once a
1787
1988
  * provider is revoked it is no longer returned.
1788
1989
  */
1789
1990
  extensionPointAccess = {
@@ -1806,23 +2007,120 @@ let ExtensionHost = class ExtensionHost {
1806
2007
  };
1807
2008
  }
1808
2009
  /**
1809
- * 按加载参数建一个新实例(setup 期间的 ctx 记在 `settingUp`,close() 时立即关闭)。
1810
- * `timeoutMs`(运行中重新加载):setup 超时或宿主被关闭时关闭这个 ctx 并抛错;迟到完成的实例随即撤销。
1811
- * 配置声明的插件启动时不设时限(见 {@link load})。
2010
+ * Build a new generation. Track its context during setup so shutdown can close it immediately.
2011
+ * A reload deadline closes incomplete setup and any late instance that reaches registration.
1812
2012
  */
1813
2013
  async setup(spec, timeoutMs) {
1814
2014
  if (this.imports.record(spec.manifest.name, spec.entryUrl)) {
1815
2015
  warnUpgrades(this.log, this.imports);
1816
2016
  }
1817
2017
  let ctx;
2018
+ let active;
2019
+ let lanes;
2020
+ const authority = spec.isolated ? new AbortController() : undefined;
1818
2021
  const name = spec.manifest.name;
1819
2022
  const identity = this.dbIdentity.resolve(name);
1820
2023
  const extensionDb = extensionDbPool(identity, name, this.config.get().db, (err) => this.log.warn("extension database pool error", { plugin: name, err }));
1821
2024
  const p = (async () => {
2025
+ let manifest = spec.manifest;
2026
+ if (spec.isolated && authority) {
2027
+ const isolation = this.config.get().extensionHost.isolation;
2028
+ if (!isolation)
2029
+ throw new Error("The isolated extension supervisor is not configured");
2030
+ let quota = this.quota.get(name);
2031
+ if (!quota) {
2032
+ quota = new IsolatedExtensionQuota();
2033
+ this.quota.set(name, quota);
2034
+ }
2035
+ const modules = this.modules;
2036
+ const db = kernelDb(this.deps.db);
2037
+ const current = () => active !== undefined &&
2038
+ !authority.signal.aborted &&
2039
+ !this.closed &&
2040
+ this.registry.current(name) === active;
2041
+ const authorize = (orgId) => {
2042
+ if (!current())
2043
+ return Promise.resolve(undefined);
2044
+ const scope = orgId === undefined ? { plugin: name } : { plugin: name, orgId };
2045
+ const check = async () => current() &&
2046
+ (await readIsolatedGrant(db, {
2047
+ plugin: name,
2048
+ installedSha: spec.source === "install" ? spec.sha256 : undefined,
2049
+ permissions: spec.permissions,
2050
+ orgId,
2051
+ })) &&
2052
+ current();
2053
+ return this.isolatedGrants.issue(scope, () => (orgId === undefined ? check() : withOrgScope(orgId, check)), () => lanes?.revokeOrg(orgId), authority.signal);
2054
+ };
2055
+ const declared = spec.manifest.permissions?.network ?? [];
2056
+ manifest = await isolatedRevision({
2057
+ manifest,
2058
+ revision: spec.sha256 ?? spec.entryUrl,
2059
+ section: spec.isolated.section,
2060
+ identity,
2061
+ sandbox: {
2062
+ dockerSocket: isolation.dockerSocket,
2063
+ image: isolation.image,
2064
+ postgresSocket: isolation.postgresSocket,
2065
+ packageRoot: spec.isolated.root,
2066
+ },
2067
+ socketDir: isolation.socketDir,
2068
+ runtimeUrl: this.config.get().db.url,
2069
+ signal: AbortSignal.any([this.abort.signal, authority.signal]),
2070
+ quota,
2071
+ onLanes: (value) => {
2072
+ lanes = value;
2073
+ },
2074
+ onCrash: (retryAfterMs) => {
2075
+ this.log.warn("Isolated extension sandbox exited unexpectedly", {
2076
+ plugin: name,
2077
+ retryAfterMs,
2078
+ });
2079
+ void this.status
2080
+ .note(name, `Isolated sandbox crashed. Retry is delayed by ${retryAfterMs} ms.`)
2081
+ .catch(() => { });
2082
+ },
2083
+ cleanupFault: () => {
2084
+ this.log.error("Isolated extension sandbox removal could not be confirmed", {
2085
+ plugin: name,
2086
+ });
2087
+ void this.status
2088
+ .note(name, "Isolated sandbox cleanup could not be confirmed")
2089
+ .catch(() => { });
2090
+ },
2091
+ rls: this.config.get().db.rls,
2092
+ roles: this.config.get().roles,
2093
+ effective: (orgId) => this.effective.get(orgId, name),
2094
+ authorize,
2095
+ broker: {
2096
+ plugin: name,
2097
+ current,
2098
+ effects: () => {
2099
+ if (!modules)
2100
+ throw new Error("Extension effects are unavailable");
2101
+ return modules.get(ExtensionEffects, { strict: false });
2102
+ },
2103
+ keys: () => {
2104
+ if (!modules)
2105
+ throw new Error("Extension effect keys are unavailable");
2106
+ return modules.get(ExtensionEffectKeys, { strict: false });
2107
+ },
2108
+ network: async (url, orgId) => {
2109
+ const approved = (value) => value === url.hostname || value === url.origin;
2110
+ if (declared.some(approved))
2111
+ return true;
2112
+ if (orgId === undefined)
2113
+ return false;
2114
+ const policy = await this.allowances.policyFor(orgId);
2115
+ return (policy.trustedOrigins.some(approved) || policy.allowPrivateHosts.some(approved));
2116
+ },
2117
+ },
2118
+ });
2119
+ }
1822
2120
  if (!identity.separate) {
1823
2121
  await ensureLocalExtensionHandoff(this.deps.db, this.deps.dbUrl, pluginSchemaName(name), this.deps.connectTimeoutMs);
1824
2122
  }
1825
- return setupInstance(this.loadDeps, spec.manifest, {
2123
+ active = await setupInstance(this.loadDeps, manifest, {
1826
2124
  entryUrl: spec.entryUrl,
1827
2125
  source: spec.source,
1828
2126
  sha256: spec.sha256,
@@ -1837,7 +2135,13 @@ let ExtensionHost = class ExtensionHost {
1837
2135
  this.settingUp = c;
1838
2136
  },
1839
2137
  });
2138
+ if (authority)
2139
+ this.isolatedAuthority.set(active, authority);
2140
+ if (lanes)
2141
+ this.isolatedLanes.set(active, lanes);
2142
+ return active;
1840
2143
  })().catch(async (error) => {
2144
+ authority?.abort();
1841
2145
  if (!ctx)
1842
2146
  await extensionDb.destroy();
1843
2147
  throw error;
@@ -2302,6 +2606,7 @@ let ExtensionHost = class ExtensionHost {
2302
2606
  const inst = this.registry.deactivate(plugin);
2303
2607
  if (!inst)
2304
2608
  return undefined;
2609
+ this.isolatedAuthority.get(inst)?.abort();
2305
2610
  if (reason === "dependency")
2306
2611
  this.unloadedForDependency.add(plugin);
2307
2612
  else
@@ -2319,6 +2624,22 @@ let ExtensionHost = class ExtensionHost {
2319
2624
  this.log.info("plugin unloaded", { plugin, generation: inst.generation, reason });
2320
2625
  return inst;
2321
2626
  }
2627
+ async assertCurrentInstall(spec) {
2628
+ const name = spec.manifest.name;
2629
+ const loader = this.installLoader;
2630
+ const revision = loader && (await loader.desired()).find((d) => d.name === name);
2631
+ if (!loader || !revision || revision.sha256 !== spec.sha256) {
2632
+ throw new Error("The cached extension revision is no longer desired");
2633
+ }
2634
+ const tier = await this.tierOf(loader, revision, true);
2635
+ if (tier !== (spec.isolated ? "isolated" : "trusted")) {
2636
+ throw new Error("The cached extension revision no longer passes trust admission");
2637
+ }
2638
+ const snapshots = await this.approvals.all();
2639
+ if (!snapshotCovers(snapshots.get(name), spec.permissions)) {
2640
+ throw new Error("The cached extension revision no longer has its approved permissions");
2641
+ }
2642
+ }
2322
2643
  /** 新建实例并原子替换、撤销旧实例(不做连锁)。 */
2323
2644
  async doReload(plugin, drainMs) {
2324
2645
  if (this.closed)
@@ -2326,6 +2647,8 @@ let ExtensionHost = class ExtensionHost {
2326
2647
  const spec = this.specs.get(plugin);
2327
2648
  if (!spec)
2328
2649
  throw new Error(`plugin ${plugin} has never been loaded in this process`);
2650
+ if (spec.source === "install")
2651
+ await this.assertCurrentInstall(spec);
2329
2652
  const available = new Set(this.registry
2330
2653
  .all()
2331
2654
  .filter((i) => i.name !== plugin)
@@ -2341,6 +2664,8 @@ let ExtensionHost = class ExtensionHost {
2341
2664
  }
2342
2665
  this.unloadedForDependency.delete(plugin);
2343
2666
  const old = this.registry.activate(inst);
2667
+ if (old)
2668
+ this.isolatedAuthority.get(old)?.abort();
2344
2669
  await this.writeStatus({
2345
2670
  plugin,
2346
2671
  version: inst.version,
@@ -2464,6 +2789,7 @@ let ExtensionHost = class ExtensionHost {
2464
2789
  async close(opts = {}) {
2465
2790
  this.closed = true;
2466
2791
  this.abort.abort();
2792
+ this.revokeIsolatedInvocations({});
2467
2793
  await this.migrating?.catch(() => { });
2468
2794
  const lifecycleWaitMs = opts.lifecycleWaitMs ?? CLOSE_LIFECYCLE_WAIT_MS;
2469
2795
  await waitWithin(this.lifecycle.catch(() => { }), lifecycleWaitMs);