@capybara-hq/kernel 0.1.0-rc.132 → 0.1.0-rc.134

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 (173) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/admin.schemas.d.ts +4 -0
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/admin/setup.service.js +6 -1
  7. package/dist/agents/agents.controller.js +3 -2
  8. package/dist/agents/agents.service.d.ts +2 -0
  9. package/dist/agents/agents.service.js +7 -0
  10. package/dist/automations/events/trigger-events.service.d.ts +13 -1
  11. package/dist/automations/events/trigger-events.service.js +27 -14
  12. package/dist/catalog/catalog.service.d.ts +2 -0
  13. package/dist/catalog/catalog.service.js +28 -5
  14. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  15. package/dist/catalog/marketplace-fetch.js +15 -0
  16. package/dist/catalog/marketplaces.service.d.ts +4 -4
  17. package/dist/catalog/marketplaces.service.js +3 -2
  18. package/dist/catalog/owned-items.d.ts +2 -0
  19. package/dist/catalog/owned-items.js +30 -31
  20. package/dist/catalog/ownership.js +40 -38
  21. package/dist/catalog/plugin-import.d.ts +3 -4
  22. package/dist/catalog/plugin-import.js +50 -1
  23. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  24. package/dist/catalog/plugin-upgrade.js +95 -7
  25. package/dist/catalog/publisher-policy.d.ts +9 -0
  26. package/dist/catalog/publisher-policy.js +12 -0
  27. package/dist/catalog/unshare.js +66 -58
  28. package/dist/client/client-access.service.js +5 -3
  29. package/dist/config/schema.d.ts +1 -0
  30. package/dist/config/schema.js +8 -1
  31. package/dist/conversations/conversations.controller.js +4 -14
  32. package/dist/conversations/conversations.service.d.ts +14 -0
  33. package/dist/conversations/conversations.service.js +20 -2
  34. package/dist/ctx/create-ctx.d.ts +15 -2
  35. package/dist/ctx/create-ctx.js +195 -79
  36. package/dist/ctx/durable-cancellation.d.ts +3 -0
  37. package/dist/ctx/durable-cancellation.js +8 -0
  38. package/dist/ctx/durable-effects.service.d.ts +81 -0
  39. package/dist/ctx/durable-effects.service.js +316 -0
  40. package/dist/ctx/durable-envelope.d.ts +24 -0
  41. package/dist/ctx/durable-envelope.js +80 -0
  42. package/dist/ctx/durable-failure.d.ts +7 -0
  43. package/dist/ctx/durable-failure.js +32 -0
  44. package/dist/ctx/durable-job.d.ts +9 -0
  45. package/dist/ctx/durable-job.js +2 -0
  46. package/dist/ctx/durable-keys.d.ts +27 -0
  47. package/dist/ctx/durable-keys.js +138 -0
  48. package/dist/ctx/durable-relay.d.ts +29 -0
  49. package/dist/ctx/durable-relay.js +250 -0
  50. package/dist/ctx/queue.d.ts +2 -0
  51. package/dist/ctx/queue.js +25 -15
  52. package/dist/db/extension-db.js +2 -0
  53. package/dist/db/extension-handoff-schema.d.ts +6 -0
  54. package/dist/db/extension-handoff-schema.js +72 -0
  55. package/dist/db/extension-rls-predicate.d.ts +1 -0
  56. package/dist/db/extension-rls-predicate.js +8 -0
  57. package/dist/db/extension-schema-transfer.d.ts +1 -1
  58. package/dist/db/extension-schema-transfer.js +18 -6
  59. package/dist/db/kernel-schema.d.ts +64 -0
  60. package/dist/db/migrator.js +6 -13
  61. package/dist/db/pool.d.ts +2 -2
  62. package/dist/db/pool.js +2 -2
  63. package/dist/db/sql-statements.d.ts +3 -0
  64. package/dist/db/sql-statements.js +15 -5
  65. package/dist/device-access/device-access.module.js +12 -2
  66. package/dist/device-access/device-access.service.d.ts +30 -2
  67. package/dist/device-access/device-access.service.js +38 -4
  68. package/dist/device-access/host-gate.d.ts +45 -0
  69. package/dist/device-access/host-gate.js +92 -0
  70. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  71. package/dist/device-access/host-service-stop-sweep.js +112 -0
  72. package/dist/device-access/host-service-stop.d.ts +78 -0
  73. package/dist/device-access/host-service-stop.js +144 -0
  74. package/dist/device-access/host-services.d.ts +211 -0
  75. package/dist/device-access/host-services.js +803 -0
  76. package/dist/device-access/person-handles.d.ts +10 -0
  77. package/dist/device-access/person-handles.js +25 -0
  78. package/dist/device-access/service-events.d.ts +199 -0
  79. package/dist/device-access/service-events.js +704 -0
  80. package/dist/device-access/token.d.ts +5 -0
  81. package/dist/device-access/token.js +5 -0
  82. package/dist/devices/devices.service.js +3 -0
  83. package/dist/dial-in/access.d.ts +5 -5
  84. package/dist/dial-in/access.js +19 -12
  85. package/dist/dial-in/gateway.js +6 -2
  86. package/dist/dial-in/machines.d.ts +9 -2
  87. package/dist/dial-in/machines.js +27 -4
  88. package/dist/erasure/device-cleanup.js +12 -0
  89. package/dist/erasure/org-catalog.js +2 -2
  90. package/dist/erasure/org-rules.js +10 -0
  91. package/dist/errors.d.ts +2 -0
  92. package/dist/errors.js +2 -0
  93. package/dist/extensions/admin-ops.js +8 -2
  94. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  95. package/dist/extensions/deployed-snapshots.js +7 -2
  96. package/dist/extensions/extensions.module.js +10 -0
  97. package/dist/extensions/host.d.ts +12 -2
  98. package/dist/extensions/host.js +44 -22
  99. package/dist/extensions/instance.d.ts +5 -0
  100. package/dist/extensions/instance.js +10 -0
  101. package/dist/extensions/ledger.d.ts +1 -1
  102. package/dist/extensions/lifecycle-hooks.js +3 -3
  103. package/dist/extensions/org-config.js +6 -1
  104. package/dist/extensions/permission-set.d.ts +7 -0
  105. package/dist/extensions/permission-set.js +10 -0
  106. package/dist/extensions/permission-view.d.ts +1 -1
  107. package/dist/extensions/permission-view.js +10 -1
  108. package/dist/extensions/sources.d.ts +1 -0
  109. package/dist/extensions/sources.js +9 -0
  110. package/dist/git/tickets.js +32 -27
  111. package/dist/http/app.js +5 -3
  112. package/dist/identity/accounts.d.ts +6 -1
  113. package/dist/identity/accounts.js +11 -2
  114. package/dist/identity/api-tokens.js +7 -6
  115. package/dist/identity/settings.d.ts +9 -1
  116. package/dist/identity/settings.js +16 -1
  117. package/dist/inbox/inbox-items.service.d.ts +5 -0
  118. package/dist/inbox/inbox-items.service.js +57 -33
  119. package/dist/inbox/org-notices.js +3 -2
  120. package/dist/index.d.ts +1 -0
  121. package/dist/index.js +1 -0
  122. package/dist/infra/database/extension-effect-key-lock.d.ts +10 -0
  123. package/dist/infra/database/extension-effect-key-lock.js +69 -0
  124. package/dist/infra/database/extension-handoff.d.ts +27 -0
  125. package/dist/infra/database/extension-handoff.js +113 -0
  126. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  127. package/dist/infra/database/scoped-dialect.js +260 -72
  128. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  129. package/dist/infra/database/startup-activation-transaction.js +3 -2
  130. package/dist/infra/outbox/outbox.dispatcher.d.ts +6 -1
  131. package/dist/infra/outbox/outbox.dispatcher.js +64 -4
  132. package/dist/infra/outbox/outbox.module.js +2 -0
  133. package/dist/infra/outbox/registry.d.ts +40 -0
  134. package/dist/infra/outbox/registry.js +42 -0
  135. package/dist/infra/queue/queue-names.d.ts +1 -1
  136. package/dist/infra/queue/queue-names.js +1 -0
  137. package/dist/infra/queue/run-job.d.ts +4 -1
  138. package/dist/infra/queue/run-job.js +10 -2
  139. package/dist/kernel.js +1 -0
  140. package/dist/kernel.module.js +3 -0
  141. package/dist/orgs/offboarding.js +18 -9
  142. package/dist/orgs/orgs.service.js +16 -0
  143. package/dist/orgs/settings.service.js +3 -0
  144. package/dist/packages/npm-publish-keys.json +27 -0
  145. package/dist/packages/official-publisher.d.ts +19 -0
  146. package/dist/packages/official-publisher.js +152 -0
  147. package/dist/packages/provenance.d.ts +7 -0
  148. package/dist/packages/provenance.js +22 -19
  149. package/dist/packages/sigstore-trusted-root.json +126 -0
  150. package/dist/platform/ops/admin.ops.js +2 -1
  151. package/dist/platform/ops/orgs.ops.js +1 -0
  152. package/dist/roles/worker-role.d.ts +6 -3
  153. package/dist/roles/worker-role.js +12 -4
  154. package/dist/roles/worker.module.js +9 -0
  155. package/dist/runtime/maintenance.d.ts +5 -2
  156. package/dist/runtime/maintenance.js +18 -4
  157. package/dist/sandbox/device-reports.d.ts +4 -4
  158. package/dist/sandbox/device-reports.js +40 -30
  159. package/dist/sandbox/device-services.d.ts +2 -1
  160. package/dist/sandbox/device-services.js +5 -1
  161. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  162. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  163. package/dist/sandbox/permission-config-publication.js +5 -1
  164. package/dist/themes/theme-state.js +24 -13
  165. package/dist/tools/call-scope.d.ts +6 -0
  166. package/dist/tools/call-scope.js +22 -0
  167. package/dist/tools/registry.js +20 -2
  168. package/dist/ui/views.js +36 -8
  169. package/package.json +9 -4
  170. package/src/migrations/0222_device_host_services.sql +27 -0
  171. package/src/migrations/0223_device_service_events.sql +54 -0
  172. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
  173. package/src/migrations/0225_extension_effect_receipts.sql +25 -0
