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

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 (113) hide show
  1. package/bootstrap.json +1 -1
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/health.service.d.ts +2 -2
  4. package/dist/admin/health.service.js +6 -2
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/config/schema.d.ts +7 -0
  7. package/dist/config/schema.js +60 -2
  8. package/dist/conversations/access.d.ts +15 -7
  9. package/dist/conversations/access.js +59 -10
  10. package/dist/conversations/conversation-agent.d.ts +18 -0
  11. package/dist/conversations/conversation-agent.js +23 -0
  12. package/dist/conversations/conversation-ref.d.ts +3 -2
  13. package/dist/conversations/conversation-ref.js +6 -1
  14. package/dist/conversations/conversations.controller.d.ts +28 -5
  15. package/dist/conversations/conversations.controller.js +99 -10
  16. package/dist/conversations/conversations.module.js +10 -0
  17. package/dist/conversations/conversations.schemas.d.ts +6 -0
  18. package/dist/conversations/conversations.schemas.js +15 -0
  19. package/dist/conversations/conversations.service.d.ts +125 -21
  20. package/dist/conversations/conversations.service.js +260 -90
  21. package/dist/conversations/event-log.d.ts +9 -1
  22. package/dist/conversations/event-log.js +2 -0
  23. package/dist/conversations/events.d.ts +57 -0
  24. package/dist/conversations/events.js +73 -1
  25. package/dist/conversations/external/external-calls.d.ts +75 -0
  26. package/dist/conversations/external/external-calls.js +91 -0
  27. package/dist/conversations/external/external-calls.processor.d.ts +45 -0
  28. package/dist/conversations/external/external-calls.processor.js +144 -0
  29. package/dist/conversations/external/external-conversations.service.d.ts +266 -0
  30. package/dist/conversations/external/external-conversations.service.js +1138 -0
  31. package/dist/conversations/external/external.schemas.d.ts +63 -0
  32. package/dist/conversations/external/external.schemas.js +52 -0
  33. package/dist/conversations/external/token.d.ts +6 -0
  34. package/dist/conversations/external/token.js +6 -0
  35. package/dist/conversations/permission-profile-store.d.ts +4 -1
  36. package/dist/conversations/permission-profiles.controller.d.ts +33 -9
  37. package/dist/conversations/permission-profiles.controller.js +86 -6
  38. package/dist/conversations/prompt-suggestions.js +2 -1
  39. package/dist/conversations/queue.js +2 -1
  40. package/dist/conversations/titles.js +4 -3
  41. package/dist/ctx/create-ctx.d.ts +7 -0
  42. package/dist/ctx/create-ctx.js +45 -2
  43. package/dist/db/extension-db.d.ts +8 -3
  44. package/dist/db/extension-db.js +107 -7
  45. package/dist/db/extension-role-provision.d.ts +9 -0
  46. package/dist/db/extension-role-provision.js +89 -0
  47. package/dist/db/extension-schema-transfer.d.ts +2 -1
  48. package/dist/db/extension-schema-transfer.js +103 -19
  49. package/dist/db/kernel-schema.d.ts +31 -4
  50. package/dist/db/migrator.d.ts +2 -0
  51. package/dist/db/migrator.js +4 -3
  52. package/dist/device-access/host-services.js +3 -2
  53. package/dist/device-access/person-handles.d.ts +16 -7
  54. package/dist/device-access/person-handles.js +14 -9
  55. package/dist/devices/conversation-devices.d.ts +5 -0
  56. package/dist/devices/conversation-devices.js +16 -0
  57. package/dist/erasure/org-catalog.js +2 -2
  58. package/dist/errors.d.ts +34 -0
  59. package/dist/errors.js +34 -0
  60. package/dist/evals/snapshot.js +3 -1
  61. package/dist/evals/trajectory.service.d.ts +2 -2
  62. package/dist/evals/trajectory.service.js +11 -7
  63. package/dist/extensions/admin-ops.js +17 -1
  64. package/dist/extensions/extensions.module.js +3 -0
  65. package/dist/extensions/host.d.ts +9 -1
  66. package/dist/extensions/host.js +14 -2
  67. package/dist/extensions/migrate-lock.js +1 -0
  68. package/dist/extensions/permission-view.d.ts +3 -1
  69. package/dist/extensions/permission-view.js +4 -1
  70. package/dist/extensions/point-defaults.d.ts +13 -21
  71. package/dist/extensions/point-defaults.js +32 -72
  72. package/dist/extensions/point-serving.d.ts +56 -0
  73. package/dist/extensions/point-serving.js +120 -0
  74. package/dist/inbox/inbox-items.service.d.ts +11 -0
  75. package/dist/inbox/inbox-items.service.js +39 -0
  76. package/dist/index.d.ts +3 -1
  77. package/dist/index.js +3 -1
  78. package/dist/infra/database/rls-role.d.ts +4 -11
  79. package/dist/infra/database/rls-role.js +71 -27
  80. package/dist/infra/outbox/registry.d.ts +70 -0
  81. package/dist/infra/outbox/registry.js +44 -0
  82. package/dist/infra/queue/queue-names.d.ts +1 -1
  83. package/dist/infra/queue/queue-names.js +1 -0
  84. package/dist/kernel.d.ts +2 -0
  85. package/dist/kernel.js +12 -2
  86. package/dist/kernel.module.js +4 -0
  87. package/dist/lifecycle/kernel-lifecycle.js +2 -3
  88. package/dist/platform/exclusions.js +10 -0
  89. package/dist/platform/ops/conversations.ops.d.ts +8 -1
  90. package/dist/platform/ops/conversations.ops.js +52 -14
  91. package/dist/plugin-reads/plugin-reads.service.js +4 -1
  92. package/dist/push/recipients.js +5 -2
  93. package/dist/retention/worker.js +2 -1
  94. package/dist/roles/worker-role.d.ts +3 -1
  95. package/dist/roles/worker-role.js +8 -2
  96. package/dist/roles/worker.module.js +3 -0
  97. package/dist/runtime/context/build.js +8 -0
  98. package/dist/runtime/context/compaction.js +7 -0
  99. package/dist/runtime/idle-arm.js +3 -1
  100. package/dist/runtime/idle-compaction.js +2 -1
  101. package/dist/runtime/run-finish.js +2 -1
  102. package/dist/runtime/run-jobs.js +2 -1
  103. package/dist/runtime/run-queue.js +4 -2
  104. package/dist/runtime/run-worker.js +5 -2
  105. package/dist/runtime/stream.js +10 -0
  106. package/dist/runtime/usage-report.js +2 -1
  107. package/dist/runtime/waits.js +2 -1
  108. package/dist/tools/approvals.service.js +6 -2
  109. package/dist/tools/builtins/skill-load.js +3 -2
  110. package/dist/tools/tool-watch.service.js +3 -1
  111. package/package.json +3 -3
  112. package/src/migrations/0226_enable_kernel_rls.sql +30 -0
  113. package/src/migrations/0227_external_conversations.sql +33 -0
