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

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 (135) 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/catalog/catalog.service.d.ts +2 -0
  11. package/dist/catalog/catalog.service.js +28 -5
  12. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  13. package/dist/catalog/marketplace-fetch.js +15 -0
  14. package/dist/catalog/marketplaces.service.d.ts +4 -4
  15. package/dist/catalog/marketplaces.service.js +3 -2
  16. package/dist/catalog/owned-items.d.ts +2 -0
  17. package/dist/catalog/owned-items.js +30 -31
  18. package/dist/catalog/ownership.js +40 -38
  19. package/dist/catalog/plugin-import.d.ts +3 -4
  20. package/dist/catalog/plugin-import.js +50 -1
  21. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  22. package/dist/catalog/plugin-upgrade.js +95 -7
  23. package/dist/catalog/publisher-policy.d.ts +9 -0
  24. package/dist/catalog/publisher-policy.js +12 -0
  25. package/dist/catalog/unshare.js +66 -58
  26. package/dist/client/client-access.service.js +5 -3
  27. package/dist/config/schema.js +1 -1
  28. package/dist/conversations/conversations.controller.js +4 -14
  29. package/dist/conversations/conversations.service.d.ts +14 -0
  30. package/dist/conversations/conversations.service.js +20 -2
  31. package/dist/ctx/create-ctx.d.ts +11 -2
  32. package/dist/ctx/create-ctx.js +121 -52
  33. package/dist/ctx/queue.js +7 -4
  34. package/dist/db/extension-rls-predicate.d.ts +1 -0
  35. package/dist/db/extension-rls-predicate.js +8 -0
  36. package/dist/db/kernel-schema.d.ts +48 -0
  37. package/dist/db/migrator.js +6 -13
  38. package/dist/db/pool.d.ts +2 -2
  39. package/dist/db/pool.js +2 -2
  40. package/dist/db/sql-statements.d.ts +3 -0
  41. package/dist/db/sql-statements.js +15 -5
  42. package/dist/device-access/device-access.module.js +12 -2
  43. package/dist/device-access/device-access.service.d.ts +30 -2
  44. package/dist/device-access/device-access.service.js +38 -4
  45. package/dist/device-access/host-gate.d.ts +45 -0
  46. package/dist/device-access/host-gate.js +92 -0
  47. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  48. package/dist/device-access/host-service-stop-sweep.js +112 -0
  49. package/dist/device-access/host-service-stop.d.ts +78 -0
  50. package/dist/device-access/host-service-stop.js +144 -0
  51. package/dist/device-access/host-services.d.ts +211 -0
  52. package/dist/device-access/host-services.js +803 -0
  53. package/dist/device-access/person-handles.d.ts +10 -0
  54. package/dist/device-access/person-handles.js +25 -0
  55. package/dist/device-access/service-events.d.ts +199 -0
  56. package/dist/device-access/service-events.js +704 -0
  57. package/dist/device-access/token.d.ts +5 -0
  58. package/dist/device-access/token.js +5 -0
  59. package/dist/devices/devices.service.js +3 -0
  60. package/dist/dial-in/access.d.ts +5 -5
  61. package/dist/dial-in/access.js +19 -12
  62. package/dist/dial-in/gateway.js +6 -2
  63. package/dist/dial-in/machines.d.ts +9 -2
  64. package/dist/dial-in/machines.js +27 -4
  65. package/dist/erasure/device-cleanup.js +12 -0
  66. package/dist/erasure/org-catalog.js +2 -2
  67. package/dist/erasure/org-rules.js +9 -0
  68. package/dist/errors.d.ts +2 -0
  69. package/dist/errors.js +2 -0
  70. package/dist/extensions/admin-ops.js +8 -2
  71. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  72. package/dist/extensions/deployed-snapshots.js +7 -2
  73. package/dist/extensions/host.d.ts +7 -2
  74. package/dist/extensions/host.js +11 -2
  75. package/dist/extensions/instance.d.ts +3 -0
  76. package/dist/extensions/instance.js +4 -0
  77. package/dist/extensions/ledger.d.ts +1 -1
  78. package/dist/extensions/lifecycle-hooks.js +3 -3
  79. package/dist/extensions/org-config.js +6 -1
  80. package/dist/extensions/permission-set.d.ts +7 -0
  81. package/dist/extensions/permission-set.js +10 -0
  82. package/dist/extensions/permission-view.d.ts +1 -1
  83. package/dist/extensions/permission-view.js +10 -1
  84. package/dist/git/tickets.js +32 -27
  85. package/dist/http/app.js +5 -3
  86. package/dist/identity/accounts.d.ts +6 -1
  87. package/dist/identity/accounts.js +11 -2
  88. package/dist/identity/api-tokens.js +7 -6
  89. package/dist/identity/settings.d.ts +9 -1
  90. package/dist/identity/settings.js +16 -1
  91. package/dist/inbox/org-notices.js +3 -2
  92. package/dist/index.d.ts +1 -0
  93. package/dist/index.js +1 -0
  94. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  95. package/dist/infra/database/scoped-dialect.js +260 -72
  96. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  97. package/dist/infra/database/startup-activation-transaction.js +3 -2
  98. package/dist/infra/outbox/registry.d.ts +28 -0
  99. package/dist/infra/outbox/registry.js +30 -0
  100. package/dist/infra/queue/queue-names.d.ts +1 -1
  101. package/dist/infra/queue/queue-names.js +1 -0
  102. package/dist/infra/queue/run-job.d.ts +4 -1
  103. package/dist/infra/queue/run-job.js +10 -2
  104. package/dist/kernel.module.js +3 -0
  105. package/dist/orgs/offboarding.js +18 -9
  106. package/dist/orgs/settings.service.js +3 -0
  107. package/dist/packages/npm-publish-keys.json +27 -0
  108. package/dist/packages/official-publisher.d.ts +19 -0
  109. package/dist/packages/official-publisher.js +152 -0
  110. package/dist/packages/provenance.d.ts +7 -0
  111. package/dist/packages/provenance.js +22 -19
  112. package/dist/packages/sigstore-trusted-root.json +126 -0
  113. package/dist/platform/ops/admin.ops.js +2 -1
  114. package/dist/platform/ops/orgs.ops.js +1 -0
  115. package/dist/roles/worker-role.d.ts +6 -3
  116. package/dist/roles/worker-role.js +12 -4
  117. package/dist/roles/worker.module.js +7 -0
  118. package/dist/runtime/maintenance.d.ts +5 -2
  119. package/dist/runtime/maintenance.js +18 -4
  120. package/dist/sandbox/device-reports.d.ts +4 -4
  121. package/dist/sandbox/device-reports.js +40 -30
  122. package/dist/sandbox/device-services.d.ts +2 -1
  123. package/dist/sandbox/device-services.js +5 -1
  124. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  125. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  126. package/dist/sandbox/permission-config-publication.js +5 -1
  127. package/dist/themes/theme-state.js +24 -13
  128. package/dist/tools/call-scope.d.ts +6 -0
  129. package/dist/tools/call-scope.js +22 -0
  130. package/dist/tools/registry.js +20 -2
  131. package/dist/ui/views.js +36 -8
  132. package/package.json +9 -4
  133. package/src/migrations/0222_device_host_services.sql +27 -0
  134. package/src/migrations/0223_device_service_events.sql +54 -0
  135. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