@@ -4,16 +4,18 @@ import { conversationTopic } from "../conversations/event-log.js";
4
4
  import { pluginSchemaName } from "../db/extension-db.js";
5
5
  import { kernelDb } from "../db/kernel-schema.js";
6
6
  import { ApiError } from "../errors.js";
7
- import { enabledExtensionsQuery, isExtensionEnabled } from "../extensions/enabled.js";
7
+ import { enabledExtensionsQuery } from "../extensions/enabled.js";
8
8
  import { checkHookRegistration } from "../extensions/hooks.js";
9
9
  import { RegistrationLedger } from "../extensions/ledger.js";
10
10
  import { audit } from "../identity/audit.js";
11
- import { withOrgScope } from "../infra/database/org-scope.js";
11
+ import { appendEffect, isExtensionTransaction } from "../infra/database/extension-handoff.js";
12
+ import { currentScope, withOrgScope } from "../infra/database/org-scope.js";
12
13
  import { can } from "../orgs/roles.js";
13
14
  import { PrefixedStorage } from "../storage/storage.service.js";
14
15
  import { canUseSlot, orgUiTopic, PLATFORM_UI_TOPIC, PluginUiRegistration, } from "../ui/registry.js";
15
16
  import { createBus } from "./bus.js";
16
17
  import { checkDeviceProvider } from "./device-provider-check.js";