@@ -0,0 +1,56 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import type { KernelLogger } from "../log.js";
3
+ import { EffectiveConfigs } from "./effective-config.js";
4
+ import { ExtensionRegistry } from "./registry.js";
5
+ /**
6
+ * One provider of a multi-provider extension point for an org (`ExtensionPointDefaults`), with its
7
+ * effective deployment config for the org, to pass back to it.
8
+ */
9
+ export interface PointProvider<T> {
10
+ extension: string;
11
+ impl: T;
12
+ config: unknown;
13
+ }
14
+ /** A provider that could serve an org now, with its effective config for the org. */
15
+ export interface Candidate {
16
+ extension: string;
17
+ impl: unknown;
18
+ config: unknown;
19
+ }
20
+ /**
21
+ * Whether one provider of an extension point serves an org now (web tools spec §6, layering spec
22
+ * A §6): loaded on this replica and providing the point, enabled in the org, a valid effective
23
+ * config for the org, and `configured(config)` not false. Per call, never cached in process.
24
+ * `ExtensionPointDefaults` evaluates its candidates through it; it sits below the extensions
25
+ * module (registry, effective configs and the database only), so the conversation access check
26
+ * (an external conversation is visible while its target serves the org) can inject it without a
27
+ * module cycle (writing-kernel-api: a cycle is cut by a shared provider both sides inject).
28
+ */
29
+ export declare class ExtensionPointServing {
30
+ private readonly kdb;
31
+ private readonly registry;
32
+ private readonly effective;
33
+ private readonly log;
34
+ constructor(kdb: KernelDb, registry: Pick<ExtensionRegistry, "list">, effective: Pick<EffectiveConfigs, "get">, log: KernelLogger);
35
+ /**
36
+ * Whether the one provider `extension` of `point` (the name without the major) serves `orgId`
37
+ * now. A provider whose status cannot be read counts as not serving (logged to `log`, the
38
+ * caller's context logger when it passes one).
39
+ */
40
+ serves(orgId: string, point: string, extension: string, log?: KernelLogger): Promise<boolean>;
41
+ /**
42
+ * The one provider `extension` of `point` when it {@link serves} `orgId` now, with its
43
+ * implementation and effective config for the org; null otherwise.
44
+ */
45
+ providerOf<T>(orgId: string, point: string, extension: string, log?: KernelLogger): Promise<PointProvider<T> | null>;
46
+ /**
47
+ * The candidacy of a provider the caller found enabled in the org: a valid effective config and
48
+ * `configured(config)` not false. Undefined when it is off; a provider whose status could not be
49
+ * read is also added to `failed` and logged to `log` (the caller's context logger, so the warning
50
+ * names the service that excluded it).
51
+ */
52
+ evaluate(orgId: string, point: string, extension: string, impl: unknown, failed: Set<string>, log?: KernelLogger): Promise<Candidate | undefined>;
53
+ }
54
+ /** The one {@link ExtensionPointServing} (below `ExtensionsModule`, which re-exports it). */
55
+ export declare class ExtensionPointServingModule {
56
+ }
@@ -0,0 +1,120 @@
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 { Inject, Injectable, Module } from "@nestjs/common";
11
+ import { KernelDb } from "../infra/database/kernel-db.js";
12
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
13
+ import { EffectiveConfigs } from "./effective-config.js";
14
+ import { isExtensionEnabled } from "./enabled.js";
15
+ import { ExtensionRegistry } from "./registry.js";
16
+ import { ExtensionStateModule } from "./state.module.js";
17
+ /**
18
+ * Whether one provider of an extension point serves an org now (web tools spec §6, layering spec
19
+ * A §6): loaded on this replica and providing the point, enabled in the org, a valid effective
20
+ * config for the org, and `configured(config)` not false. Per call, never cached in process.
21
+ * `ExtensionPointDefaults` evaluates its candidates through it; it sits below the extensions
22
+ * module (registry, effective configs and the database only), so the conversation access check
23
+ * (an external conversation is visible while its target serves the org) can inject it without a
24
+ * module cycle (writing-kernel-api: a cycle is cut by a shared provider both sides inject).
25
+ */
26
+ let ExtensionPointServing = class ExtensionPointServing {
27
+ kdb;
28
+ registry;
29
+ effective;
30
+ log;
31
+ constructor(kdb, registry, effective, log) {
32
+ this.kdb = kdb;
33
+ this.registry = registry;
34
+ this.effective = effective;
35
+ this.log = log;
36
+ }
37
+ /**
38
+ * Whether the one provider `extension` of `point` (the name without the major) serves `orgId`
39
+ * now. A provider whose status cannot be read counts as not serving (logged to `log`, the
40
+ * caller's context logger when it passes one).
41
+ */
42
+ async serves(orgId, point, extension, log = this.log) {
43
+ return (await this.providerOf(orgId, point, extension, log)) !== null;
44
+ }
45
+ /**
46
+ * The one provider `extension` of `point` when it {@link serves} `orgId` now, with its
47
+ * implementation and effective config for the org; null otherwise.
48
+ */
49
+ async providerOf(orgId, point, extension, log = this.log) {
50
+ const entry = this.registry.list(point).find((e) => e.plugin === extension);
51
+ if (!entry || !(await isExtensionEnabled(this.kdb.db, orgId, extension)))
52
+ return null;
53
+ const c = await this.evaluate(orgId, point, extension, entry.impl, new Set(), log);
54
+ return c === undefined ? null : { extension: c.extension, impl: c.impl, config: c.config };
55
+ }
56
+ /**
57
+ * The candidacy of a provider the caller found enabled in the org: a valid effective config and
58
+ * `configured(config)` not false. Undefined when it is off; a provider whose status could not be
59
+ * read is also added to `failed` and logged to `log` (the caller's context logger, so the warning
60
+ * names the service that excluded it).
61
+ */
62
+ async evaluate(orgId, point, extension, impl, failed, log = this.log) {
63
+ // spec A §6: an org whose effective config is not valid gets no call from this extension
64
+ let effective;
65
+ try {
66
+ effective = await this.effective.get(orgId, extension);
67
+ }
68
+ catch (err) {
69
+ log.warn("extension point provider excluded, cannot read its effective config", {
70
+ orgId,
71
+ point,
72
+ extension,
73
+ err,
74
+ });
75
+ failed.add(extension);
76
+ return undefined;
77
+ }
78
+ if (!effective.ok)
79
+ return undefined;
80
+ const configured = impl.configured;
81
+ if (typeof configured === "function") {
82
+ let ok;
83
+ try {
84
+ ok = configured.call(impl, effective.config) !== false;
85
+ }
86
+ catch (err) {
87
+ log.warn("extension point provider excluded, configured() threw", {
88
+ orgId,
89
+ point,
90
+ extension,
91
+ err,
92
+ });
93
+ failed.add(extension);
94
+ return undefined;
95
+ }
96
+ if (!ok)
97
+ return undefined;
98
+ }
99
+ return { extension, impl, config: effective.config };
100
+ }
101
+ };
102
+ ExtensionPointServing = __decorate([
103
+ Injectable(),
104
+ __param(0, Inject(KernelDb)),
105
+ __param(1, Inject(ExtensionRegistry)),
106
+ __param(2, Inject(EffectiveConfigs)),
107
+ __param(3, Inject(KERNEL_LOGGER))
108
+ ], ExtensionPointServing);
109
+ export { ExtensionPointServing };
110
+ /** The one {@link ExtensionPointServing} (below `ExtensionsModule`, which re-exports it). */
111
+ let ExtensionPointServingModule = class ExtensionPointServingModule {
112
+ };
113
+ ExtensionPointServingModule = __decorate([
114
+ Module({
115
+ imports: [ExtensionStateModule],
116
+ providers: [ExtensionPointServing],
117
+ exports: [ExtensionPointServing],
118
+ })
119
+ ], ExtensionPointServingModule);
120
+ export { ExtensionPointServingModule };
@@ -93,6 +93,17 @@ export declare class InboxItemsService {
93
93
  * unknown id throws `InboxError("not_found")`. The caller runs it in the org's scope.
94
94
  */
95
95
  resolveForPlugin(plugin: string, orgId: string, itemId: string): Promise<void>;
96
+ /**
97
+ * Resolves the open kernel item of `accountId` in `orgId` posted with `dedupeKey` (the thing it
98
+ * asked about was settled elsewhere); none open is no change. The caller runs it in the org's
99
+ * scope.
100
+ */
101
+ resolveKernelItem(orgId: string, accountId: string, dedupeKey: string): Promise<void>;
102
+ /**
103
+ * Resolves every open kernel item of `accountId` in `orgId` whose dedupe key starts with
104
+ * `prefix` (the things they asked about are gone). The caller runs it in the org's scope.
105
+ */
106
+ resolveKernelItems(orgId: string, accountId: string, prefix: string): Promise<void>;
96
107
  /** Marks an open item resolved; whether it was open. */
97
108
  close(orgId: string, itemId: string): Promise<boolean>;
98
109
  /** The open, unexpired item `itemId` of `accountId` in `orgId`, or `inbox.item_not_found`. */
@@ -222,6 +222,39 @@ let InboxItemsService = class InboxItemsService {
222
222
  throw new InboxError("not_found", "inbox item not found");
223
223
  await this.close(orgId, itemId);
224
224
  }
225
+ /**
226
+ * Resolves the open kernel item of `accountId` in `orgId` posted with `dedupeKey` (the thing it
227
+ * asked about was settled elsewhere); none open is no change. The caller runs it in the org's
228
+ * scope.
229
+ */
230
+ async resolveKernelItem(orgId, accountId, dedupeKey) {
231
+ await this.kdb.db
232
+ .updateTable("inbox_items")
233
+ .set({ state: "resolved", resolved_at: sql `now()` })
234
+ .where("org_id", "=", orgId)
235
+ .where("account_id", "=", accountId)
236
+ .where("source", "=", "kernel")
237
+ .where("plugin", "is", null)
238
+ .where("dedupe_key", "=", dedupeKey)
239
+ .where("state", "=", "open")
240
+ .execute();
241
+ }
242
+ /**
243
+ * Resolves every open kernel item of `accountId` in `orgId` whose dedupe key starts with
244
+ * `prefix` (the things they asked about are gone). The caller runs it in the org's scope.
245
+ */
246
+ async resolveKernelItems(orgId, accountId, prefix) {
247
+ await this.kdb.db
248
+ .updateTable("inbox_items")
249
+ .set({ state: "resolved", resolved_at: sql `now()` })
250
+ .where("org_id", "=", orgId)
251
+ .where("account_id", "=", accountId)
252
+ .where("source", "=", "kernel")
253
+ .where("plugin", "is", null)
254
+ .where(sql `starts_with(dedupe_key, ${prefix})`)
255
+ .where("state", "=", "open")
256
+ .execute();
257
+ }
225
258
  /** Marks an open item resolved; whether it was open. */
226
259
  async close(orgId, itemId) {
227
260
  const r = await this.kdb.db
@@ -326,6 +359,12 @@ __decorate([
326
359
  __decorate([
327
360
  Transactional()
328
361
  ], InboxItemsService.prototype, "resolveForPlugin", null);
362
+ __decorate([
363
+ Transactional()
364
+ ], InboxItemsService.prototype, "resolveKernelItem", null);
365
+ __decorate([
366
+ Transactional()
367
+ ], InboxItemsService.prototype, "resolveKernelItems", null);
329
368
  __decorate([
330
369
  Transactional()
331
370
  ], InboxItemsService.prototype, "close", null);
package/dist/index.d.ts CHANGED
@@ -20,6 +20,8 @@ export { createKv } from "./ctx/kv.js";
20
20
  export { createLock } from "./ctx/lock.js";
21
21
  export { createQueue } from "./ctx/queue.js";
22
22
  export { createKeyring, createSecrets, type DerivedKeys, type Keyring, REWRAP_BATCH_SIZE, type RewrapResult, rewrapToCurrentMasterKey, } from "./ctx/secrets.js";
23
+ export { extensionDbIdentity } from "./db/extension-db.js";
24
+ export { createProvisionedExtensionSchema, provisionExtensionRole, } from "./db/extension-role-provision.js";
23
25
  export { type KernelDatabase, type KernelSchemaDb, kernelDb } from "./db/kernel-schema.js";
24
26
  export { type MigrationOwner, migrate } from "./db/migrator.js";
25
27
  export { createDb } from "./db/pool.js";
@@ -64,7 +66,7 @@ export type { RlsMode } from "./infra/database/scoped-dialect.js";
64
66
  export { onProcessFault } from "./infra/health/process-fault.js";
65
67
  export { GUARD_CIRCUIT_LIMIT, GUARD_CIRCUIT_WINDOW_MS, installProcessGuards, type ProcessGuardDeps, } from "./infra/lifecycle/process-guards.js";
66
68
  export { handleShutdownSignals, type ShutdownSignalHandle, type ShutdownSignalOptions, } from "./infra/lifecycle/shutdown-signals.js";
67
- export { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
69
+ export { declaredExtensionNames, KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
68
70
  export { createLogger, type KernelLogger, LOG_FORMATS, LOG_LEVELS, type LogFormat, type LoggerOptions, type LogLevel, type LogOutput, } from "./log.js";
69
71
  export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js";
70
72
  export { type ContextJob, type JobWrapper, type LogContext, logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
package/dist/index.js CHANGED
@@ -19,6 +19,8 @@ export { createKv } from "./ctx/kv.js";
19
19
  export { createLock } from "./ctx/lock.js";
20
20
  export { createQueue } from "./ctx/queue.js";
21
21
  export { createKeyring, createSecrets, REWRAP_BATCH_SIZE, rewrapToCurrentMasterKey, } from "./ctx/secrets.js";
22
+ export { extensionDbIdentity } from "./db/extension-db.js";
23
+ export { createProvisionedExtensionSchema, provisionExtensionRole, } from "./db/extension-role-provision.js";
22
24
  export { kernelDb } from "./db/kernel-schema.js";
23
25
  export { migrate } from "./db/migrator.js";
24
26
  export { createDb } from "./db/pool.js";
@@ -61,7 +63,7 @@ export { asPlatform, currentScope, setUnscopedQueryCheck, withOrgScope, } from "
61
63
  export { onProcessFault } from "./infra/health/process-fault.js";
62
64
  export { GUARD_CIRCUIT_LIMIT, GUARD_CIRCUIT_WINDOW_MS, installProcessGuards, } from "./infra/lifecycle/process-guards.js";
63
65
  export { handleShutdownSignals, } from "./infra/lifecycle/shutdown-signals.js";
64
- export { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
66
+ export { declaredExtensionNames, KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
65
67
  export { createLogger, LOG_FORMATS, LOG_LEVELS, } from "./log.js";
66
68
  export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js";
67
69
  export { logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
@@ -1,11 +1,4 @@
1
- import { type Kysely } from "kysely";
2
- /**
3
- * Why `db.rls: enforce` would filter nothing on this pool, or undefined when it can work (RLS spec
4
- * §10):
5
- * - PostgreSQL never applies a row level security policy to a superuser or a role with BYPASSRLS,
6
- * even on a table that forces RLS. The official compose file's `POSTGRES_USER` is a superuser, so
7
- * such a deployment needs a role of its own before enforcing;
8
- * - the policies ship dark: migration 0182 creates them without `ENABLE` / `FORCE ROW LEVEL
9
- * SECURITY`, which a later migration (phase 5) runs. Until then no org-scoped table applies them.
10
- */
11
- export declare function rlsEnforceProblem(pool: Kysely<any>): Promise<string | undefined>;
1
+ import { type QueryExecutorProvider } from "kysely";
2
+ export declare function matchesOrgScopePredicate(clause: string | null): boolean;
3
+ /** Checks the serving login and migrated schema before the kernel starts in enforce mode. */
4
+ export declare function rlsEnforceProblem(pool: QueryExecutorProvider, expectedOwner: string): Promise<string | undefined>;
@@ -1,33 +1,77 @@
1
1
  import { sql } from "kysely";
2
- /**
3
- * Why `db.rls: enforce` would filter nothing on this pool, or undefined when it can work (RLS spec
4
- * §10):
5
- * - PostgreSQL never applies a row level security policy to a superuser or a role with BYPASSRLS,
6
- * even on a table that forces RLS. The official compose file's `POSTGRES_USER` is a superuser, so
7
- * such a deployment needs a role of its own before enforcing;
8
- * - the policies ship dark: migration 0182 creates them without `ENABLE` / `FORCE ROW LEVEL
9
- * SECURITY`, which a later migration (phase 5) runs. Until then no org-scoped table applies them.
10
- */
11
- // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
12
- export async function rlsEnforceProblem(pool) {
13
- const role = await sql `
14
- select rolsuper as superuser, rolbypassrls as bypass from pg_roles
15
- where rolname = current_user`.execute(pool);
16
- const row = role.rows[0];
17
- if (row?.superuser)
2
+ // PostgreSQL deparses the uncorrelated subqueries with result aliases. Check the
3
+ // policy expression in full so an extra condition or a substituted setting is drift.
4
+ export function matchesOrgScopePredicate(clause) {
5
+ const normalized = clause
6
+ ?.replace(/\s+/g, " ")
7
+ .replace(/\b(?:capybara|pg_catalog)\.(?=\w+\()/g, "");
8
+ return (normalized === "rls_admits(org_id)" ||
9
+ normalized ===
10
+ "rls_admits(org_id, ( SELECT rls_scope_unrestricted() AS rls_scope_unrestricted), " +
11
+ "( SELECT current_setting('capybara.org_id'::text, true) AS current_setting))");
12
+ }
13
+ /** Checks the serving login and migrated schema before the kernel starts in enforce mode. */
14
+ export async function rlsEnforceProblem(pool, expectedOwner) {
15
+ const { rows: [role], } = await sql `
16
+ select bool_or(rolsuper) as superuser, bool_or(rolbypassrls) as bypass
17
+ from pg_catalog.pg_roles where rolname in (current_user, session_user)`.execute(pool);
18
+ if (role?.superuser)
18
19
  return "the database role is a superuser";
19
- if (row?.bypass)
20
+ if (role?.bypass)
20
21
  return "the database role has BYPASSRLS";
21
- const off = await sql `
22
- select c.relname as table from pg_class c
23
- join pg_namespace n on n.oid = c.relnamespace and n.nspname = 'capybara'
24
- where c.relkind = 'r' and not (c.relrowsecurity and c.relforcerowsecurity)
25
- and exists (select 1 from pg_attribute a
26
- where a.attrelid = c.oid and a.attname = 'org_id' and not a.attisdropped)
27
- order by 1`.execute(pool);
28
- if (off.rows.length > 0) {
29
- const first = off.rows[0]?.table;
30
- return `row level security is not enabled and forced on ${off.rows.length} org-scoped table(s) (${first}, …; RLS spec phase 5 enables them)`;
22
+ const { rows: [schema], } = await sql `
23
+ select pg_catalog.pg_get_userbyid(nspowner) as owner,
24
+ (pg_catalog.pg_has_role(current_user, nspowner, 'MEMBER')
25
+ or pg_catalog.pg_has_role(session_user, nspowner, 'MEMBER')) as "canOwn"
26
+ from pg_catalog.pg_namespace where nspname = 'capybara'`.execute(pool);
27
+ if (!schema)
28
+ return "the capybara schema is missing";
29
+ if (schema.canOwn)
30
+ return "the database role owns or is a member of the owner of the capybara schema";
31
+ if (schema.owner !== expectedOwner)
32
+ return `the capybara schema has unexpected owner ${schema.owner}; expected ${expectedOwner}`;
33
+ // The deparser may omit a visible function's schema. Check its catalog dependencies too.
34
+ const { rows: tables } = await sql `
35
+ select c.relname as "table", pg_catalog.pg_get_userbyid(c.relowner) as owner,
36
+ (c.relrowsecurity and c.relforcerowsecurity) as active,
37
+ p.polcmd as command,
38
+ pg_catalog.pg_get_expr(p.polqual, c.oid) as "using",
39
+ pg_catalog.pg_get_expr(p.polwithcheck, c.oid) as "withCheck",
40
+ exists (
41
+ select from pg_catalog.pg_depend d
42
+ where d.classid = 'pg_catalog.pg_policy'::pg_catalog.regclass and d.objid = p.oid
43
+ and d.refclassid = 'pg_catalog.pg_proc'::pg_catalog.regclass
44
+ and not exists (
45
+ select from (values
46
+ (pg_catalog.to_regprocedure('capybara.rls_admits(text)')),
47
+ (pg_catalog.to_regprocedure('capybara.rls_admits(text,boolean,text)')),
48
+ (pg_catalog.to_regprocedure('capybara.rls_scope_unrestricted()'))
49
+ ) as allowed(oid) where allowed.oid = d.refobjid
50
+ )
51
+ ) as "hasOtherFunctions",
52
+ (c.relname = 'conversation_events' and not a.attnotnull) as "nullableEventOrg"
53
+ from pg_catalog.pg_class c
54
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace and n.nspname = 'capybara'
55
+ join pg_catalog.pg_attribute a on a.attrelid = c.oid and a.attname = 'org_id' and not a.attisdropped
56
+ left join pg_catalog.pg_policy p on p.polrelid = c.oid and p.polname = 'org_scope'
57
+ where c.relkind in ('r', 'p')
58
+ order by c.relname`.execute(pool);
59
+ for (const table of tables) {
60
+ const name = `capybara.${table.table}`;
61
+ if (table.owner !== expectedOwner)
62
+ return `${name} has unexpected owner ${table.owner}; expected ${expectedOwner}`;
63
+ if (table.command === null)
64
+ return `${name} is missing its org_scope policy`;
65
+ if (!table.active)
66
+ return `row level security is not enabled and forced on ${name}`;
67
+ if (table.command !== "*")
68
+ return `${name} org_scope policy must apply to ALL commands`;
69
+ if (table.hasOtherFunctions ||
70
+ !matchesOrgScopePredicate(table.using) ||
71
+ !matchesOrgScopePredicate(table.withCheck))
72
+ return `${name} org_scope policy must use the kernel rls_admits(org_id) predicate for USING and WITH CHECK`;
73
+ if (table.nullableEventOrg)
74
+ return "capybara.conversation_events.org_id must be NOT NULL";
31
75
  }
32
76
  return undefined;
33
77
  }
@@ -610,6 +610,76 @@ export declare const OUTBOX_JOBS: {
610
610
  readonly removeOnFail: true;
611
611
  };
612
612
  };
613
+ readonly "external-start": {
614
+ readonly queue: "cap-external-calls";
615
+ readonly idempotent: "the delivery goes only while its deliverySeq is the next after the conversation's cursor, which it moves when done; the target's start is idempotent by messageId";
616
+ readonly processedIn: "packages/kernel/src/conversations/external/external-calls.processor.ts";
617
+ readonly opts: {
618
+ readonly attempts: 10;
619
+ readonly backoff: {
620
+ readonly type: "exponential";
621
+ readonly delay: 2000;
622
+ };
623
+ readonly removeOnComplete: true;
624
+ readonly removeOnFail: true;
625
+ };
626
+ };
627
+ readonly "external-send": {
628
+ readonly queue: "cap-external-calls";
629
+ readonly idempotent: "the delivery goes only while its deliverySeq is the next after the conversation's cursor, which it moves when done; the target's send is idempotent by messageId";
630
+ readonly processedIn: "packages/kernel/src/conversations/external/external-calls.processor.ts";
631
+ readonly opts: {
632
+ readonly attempts: 10;
633
+ readonly backoff: {
634
+ readonly type: "exponential";
635
+ readonly delay: 2000;
636
+ };
637
+ readonly removeOnComplete: true;
638
+ readonly removeOnFail: true;
639
+ };
640
+ };
641
+ readonly "external-answer": {
642
+ readonly queue: "cap-external-calls";
643
+ readonly idempotent: "the answer is written once per request (its idempotency key); the target's answer is idempotent by requestId";
644
+ readonly processedIn: "packages/kernel/src/conversations/external/external-calls.processor.ts";
645
+ readonly opts: {
646
+ readonly attempts: 10;
647
+ readonly backoff: {
648
+ readonly type: "exponential";
649
+ readonly delay: 2000;
650
+ };
651
+ readonly removeOnComplete: true;
652
+ readonly removeOnFail: true;
653
+ };
654
+ };
655
+ readonly "external-stop": {
656
+ readonly queue: "cap-external-calls";
657
+ readonly idempotent: "stopping a turn that is not running is a no-op for the target; the job id is per conversation and last seq";
658
+ readonly processedIn: "packages/kernel/src/conversations/external/external-calls.processor.ts";
659
+ readonly opts: {
660
+ readonly attempts: 10;
661
+ readonly backoff: {
662
+ readonly type: "exponential";
663
+ readonly delay: 2000;
664
+ };
665
+ readonly removeOnComplete: true;
666
+ readonly removeOnFail: true;
667
+ };
668
+ };
669
+ readonly "external-deleted": {
670
+ readonly queue: "cap-external-calls";
671
+ readonly idempotent: "releasing what the target holds for a deleted conversation twice releases nothing more; the job id is per conversation and last seq";
672
+ readonly processedIn: "packages/kernel/src/conversations/external/external-calls.processor.ts";
673
+ readonly opts: {
674
+ readonly attempts: 10;
675
+ readonly backoff: {
676
+ readonly type: "exponential";
677
+ readonly delay: 2000;
678
+ };
679
+ readonly removeOnComplete: true;
680
+ readonly removeOnFail: true;
681
+ };
682
+ };
613
683
  readonly "hook-run-lifecycle": {
614
684
  readonly queue: "cap-kernel-lifecycle";
615
685
  readonly idempotent: "the `run.lifecycle` handler sets a display state keyed by the run and phase (the SDK contract: handlers are idempotent); the job id is deterministic per run, phase and wait";
@@ -16,6 +16,17 @@ const SCOPE_JOB_OPTS = {
16
16
  removeOnComplete: true,
17
17
  removeOnFail: true,
18
18
  };
19
+ /**
20
+ * The external conversation calls' retry policy: 10 attempts from 2 s, doubling (about 17 min in
21
+ * all) before the call is dropped with a failed turn; removed once done, so the same id owed again
22
+ * (a chained send) is not deduped away.
23
+ */
24
+ const EXTERNAL_CALL_OPTS = {
25
+ attempts: 10,
26
+ backoff: { type: "exponential", delay: 2_000 },
27
+ removeOnComplete: true,
28
+ removeOnFail: true,
29
+ };
19
30
  /**
20
31
  * Every job name added through the outbox. The task that introduces a job name adds its entry; a
21
32
  * name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
@@ -554,6 +565,39 @@ export const OUTBOX_JOBS = {
554
565
  removeOnFail: true,
555
566
  },
556
567
  },
568
+ // `conversations/external/external-calls.ts` EXTERNAL_CALL_JOBS: owed by the transaction that
569
+ // writes a person's message to an external conversation (start, send), their answer to its
570
+ // request, a stop, or its deletion (local agents spec Part 2), under `externalCallJob`
571
+ "external-start": {
572
+ queue: "cap-external-calls",
573
+ idempotent: "the delivery goes only while its deliverySeq is the next after the conversation's cursor, which it moves when done; the target's start is idempotent by messageId",
574
+ processedIn: "packages/kernel/src/conversations/external/external-calls.processor.ts",
575
+ opts: EXTERNAL_CALL_OPTS,
576
+ },
577
+ "external-send": {
578
+ queue: "cap-external-calls",
579
+ idempotent: "the delivery goes only while its deliverySeq is the next after the conversation's cursor, which it moves when done; the target's send is idempotent by messageId",
580
+ processedIn: "packages/kernel/src/conversations/external/external-calls.processor.ts",
581
+ opts: EXTERNAL_CALL_OPTS,
582
+ },
583
+ "external-answer": {
584
+ queue: "cap-external-calls",
585
+ idempotent: "the answer is written once per request (its idempotency key); the target's answer is idempotent by requestId",
586
+ processedIn: "packages/kernel/src/conversations/external/external-calls.processor.ts",
587
+ opts: EXTERNAL_CALL_OPTS,
588
+ },
589
+ "external-stop": {
590
+ queue: "cap-external-calls",
591
+ idempotent: "stopping a turn that is not running is a no-op for the target; the job id is per conversation and last seq",
592
+ processedIn: "packages/kernel/src/conversations/external/external-calls.processor.ts",
593
+ opts: EXTERNAL_CALL_OPTS,
594
+ },
595
+ "external-deleted": {
596
+ queue: "cap-external-calls",
597
+ idempotent: "releasing what the target holds for a deleted conversation twice releases nothing more; the job id is per conversation and last seq",
598
+ processedIn: "packages/kernel/src/conversations/external/external-calls.processor.ts",
599
+ opts: EXTERNAL_CALL_OPTS,
600
+ },
557
601
  // `extensions/run-lifecycle-owe.ts` RUN_LIFECYCLE_JOB: owed by the transaction that starts a
558
602
  // run, suspends it on a person, resumes it, ends it (finished, failed, aborted) or declines,
559
603
  // expires or gives up on directed work, once per phase of a run (and wait) and plugin
@@ -4,5 +4,5 @@
4
4
  * (admin/health.service.ts) lists the same names from the feature constants;
5
5
  * test/infra/queue-names.test.ts keeps the two equal.
6
6
  */
7
- export declare const KERNEL_QUEUES: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs", "cap-kernel-channels", "cap-kernel-maintenance", "cap-kernel-tool-watch", "cap-kernel-plugin-scope", "cap-kernel-titles", "cap-kernel-suggestions", "cap-kernel-usage-report", "cap-kernel-evals", "cap-kernel-lifecycle", "cap-push-deliver", "cap-connector-tools", "cap-template-connectors", "cap-device-service-events"];
7
+ export declare const KERNEL_QUEUES: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs", "cap-kernel-channels", "cap-kernel-maintenance", "cap-kernel-tool-watch", "cap-kernel-plugin-scope", "cap-kernel-titles", "cap-kernel-suggestions", "cap-kernel-usage-report", "cap-kernel-evals", "cap-kernel-lifecycle", "cap-push-deliver", "cap-connector-tools", "cap-template-connectors", "cap-device-service-events", "cap-external-calls"];
8
8
  export type KernelQueueName = (typeof KERNEL_QUEUES)[number];
@@ -20,4 +20,5 @@ export const KERNEL_QUEUES = [
20
20
  "cap-connector-tools",
21
21
  "cap-template-connectors",
22
22
  "cap-device-service-events",
23
+ "cap-external-calls",
23
24
  ];
package/dist/kernel.d.ts CHANGED
@@ -10,6 +10,8 @@ import type { PendingExtension } from "./extensions/approvals.js";
10
10
  export declare const KERNEL_MIGRATIONS_DIR: string;
11
11
  /** The kernel's PG schema. */
12
12
  export declare const KERNEL_SCHEMA = "capybara";
13
+ /** Static names of config-declared extensions, for deployment and fixture provisioning. */
14
+ export declare function declaredExtensionNames(specifiers: string[], resolveFrom?: string): Promise<Set<string>>;
13
15
  /** Only a login with migration privileges can initialize the kernel schema at startup. */
14
16
  export declare function prepareKernelDatabase(db: KernelConfig["db"], opts?: {
15
17
  pool?: QueryExecutorProvider;
package/dist/kernel.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { fileURLToPath } from "node:url";
2
- import { extensionDbIdentity } from "./db/extension-db.js";
2
+ import { extensionDbIdentity, validateExtensionCredentials } from "./db/extension-db.js";
3
3
  import { canMigrateKernel, migrate, verifyMigrations } from "./db/migrator.js";
4
4
  import { createDb } from "./db/pool.js";
5
5
  import { ExtensionHost } from "./extensions/host.js";
@@ -12,11 +12,18 @@ import { ExtensionHost } from "./extensions/host.js";
12
12
  export const KERNEL_MIGRATIONS_DIR = fileURLToPath(new URL("../src/migrations/", import.meta.url));
13
13
  /** The kernel's PG schema. */
14
14
  export const KERNEL_SCHEMA = "capybara";
15
+ /** Static names of config-declared extensions, for deployment and fixture provisioning. */
16
+ export function declaredExtensionNames(specifiers, resolveFrom) {
17
+ return ExtensionHost.declaredNames(specifiers, resolveFrom === undefined ? {} : { resolveFrom });
18
+ }
15
19
  const coreMigrations = { schema: KERNEL_SCHEMA, dir: KERNEL_MIGRATIONS_DIR };
16
20
  /** Only a login with migration privileges can initialize the kernel schema at startup. */
17
21
  export async function prepareKernelDatabase(db, opts = {}) {
18
22
  if (db.migrationUrl !== undefined)
19
23
  throw new Error("db.migrationUrl may only be set for capybara migrate");
24
+ if (db.extensionProvisioningUrl !== undefined)
25
+ throw new Error("db.extensionProvisioningUrl may only be set for capybara migrate");
26
+ validateExtensionCredentials(db);
20
27
  const prepare = async (pool) => {
21
28
  if (await canMigrateKernel(pool)) {
22
29
  await migrate(db.url, coreMigrations, {
@@ -45,6 +52,9 @@ export async function prepareKernelDatabase(db, opts = {}) {
45
52
  */
46
53
  export async function migrateAll(config, opts = {}) {
47
54
  const connectTimeoutMs = config.db.connectTimeoutMs;
55
+ if (config.db.extensionProvisioningUrl !== undefined && config.db.extensionsUrl === undefined)
56
+ throw new Error("db.extensionProvisioningUrl requires db.extensionsUrl");
57
+ validateExtensionCredentials(config.db);
48
58
  const kernel = await migrate(config.db.migrationUrl ?? config.db.url, coreMigrations, {
49
59
  connectTimeoutMs,
50
60
  });
@@ -52,7 +62,7 @@ export async function migrateAll(config, opts = {}) {
52
62
  dbUrl: config.db.url,
53
63
  ...(config.db.extensionsUrl !== undefined && {
54
64
  extensionIdentity: extensionDbIdentity(config.db),
55
- handoffRuntimeLogin: config.db.extensionEffectRelayLogin ?? "capybara_runtime",
65
+ extensionProvisioning: config.db,
56
66
  }),
57
67
  connectTimeoutMs,
58
68
  autoApprove: config.extensionPermissions.autoApprove,
@@ -11,6 +11,7 @@ import { TriggerEventsModule } from "./automations/events/events.module.js";
11
11
  import { CatalogModule } from "./catalog/catalog.module.js";
12
12
  import { ChannelsModule } from "./channels/channels.module.js";
13
13
  import { ClientModule } from "./client/client.module.js";
14
+ import { ExternalConversationsModule } from "./conversations/external/external-conversations.service.js";
14
15
  import { PromptSuggestionsModule } from "./conversations/prompt-suggestions.js";
15
16
  import { TitlesModule } from "./conversations/titles.js";
16
17
  import { ExtensionDeviceAccessModule } from "./device-access/device-access.module.js";
@@ -143,6 +144,9 @@ let KernelModule = KernelModule_1 = class KernelModule {
143
144
  InboxItemsModule,
144
145
  // ctx.agents / ctx.conversations / ctx.people: read-only org facts (found at the time of use)
145
146
  PluginReadsModule,
147
+ // ctx.conversations' external methods and the external conversation calls' queue (found at
148
+ // the time of use)
149
+ ExternalConversationsModule,
146
150
  // the Platform tool's operation registry and actor facts
147
151
  PlatformModule,
148
152
  // its operations (skills, agents, ...), registered at start on every role