@@ -778,6 +778,10 @@ let ConversationsService = class ConversationsService {
778
778
  const { kind: _kind, ...row } = await this.readable(orgId, conversationId, viewerAccountId);
779
779
  return toView(row);
780
780
  }
781
+ async getWithOwner(orgId, conversationId, viewerAccountId) {
782
+ const conversation = await this.get(orgId, conversationId, viewerAccountId);
783
+ return { ...conversation, owner: await this.person(conversation.accountId) };
784
+ }
781
785
  /**
782
786
  * {@link get} for a change made by a person (a message, rename, queue, model switch): a
783
787
  * sub-agent's conversation is read-only (sub-agents spec §6.1) → `conversation.read_only`.
@@ -837,8 +841,8 @@ let ConversationsService = class ConversationsService {
837
841
  .$if(opts.total === true, (qb) => qb.select(sql `count(*) OVER ()`.as("total_count")))
838
842
  .where("org_id", "=", orgId)
839
843
  .where("account_id", "=", accountId)
840
- // 评测回放的隐藏对话(kind = 'eval')不在「我的对话」里
841
- .where("kind", "=", "chat")
844
+ // Keep the fixed kind literal so generic plans can use the partial chat index.
845
+ .where("kind", "=", sql.lit("chat"))
842
846
  .where("deleted_at", "is", null)
843
847
  .where("archived_at", opts.archived === true ? "is not" : "is", null)
844
848
  .where((eb) => eb.exists(eb
@@ -1151,6 +1155,14 @@ let ConversationsService = class ConversationsService {
1151
1155
  await this.get(orgId, conversationId, viewerAccountId);
1152
1156
  return this.eventLog.readTurnPageBefore(conversationId, beforeSeq, limit, EVENTS_TURN_EXTEND);
1153
1157
  }
1158
+ async listEventsWithPeople(orgId, conversationId, viewerAccountId, page) {
1159
+ const result = "before" in page
1160
+ ? await this.listEventsBefore(orgId, conversationId, viewerAccountId, page.before, page.limit)
1161
+ : {
1162
+ events: await this.listEvents(orgId, conversationId, viewerAccountId, page.after, page.limit),
1163
+ };
1164
+ return { ...result, people: await this.eventPeople(result.events) };
1165
+ }
1154
1166
  /**
1155
1167
  * Appends a user message; a repeated send with the same `clientMessageId` returns the same
1156
1168
  * event. After the write it calls `ensureRun`: with no run in progress it enqueues one; during
@@ -1976,6 +1988,12 @@ __decorate([
1976
1988
  __decorate([
1977
1989
  Transactional()
1978
1990
  ], ConversationsService.prototype, "markDeleted", null);
1991
+ __decorate([
1992
+ Transactional({ accessMode: "read only" })
1993
+ ], ConversationsService.prototype, "getWithOwner", null);
1994
+ __decorate([
1995
+ Transactional({ accessMode: "read only" })
1996
+ ], ConversationsService.prototype, "listEventsWithPeople", null);
1979
1997
  __decorate([
1980
1998
  Transactional({ propagation: "requires_new" })
1981
1999
  ], ConversationsService.prototype, "postIn", null);
@@ -4,6 +4,7 @@ import { Kysely } from "kysely";
4
4
  import type { TriggerEventsService } from "../automations/events/trigger-events.service.js";
5
5
  import { pluginSchemaName } from "../db/extension-db.js";
6
6
  import type { DeviceAccessService } from "../device-access/device-access.service.js";
7
+ import type { ServiceEventHandler, ServiceEventsBackend } from "../device-access/service-events.js";
7
8
  import type { DialInAccess } from "../dial-in/access.js";
8
9
  import { type RegisteredHook } from "../extensions/hooks.js";
9
10
  import { RegistrationLedger } from "../extensions/ledger.js";
@@ -68,7 +69,7 @@ export interface KernelDeps {
68
69
  * served by the calling extension. Absent (a ctx built alone in a test): `ctx.dialIn` calls
69
70
  * reject.
70
71
  */
