@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
@@ -0,0 +1,250 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
14
+ import { ExtensionRegistry } from "../extensions/registry.js";
15
+ import { ReplicaStatusStore } from "../extensions/sources.js";
16
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
17
+ import { handoffReference, markHandoffParked, readHandoff, readHandoffRow, readUnreferencedParks, retryHandoff, settleHandoff, } from "../infra/database/extension-handoff.js";
18
+ import { KernelDb } from "../infra/database/kernel-db.js";
19
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
20
+ import { LockService } from "../infra/lock/lock.service.js";
21
+ import { OutboxDispatcher } from "../infra/outbox/outbox.dispatcher.js";
22
+ import { LockedInterval } from "../infra/schedule/locked-interval.js";
23
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
24
+ import { ExtensionEffects } from "./durable-effects.service.js";
25
+ import { ExtensionEnvelopeClockSkew, effectHash, InvalidExtensionEnvelope, } from "./durable-envelope.js";
26
+ import { classifyEffectFailure, ExtensionEffectFailure, effectFailureMessage, } from "./durable-failure.js";
27
+ import { EXTENSION_EFFECT_REDRIVE_JOB } from "./durable-job.js";
28
+ import { ExtensionEffectKeys } from "./durable-keys.js";
29
+ const EXTENSION_HANDOFF_RELAY = "extension-handoff-relay";
30
+ const BATCH = 32;
31
+ const PARK_BUDGET = 4;
32
+ const LAST_RETRY = 19;
33
+ const HANDOFF_MISSING = "handoff_missing: The extension handoff table is missing";
34
+ let ExtensionEffectRelay = class ExtensionEffectRelay {
35
+ dispatcher;
36
+ effects;
37
+ keys;
38
+ identity;
39
+ registry;
40
+ status;
41
+ db;
42
+ config;
43
+ lockService;
44
+ log;
45
+ constructor(dispatcher, effects, keys, identity, registry, status, db, config, lockService, log) {
46
+ this.dispatcher = dispatcher;
47
+ this.effects = effects;
48
+ this.keys = keys;
49
+ this.identity = identity;
50
+ this.registry = registry;
51
+ this.status = status;
52
+ this.db = db;
53
+ this.config = config;
54
+ this.lockService = lockService;
55
+ this.log = log;
56
+ }
57
+ async relay(signal) {
58
+ await this.relayOnce(signal);
59
+ }
60
+ async retireKeys() {
61
+ await this.keys.retireUnused();
62
+ }
63
+ async relayOnce(signal) {
64
+ const plugins = await asPlatform("Find known extension handoff tables", () => this.db.db.selectFrom("extension_name_owners").select("name").execute());
65
+ const names = new Set([
66
+ ...plugins.map(({ name }) => name),
67
+ ...this.registry.all().map(({ name }) => name),
68
+ ]);
69
+ let loaded;
70
+ let loadedAt = 0;
71
+ let refreshed = false;
72
+ const load = () => {
73
+ loadedAt = Date.now();
74
+ return this.keys.forVerification();
75
+ };
76
+ const ring = async (row) => {
77
+ loaded ??= load();
78
+ let keys = await loaded;
79
+ const keyId = row.envelope?.keyId;
80
+ if (typeof keyId !== "string" || Object.hasOwn(keys.keys, keyId))
81
+ return keys;
82
+ if (!refreshed && /^[a-f0-9-]{36}$/i.test(keyId)) {
83
+ refreshed = true;
84
+ loaded = load();
85
+ keys = await loaded;
86
+ }
87
+ if (!Object.hasOwn(keys.keys, keyId) && row.created_at.getTime() >= loadedAt - 1000) {
88
+ throw new ExtensionEnvelopeClockSkew("The handoff was written after the verification snapshot");
89
+ }
90
+ return keys;
91
+ };
92
+ for (const plugin of names) {
93
+ if (signal?.aborted)
94
+ return;
95
+ if (!EXTENSION_NAME_RE.test(plugin))
96
+ continue;
97
+ const lease = await this.lockService.acquire(`extension-effect-relay-${plugin}`, {
98
+ ttlMs: 30_000,
99
+ ...(signal && { signal }),
100
+ });
101
+ if (!lease)
102
+ continue;
103
+ const active = signal ? AbortSignal.any([lease.lost, signal]) : lease.lost;
104
+ try {
105
+ const identity = this.identity.resolve(plugin);
106
+ const login = identity.separate ? identity.login : null;
107
+ await asPlatform("Relay extension handoffs and their outbox references", async () => {
108
+ await this.redrive(plugin, login, ring, active);
109
+ await this.ingest(plugin, login, ring, active);
110
+ await this.cleanup(plugin, login, ring, active);
111
+ });
112
+ await this.status.clearNote(plugin, HANDOFF_MISSING);
113
+ }
114
+ catch (error) {
115
+ const failure = classifyEffectFailure(error);
116
+ if (failure.code === "handoff_missing") {
117
+ this.log.error("Extension handoff health fault", {
118
+ plugin,
119
+ code: failure.code,
120
+ message: failure.message,
121
+ });
122
+ await this.status.note(plugin, HANDOFF_MISSING);
123
+ }
124
+ else {
125
+ this.log.warn("Extension handoff relay failed", { plugin, code: failure.code });
126
+ }
127
+ }
128
+ finally {
129
+ await lease.release();
130
+ }
131
+ }
132
+ }
133
+ async redrive(plugin, login, ring, signal) {
134
+ // org-filter: deployment-wide outbox scan by plugin; only the verified envelope supplies delivery scope.
135
+ const rows = await asPlatform("Find due extension redrive references", () => this.db.db
136
+ .selectFrom("outbox")
137
+ .select(["id", "org_id", "data"])
138
+ .where("job_name", "=", EXTENSION_EFFECT_REDRIVE_JOB)
139
+ .where(sql `data->>'plugin' = ${plugin}`)
140
+ .where("dead_at", "is", null)
141
+ .where("next_attempt_at", "<=", sql `now()`)
142
+ .orderBy("id")
143
+ .limit(BATCH)
144
+ .execute());
145
+ for (const row of rows) {
146
+ if (signal.aborted)
147
+ return;
148
+ try {
149
+ const reference = row.data;
150
+ if (typeof reference.rowId !== "string" || typeof reference.hash !== "string") {
151
+ throw new ExtensionEffectFailure("handoff_changed", "The redrive reference is invalid");
152
+ }
153
+ const source = await readHandoffRow(this.db.pool, plugin, login, reference.rowId);
154
+ if (!source || handoffReference(plugin, source).hash !== reference.hash) {
155
+ throw new ExtensionEffectFailure("handoff_changed", "The original handoff is missing or has changed");
156
+ }
157
+ const body = await this.effects.verify(source.envelope, await ring(source));
158
+ if (body.plugin !== plugin || body.orgId !== row.org_id) {
159
+ throw new ExtensionEffectFailure("scope_mismatch", "The verified handoff scope differs from the redrive row");
160
+ }
161
+ await withOrgScope(body.orgId, () => this.effects.deliver(body));
162
+ // org-filter: the deployment relay settles the redrive row by its kernel-owned ID.
163
+ await this.db.db.deleteFrom("outbox").where("id", "=", row.id).execute();
164
+ await settleHandoff(this.db.pool, plugin, login, source.id);
165
+ }
166
+ catch (error) {
167
+ if (!(error instanceof ExtensionEnvelopeClockSkew))
168
+ await this.dispatcher.deferDirect(row.id, effectFailureMessage(classifyEffectFailure(error)));
169
+ }
170
+ }
171
+ }
172
+ async ingest(plugin, login, ring, signal) {
173
+ const rows = await readHandoff(this.db.pool, plugin, login, BATCH);
174
+ let parks = 0;
175
+ for (const row of rows) {
176
+ if (signal.aborted)
177
+ return;
178
+ let body;
179
+ let verified = false;
180
+ let failure;
181
+ try {
182
+ body = await this.effects.verify(row.envelope, await ring(row));
183
+ if (body.plugin !== plugin) {
184
+ throw new ExtensionEffectFailure("scope_mismatch", "The verified handoff belongs to another extension");
185
+ }
186
+ verified = true;
187
+ const effect = body;
188
+ await withOrgScope(effect.orgId, () => this.effects.deliver(effect));
189
+ }
190
+ catch (error) {
191
+ if (error instanceof ExtensionEnvelopeClockSkew)
192
+ continue;
193
+ if (!verified &&
194
+ !(error instanceof InvalidExtensionEnvelope || error instanceof ExtensionEffectFailure))
195
+ throw error;
196
+ failure = classifyEffectFailure(error);
197
+ const reason = effectFailureMessage(failure);
198
+ if ((verified && row.attempts < LAST_RETRY) || parks >= PARK_BUDGET) {
199
+ await retryHandoff(this.db.pool, plugin, login, row, reason);
200
+ continue;
201
+ }
202
+ const reference = handoffReference(plugin, row);
203
+ const org = verified ? body?.orgId : undefined;
204
+ const jobId = `extension-handoff-${effectHash([plugin, row.id])}`;
205
+ if (!(await this.effects.park(org, jobId, reference, reason, row.attempts + 1))) {
206
+ await retryHandoff(this.db.pool, plugin, login, row, reason);
207
+ continue;
208
+ }
209
+ parks++;
210
+ if (verified) {
211
+ await markHandoffParked(this.db.pool, plugin, login, row.id, reason);
212
+ continue;
213
+ }
214
+ }
215
+ await settleHandoff(this.db.pool, plugin, login, row.id);
216
+ }
217
+ }
218
+ async cleanup(plugin, login, ring, signal) {
219
+ for (const row of await readUnreferencedParks(this.db.pool, plugin, login, BATCH)) {
220
+ if (signal.aborted)
221
+ return;
222
+ const body = await this.effects.verify(row.envelope, await ring(row));
223
+ if (body.plugin !== plugin)
224
+ throw new ExtensionEffectFailure("scope_mismatch", "The parked row belongs to a different extension");
225
+ const cancelled = await withOrgScope(body.orgId, () => this.effects.cancelIfDeleted(body));
226
+ if (cancelled || !row.has_reference)
227
+ await settleHandoff(this.db.pool, plugin, login, row.id);
228
+ }
229
+ }
230
+ };
231
+ __decorate([
232
+ LockedInterval(EXTENSION_HANDOFF_RELAY, () => 2000)
233
+ ], ExtensionEffectRelay.prototype, "relay", null);
234
+ __decorate([
235
+ LockedInterval("extension-effect-key-retirement", () => 60_000)
236
+ ], ExtensionEffectRelay.prototype, "retireKeys", null);
237
+ ExtensionEffectRelay = __decorate([
238
+ Injectable(),
239
+ __param(0, Inject(OutboxDispatcher)),
240
+ __param(1, Inject(ExtensionEffects)),
241
+ __param(2, Inject(ExtensionEffectKeys)),
242
+ __param(3, Inject(ConfiguredExtensionDbIdentity)),
243
+ __param(4, Inject(ExtensionRegistry)),
244
+ __param(5, Inject(ReplicaStatusStore)),
245
+ __param(6, Inject(KernelDb)),
246
+ __param(7, Inject(KernelConfigService)),
247
+ __param(8, Inject(LockService)),
248
+ __param(9, Inject(KERNEL_LOGGER))
249
+ ], ExtensionEffectRelay);
250
+ export { ExtensionEffectRelay };
@@ -11,6 +11,8 @@ export declare function createQueue(redisUrl: string, namespace: string, opts: {
11
11
  runWorkers: boolean;
12
12
  log?: Pick<Logger, "error">;
13
13
  }): ExtensionContext["queue"] & {
14
+ hasDefined(name: string): boolean;
15
+ dispatchEffect(name: string, data: unknown, jobId: string, delayMs?: number): Promise<void>;
14
16
  close(): Promise<void>;
15
17
  /** 停止取新任务(不等进行中的):撤销插件实例的第一步。 */
16
18
  pauseWorkers(): Promise<void>;
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。 */
@@ -50,7 +51,24 @@ export function createQueue(redisUrl, namespace, opts) {
50
51
  }
51
52
  return q;
52
53
  };