18
+ import { assertEffectKey, } from "./durable-effects.service.js";
17
19
  import { createKv } from "./kv.js";
18
20
  import { createLock } from "./lock.js";
19
21
  import { createExtensionNet } from "./net.js";
@@ -96,20 +98,27 @@ export async function currentPlatformAccount(db, accountId) {
96
98
  .executeTakeFirst();
97
99
  return row !== undefined;
98
100
  }
99
- /** `ui.invalidate` 目标的一条查询:插件在该组织启用,且(带对话时)对话属于该组织。 */
101
+ /**
102
+ * An invalidation target must be in a live org where the extension is enabled. A supplied
103
+ * conversation must be live and belong to that same org.
104
+ */
100
105
  async function invalidateTargetOk(db, plugin, orgId, conversationId) {
101
106
  const k = kernelDb(db);
102
- if (!(await isExtensionEnabled(k, orgId, plugin)))
103
- return false;
104
- if (conversationId === undefined)
105
- return true;
106
- const conv = await k
107
- .selectFrom("conversations")
108
- .select("conversations.id")
109
- .where("conversations.id", "=", conversationId)
110
- .where("conversations.org_id", "=", orgId)
111
- .executeTakeFirst();
112
- return conv !== undefined;
107
+ let target = k
108
+ .selectFrom("orgs")
109
+ .innerJoin(enabledExtensionsQuery(k, orgId).as("en"), (join) => join.on("en.plugin", "=", plugin))
110
+ .select("orgs.id")
111
+ .where("orgs.id", "=", orgId)
112
+ .where("orgs.deleted_at", "is", null);
113
+ if (conversationId !== undefined) {
114
+ target = target.where((eb) => eb.exists(eb
115
+ .selectFrom("conversations")
116
+ .select("conversations.id")
117
+ .where("conversations.id", "=", conversationId)
118
+ .where("conversations.org_id", "=", orgId)
119
+ .where("conversations.deleted_at", "is", null)));
120
+ }
121
+ return (await target.executeTakeFirst()) !== undefined;
113
122
  }
114
123
  /** 越权审计去重键的 TTL:同一插件同一项在此期间只记一次。 */
115
124
  const DENIAL_DEDUPE_TTL_SECONDS = 30 * 24 * 3600;
@@ -149,9 +158,8 @@ async function recordDenial(deps, plugin, item) {
149
158
  * 受控事务的 `Command`):其方法收到的回调拿到的 Kysely(`transaction().execute(cb)`、
150
159
  * `connection().execute(cb)`)与返回的 Promise 结果(`startTransaction().execute()` 得到的受控事务)。
151
160
  */