71
- dialIn?: Pick<DialInAccess, "serves" | "request" | "online" | "capacity" | "stop" | "openStream">;
72
+ dialIn?: Pick<DialInAccess, "servedOrg" | "request" | "online" | "capacity" | "stop" | "openStream">;
72
73
  /**
73
74
  * What `ctx.devices` is built from (`DeviceReports`): `changed` reads a device's report again
74
75
  * from the calling provider and refuses (`not-served`) a device bound to another one. Absent
@@ -81,6 +82,12 @@ export interface KernelDeps {
81
82
  * a test, the CLI): `ctx.deviceAccess` calls are refused.
82
83
  */
83
84
  deviceAccess?: () => DeviceAccessBackend | undefined;
85
+ /**
86
+ * What `ctx.devices.serviceEvent` calls through (`ServiceEvents`), found at the time of use like
87
+ * `deviceAccess`. Absent, or resolving to undefined (a ctx built alone in a test, the CLI):
88
+ * `ctx.devices.serviceEvent` rejects.
89
+ */
90
+ serviceEvents?: () => ServiceEventsBackend | undefined;
84
91
  /**
85
92
  * What `ctx.triggers` calls through (`TriggerEventsService`), found at the time of use like
86
93
  * `deviceAccess`. Absent, or resolving to undefined (a ctx built alone in a test, the CLI):
@@ -105,7 +112,7 @@ export interface KernelDeps {
105
112
  };
106
113
  }
107
114
  /** What `ctx.deviceAccess` calls through (`DeviceAccessService`). */
108
- export type DeviceAccessBackend = Pick<DeviceAccessService, "ensureService" | "request" | "reportBlockedHosts" | "requestSiteAccess" | "siteGrants" | "revokeSiteGrant" | "streamTicket" | "addNetworkHosts" | "answerHandoff" | "grantLoopbackPort" | "revokeLoopbackPort" | "loopbackPorts">;
115
+ export type DeviceAccessBackend = Pick<DeviceAccessService, "ensureService" | "request" | "reportBlockedHosts" | "requestSiteAccess" | "siteGrants" | "revokeSiteGrant" | "streamTicket" | "addNetworkHosts" | "answerHandoff" | "grantLoopbackPort" | "revokeLoopbackPort" | "loopbackPorts" | "ensureHostService" | "hostRequest" | "stopHostService" | "personalDevices">;
109
116
  /** What `ctx.triggers` calls through (`TriggerEventsService`). */
110
117
  export type TriggersBackend = Pick<TriggerEventsService, "emit" | "causeOf">;
111
118
  /** What `ctx.inbox` calls through (`InboxItemsService`). */
