@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.
- package/bootstrap.json +5 -5
- package/dist/admin/admin.module.js +3 -0
- package/dist/admin/admin.schemas.d.ts +4 -0
- package/dist/admin/health.service.d.ts +2 -2
- package/dist/admin/health.service.js +6 -2
- package/dist/admin/setup.service.js +6 -1
- package/dist/agents/agents.controller.js +3 -2
- package/dist/agents/agents.service.d.ts +2 -0
- package/dist/agents/agents.service.js +7 -0
- package/dist/automations/events/trigger-events.service.d.ts +13 -1
- package/dist/automations/events/trigger-events.service.js +27 -14
- package/dist/catalog/catalog.service.d.ts +2 -0
- package/dist/catalog/catalog.service.js +28 -5
- package/dist/catalog/marketplace-fetch.d.ts +2 -0
- package/dist/catalog/marketplace-fetch.js +15 -0
- package/dist/catalog/marketplaces.service.d.ts +4 -4
- package/dist/catalog/marketplaces.service.js +3 -2
- package/dist/catalog/owned-items.d.ts +2 -0
- package/dist/catalog/owned-items.js +30 -31
- package/dist/catalog/ownership.js +40 -38
- package/dist/catalog/plugin-import.d.ts +3 -4
- package/dist/catalog/plugin-import.js +50 -1
- package/dist/catalog/plugin-upgrade.d.ts +8 -0
- package/dist/catalog/plugin-upgrade.js +95 -7
- package/dist/catalog/publisher-policy.d.ts +9 -0
- package/dist/catalog/publisher-policy.js +12 -0
- package/dist/catalog/unshare.js +66 -58
- package/dist/client/client-access.service.js +5 -3
- package/dist/config/schema.d.ts +1 -0
- package/dist/config/schema.js +8 -1
- package/dist/conversations/conversations.controller.js +4 -14
- package/dist/conversations/conversations.service.d.ts +14 -0
- package/dist/conversations/conversations.service.js +20 -2
- package/dist/ctx/create-ctx.d.ts +15 -2
- package/dist/ctx/create-ctx.js +195 -79
- package/dist/ctx/durable-cancellation.d.ts +3 -0
- package/dist/ctx/durable-cancellation.js +8 -0
- package/dist/ctx/durable-effects.service.d.ts +81 -0
- package/dist/ctx/durable-effects.service.js +316 -0
- package/dist/ctx/durable-envelope.d.ts +24 -0
- package/dist/ctx/durable-envelope.js +80 -0
- package/dist/ctx/durable-failure.d.ts +7 -0
- package/dist/ctx/durable-failure.js +32 -0
- package/dist/ctx/durable-job.d.ts +9 -0
- package/dist/ctx/durable-job.js +2 -0
- package/dist/ctx/durable-keys.d.ts +27 -0
- package/dist/ctx/durable-keys.js +138 -0
- package/dist/ctx/durable-relay.d.ts +29 -0
- package/dist/ctx/durable-relay.js +250 -0
- package/dist/ctx/queue.d.ts +2 -0
- package/dist/ctx/queue.js +25 -15
- package/dist/db/extension-db.js +2 -0
- package/dist/db/extension-handoff-schema.d.ts +6 -0
- package/dist/db/extension-handoff-schema.js +72 -0
- package/dist/db/extension-rls-predicate.d.ts +1 -0
- package/dist/db/extension-rls-predicate.js +8 -0
- package/dist/db/extension-schema-transfer.d.ts +1 -1
- package/dist/db/extension-schema-transfer.js +18 -6
- package/dist/db/kernel-schema.d.ts +64 -0
- package/dist/db/migrator.js +6 -13
- package/dist/db/pool.d.ts +2 -2
- package/dist/db/pool.js +2 -2
- package/dist/db/sql-statements.d.ts +3 -0
- package/dist/db/sql-statements.js +15 -5
- package/dist/device-access/device-access.module.js +12 -2
- package/dist/device-access/device-access.service.d.ts +30 -2
- package/dist/device-access/device-access.service.js +38 -4
- package/dist/device-access/host-gate.d.ts +45 -0
- package/dist/device-access/host-gate.js +92 -0
- package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
- package/dist/device-access/host-service-stop-sweep.js +112 -0
- package/dist/device-access/host-service-stop.d.ts +78 -0
- package/dist/device-access/host-service-stop.js +144 -0
- package/dist/device-access/host-services.d.ts +211 -0
- package/dist/device-access/host-services.js +803 -0
- package/dist/device-access/person-handles.d.ts +10 -0
- package/dist/device-access/person-handles.js +25 -0
- package/dist/device-access/service-events.d.ts +199 -0
- package/dist/device-access/service-events.js +704 -0
- package/dist/device-access/token.d.ts +5 -0
- package/dist/device-access/token.js +5 -0
- package/dist/devices/devices.service.js +3 -0
- package/dist/dial-in/access.d.ts +5 -5
- package/dist/dial-in/access.js +19 -12
- package/dist/dial-in/gateway.js +6 -2
- package/dist/dial-in/machines.d.ts +9 -2
- package/dist/dial-in/machines.js +27 -4
- package/dist/erasure/device-cleanup.js +12 -0
- package/dist/erasure/org-catalog.js +2 -2
- package/dist/erasure/org-rules.js +10 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/extensions/admin-ops.js +8 -2
- package/dist/extensions/deployed-snapshots.d.ts +4 -1
- package/dist/extensions/deployed-snapshots.js +7 -2
- package/dist/extensions/extensions.module.js +10 -0
- package/dist/extensions/host.d.ts +12 -2
- package/dist/extensions/host.js +44 -22
- package/dist/extensions/instance.d.ts +5 -0
- package/dist/extensions/instance.js +10 -0
- package/dist/extensions/ledger.d.ts +1 -1
- package/dist/extensions/lifecycle-hooks.js +3 -3
- package/dist/extensions/org-config.js +6 -1
- package/dist/extensions/permission-set.d.ts +7 -0
- package/dist/extensions/permission-set.js +10 -0
- package/dist/extensions/permission-view.d.ts +1 -1
- package/dist/extensions/permission-view.js +10 -1
- package/dist/extensions/sources.d.ts +1 -0
- package/dist/extensions/sources.js +9 -0
- package/dist/git/tickets.js +32 -27
- package/dist/http/app.js +5 -3
- package/dist/identity/accounts.d.ts +6 -1
- package/dist/identity/accounts.js +11 -2
- package/dist/identity/api-tokens.js +7 -6
- package/dist/identity/settings.d.ts +9 -1
- package/dist/identity/settings.js +16 -1
- package/dist/inbox/inbox-items.service.d.ts +5 -0
- package/dist/inbox/inbox-items.service.js +57 -33
- package/dist/inbox/org-notices.js +3 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/infra/database/extension-effect-key-lock.d.ts +10 -0
- package/dist/infra/database/extension-effect-key-lock.js +69 -0
- package/dist/infra/database/extension-handoff.d.ts +27 -0
- package/dist/infra/database/extension-handoff.js +113 -0
- package/dist/infra/database/scoped-dialect.d.ts +3 -2
- package/dist/infra/database/scoped-dialect.js +260 -72
- package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
- package/dist/infra/database/startup-activation-transaction.js +3 -2
- package/dist/infra/outbox/outbox.dispatcher.d.ts +6 -1
- package/dist/infra/outbox/outbox.dispatcher.js +64 -4
- package/dist/infra/outbox/outbox.module.js +2 -0
- package/dist/infra/outbox/registry.d.ts +40 -0
- package/dist/infra/outbox/registry.js +42 -0
- package/dist/infra/queue/queue-names.d.ts +1 -1
- package/dist/infra/queue/queue-names.js +1 -0
- package/dist/infra/queue/run-job.d.ts +4 -1
- package/dist/infra/queue/run-job.js +10 -2
- package/dist/kernel.js +1 -0
- package/dist/kernel.module.js +3 -0
- package/dist/orgs/offboarding.js +18 -9
- package/dist/orgs/orgs.service.js +16 -0
- package/dist/orgs/settings.service.js +3 -0
- package/dist/packages/npm-publish-keys.json +27 -0
- package/dist/packages/official-publisher.d.ts +19 -0
- package/dist/packages/official-publisher.js +152 -0
- package/dist/packages/provenance.d.ts +7 -0
- package/dist/packages/provenance.js +22 -19
- package/dist/packages/sigstore-trusted-root.json +126 -0
- package/dist/platform/ops/admin.ops.js +2 -1
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/roles/worker-role.d.ts +6 -3
- package/dist/roles/worker-role.js +12 -4
- package/dist/roles/worker.module.js +9 -0
- package/dist/runtime/maintenance.d.ts +5 -2
- package/dist/runtime/maintenance.js +18 -4
- package/dist/sandbox/device-reports.d.ts +4 -4
- package/dist/sandbox/device-reports.js +40 -30
- package/dist/sandbox/device-services.d.ts +2 -1
- package/dist/sandbox/device-services.js +5 -1
- package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
- package/dist/sandbox/permission-ceiling-writes.js +21 -0
- package/dist/sandbox/permission-config-publication.js +5 -1
- package/dist/themes/theme-state.js +24 -13
- package/dist/tools/call-scope.d.ts +6 -0
- package/dist/tools/call-scope.js +22 -0
- package/dist/tools/registry.js +20 -2
- package/dist/ui/views.js +36 -8
- package/package.json +9 -4
- package/src/migrations/0222_device_host_services.sql +27 -0
- package/src/migrations/0223_device_service_events.sql +54 -0
- package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
- package/src/migrations/0225_extension_effect_receipts.sql +25 -0
package/dist/ctx/create-ctx.js
CHANGED
|
@@ -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
|
|
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 {
|
|
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
|
-
/**
|
|
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
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
.
|
|
108
|
-
|
|
109
|
-
.where(
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
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
|
-
|
|
153
|
-
|
|
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
|
|
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
|
-
|
|
327
|
+
const models = deps.models;
|
|
328
|
+
if (!models)
|
|
315
329
|
throw new Error(`plugin ${name}: ctx.models is not available`);
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
|
|
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
|
-
|
|
321
|
-
|
|
322
|
-
|
|
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
|
|
353
|
+
const inServedOrg = async (deviceId, run) => {
|
|
334
354
|
if (!access)
|
|
335
355
|
throw new Error(`plugin ${name}: ctx.dialIn is not available`);
|
|
336
|
-
|
|
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
|
|
365
|
+
return withOrgScope(orgId, () => run(access));
|
|
345
366
|
};
|
|
346
367
|
return {
|
|
347
|
-
request:
|
|
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
|
-
//
|
|
353
|
-
return
|
|
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:
|
|
359
|
-
capacity:
|
|
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
|
|
383
|
+
await inServedOrg(deviceId, (dialIn) => dialIn.stop(deviceId, reason));
|
|
364
384
|
},
|
|
365
|
-
//
|
|
366
|
-
//
|
|
367
|
-
openStream:
|
|
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
|
|
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
|
|
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
|
-
|
|
499
|
-
|
|
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
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
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
|
-
//
|
|
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
|
-
|
|
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,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 {};
|