152
- // biome-ignore lint/suspicious/noExplicitAny: 内核不持有表结构类型
153
- function guardDb(db, plugin) {
154
- return new Proxy(db, {
161
+ function guardDb(db, plugin, transactions) {
162
+ const guarded = new Proxy(db, {
155
163
  get(target, prop) {
156
164
  // `await using` 经 Symbol.asyncDispose 调用 destroy,同样拦截
157
165
  if (prop === "destroy" || prop === Symbol.asyncDispose) {
@@ -162,24 +170,26 @@ function guardDb(db, plugin) {
162
170
  const value = Reflect.get(target, prop, target);
163
171
  if (typeof value !== "function")
164
172
  return value;
165
- return (...args) => guardValue(value.apply(target, args), plugin);
173
+ return (...args) => guardValue(value.apply(target, args), plugin, transactions);
166
174
  },
167
175
  });
176
+ if (isExtensionTransaction(db))
177
+ transactions.set(guarded, db);
178
+ return guarded;
168
179
  }
169
180
  /** 能(经回调或返回值)再拿到 Kysely 的构建器类。 */
170
181
  const BUILDERS = [ConnectionBuilder, TransactionBuilder, ControlledTransactionBuilder, Command];
171
182
  const isBuilder = (v) => BUILDERS.some((B) => v instanceof B);
172
183
  /** Kysely → guardDb;构建器 → guardBuilder;其余原样返回。 */
173
- function guardValue(v, plugin) {
174
- // biome-ignore lint/suspicious/noExplicitAny: 内核不持有表结构类型
184
+ function guardValue(v, plugin, transactions) {
175
185
  if (v instanceof Kysely)
176
- return guardDb(v, plugin);
186
+ return guardDb(v, plugin, transactions);
177
187
  if (isBuilder(v))
178
- return guardBuilder(v, plugin);
188
+ return guardBuilder(v, plugin, transactions);
179
189
  return v;
180
190
  }
181
191
  /** 包装构建器:回调参数里的 Kysely、返回值与 Promise 结果都经 guardValue。 */
182
- function guardBuilder(builder, plugin) {
192
+ function guardBuilder(builder, plugin, transactions) {
183
193
  return new Proxy(builder, {
184
194
  get(target, prop) {
185
195
  const value = Reflect.get(target, prop, target);
@@ -187,10 +197,12 @@ function guardBuilder(builder, plugin) {
187
197
  return value;
188
198
  return (...args) => {
189
199
  const wrapped = args.map((a) => typeof a === "function"
190
- ? (...cbArgs) => a(...cbArgs.map((c) => guardValue(c, plugin)))
200
+ ? (...cbArgs) => a(...cbArgs.map((c) => guardValue(c, plugin, transactions)))
191
201
  : a);
192
- const out = guardValue(value.apply(target, wrapped), plugin);
193
- return out instanceof Promise ? out.then((r) => guardValue(r, plugin)) : out;
202
+ const out = guardValue(value.apply(target, wrapped), plugin, transactions);
203
+ return out instanceof Promise
204
+ ? out.then((r) => guardValue(r, plugin, transactions))
205
+ : out;
194
206
  };
195
207
  },
196
208
  });
@@ -262,6 +274,7 @@ identity = { sha256: null }) {
262
274
  // 界面刷新发在内核命名空间(会话主题 conv.<id> / 组织主题 org-ui.<orgId>),不在插件自己的命名空间
263
275
  const kernelBus = createBus(deps.redis, deps.busSubscriber, "kernel", deps.log);
264
276
  const ledger = new RegistrationLedger(name);
277
+ const serviceEventHandlers = new Map();
265
278
  const lifecycle = new AbortController();
266
279
  /** 撤销时队列 worker 排空的截止时刻(epoch 毫秒);undefined = 一直等(停机路径)。 */
267
280
  let drainDeadline;
@@ -311,15 +324,22 @@ identity = { sha256: null }) {
311
324
  // by the declared purpose's kind; an undeclared purpose has none, so its refusal
312
325
  // (model.purpose_unknown) names no kind
313
326
  describe: async (req) => {
314
- if (!deps.models)
327
+ const models = deps.models;
328
+ if (!models)
315
329
  throw new Error(`plugin ${name}: ctx.models is not available`);
316
- const kind = declaredModels.find((d) => d.purpose === req?.purpose)?.kind;
317
- if (kind === undefined && typeof req?.purpose === "string") {
318
- throw new ApiError("model.purpose_unknown", `Extension ${name} declared no model purpose "${req.purpose}" in permissions.models`);
330
+ const orgId = req?.orgId;
331
+ const purpose = req?.purpose;
332
+ const kind = declaredModels.find((d) => d.purpose === purpose)?.kind;
333
+ if (kind === undefined && typeof purpose === "string") {
334
+ throw new ApiError("model.purpose_unknown", `Extension ${name} declared no model purpose "${purpose}" in permissions.models`);
335
+ }
336
+ if (typeof orgId !== "string" || orgId === "" || typeof purpose !== "string") {
337
+ throw new ApiError("validation_failed", "describe needs orgId and purpose strings");
319
338
  }
320
- return kind === "image_generation"
321
- ? deps.models.images.describeForExtension(name, declaredModels, req)
322
- : deps.models.embeddings.describe(name, declaredModels, req);
339
+ const target = { orgId, purpose };
340
+ return withOrgScope(orgId, () => kind === "image_generation"
341
+ ? models.images.describeForExtension(name, declaredModels, target)
342
+ : models.embeddings.describe(name, declaredModels, target));
323
343
  },
324
344
  }
325
345
  : undefined;
@@ -330,10 +350,11 @@ identity = { sha256: null }) {
330
350
  const dialInApi = perms.dialIn
331
351
  ? (() => {
332
352
  const access = deps.dialIn;
333
- const served = async (deviceId) => {
353
+ const inServedOrg = async (deviceId, run) => {
334
354
  if (!access)
335
355
  throw new Error(`plugin ${name}: ctx.dialIn is not available`);
336
- if (typeof deviceId !== "string" || !(await access.serves(name, deviceId))) {
356
+ const orgId = typeof deviceId === "string" ? await access.servedOrg(name, deviceId) : undefined;
357
+ if (orgId === undefined) {
337
358
  const item = `dialIn:device ${String(deviceId)}`;
338
359
  const p = recordDenial(deps, name, item).finally(() => audits.delete(p));
339
360
  audits.add(p);
@@ -341,36 +362,33 @@ identity = { sha256: null }) {
341
362
  e.message = `device ${String(deviceId)} is not served by ${name}`;
342
363
  throw e;
343
364
  }
344
- return deviceId;
365
+ return withOrgScope(orgId, () => run(access));
345
366
  };
346
367
  return {
347
- request: async (deviceId, frame, opts) => {
348
- const id = await served(deviceId);
368
+ request: (deviceId, frame, opts) => inServedOrg(deviceId, (dialIn) => {
349
369
  const signal = opts?.signal
350
370
  ? AbortSignal.any([lifecycle.signal, opts.signal])
351
371
  : lifecycle.signal;
352
- // only the options an extension may pass: never the kernel's connection fences
353
- return access.request(id, frame, {
372
+ // Only the options an extension may pass, excluding the kernel's connection fences.
373
+ return dialIn.request(deviceId, frame, {
354
374
  timeoutMs: Number(opts?.timeoutMs),
355
375
  signal,
356
376
  });
357
- },
358
- online: async (deviceId) => access.online(await served(deviceId)),
359
- capacity: async (deviceId) => access.capacity(await served(deviceId)),
377
+ }),
378
+ online: (deviceId) => inServedOrg(deviceId, (dialIn) => dialIn.online(deviceId)),
379
+ capacity: (deviceId) => inServedOrg(deviceId, (dialIn) => dialIn.capacity(deviceId)),
360
380
  stop: async (deviceId, reason) => {
361
381
  if (reason !== "drain" && reason !== "stop")
362
382
  throw new TypeError(`plugin ${name}: ctx.dialIn.stop reason must be drain or stop`);
363
- await access.stop(await served(deviceId), reason);
383
+ await inServedOrg(deviceId, (dialIn) => dialIn.stop(deviceId, reason));
364
384
  },
365
- // only on the gateway replica holding the machine's socket (DialInGateway); elsewhere
366
- // DialInStreamElsewhereError. The extension's end closes its streams.
367
- openStream: async (deviceId, body, opts) => {
368
- const id = await served(deviceId);
369
- // the SDK requires the signal: an open nobody can abort is refused up front
385
+ // Only the gateway replica holding the machine's socket opens the stream.
386
+ // The extension's end closes its streams.
387
+ openStream: (deviceId, body, opts) => inServedOrg(deviceId, async (dialIn) => {
370
388
  if (!(opts?.signal instanceof AbortSignal))
371
389
  throw new TypeError(`plugin ${name}: ctx.dialIn.openStream needs opts.signal`);
372
390
  const signal = AbortSignal.any([lifecycle.signal, opts.signal]);
373
- const stream = await access.openStream(id, body, signal);
391
+ const stream = await dialIn.openStream(deviceId, body, signal);
374
392
  const onEnd = () => stream.close("extension stopped");
375
393
  if (lifecycle.signal.aborted)
376
394
  onEnd();
@@ -379,7 +397,7 @@ identity = { sha256: null }) {
379
397
  void stream.closed.then(() => lifecycle.signal.removeEventListener("abort", onEnd));
380
398
  }
381
399
  return stream;
382
- },
400
+ }),
383
401
  };
384
402
  })()
385
403
  : undefined;
@@ -388,6 +406,30 @@ identity = { sha256: null }) {
388
406
  // and, when its revision changed, moves the device authority epoch (device-provider spec §6.7)
389
407
  const devicesApi = manifest.provides.includes(DEVICE_PROVIDER_EXTENSION_POINT)
390
408
  ? {
409
+ // stored with its owed delivery (ServiceEvents); resolves once committed, so the provider
410
+ // acks the machine only then. An event of a service the kernel did not place there as a
411
+ // host service resolves too (dropped, logged): the machine stops sending it
412
+ serviceEvent: async (args) => {
413
+ const events = deps.serviceEvents?.();
414
+ if (!events)
415
+ throw new Error(`plugin ${name}: ctx.devices.serviceEvent is not available`);
416
+ // one snapshot, read once: what is checked is what is stored
417
+ const e = {
418
+ deviceId: args?.deviceId,
419
+ service: args?.service,
420
+ seq: args?.seq,
421
+ body: args?.body,
422
+ };
423
+ const outcome = await events.record(name, e);
424
+ if (outcome === "not-served") {
425
+ const item = `devices:device ${String(e.deviceId)}`;
426
+ const p = recordDenial(deps, name, item).finally(() => audits.delete(p));
427
+ audits.add(p);
428
+ const err = new ExtensionPermissionError(name, `provides ${DEVICE_PROVIDER_EXTENSION_POINT}`);
429
+ err.message = `device ${String(e.deviceId)} is not served by ${name}`;
430
+ throw err;
431
+ }
432
+ },
391
433
  reportChanged: async (deviceId) => {
392
434
  const reports = deps.devices;
393
435
  if (!reports)
@@ -419,6 +461,8 @@ identity = { sha256: null }) {
419
461
  // read from the approved manifest: an upgrade adding it waits for approval again
420
462
  loopbackPorts: perms.deviceAccess?.loopbackPorts === true,
421
463
  siteAccess: perms.deviceAccess?.siteAccess === true,
464
+ // read from the approved manifest: only these may run outside the device sandbox
465
+ hostServices: [...(perms.deviceAccess?.hostServices ?? [])],
422
466
  };
423
467
  const backend = () => {
424
468
  const b = deps.deviceAccess?.();
@@ -439,26 +483,95 @@ identity = { sha256: null }) {
439
483
  requestSiteAccess: (call, ask) => backend().requestSiteAccess(caller, call, ask),
440
484
  siteGrants: async (scope) => backend().siteGrants(caller, scope),
441
485
  revokeSiteGrant: async (scope) => backend().revokeSiteGrant(caller, scope),
486
+ // host services: the approved manifest's hostServices, on the person's own machine
487
+ ensureHostService: async (at, spec) => backend().ensureHostService(caller, at, spec),
488
+ hostRequest: async (at, req) => backend().hostRequest(caller, at, req),
489
+ stopHostService: async (at, service) => backend().stopHostService(caller, at, service),
490
+ personalDevices: async (args) => backend().personalDevices(caller, args),
491
+ // during setup only, for a host service of the approved manifest: the deliveries
492
+ // (ServiceEvents, worker role) call it on whichever replica takes the job
493
+ onServiceEvent: (service, handler) => {
494
+ if (toolsSealed)
495
+ throw new Error(`plugin ${name}: deviceAccess.onServiceEvent is only allowed during setup; setup has completed`);
496
+ if (typeof service !== "string" || !caller.hostServices.includes(service))
497
+ throw new DeviceAccessError("host_not_declared", `The host service ${JSON.stringify(service)} is not declared in permissions.deviceAccess.hostServices.`);
498
+ if (typeof handler !== "function")
499
+ throw new Error(`plugin ${name}: onServiceEvent("${service}") needs a handler function`);
500
+ if (serviceEventHandlers.has(service))
501
+ throw new Error(`plugin ${name}: duplicate onServiceEvent handler for "${service}"`);
502
+ serviceEventHandlers.set(service, handler);
503
+ ledger.add({
504
+ kind: "service.event",
505
+ key: service,
506
+ dispose: async () => {
507
+ if (serviceEventHandlers.get(service) === handler)
508
+ serviceEventHandlers.delete(service);
509
+ },
510
+ });
511
+ },
442
512
  };
443
513
  })()
444
514
  : undefined;
515
+ const effectTransactions = new WeakMap();
516
+ const warnedLegacyEffects = new Set();
517
+ const durable = async (orgId, effect, options) => {
518
+ const backend = deps.durableEffects?.();
519
+ if (!backend)
520
+ throw new Error("Durable extension effects are not available in this process.");
521
+ const scope = currentScope();
522
+ if (scope?.kind === "org" && scope.orgId !== orgId) {
523
+ throw new Error("Extension effect org does not match the invocation scope");
524
+ }
525
+ if (options === undefined && (effect.kind === "trigger" || effect.kind === "inbox.post")) {
526
+ if (!warnedLegacyEffects.has(effect.kind)) {
527
+ const method = effect.kind === "trigger" ? "ctx.triggers.emit" : "ctx.inbox.post";
528
+ deps.log.warn(`${method} without idempotencyKey is deprecated and will be removed in the next release`, {
529
+ plugin: name,
530
+ });
531
+ warnedLegacyEffects.add(effect.kind);
532
+ }
533
+ return withOrgScope(orgId, () => backend.commit(name, orgId, undefined, effect));
534
+ }
535
+ const key = options?.idempotencyKey;
536
+ assertEffectKey(key);
537
+ const tx = options?.tx && effectTransactions.get(options.tx);
538
+ if (options?.tx !== undefined && !tx) {
539
+ throw new Error("The effect requires a live transaction from this extension's ctx.db");
540
+ }
541
+ if (tx === undefined) {
542
+ return withOrgScope(orgId, () => backend.commit(name, orgId, key, effect));
543
+ }
544
+ const envelope = await withOrgScope(orgId, () => backend.prepare(name, orgId, key, effect, tx));
545
+ await appendEffect(tx, name, envelope);
546
+ return { status: "staged", idempotencyKey: key };
547
+ };
548
+ const addOutbox = (async (effect, options) => {
549
+ const snapshot = structuredClone(effect);
550
+ if (!snapshot?.orgId || typeof snapshot.orgId !== "string") {
551
+ throw new Error("An extension outbox effect requires an org id");
552
+ }
553
+ if (snapshot.kind === "inbox.resolve" && !perms.inbox) {
554
+ throw new Error("Resolving an inbox item requires inbox permission");
555
+ }
556
+ if (snapshot.kind !== "inbox.resolve" && snapshot.kind !== "queue") {
557
+ throw new Error("Unknown extension outbox effect kind");
558
+ }
559
+ const result = await durable(snapshot.orgId, snapshot, options);
560
+ return options.tx ? result : undefined;
561
+ });
445
562
  // ctx.triggers: only with permissions.triggers; the event types come from the approved manifest
446
563
  // (a frozen copy: the extension changing its manifest object later changes nothing), and the
447
564
  // event is stored in its own org's scope (TriggerEventsService checks the rest)
448
565
  const triggersApi = perms.triggers
449
566
  ? (() => {
450
- const declared = Object.freeze([...(perms.triggers?.emit ?? [])]);
451
567
  return {
452
- emit: async (event) => {
453
- const b = deps.triggers?.();
454
- if (!b)
455
- throw new Error("Trigger events are not available in this process.");
568
+ emit: (async (event, options) => {
456
569
  // one snapshot, read once: what is checked is what is stored
457
570
  const snap = snapshotTriggerEvent(event);
458
571
  if (typeof snap.orgId !== "string" || snap.orgId === "")
459
572
  throw new TriggerError("invalid_event", "invalid event: missing_org_id");
460
- return withOrgScope(snap.orgId, () => b.emit(name, declared, snap));
461
- },
573
+ return durable(snap.orgId, { kind: "trigger", data: snap }, options);
574
+ }),
462
575
  // a handle bound to this extension and the call's run, in the call's org (the service
463
576
  // checks the context is the pipeline's and its run is of that org)
464
577
  causeOf: async (call) => {
@@ -479,10 +592,7 @@ identity = { sha256: null }) {
479
592
  // copy read once (what is checked is what is stored)
480
593
  const inboxApi = perms.inbox
481
594
  ? {
482
- post: async (p) => {
483
- const b = deps.inbox?.();
484
- if (!b)
485
- throw new Error("The inbox is not available in this process.");
595
+ post: (async (p, options) => {
486
596
  let snap;
487
597
  try {
488
598
  snap = structuredClone(p);
@@ -495,9 +605,8 @@ identity = { sha256: null }) {
495
605
  typeof snap.orgId !== "string" ||
496
606
  snap.orgId === "")
497
607
  throw new InboxError("invalid_item", "invalid inbox item: missing_org_id");
498
- const orgId = snap.orgId;
499
- return withOrgScope(orgId, () => b.post({ kind: "plugin", plugin: name }, snap));
500
- },
608
+ return durable(snap.orgId, { kind: "inbox.post", data: snap }, options);
609
+ }),
501
610
  resolve: async (args) => {
502
611
  const b = deps.inbox?.();
503
612
  if (!b)
@@ -665,15 +774,17 @@ identity = { sha256: null }) {
665
774
  * the org (layering spec A §6: a call on behalf of an org never reaches such a provider).
666
775
  */
667
776
  const forOrg = async (orgScoped, orgId, entries) => {
668
- if (entries.length === 0)
669
- return entries;
670
- let out = entries;
671
- if (orgScoped) {
672
- const enabled = await extensionPointAccess.enabledPlugins(orgId);
673
- out = out.filter((e) => enabled.has(e.plugin));
674
- }
675
- const ok = await Promise.all(out.map((e) => extensionPointAccess.configOk(orgId, e.plugin)));
676
- return out.filter((_, i) => ok[i]);
777
+ if (orgId === "" || entries.length === 0)
778
+ return [];
779
+ return withOrgScope(orgId, async () => {
780
+ let out = entries;
781
+ if (orgScoped) {
782
+ const enabled = await extensionPointAccess.enabledPlugins(orgId);
783
+ out = out.filter((e) => enabled.has(e.plugin));
784
+ }
785
+ const ok = await Promise.all(out.map((e) => extensionPointAccess.configOk(orgId, e.plugin)));
786
+ return out.filter((_, i) => ok[i]);
787
+ });
677
788
  };
678
789
  const listAll = (ref) => {
679
790
  const info = checkExtensionPoint(ref);
@@ -761,7 +872,10 @@ identity = { sha256: null }) {
761
872
  },
762
873
  add: queue.add,
763
874
  },
764
- db: guardDb((identity.db ?? deps.db).withSchema(pluginSchemaName(name)), name),
875
+ db: guardDb((identity.db ?? deps.db).withSchema(pluginSchemaName(name)), name, effectTransactions),
876
+ hasEffectQueue: queue.hasDefined,
877
+ dispatchEffectQueue: queue.dispatchEffect,
878
+ outbox: { add: addOutbox },
765
879
  http: {
766
880
  route(method, path, handler) {
767
881
  if (typeof path !== "string" || !path.startsWith("/")) {
@@ -937,9 +1051,7 @@ identity = { sha256: null }) {
937
1051
  },
938
1052
  });
939
1053
  },
940
- // 目标先核对(一条查询):插件在 orgId 启用;带对话时对话属于 orgId。不满足就只记 debug、不发
941
- // (插件拿着过期或别的组织的 id 调用不是错误,但不能借它往别的组织的流里发刷新)。A `platform.page`
942
- // contribution takes no orgId and refreshes the platform stream (super admins only)
1054
+ // Verify the target before publishing a refresh hint. Platform pages use their own stream.
943
1055
  async invalidate(target) {
944
1056
  const t = uiReg.target(target, platformUi);
945
1057
  // `queries`: the contribution's component queries are refetched too (full pages spec §4.1)
@@ -953,7 +1065,10 @@ identity = { sha256: null }) {
953
1065
  await kernelBus.publish(PLATFORM_UI_TOPIC, msg);
954
1066
  return;
955
1067
  }
956
- if (!(await invalidateTargetOk(deps.db, name, t.orgId, t.conversationId))) {
1068
+ const scope = currentScope();
1069
+ const allowed = (scope?.kind !== "org" || scope.orgId === t.orgId) &&
1070
+ (await withOrgScope(t.orgId, () => invalidateTargetOk(deps.db, name, t.orgId, t.conversationId)));
1071
+ if (!allowed) {
957
1072
  deps.log.debug?.("plugin ui invalidate ignored: plugin not enabled or conversation not in org", {
958
1073
  plugin: name,
959
1074
  orgId: t.orgId,
@@ -1009,6 +1124,7 @@ identity = { sha256: null }) {
1009
1124
  uiActions: uiReg.actions,
1010
1125
  uiQueries: uiReg.queries,
1011
1126
  setupChecks,
1127
+ serviceEventHandlers,
1012
1128
  ledger,
1013
1129
  async beginDispose(deadline) {
1014
1130
  drainDeadline = deadline;
@@ -0,0 +1,3 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ /** The caller records and settles the cancellation using its current kernel transaction. */
3
+ export declare function cancelDeletedOrgEffect(db: KernelSchemaDb, plugin: string, id: string): Promise<void>;
@@ -0,0 +1,8 @@
1
+ /** The caller records and settles the cancellation using its current kernel transaction. */
2
+ export async function cancelDeletedOrgEffect(db, plugin, id) {
3
+ await db
4
+ .insertInto("extension_effect_cancellations")
5
+ .values({ id, plugin, reason: "organization_deleted" })
6
+ .onConflict((conflict) => conflict.doNothing())
7
+ .execute();
8
+ }
@@ -0,0 +1,81 @@
1
+ import type { ExtensionOutboxEffect, InboxPost, TriggerEvent } from "@capybara-hq/plugin-sdk";
2
+ import { type Kysely } from "kysely";
3
+ import { TriggerEventsService, type VerifiedCause } from "../automations/events/trigger-events.service.js";
4
+ import { ExtensionRegistry } from "../extensions/registry.js";
5
+ import { InboxItemsService } from "../inbox/inbox-items.service.js";
6
+ import type { HandoffReference } from "../infra/database/extension-handoff.js";
7
+ import { KernelDb } from "../infra/database/kernel-db.js";
8
+ import { TransactionHost } from "../infra/database/transaction-host.js";
9
+ import { XactLock } from "../infra/database/xact-lock.js";
10
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
11
+ import type { EnvelopeKeyring } from "./durable-envelope.js";
12
+ import { type SignedEnvelope } from "./durable-envelope.js";
13
+ import { ExtensionEffectKeys } from "./durable-keys.js";
14
+ export type ExtensionEffect = {
15
+ kind: "trigger";
16
+ data: TriggerEvent;
17
+ } | {
18
+ kind: "inbox.post";
19
+ data: InboxPost;
20
+ } | ExtensionOutboxEffect;
21
+ type PreparedEffect = {
22
+ kind: "trigger";
23
+ data: Omit<TriggerEvent, "cause">;
24
+ cause: VerifiedCause;
25
+ } | Exclude<ExtensionEffect, {
26
+ kind: "trigger";
27
+ }>;
28
+ type EffectBody = {
29
+ plugin: string;
30
+ principal: {
31
+ kind: "extension";
32
+ name: string;
33
+ };
34
+ orgId: string;
35
+ key: string;
36
+ effect: PreparedEffect;
37
+ payloadHash: string;
38
+ issuedAt: number;
39
+ causeWindow?: NonNullable<VerifiedCause["causeWindow"]>;
40
+ };
41
+ export type ExtensionEffectEnvelope = SignedEnvelope<EffectBody>;
42
+ export declare function assertEffectKey(key: unknown): asserts key is string;
43
+ export declare class ExtensionEffects {
44
+ private readonly kdb;
45
+ readonly txHost: TransactionHost;
46
+ private readonly lock;
47
+ private readonly registry;
48
+ private readonly triggers;
49
+ private readonly inbox;
50
+ private readonly outbox;
51
+ private readonly keys;
52
+ constructor(kdb: KernelDb, txHost: TransactionHost, lock: XactLock, registry: ExtensionRegistry, triggers: TriggerEventsService, inbox: InboxItemsService, outbox: OutboxService, keys: ExtensionEffectKeys);
53
+ private instance;
54
+ private normalize;
55
+ prepare(plugin: string, orgId: string, key: string, effect: ExtensionEffect, extensionTx?: Kysely<unknown>): Promise<SignedEnvelope<{
56
+ plugin: string;
57
+ principal: {
58
+ kind: "extension";
59
+ name: string;
60
+ };
61
+ orgId: string;
62
+ key: string;
63
+ effect: PreparedEffect;
64
+ payloadHash: string;
65
+ issuedAt: number;
66
+ causeWindow?: {
67
+ createdAt: number;
68
+ expiresAt: number;
69
+ };
70
+ }>>;
71
+ verify(envelope: ExtensionEffectEnvelope, ring?: EnvelopeKeyring): Promise<EffectBody>;
72
+ commit(plugin: string, orgId: string, key: string | undefined, effect: ExtensionEffect): Promise<unknown>;
73
+ deliver(body: EffectBody): Promise<unknown>;
74
+ cancelIfDeleted(body: EffectBody): Promise<boolean>;
75
+ private activeOrg;
76
+ private apply;
77
+ private applyNew;
78
+ park(orgId: string | undefined, jobId: string, data: HandoffReference, reason: string, attempts: number): Promise<boolean>;
79
+ private inboxKeyIsResolved;
80
+ }
81
+ export {};