@@ -216,6 +223,8 @@ export type KernelExtensionContext = ExtensionContext & {
216
223
  uiQueries: ReadonlyMap<string, UiQueryHandler>;
217
224
  /** Setup checks registered through `ctx.setup.check`, by id. */
218
225
  setupChecks: ReadonlyMap<string, RegisteredSetupCheck>;
226
+ /** Handlers registered through `ctx.deviceAccess.onServiceEvent`, by host service name. */
227
+ serviceEventHandlers: ReadonlyMap<string, ServiceEventHandler>;
219
228
  /**
220
229
  * setup 结束后调用:此后 `tools.register`、`ui.view`、`ui.action`、`hooks.on`、`setup.check` 抛错。
221
230
  */
@@ -4,11 +4,11 @@ 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 { currentScope, withOrgScope } from "../infra/database/org-scope.js";
12
12
  import { can } from "../orgs/roles.js";
13
13
  import { PrefixedStorage } from "../storage/storage.service.js";
14
14
  import { canUseSlot, orgUiTopic, PLATFORM_UI_TOPIC, PluginUiRegistration, } from "../ui/registry.js";
@@ -96,20 +96,27 @@ export async function currentPlatformAccount(db, accountId) {
96
96
  .executeTakeFirst();
97
97
  return row !== undefined;
98
98
  }
99
- /** `ui.invalidate` 目标的一条查询:插件在该组织启用,且(带对话时)对话属于该组织。 */
99
+ /**
100
+ * An invalidation target must be in a live org where the extension is enabled. A supplied
101
+ * conversation must be live and belong to that same org.
102
+ */
100
103
  async function invalidateTargetOk(db, plugin, orgId, conversationId) {
101
104
  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;
105
+ let target = k
106
+ .selectFrom("orgs")
107
+ .innerJoin(enabledExtensionsQuery(k, orgId).as("en"), (join) => join.on("en.plugin", "=", plugin))
108
+ .select("orgs.id")
109
+ .where("orgs.id", "=", orgId)
110
+ .where("orgs.deleted_at", "is", null);
111
+ if (conversationId !== undefined) {
112
+ target = target.where((eb) => eb.exists(eb
113
+ .selectFrom("conversations")
114
+ .select("conversations.id")
115
+ .where("conversations.id", "=", conversationId)
116
+ .where("conversations.org_id", "=", orgId)
117
+ .where("conversations.deleted_at", "is", null)));
118
+ }
119
+ return (await target.executeTakeFirst()) !== undefined;
113
120
  }
114
121
  /** 越权审计去重键的 TTL:同一插件同一项在此期间只记一次。 */
115
122
  const DENIAL_DEDUPE_TTL_SECONDS = 30 * 24 * 3600;
@@ -262,6 +269,7 @@ identity = { sha256: null }) {
262
269
  // 界面刷新发在内核命名空间(会话主题 conv.<id> / 组织主题 org-ui.<orgId>),不在插件自己的命名空间
263
270
  const kernelBus = createBus(deps.redis, deps.busSubscriber, "kernel", deps.log);
264
271
  const ledger = new RegistrationLedger(name);
272
+ const serviceEventHandlers = new Map();
265
273
  const lifecycle = new AbortController();
266
274
  /** 撤销时队列 worker 排空的截止时刻(epoch 毫秒);undefined = 一直等(停机路径)。 */
267
275
  let drainDeadline;
@@ -311,15 +319,22 @@ identity = { sha256: null }) {
311
319
  // by the declared purpose's kind; an undeclared purpose has none, so its refusal
312
320
  // (model.purpose_unknown) names no kind
313
321
  describe: async (req) => {
314
- if (!deps.models)
322
+ const models = deps.models;
323
+ if (!models)
315
324
  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`);
325
+ const orgId = req?.orgId;
326
+ const purpose = req?.purpose;
327
+ const kind = declaredModels.find((d) => d.purpose === purpose)?.kind;
328
+ if (kind === undefined && typeof purpose === "string") {
329
+ throw new ApiError("model.purpose_unknown", `Extension ${name} declared no model purpose "${purpose}" in permissions.models`);
319
330
  }
320
- return kind === "image_generation"
321
- ? deps.models.images.describeForExtension(name, declaredModels, req)
322
- : deps.models.embeddings.describe(name, declaredModels, req);
331
+ if (typeof orgId !== "string" || orgId === "" || typeof purpose !== "string") {
332
+ throw new ApiError("validation_failed", "describe needs orgId and purpose strings");
333
+ }
334
+ const target = { orgId, purpose };
335
+ return withOrgScope(orgId, () => kind === "image_generation"
336
+ ? models.images.describeForExtension(name, declaredModels, target)
337
+ : models.embeddings.describe(name, declaredModels, target));
323
338
  },
324
339
  }
325
340
  : undefined;
@@ -330,10 +345,11 @@ identity = { sha256: null }) {
330
345
  const dialInApi = perms.dialIn
331
346
  ? (() => {
332
347
  const access = deps.dialIn;
333
- const served = async (deviceId) => {
348
+ const inServedOrg = async (deviceId, run) => {
334
349
  if (!access)
335
350
  throw new Error(`plugin ${name}: ctx.dialIn is not available`);
336
- if (typeof deviceId !== "string" || !(await access.serves(name, deviceId))) {
351
+ const orgId = typeof deviceId === "string" ? await access.servedOrg(name, deviceId) : undefined;
352
+ if (orgId === undefined) {
337
353
  const item = `dialIn:device ${String(deviceId)}`;
338
354
  const p = recordDenial(deps, name, item).finally(() => audits.delete(p));
339
355
  audits.add(p);
@@ -341,36 +357,33 @@ identity = { sha256: null }) {
341
357
  e.message = `device ${String(deviceId)} is not served by ${name}`;
342
358
  throw e;
343
359
  }
344
- return deviceId;
360
+ return withOrgScope(orgId, () => run(access));
345
361
  };
346
362
  return {
347
- request: async (deviceId, frame, opts) => {
348
- const id = await served(deviceId);
363
+ request: (deviceId, frame, opts) => inServedOrg(deviceId, (dialIn) => {
349
364
  const signal = opts?.signal
350
365
  ? AbortSignal.any([lifecycle.signal, opts.signal])
351
366
  : lifecycle.signal;
352
- // only the options an extension may pass: never the kernel's connection fences
353
- return access.request(id, frame, {
367
+ // Only the options an extension may pass, excluding the kernel's connection fences.
368
+ return dialIn.request(deviceId, frame, {
354
369
  timeoutMs: Number(opts?.timeoutMs),
355
370
  signal,
356
371
  });
357
- },
358
- online: async (deviceId) => access.online(await served(deviceId)),
359
- capacity: async (deviceId) => access.capacity(await served(deviceId)),
372
+ }),
373
+ online: (deviceId) => inServedOrg(deviceId, (dialIn) => dialIn.online(deviceId)),
374
+ capacity: (deviceId) => inServedOrg(deviceId, (dialIn) => dialIn.capacity(deviceId)),
360
375
  stop: async (deviceId, reason) => {
361
376
  if (reason !== "drain" && reason !== "stop")
362
377
  throw new TypeError(`plugin ${name}: ctx.dialIn.stop reason must be drain or stop`);
363
- await access.stop(await served(deviceId), reason);
378
+ await inServedOrg(deviceId, (dialIn) => dialIn.stop(deviceId, reason));
364
379
  },
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
380
+ // Only the gateway replica holding the machine's socket opens the stream.
381
+ // The extension's end closes its streams.
382
+ openStream: (deviceId, body, opts) => inServedOrg(deviceId, async (dialIn) => {
370
383
  if (!(opts?.signal instanceof AbortSignal))
371
384
  throw new TypeError(`plugin ${name}: ctx.dialIn.openStream needs opts.signal`);
372
385
  const signal = AbortSignal.any([lifecycle.signal, opts.signal]);
373
- const stream = await access.openStream(id, body, signal);
386
+ const stream = await dialIn.openStream(deviceId, body, signal);
374
387
  const onEnd = () => stream.close("extension stopped");
375
388
  if (lifecycle.signal.aborted)
376
389
  onEnd();
@@ -379,7 +392,7 @@ identity = { sha256: null }) {
379
392
  void stream.closed.then(() => lifecycle.signal.removeEventListener("abort", onEnd));
380
393
  }
381
394
  return stream;
382
- },
395
+ }),
383
396
  };
384
397
  })()
385
398
  : undefined;
@@ -388,6 +401,30 @@ identity = { sha256: null }) {
388
401
  // and, when its revision changed, moves the device authority epoch (device-provider spec §6.7)
389
402
  const devicesApi = manifest.provides.includes(DEVICE_PROVIDER_EXTENSION_POINT)
390
403
  ? {
404
+ // stored with its owed delivery (ServiceEvents); resolves once committed, so the provider
405
+ // acks the machine only then. An event of a service the kernel did not place there as a
406
+ // host service resolves too (dropped, logged): the machine stops sending it
407
+ serviceEvent: async (args) => {
408
+ const events = deps.serviceEvents?.();
409
+ if (!events)
410
+ throw new Error(`plugin ${name}: ctx.devices.serviceEvent is not available`);
411
+ // one snapshot, read once: what is checked is what is stored
412
+ const e = {
413
+ deviceId: args?.deviceId,
414
+ service: args?.service,
415
+ seq: args?.seq,
416
+ body: args?.body,
417
+ };
418
+ const outcome = await events.record(name, e);
419
+ if (outcome === "not-served") {
420
+ const item = `devices:device ${String(e.deviceId)}`;
421
+ const p = recordDenial(deps, name, item).finally(() => audits.delete(p));
422
+ audits.add(p);
423
+ const err = new ExtensionPermissionError(name, `provides ${DEVICE_PROVIDER_EXTENSION_POINT}`);
424
+ err.message = `device ${String(e.deviceId)} is not served by ${name}`;
425
+ throw err;
426
+ }
427
+ },
391
428
  reportChanged: async (deviceId) => {
392
429
  const reports = deps.devices;
393
430
  if (!reports)
@@ -419,6 +456,8 @@ identity = { sha256: null }) {
419
456
  // read from the approved manifest: an upgrade adding it waits for approval again
420
457
  loopbackPorts: perms.deviceAccess?.loopbackPorts === true,
421
458
  siteAccess: perms.deviceAccess?.siteAccess === true,
459
+ // read from the approved manifest: only these may run outside the device sandbox
460
+ hostServices: [...(perms.deviceAccess?.hostServices ?? [])],
422
461
  };
423
462
  const backend = () => {
424
463
  const b = deps.deviceAccess?.();
@@ -439,6 +478,32 @@ identity = { sha256: null }) {
439
478
  requestSiteAccess: (call, ask) => backend().requestSiteAccess(caller, call, ask),
440
479
  siteGrants: async (scope) => backend().siteGrants(caller, scope),
441
480
  revokeSiteGrant: async (scope) => backend().revokeSiteGrant(caller, scope),
481
+ // host services: the approved manifest's hostServices, on the person's own machine
482
+ ensureHostService: async (at, spec) => backend().ensureHostService(caller, at, spec),
483
+ hostRequest: async (at, req) => backend().hostRequest(caller, at, req),
484
+ stopHostService: async (at, service) => backend().stopHostService(caller, at, service),
485
+ personalDevices: async (args) => backend().personalDevices(caller, args),
486
+ // during setup only, for a host service of the approved manifest: the deliveries
487
+ // (ServiceEvents, worker role) call it on whichever replica takes the job
488
+ onServiceEvent: (service, handler) => {
489
+ if (toolsSealed)
490
+ throw new Error(`plugin ${name}: deviceAccess.onServiceEvent is only allowed during setup; setup has completed`);
491
+ if (typeof service !== "string" || !caller.hostServices.includes(service))
492
+ throw new DeviceAccessError("host_not_declared", `The host service ${JSON.stringify(service)} is not declared in permissions.deviceAccess.hostServices.`);
493
+ if (typeof handler !== "function")
494
+ throw new Error(`plugin ${name}: onServiceEvent("${service}") needs a handler function`);
495
+ if (serviceEventHandlers.has(service))
496
+ throw new Error(`plugin ${name}: duplicate onServiceEvent handler for "${service}"`);
497
+ serviceEventHandlers.set(service, handler);
498
+ ledger.add({
499
+ kind: "service.event",
500
+ key: service,
501
+ dispose: async () => {
502
+ if (serviceEventHandlers.get(service) === handler)
503
+ serviceEventHandlers.delete(service);
504
+ },
505
+ });
506
+ },
442
507
  };
443
508
  })()
444
509
  : undefined;
@@ -665,15 +730,17 @@ identity = { sha256: null }) {
665
730
  * the org (layering spec A §6: a call on behalf of an org never reaches such a provider).
666
731
  */
667
732
  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]);
733
+ if (orgId === "" || entries.length === 0)
734
+ return [];
735
+ return withOrgScope(orgId, async () => {
736
+ let out = entries;
737
+ if (orgScoped) {
738
+ const enabled = await extensionPointAccess.enabledPlugins(orgId);
739
+ out = out.filter((e) => enabled.has(e.plugin));
740
+ }
741
+ const ok = await Promise.all(out.map((e) => extensionPointAccess.configOk(orgId, e.plugin)));
742
+ return out.filter((_, i) => ok[i]);
743
+ });
677
744
  };
678
745
  const listAll = (ref) => {
679
746
  const info = checkExtensionPoint(ref);
@@ -937,9 +1004,7 @@ identity = { sha256: null }) {
937
1004
  },
938
1005
  });
939
1006
  },
940
- // 目标先核对(一条查询):插件在 orgId 启用;带对话时对话属于 orgId。不满足就只记 debug、不发
941
- // (插件拿着过期或别的组织的 id 调用不是错误,但不能借它往别的组织的流里发刷新)。A `platform.page`
942
- // contribution takes no orgId and refreshes the platform stream (super admins only)
1007
+ // Verify the target before publishing a refresh hint. Platform pages use their own stream.
943
1008
  async invalidate(target) {
944
1009
  const t = uiReg.target(target, platformUi);
945
1010
  // `queries`: the contribution's component queries are refetched too (full pages spec §4.1)
@@ -953,7 +1018,10 @@ identity = { sha256: null }) {
953
1018
  await kernelBus.publish(PLATFORM_UI_TOPIC, msg);
954
1019
  return;
955
1020
  }
956
- if (!(await invalidateTargetOk(deps.db, name, t.orgId, t.conversationId))) {
1021
+ const scope = currentScope();
1022
+ const allowed = (scope?.kind !== "org" || scope.orgId === t.orgId) &&
1023
+ (await withOrgScope(t.orgId, () => invalidateTargetOk(deps.db, name, t.orgId, t.conversationId)));
1024
+ if (!allowed) {
957
1025
  deps.log.debug?.("plugin ui invalidate ignored: plugin not enabled or conversation not in org", {
958
1026
  plugin: name,
959
1027
  orgId: t.orgId,
@@ -1009,6 +1077,7 @@ identity = { sha256: null }) {
1009
1077
  uiActions: uiReg.actions,
1010
1078
  uiQueries: uiReg.queries,
1011
1079
  setupChecks,
1080
+ serviceEventHandlers,
1012
1081
  ledger,
1013
1082
  async beginDispose(deadline) {
1014
1083
  drainDeadline = deadline;
package/dist/ctx/queue.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Queue, Worker } from "bullmq";
2
2
  import { Redis } from "ioredis";
3
+ import { currentScope } from "../infra/database/org-scope.js";
3
4
  import { runJob } from "../infra/queue/run-job.js";
4
5
  import { assertNamespace } from "./namespace.js";
5
6
  /** 未注入 logger 时的兜底:输出到 stderr。 */
@@ -62,7 +63,7 @@ export function createQueue(redisUrl, namespace, opts) {
62
63
  const st = { n: 0, idle: [] };
63
64
  active.set(name, st);
64
65
  const worker = new Worker(queueName(name),
65
- // runJob: the log context and the org scope of the job (its data's `orgId`, else platform)
66
+ // A job from an older producer has no recorded scope and runs unscoped.
66
67
  (job) => runJob(queueName(name), job, async () => {
67
68
  st.n += 1;
68
69
  try {
@@ -74,7 +75,7 @@ export function createQueue(redisUrl, namespace, opts) {
74
75
  for (const w of st.idle.splice(0))
75
76
  w();
76
77
  }
77
- }),
78
+ }, { scope: job.opts.capybaraScope ?? null }),
78
79
  // 撤销插件实例时到点仍未完成的任务被强制留在队列里(锁过期后按 stalled 交回),新实例再执行一次:
79
80
  // 任务是至少一次。stalled 次数放宽到 3,连续几次撤销 / 升级不至于把任务判为失败
80
81
  { connection: newConn(), concurrency: o?.concurrency ?? 1, maxStalledCount: 3 });
@@ -87,14 +88,16 @@ export function createQueue(redisUrl, namespace, opts) {
87
88
  assertNoColon("queue name", name);
88
89
  if (o?.jobId !== undefined)
89
90
  assertNoColon("jobId", o.jobId);
90
- await getQueue(name).add(name, data, {
91
+ const jobOptions = {
92
+ capybaraScope: currentScope() ?? null,
91
93
  ...(o?.jobId !== undefined && { jobId: o.jobId }),
92
94
  ...(o?.delayMs !== undefined && { delay: o.delayMs }),
93
95
  attempts: 3,
94
96
  backoff: { type: "exponential", delay: 1000 },
95
97
  removeOnComplete: 1000,
96
98
  removeOnFail: 5000,
97
- });
99
+ };
100
+ await getQueue(name).add(name, data, jobOptions);
98
101
  },
99
102
  async pauseWorkers() {
100
103
  await Promise.all([...workers.values()].map((w) => w.pause(true).catch(() => { })));
@@ -0,0 +1 @@
1
+ export declare const EXTENSION_RLS_PREDICATE = "CREATE OR REPLACE FUNCTION rls_admits(row_org text) RETURNS boolean\nLANGUAGE sql STABLE PARALLEL SAFE AS $$\n SELECT coalesce(pg_catalog.current_setting('capybara.rls', true), '') <> 'enforce'\n OR pg_catalog.current_setting('capybara.scope', true) = 'platform'\n OR row_org = pg_catalog.current_setting('capybara.org_id', true)\n$$;";
@@ -0,0 +1,8 @@
1
+ // The host installs this exact statement in each extension schema. Package review also
2
+ // accepts this spelling in plugin migrations that support deployments with a single login.
3
+ export const EXTENSION_RLS_PREDICATE = `CREATE OR REPLACE FUNCTION rls_admits(row_org text) RETURNS boolean
4
+ LANGUAGE sql STABLE PARALLEL SAFE AS $$
5
+ SELECT coalesce(pg_catalog.current_setting('capybara.rls', true), '') <> 'enforce'
6
+ OR pg_catalog.current_setting('capybara.scope', true) = 'platform'
7
+ OR row_org = pg_catalog.current_setting('capybara.org_id', true)
8
+ $$;`;
@@ -1300,6 +1300,51 @@ export interface DeviceSiteGrantsTable {
1300
1300
  expires_at: ColumnType<Date, Date | string, Date | string>;
1301
1301
  revoked_at: TsNullable;
1302
1302
  }
1303
+ /**
1304
+ * 0222: a host device service running, or being started, on a personal machine (intent first,
1305
+ * deleted on a confirmed stop); `stop_owed_at` marks a stop the kernel owes until the machine
1306
+ * confirms it.
1307
+ */
1308
+ export interface DeviceHostServicesTable {
1309
+ org_id: string;
1310
+ device_id: string;
1311
+ extension: string;
1312
+ /** The service's name as the extension declares it (the provider's id is `<extension>.<service>`). */
1313
+ service: string;
1314
+ /** The files digest last started (null before the first confirmed start). */
1315
+ digest: ColumnType<string | null, string | null | undefined, string | null>;
1316
+ started_at: TsNullable;
1317
+ stop_owed_at: TsNullable;
1318
+ created_at: Ts;
1319
+ }
1320
+ /**
1321
+ * 0223: an event a host device service emitted (`ctx.devices.serviceEvent`), delivered in `seq`
1322
+ * order per (device, extension, service) to the extension's `onServiceEvent` handler;
1323
+ * `delivered_at` is set once delivered or dropped.
1324
+ */
1325
+ export interface DeviceServiceEventsTable {
1326
+ org_id: string;
1327
+ device_id: string;
1328
+ extension: string;
1329
+ /** The service's name as the extension declares it (the provider's id is `<extension>.<service>`). */
1330
+ service: string;
1331
+ /** The device's sequence number of the event (from 1, per device and service). */
1332
+ seq: Int8;
1333
+ body: Buffer;
1334
+ created_at: Ts;
1335
+ delivered_at: TsNullable;
1336
+ /** Set when the sweep found the event's delivery stalled and owed it again. */
1337
+ stalled_at: TsNullable;
1338
+ }
1339
+ /** 0223: the last seq delivered per (device, extension, service); never swept. */
1340
+ export interface DeviceServiceEventCursorsTable {
1341
+ org_id: string;
1342
+ device_id: string;
1343
+ extension: string;
1344
+ service: string;
1345
+ delivered_seq: Int8;
1346
+ updated_at: Ts;
1347
+ }
1303
1348
  /** 0088_environments.sql, renamed in 0105: the device a member's new conversations use by default. */
1304
1349
  export interface DeviceDefaultsTable {
1305
1350
  org_id: string;
@@ -2053,6 +2098,9 @@ export interface KernelDatabase {
2053
2098
  device_conversation_notices: DeviceConversationNoticesTable;
2054
2099
  device_loopback_grants: DeviceLoopbackGrantsTable;
2055
2100
  device_site_grants: DeviceSiteGrantsTable;
2101
+ device_host_services: DeviceHostServicesTable;
2102
+ device_service_events: DeviceServiceEventsTable;
2103
+ device_service_event_cursors: DeviceServiceEventCursorsTable;
2056
2104
  background_tasks: BackgroundTasksTable;
2057
2105
  automations: AutomationsTable;
2058
2106
  automation_runs: AutomationRunsTable;
@@ -4,18 +4,10 @@ import { join } from "node:path";
4
4
  import { sql } from "kysely";
5
5
  import pg from "pg";
6
6
  import { assertExtensionSchemaOwner, assertExtensionSession } from "./extension-db.js";
7
+ import { EXTENSION_RLS_PREDICATE } from "./extension-rls-predicate.js";
7
8
  import { pgConnectOptions } from "./pool.js";
8
9
  /** 迁移文件名:`NNNN_<snake_desc>.sql`(其他文件忽略)。 */
9
10
  export const MIGRATION_FILE_RE = /^\d{4}_[a-z0-9_]+\.sql$/;
10
- // Keep this local to each extension schema so its login never needs USAGE on capybara.
11
- const extensionRlsPredicate = `
12
- create or replace function rls_admits(row_org text) returns boolean
13
- language sql stable parallel safe as $$
14
- select coalesce(pg_catalog.current_setting('capybara.rls', true), '') <> 'enforce'
15
- or pg_catalog.current_setting('capybara.scope', true) = 'platform'
16
- or row_org = pg_catalog.current_setting('capybara.org_id', true)
17
- $$
18
- `;
19
11
  const ident = (s) => `"${s.replaceAll('"', '""')}"`;
20
12
  const num = (name) => Number.parseInt(name.slice(0, 4), 10);
21
13
  export async function lockMigrationSchema(client, schema, scope) {
@@ -41,9 +33,10 @@ async function migrationFiles(dir) {
41
33
  }));
42
34
  }