54
+ const add = async (name, data, o) => {
55
+ assertOpen();
56
+ assertNoColon("queue name", name);
57
+ if (o?.jobId !== undefined)
58
+ assertNoColon("jobId", o.jobId);
59
+ const jobOptions = {
60
+ capybaraScope: currentScope() ?? null,
61
+ ...(o?.jobId !== undefined && { jobId: o.jobId }),
62
+ ...(o?.delayMs !== undefined && { delay: o.delayMs }),
63
+ attempts: 3,
64
+ backoff: { type: "exponential", delay: 1000 },
65
+ removeOnComplete: 1000,
66
+ removeOnFail: 5000,
67
+ };
68
+ await getQueue(name).add(name, data, jobOptions);
69
+ };
53
70
  return {
71
+ hasDefined: (name) => !closed && defined.has(name),
54
72
  define(name, handler, o) {
55
73
  assertOpen();
56
74
  assertNoColon("queue name", name);
@@ -62,7 +80,7 @@ export function createQueue(redisUrl, namespace, opts) {
62
80
  const st = { n: 0, idle: [] };
63
81
  active.set(name, st);
64
82
  const worker = new Worker(queueName(name),
65
- // runJob: the log context and the org scope of the job (its data's `orgId`, else platform)
83
+ // A job from an older producer has no recorded scope and runs unscoped.
66
84
  (job) => runJob(queueName(name), job, async () => {
67
85
  st.n += 1;
68
86
  try {
@@ -74,7 +92,7 @@ export function createQueue(redisUrl, namespace, opts) {
74
92
  for (const w of st.idle.splice(0))
75
93
  w();
76
94
  }
77
- }),
95
+ }, { scope: job.opts.capybaraScope ?? null }),
78
96
  // 撤销插件实例时到点仍未完成的任务被强制留在队列里(锁过期后按 stalled 交回),新实例再执行一次:
79
97
  // 任务是至少一次。stalled 次数放宽到 3,连续几次撤销 / 升级不至于把任务判为失败
80
98
  { connection: newConn(), concurrency: o?.concurrency ?? 1, maxStalledCount: 3 });
@@ -82,19 +100,11 @@ export function createQueue(redisUrl, namespace, opts) {
82
100
  worker.on("failed", (job, err) => log.error("queue job failed", { queue: name, jobId: job?.id, err }));
83
101
  workers.set(name, worker);
84
102
  },
85
- async add(name, data, o) {
86
- assertOpen();
87
- assertNoColon("queue name", name);
88
- if (o?.jobId !== undefined)
89
- assertNoColon("jobId", o.jobId);
90
- await getQueue(name).add(name, data, {
91
- ...(o?.jobId !== undefined && { jobId: o.jobId }),
92
- ...(o?.delayMs !== undefined && { delay: o.delayMs }),
93
- attempts: 3,
94
- backoff: { type: "exponential", delay: 1000 },
95
- removeOnComplete: 1000,
96
- removeOnFail: 5000,
97
- });
103
+ add,
104
+ async dispatchEffect(name, data, jobId, delayMs) {
105
+ if (!defined.has(name))
106
+ throw new Error("Extension effect queue is not registered");
107
+ await add(name, data, { jobId, ...(delayMs === undefined ? {} : { delayMs }) });
98
108
  },
99
109
  async pauseWorkers() {
100
110
  await Promise.all([...workers.values()].map((w) => w.pause(true).catch(() => { })));
@@ -83,6 +83,8 @@ export function extensionDbPool(identity, name, config, onError) {
83
83
  rls: config.rls,
84
84
  closeActiveOnDestroy: true,
85
85
  onConnect: async (client) => {
86
+ if (!identity.separate)
87
+ return;
86
88
  await assertExtensionSession(client, identity.login);
87
89
  await assertExtensionSchemaOwner(client, schema, identity.login);
88
90
  await client.query("select pg_catalog.set_config('search_path', $1, false)", [searchPath]);
@@ -0,0 +1,6 @@
1
+ import { type Kysely } from "kysely";
2
+ import pg from "pg";
3
+ /** Creates a handoff owned by the one-shot provisioner. The extension can append only. */
4
+ export declare function provisionExtensionHandoff(owner: pg.ClientBase, schema: string, extensionLogin: string, runtimeLogin: string): Promise<void>;
5
+ /** Single-login deployments use the kernel's own connection for this table. */
6
+ export declare function ensureLocalExtensionHandoff(db: Kysely<unknown>, dbUrl: string, schema: string, connectTimeoutMs: number | undefined): Promise<void>;
@@ -0,0 +1,72 @@
1
+ import { sql } from "kysely";
2
+ import pg from "pg";
3
+ import { EXTENSION_EFFECT_HANDOFF } from "../infra/database/extension-handoff.js";
4
+ import { lockMigrationSchema } from "./migrator.js";
5
+ import { pgConnectOptions } from "./pool.js";
6
+ function createHandoffTable(table) {
7
+ return `
8
+ create table if not exists ${table} (
9
+ id uuid primary key,
10
+ created_at timestamptz not null default pg_catalog.now(),
11
+ attempts integer not null default 0,
12
+ last_error text,
13
+ parked_at timestamptz,
14
+ next_attempt_at timestamptz not null default pg_catalog.now(),
15
+ envelope jsonb not null check (pg_catalog.octet_length(envelope::text) <= 131500)
16
+ );
17
+ create index if not exists _capybara_effect_due on ${table} (next_attempt_at, id)
18
+ where parked_at is null;
19
+ create index if not exists _capybara_effect_parked on ${table} (parked_at, id)
20
+ where parked_at is not null;
21
+ create index if not exists _capybara_effect_key on ${table} ((envelope->>'keyId'))
22
+ `;
23
+ }
24
+ /** Creates a handoff owned by the one-shot provisioner. The extension can append only. */
25
+ export async function provisionExtensionHandoff(owner, schema, extensionLogin, runtimeLogin) {
26
+ await lockMigrationSchema(owner, schema, "transaction");
27
+ const ns = pg.escapeIdentifier(schema);
28
+ const writer = pg.escapeIdentifier(extensionLogin);
29
+ const reader = pg.escapeIdentifier(runtimeLogin);
30
+ const table = `${ns}.${pg.escapeIdentifier(EXTENSION_EFFECT_HANDOFF)}`;
31
+ await owner.query(`create schema if not exists ${ns} authorization ${writer}`);
32
+ await owner.query(createHandoffTable(table));
33
+ const { rows: [relation], } = await owner.query(`
34
+ select c.relowner = (select oid from pg_roles where rolname = current_user) and c.relkind = 'r' as valid
35
+ from pg_class c where c.oid = to_regclass($1)
36
+ `, [table]);
37
+ if (!relation?.valid)
38
+ throw new Error(`Invalid handoff owner or type for ${schema}`);
39
+ await owner.query(`revoke all on table ${table} from public, ${writer}`);
40
+ await owner.query(`grant insert (id, envelope) on table ${table} to ${writer}`);
41
+ await owner.query(`grant usage on schema ${ns} to ${reader}`);
42
+ await owner.query(`grant select, delete on table ${table} to ${reader}`);
43
+ await owner.query(`grant update (attempts, last_error, next_attempt_at, parked_at) on table ${table} to ${reader}`);
44
+ }
45
+ /** Single-login deployments use the kernel's own connection for this table. */
46
+ export async function ensureLocalExtensionHandoff(db, dbUrl, schema, connectTimeoutMs) {
47
+ const qualified = `${schema}.${EXTENSION_EFFECT_HANDOFF}`;
48
+ const existing = await sql `
49
+ select pg_catalog.to_regclass(${qualified}) is not null as present
50
+ `.execute(db);
51
+ if (existing.rows[0]?.present)
52
+ return;
53
+ const client = new pg.Client({
54
+ connectionString: dbUrl,
55
+ ...pgConnectOptions({ connectTimeoutMs }),
56
+ });
57
+ client.on("error", () => { });
58
+ try {
59
+ await client.connect();
60
+ await client.query("begin");
61
+ await client.query("set local lock_timeout = '5s'");
62
+ await lockMigrationSchema(client, schema, "transaction");
63
+ const ns = pg.escapeIdentifier(schema);
64
+ const table = `${ns}.${pg.escapeIdentifier(EXTENSION_EFFECT_HANDOFF)}`;
65
+ await client.query(`create schema if not exists ${ns}`);
66
+ await client.query(createHandoffTable(table));
67
+ await client.query("commit");
68
+ }
69
+ finally {
70
+ await client.end();
71
+ }
72
+ }
@@ -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
+ $$;`;
@@ -3,4 +3,4 @@ import { type ExtensionDbIdentity } from "./extension-db.js";
3
3
  * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
4
4
  * to transfer ownership. Run before starting replicas with the new extension identity.
5
5
  */
6
- export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number): Promise<void>;
6
+ export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number, runtimeLogin?: string): Promise<void>;
@@ -1,6 +1,8 @@
1
1
  import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
2
2
  import pg from "pg";
3
+ import { EXTENSION_EFFECT_HANDOFF } from "../infra/database/extension-handoff.js";
3
4
  import { assertExtensionSession, pluginSchemaName, } from "./extension-db.js";
5
+ import { provisionExtensionHandoff } from "./extension-handoff-schema.js";
4
6
  import { assertSameMigrationDatabase, lockMigrationSchema } from "./migrator.js";
5
7
  import { pgConnectOptions } from "./pool.js";
6
8
  async function transferExtensionSchema(client, schema, target, sources) {
@@ -42,15 +44,17 @@ async function transferExtensionSchema(client, schema, target, sources) {
42
44
  exists (
43
45
  select from pg_depend d where d.classid = o.classid and d.objid = o.objid
44
46
  and d.objsubid = 0 and d.refclassid = 'pg_extension'::regclass and d.deptype = 'e'
45
- ) as extension_member
47
+ ) as extension_member,
48
+ (c.relname = $2 or (t.typname = $2 and t.typrelid <> 0)) as handoff
46
49
  from objects o
47
50
  cross join lateral pg_identify_object(o.classid, o.objid, 0) object
48
51
  left join pg_class c on o.classid = 'pg_class'::regclass and c.oid = o.objid
49
52
  left join pg_proc p on o.classid = 'pg_proc'::regclass and p.oid = o.objid
50
53
  left join pg_type t on o.classid = 'pg_type'::regclass and t.oid = o.objid
51
54
  order by object.identity
52
- `, [namespace.oid]);
53
- const unexpected = objects.filter((object) => !object.kind ||
55
+ `, [namespace.oid, EXTENSION_EFFECT_HANDOFF]);
56
+ const owned = objects.filter((object) => !object.handoff);
57
+ const unexpected = owned.filter((object) => !object.kind ||
54
58
  object.extension_member ||
55
59
  (object.owner !== target && object.owner !== namespace.owner));
56
60
  if (unexpected.length) {
@@ -62,7 +66,7 @@ async function transferExtensionSchema(client, schema, target, sources) {
62
66
  await client.query(`alter schema ${pg.escapeIdentifier(schema)} owner to ${quotedTarget}`);
63
67
  }
64
68
  // PostgreSQL moves table-owned sequences, row types and indexes with their parent table.
65
- for (const object of objects) {
69
+ for (const object of owned) {
66
70
  if (object.kind && object.owner !== target && !object.attached_sequence) {
67
71
  // Kind is from the fixed catalog mapping. PostgreSQL returns the quoted object identity.
68
72
  await client.query(`alter ${object.kind} ${object.identity} owner to ${quotedTarget}`);
@@ -91,7 +95,7 @@ async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
91
95
  * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
92
96
  * to transfer ownership. Run before starting replicas with the new extension identity.
93
97
  */
94
- export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs) {
98
+ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs, runtimeLogin) {
95
99
  const owner = new pg.Client({
96
100
  connectionString: bootstrapUrl,
97
101
  ...pgConnectOptions({ connectTimeoutMs }),
@@ -103,7 +107,10 @@ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, decl
103
107
  try {
104
108
  await owner.query("set local search_path = pg_catalog");
105
109
  await owner.query("set local lock_timeout = '30s'");
106
- const { rows: [legacy], } = await owner.query("select current_user as login");
110
+ const { rows: [legacy], } = await owner.query(`
111
+ select current_user as login,
112
+ pg_catalog.has_database_privilege(pg_catalog.current_database(), 'CREATE') as can_create
113
+ `);
107
114
  if (!legacy)
108
115
  throw new Error("Could not verify the schema transfer login");
109
116
  const { rows: registered } = await owner.query(`select name from capybara.extension_name_owners
@@ -127,6 +134,11 @@ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, decl
127
134
  }
128
135
  for (const { schema, target } of targets) {
129
136
  await transferExtensionSchema(owner, schema, target.login, sources);
137
+ // Repeated migrations may use the restricted runtime login. Only the one-shot
138
+ // provisioner can create the contract table and grant access to it.
139
+ if (runtimeLogin !== undefined && legacy.can_create) {
140
+ await provisionExtensionHandoff(owner, schema, target.login, runtimeLogin);
141
+ }
130
142
  }
131
143
  await owner.query("commit");
132
144
  }
@@ -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;
@@ -1798,6 +1843,20 @@ export interface StoredInboxAction {
1798
1843
  };
1799
1844
  }
1800
1845
  export type InboxItemState = "open" | "resolved" | "expired";
1846
+ export interface ExtensionEffectCancellationsTable {
1847
+ id: string;
1848
+ plugin: string;
1849
+ reason: string;
1850
+ cancelled_at: Ts;
1851
+ }
1852
+ export interface ExtensionEffectReceiptsTable {
1853
+ org_id: string;
1854
+ plugin: string;
1855
+ kind: string;
1856
+ effect_key: string;
1857
+ payload_hash: string;
1858
+ result: Json<unknown>;
1859
+ }
1801
1860
  /** 0192: a personal inbox item (collaboration spec §4.9), for one person in one org. */
1802
1861
  export interface InboxItemsTable {
1803
1862
  id: string;
@@ -2053,6 +2112,9 @@ export interface KernelDatabase {
2053
2112
  device_conversation_notices: DeviceConversationNoticesTable;
2054
2113
  device_loopback_grants: DeviceLoopbackGrantsTable;
2055
2114
  device_site_grants: DeviceSiteGrantsTable;
2115
+ device_host_services: DeviceHostServicesTable;
2116
+ device_service_events: DeviceServiceEventsTable;
2117
+ device_service_event_cursors: DeviceServiceEventCursorsTable;
2056
2118
  background_tasks: BackgroundTasksTable;
2057
2119
  automations: AutomationsTable;
2058
2120
  automation_runs: AutomationRunsTable;
@@ -2060,6 +2122,8 @@ export interface KernelDatabase {
2060
2122
  trigger_events: TriggerEventsTable;
2061
2123
  trigger_cause_handles: TriggerCauseHandlesTable;
2062
2124
  inbox_items: InboxItemsTable;
2125
+ extension_effect_receipts: ExtensionEffectReceiptsTable;
2126
+ extension_effect_cancellations: ExtensionEffectCancellationsTable;
2063
2127
  automation_acceptance: AutomationAcceptanceTable;
2064
2128
  automation_offers: AutomationOffersTable;
2065
2129
  automation_event_deliveries: AutomationEventDeliveriesTable;