43
35
  // Use the effective login on the actual connection, including when a URL sets a role.
36
+ // Roles are cluster-wide, so the schema owner in this database identifies a split installation.
44
37
  const kernelMigrationPrivileges = `
45
38
  select pg_catalog.has_database_privilege(current_user, current_database(), 'CREATE') as can_create,
46
- exists (select from pg_catalog.pg_roles where rolname = 'capybara_owner') as has_owner_role,
39
+ coalesce(n.nspowner = pg_catalog.to_regrole('capybara_owner'), false) as split_identity,
47
40
  current_user = pg_catalog.pg_get_userbyid(n.nspowner) as owns_schema
48
41
  from (values ('capybara'::name)) as target(schema_name)
49
42
  left join pg_catalog.pg_namespace n on n.nspname = target.schema_name
@@ -52,7 +45,7 @@ export async function canMigrateKernel(db) {
52
45
  const { rows: [privileges], } = await sql.raw(kernelMigrationPrivileges).execute(db);
53
46
  if (privileges === undefined)
54
47
  throw new Error("Could not read kernel migration privileges");
55
- return privileges.can_create && (privileges.owns_schema ?? !privileges.has_owner_role);
48
+ return privileges.can_create && (privileges.owns_schema ?? true);
56
49
  }
57
50
  const migrateHint = "Run capybara migrate with CAPYBARA_DB__MIGRATION_URL set to the schema owner URL for split roles.";
58
51
  /** Verify the files expected by this binary without taking a migration lock or writing the journal.
@@ -160,7 +153,7 @@ export async function migrate(connectionString, owner, opts = {}) {
160
153
  }
161
154
  if (schema === "capybara") {
162
155
  const { rows: [privileges], } = await client.query(kernelMigrationPrivileges);
163
- if (privileges?.has_owner_role && !privileges.owns_schema) {
156
+ if (privileges?.split_identity && !privileges.owns_schema) {
164
157
  throw new Error(`The migration login must own the capybara schema. ${migrateHint}`);
165
158
  }
166
159
  }
@@ -196,7 +189,7 @@ export async function migrate(connectionString, owner, opts = {}) {
196
189
  pg_catalog.set_config('capybara.org_id', '', true),
197
190
  pg_catalog.set_config('capybara.rls', 'off', true)`);
198
191
  if (applied.length === 0)
199
- await client.query(extensionRlsPredicate);
192
+ await client.query(EXTENSION_RLS_PREDICATE);
200
193
  }
201
194
  await client.query(f.content);
202
195
  await client.query(`insert into ${table} (name, checksum) values ($1, $2)`, [
package/dist/db/pool.d.ts CHANGED
@@ -31,8 +31,8 @@ export declare function createDb(url: string, poolMax: number, onError?: (err: E
31
31
  */
32
32
  onClientError?: ((err: Error) => void) | undefined;
33
33
  /**
34
- * `db.rls`: whether every connection carries the org scope of its caller (RLS spec §5.2;
35
- * `scoped-dialect.ts`). Unset = `off`, a plain pool.
34
+ * `db.rls` controls the scope carried by each PostgreSQL transaction (RLS spec §5.2).
35
+ * Unset uses a plain pool.
36
36
  */
37
37
  rls?: RlsMode | undefined;
38
38
  onConnect?: (client: pg.ClientBase) => Promise<void>;
package/dist/db/pool.js CHANGED
@@ -20,6 +20,7 @@ export function pgConnectOptions(cfg) {
20
20
  * `opts.connectTimeoutMs` 为建立连接的超时(不设则 pg 无限等待)。
21
21
  */
22
22
  export function createDb(url, poolMax, onError = (err) => console.error("[db] idle client error:", err), opts = {}) {
23
+ const rls = opts.rls ?? "off";
23
24
  const pool = new pg.Pool({
24
25
  connectionString: url,
25
26
  max: poolMax,
@@ -31,11 +32,10 @@ export function createDb(url, poolMax, onError = (err) => console.error("[db] id
31
32
  });
32
33
  pool.on("error", onError);
33
34
  pool.on("connect", (client) => client.on("error", opts.onClientError ?? onError));
34
- const rls = opts.rls ?? "off";
35
35
  return new Kysely({
36
36
  dialect: new ScopedPostgresDialect({
37
37
  pool: opts.closeActiveOnDestroy ? disposablePool(pool) : pool,
38
- }, rls),
38
+ }, rls, rls !== "off"),
39
39
  plugins: rls !== "off" && unscopedQueryCheck() ? [captureUnscopedQueryOrigins] : [],
40
40
  });
41
41
  }
@@ -5,6 +5,9 @@
5
5
  export type SqlStatement = {
6
6
  text: string;
7
7
  line: number;
8
+ /** Source range from the first token through the terminator, if present. */
9
+ startOffset: number;
10
+ endOffset: number;
8
11
  /** 语句里美元引用字符串的原文(不含定界符),按出现顺序;`DO $$ … $$` 的块体在这里。 */
9
12
  bodies: string[];
10
13
  /**