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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/admin.schemas.d.ts +4 -0
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/admin/setup.service.js +6 -1
  7. package/dist/agents/agents.controller.js +3 -2
  8. package/dist/agents/agents.service.d.ts +2 -0
  9. package/dist/agents/agents.service.js +7 -0
  10. package/dist/catalog/catalog.service.d.ts +2 -0
  11. package/dist/catalog/catalog.service.js +28 -5
  12. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  13. package/dist/catalog/marketplace-fetch.js +15 -0
  14. package/dist/catalog/marketplaces.service.d.ts +4 -4
  15. package/dist/catalog/marketplaces.service.js +3 -2
  16. package/dist/catalog/owned-items.d.ts +2 -0
  17. package/dist/catalog/owned-items.js +30 -31
  18. package/dist/catalog/ownership.js +40 -38
  19. package/dist/catalog/plugin-import.d.ts +6 -5
  20. package/dist/catalog/plugin-import.js +69 -16
  21. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  22. package/dist/catalog/plugin-upgrade.js +95 -7
  23. package/dist/catalog/publisher-policy.d.ts +9 -0
  24. package/dist/catalog/publisher-policy.js +12 -0
  25. package/dist/catalog/unshare.js +66 -58
  26. package/dist/client/client-access.service.js +5 -3
  27. package/dist/config/schema.d.ts +1 -0
  28. package/dist/config/schema.js +9 -1
  29. package/dist/conversations/conversations.controller.js +4 -14
  30. package/dist/conversations/conversations.service.d.ts +14 -0
  31. package/dist/conversations/conversations.service.js +20 -2
  32. package/dist/ctx/create-ctx.d.ts +14 -4
  33. package/dist/ctx/create-ctx.js +131 -59
  34. package/dist/ctx/queue.js +7 -4
  35. package/dist/db/extension-db.d.ts +30 -0
  36. package/dist/db/extension-db.js +91 -0
  37. package/dist/db/extension-rls-predicate.d.ts +1 -0
  38. package/dist/db/extension-rls-predicate.js +8 -0
  39. package/dist/db/extension-schema-transfer.d.ts +6 -0
  40. package/dist/db/extension-schema-transfer.js +141 -0
  41. package/dist/db/kernel-schema.d.ts +50 -4
  42. package/dist/db/migrator.d.ts +6 -0
  43. package/dist/db/migrator.js +35 -7
  44. package/dist/db/pool.d.ts +6 -2
  45. package/dist/db/pool.js +37 -2
  46. package/dist/db/sql-statements.d.ts +3 -0
  47. package/dist/db/sql-statements.js +15 -5
  48. package/dist/device-access/device-access.module.js +12 -2
  49. package/dist/device-access/device-access.service.d.ts +30 -2
  50. package/dist/device-access/device-access.service.js +38 -4
  51. package/dist/device-access/host-gate.d.ts +45 -0
  52. package/dist/device-access/host-gate.js +92 -0
  53. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  54. package/dist/device-access/host-service-stop-sweep.js +112 -0
  55. package/dist/device-access/host-service-stop.d.ts +78 -0
  56. package/dist/device-access/host-service-stop.js +144 -0
  57. package/dist/device-access/host-services.d.ts +211 -0
  58. package/dist/device-access/host-services.js +803 -0
  59. package/dist/device-access/person-handles.d.ts +10 -0
  60. package/dist/device-access/person-handles.js +25 -0
  61. package/dist/device-access/service-events.d.ts +199 -0
  62. package/dist/device-access/service-events.js +704 -0
  63. package/dist/device-access/token.d.ts +5 -0
  64. package/dist/device-access/token.js +5 -0
  65. package/dist/devices/devices.service.js +3 -0
  66. package/dist/dial-in/access.d.ts +5 -5
  67. package/dist/dial-in/access.js +19 -12
  68. package/dist/dial-in/gateway.js +6 -2
  69. package/dist/dial-in/machines.d.ts +9 -2
  70. package/dist/dial-in/machines.js +27 -4
  71. package/dist/erasure/device-cleanup.js +12 -0
  72. package/dist/erasure/org-catalog.js +2 -2
  73. package/dist/erasure/org-rules.js +9 -0
  74. package/dist/errors.d.ts +2 -0
  75. package/dist/errors.js +2 -0
  76. package/dist/extensions/admin-ops.d.ts +3 -1
  77. package/dist/extensions/admin-ops.js +19 -9
  78. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  79. package/dist/extensions/deployed-snapshots.js +7 -2
  80. package/dist/extensions/extensions.module.js +3 -0
  81. package/dist/extensions/host.d.ts +11 -3
  82. package/dist/extensions/host.js +40 -8
  83. package/dist/extensions/instance.d.ts +6 -0
  84. package/dist/extensions/instance.js +7 -1
  85. package/dist/extensions/ledger.d.ts +1 -1
  86. package/dist/extensions/lifecycle-hooks.js +3 -3
  87. package/dist/extensions/migrate-lock.d.ts +4 -1
  88. package/dist/extensions/migrate-lock.js +19 -2
  89. package/dist/extensions/org-config.js +6 -1
  90. package/dist/extensions/permission-set.d.ts +7 -0
  91. package/dist/extensions/permission-set.js +10 -0
  92. package/dist/extensions/permission-view.d.ts +1 -1
  93. package/dist/extensions/permission-view.js +10 -1
  94. package/dist/git/tickets.js +32 -27
  95. package/dist/http/app.js +5 -3
  96. package/dist/identity/accounts.d.ts +6 -1
  97. package/dist/identity/accounts.js +11 -2
  98. package/dist/identity/api-tokens.js +7 -6
  99. package/dist/identity/settings.d.ts +9 -1
  100. package/dist/identity/settings.js +16 -1
  101. package/dist/inbox/org-notices.js +3 -2
  102. package/dist/index.d.ts +1 -0
  103. package/dist/index.js +1 -0
  104. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  105. package/dist/infra/database/scoped-dialect.js +260 -72
  106. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  107. package/dist/infra/database/startup-activation-transaction.js +3 -2
  108. package/dist/infra/outbox/registry.d.ts +28 -14
  109. package/dist/infra/outbox/registry.js +30 -15
  110. package/dist/infra/queue/queue-names.d.ts +1 -1
  111. package/dist/infra/queue/queue-names.js +1 -0
  112. package/dist/infra/queue/run-job.d.ts +4 -1
  113. package/dist/infra/queue/run-job.js +10 -2
  114. package/dist/kernel.js +4 -0
  115. package/dist/kernel.module.js +3 -0
  116. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  117. package/dist/lifecycle/kernel-lifecycle.js +26 -21
  118. package/dist/orgs/offboarding.js +18 -9
  119. package/dist/orgs/settings.service.js +3 -0
  120. package/dist/packages/npm-publish-keys.json +27 -0
  121. package/dist/packages/official-publisher.d.ts +19 -0
  122. package/dist/packages/official-publisher.js +152 -0
  123. package/dist/packages/provenance.d.ts +7 -0
  124. package/dist/packages/provenance.js +22 -19
  125. package/dist/packages/sigstore-trusted-root.json +126 -0
  126. package/dist/platform/ops/admin.ops.js +2 -1
  127. package/dist/platform/ops/orgs.ops.js +1 -0
  128. package/dist/roles/worker-role.d.ts +6 -3
  129. package/dist/roles/worker-role.js +12 -4
  130. package/dist/roles/worker.module.js +7 -6
  131. package/dist/runtime/maintenance.d.ts +5 -4
  132. package/dist/runtime/maintenance.js +16 -13
  133. package/dist/sandbox/device-reports.d.ts +4 -4
  134. package/dist/sandbox/device-reports.js +40 -30
  135. package/dist/sandbox/device-services.d.ts +2 -1
  136. package/dist/sandbox/device-services.js +5 -1
  137. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  138. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  139. package/dist/sandbox/permission-config-publication.js +5 -1
  140. package/dist/themes/theme-state.js +24 -13
  141. package/dist/tools/call-scope.d.ts +6 -0
  142. package/dist/tools/call-scope.js +22 -0
  143. package/dist/tools/registry.js +20 -2
  144. package/dist/ui/views.js +36 -8
  145. package/package.json +9 -4
  146. package/src/migrations/0219_event_org_constraint_check.sql +29 -0
  147. package/src/migrations/0220_require_event_org.sql +18 -0
  148. package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
  149. package/src/migrations/0222_device_host_services.sql +27 -0
  150. package/src/migrations/0223_device_service_events.sql +54 -0
  151. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
  152. package/dist/conversations/event-org-backfill.d.ts +0 -111
  153. package/dist/conversations/event-org-backfill.js +0 -264
  154. package/dist/conversations/event-org-backfill.module.d.ts +0 -3
  155. package/dist/conversations/event-org-backfill.module.js +0 -18
@@ -0,0 +1,91 @@
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 } from "@nestjs/common";
11
+ import pg from "pg";
12
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
13
+ import { createDb } from "./pool.js";
14
+ let ConfiguredExtensionDbIdentity = class ConfiguredExtensionDbIdentity {
15
+ identity;
16
+ constructor(config) {
17
+ this.identity = extensionDbIdentity(config.get().db);
18
+ }
19
+ get sharedLogin() {
20
+ return this.identity.sharedLogin;
21
+ }
22
+ resolve(name) {
23
+ return this.identity.resolve(name);
24
+ }
25
+ };
26
+ ConfiguredExtensionDbIdentity = __decorate([
27
+ Injectable(),
28
+ __param(0, Inject(KernelConfigService))
29
+ ], ConfiguredExtensionDbIdentity);
30
+ export { ConfiguredExtensionDbIdentity };
31
+ export function extensionDbIdentity(db) {
32
+ const url = db.extensionsUrl ?? db.url;
33
+ const separate = db.extensionsUrl !== undefined;
34
+ let login;
35
+ try {
36
+ login = new pg.Client({ connectionString: url }).user;
37
+ }
38
+ catch {
39
+ throw new Error("Invalid PostgreSQL connection URL for extensions");
40
+ }
41
+ if (!login)
42
+ throw new Error("PostgreSQL connection needs a login");
43
+ return { sharedLogin: separate ? login : undefined, resolve: () => ({ login, url, separate }) };
44
+ }
45
+ export function pluginSchemaName(name) {
46
+ return `plugin_${name.replaceAll("-", "_")}`;
47
+ }
48
+ const extensionLoginCheck = `
49
+ select r.rolcanlogin and not (r.rolsuper or r.rolbypassrls or r.rolcreaterole or r.rolreplication or r.rolcreatedb)
50
+ and not exists (select from pg_catalog.pg_auth_members where member = r.oid)
51
+ and not coalesce((
52
+ select pg_catalog.has_schema_privilege(r.oid, n.oid, 'USAGE,CREATE')
53
+ from pg_catalog.pg_namespace n where n.nspname = 'capybara'
54
+ ), true)
55
+ and not coalesce((
56
+ select pg_catalog.has_schema_privilege(r.oid, n.oid, 'CREATE')
57
+ from pg_catalog.pg_namespace n where n.nspname = 'public'
58
+ ), false) as isolated
59
+ from pg_catalog.pg_roles r where r.rolname = $1
60
+ `;
61
+ export async function assertExtensionSession(client, login) {
62
+ const { rows: [actual], } = await client.query("select current_user as login");
63
+ const { rows: [role], } = await client.query(extensionLoginCheck, [login]);
64
+ if (actual?.login !== login || !role?.isolated) {
65
+ throw new Error("db.extensionsUrl must authenticate as a restricted extension login with no access to capybara");
66
+ }
67
+ }
68
+ /** A missing schema is normal before a plugin's first migration. */
69
+ export async function assertExtensionSchemaOwner(client, schema, login) {
70
+ const { rows: [namespace], } = await client.query(`select pg_catalog.pg_get_userbyid(nspowner) as owner
71
+ from pg_catalog.pg_namespace where nspname = $1`, [schema]);
72
+ if (namespace && namespace.owner !== login) {
73
+ throw new Error(`Extension schema ${schema} is owned by ${namespace.owner}, expected ${login}. Run capybara migrate with the owner URL to transfer plugin schemas.`);
74
+ }
75
+ }
76
+ /** One small, scope-aware pool per active extension instance. The host owns its lifetime. */
77
+ export function extensionDbPool(identity, name, config, onError) {
78
+ // Names come from validated manifests. Quote regardless so review and maintenance paths are safe too.
79
+ const schema = pluginSchemaName(name);
80
+ const searchPath = `"${schema.replaceAll('"', '""')}", public`;
81
+ return createDb(identity.url, config.extensionPoolMax, onError, {
82
+ connectTimeoutMs: config.connectTimeoutMs,
83
+ rls: config.rls,
84
+ closeActiveOnDestroy: true,
85
+ onConnect: async (client) => {
86
+ await assertExtensionSession(client, identity.login);
87
+ await assertExtensionSchemaOwner(client, schema, identity.login);
88
+ await client.query("select pg_catalog.set_config('search_path', $1, false)", [searchPath]);
89
+ },
90
+ });
91
+ }
@@ -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
+ $$;`;
@@ -0,0 +1,6 @@
1
+ import { type ExtensionDbIdentity } from "./extension-db.js";
2
+ /**
3
+ * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
4
+ * to transfer ownership. Run before starting replicas with the new extension identity.
5
+ */
6
+ export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number): Promise<void>;
@@ -0,0 +1,141 @@
1
+ import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
2
+ import pg from "pg";
3
+ import { assertExtensionSession, pluginSchemaName, } from "./extension-db.js";
4
+ import { assertSameMigrationDatabase, lockMigrationSchema } from "./migrator.js";
5
+ import { pgConnectOptions } from "./pool.js";
6
+ async function transferExtensionSchema(client, schema, target, sources) {
7
+ await lockMigrationSchema(client, schema, "transaction");
8
+ const { rows: [namespace], } = await client.query(`select oid, pg_catalog.pg_get_userbyid(nspowner) as owner
9
+ from pg_catalog.pg_namespace where nspname = $1`, [schema]);
10
+ if (!namespace)
11
+ return;
12
+ if (namespace.owner !== target && !sources.has(namespace.owner)) {
13
+ throw new Error(`Unexpected owner ${namespace.owner} for extension schema ${schema}`);
14
+ }
15
+ const { rows: objects } = await client.query(`
16
+ with objects(classid, objid) as (
17
+ select 'pg_class'::regclass::oid, oid from pg_class
18
+ where relnamespace = $1::oid and relkind in ('r', 'p', 'v', 'm', 'S', 'f')
19
+ union
20
+ select 'pg_proc'::regclass::oid, oid from pg_proc where pronamespace = $1::oid
21
+ union
22
+ select d.classid, d.objid from pg_depend d
23
+ where d.refclassid = 'pg_namespace'::regclass and d.refobjid = $1::oid
24
+ and d.objsubid = 0 and d.deptype = 'n' and d.classid <> 'pg_extension'::regclass
25
+ )
26
+ select object.identity,
27
+ case
28
+ when c.relkind in ('r', 'p') then 'TABLE'
29
+ when c.relkind = 'v' then 'VIEW'
30
+ when c.relkind = 'm' then 'MATERIALIZED VIEW'
31
+ when c.relkind = 'f' then 'FOREIGN TABLE'
32
+ when c.relkind = 'S' then 'SEQUENCE'
33
+ when p.oid is not null then 'ROUTINE'
34
+ when t.typtype = 'd' then 'DOMAIN'
35
+ when t.oid is not null then 'TYPE'
36
+ end as kind,
37
+ pg_get_userbyid(coalesce(c.relowner, p.proowner, t.typowner)) as owner,
38
+ c.relkind = 'S' and exists (
39
+ select from pg_depend d where d.classid = 'pg_class'::regclass and d.objid = c.oid
40
+ and d.refclassid = 'pg_class'::regclass and d.deptype in ('a', 'i')
41
+ ) as attached_sequence,
42
+ exists (
43
+ select from pg_depend d where d.classid = o.classid and d.objid = o.objid
44
+ and d.objsubid = 0 and d.refclassid = 'pg_extension'::regclass and d.deptype = 'e'
45
+ ) as extension_member
46
+ from objects o
47
+ cross join lateral pg_identify_object(o.classid, o.objid, 0) object
48
+ left join pg_class c on o.classid = 'pg_class'::regclass and c.oid = o.objid
49
+ left join pg_proc p on o.classid = 'pg_proc'::regclass and p.oid = o.objid
50
+ left join pg_type t on o.classid = 'pg_type'::regclass and t.oid = o.objid
51
+ order by object.identity
52
+ `, [namespace.oid]);
53
+ const unexpected = objects.filter((object) => !object.kind ||
54
+ object.extension_member ||
55
+ (object.owner !== target && object.owner !== namespace.owner));
56
+ if (unexpected.length) {
57
+ const names = unexpected.map((object) => `${object.identity} (owner ${object.owner ?? "unknown"})`);
58
+ throw new Error(`Unexpected objects in extension schema ${schema}: ${names.join(", ")}`);
59
+ }
60
+ const quotedTarget = pg.escapeIdentifier(target);
61
+ if (namespace.owner !== target) {
62
+ await client.query(`alter schema ${pg.escapeIdentifier(schema)} owner to ${quotedTarget}`);
63
+ }
64
+ // PostgreSQL moves table-owned sequences, row types and indexes with their parent table.
65
+ for (const object of objects) {
66
+ if (object.kind && object.owner !== target && !object.attached_sequence) {
67
+ // Kind is from the fixed catalog mapping. PostgreSQL returns the quoted object identity.
68
+ await client.query(`alter ${object.kind} ${object.identity} owner to ${quotedTarget}`);
69
+ }
70
+ }
71
+ }
72
+ async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
73
+ const client = new pg.Client({
74
+ connectionString: target.url,
75
+ ...pgConnectOptions({ connectTimeoutMs }),
76
+ });
77
+ client.on("error", () => { });
78
+ try {
79
+ await client.connect();
80
+ await assertExtensionSession(client, target.login);
81
+ await assertSameMigrationDatabase(owner, client);
82
+ }
83
+ catch (cause) {
84
+ throw new Error(`Cannot verify extension database login ${target.login}. Check db.extensionsUrl and use the same database as db.url.`, { cause });
85
+ }
86
+ finally {
87
+ await client.end();
88
+ }
89
+ }
90
+ /**
91
+ * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
92
+ * to transfer ownership. Run before starting replicas with the new extension identity.
93
+ */
94
+ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs) {
95
+ const owner = new pg.Client({
96
+ connectionString: bootstrapUrl,
97
+ ...pgConnectOptions({ connectTimeoutMs }),
98
+ });
99
+ owner.on("error", () => { });
100
+ try {
101
+ await owner.connect();
102
+ await owner.query("begin");
103
+ try {
104
+ await owner.query("set local search_path = pg_catalog");
105
+ await owner.query("set local lock_timeout = '30s'");
106
+ const { rows: [legacy], } = await owner.query("select current_user as login");
107
+ if (!legacy)
108
+ throw new Error("Could not verify the schema transfer login");
109
+ const { rows: registered } = await owner.query(`select name from capybara.extension_name_owners
110
+ union select name from capybara.extension_installs`);
111
+ const names = new Set([...declaredNames, ...registered.map((row) => row.name)]);
112
+ const resolved = [...names].sort().map((name) => {
113
+ if (!EXTENSION_NAME_RE.test(name))
114
+ throw new Error(`Invalid extension name: ${name}`);
115
+ return { schema: pluginSchemaName(name), target: identity.resolve(name) };
116
+ });
117
+ const sources = new Set([legacy.login, ...resolved.map(({ target }) => target.login)]);
118
+ if (identity.sharedLogin !== undefined)
119
+ sources.add(identity.sharedLogin);
120
+ const targets = resolved.filter(({ target }) => target.separate);
121
+ const validated = new Set();
122
+ for (const { target } of targets) {
123
+ if (validated.has(target.url))
124
+ continue;
125
+ await confirmTargetDatabase(owner, target, connectTimeoutMs);
126
+ validated.add(target.url);
127
+ }
128
+ for (const { schema, target } of targets) {
129
+ await transferExtensionSchema(owner, schema, target.login, sources);
130
+ }
131
+ await owner.query("commit");
132
+ }
133
+ catch (error) {
134
+ await owner.query("rollback").catch(() => { });
135
+ throw error;
136
+ }
137
+ }
138
+ finally {
139
+ await owner.end();
140
+ }
141
+ }
@@ -519,8 +519,8 @@ export type ConversationKind = "chat" | "eval" | "subagent";
519
519
  /** 0006_conversations.sql: append-only conversation event log. */
520
520
  export interface ConversationEventsTable {
521
521
  conversation_id: string;
522
- /** 0215: owning org (nullable during expand; populated by app and backfill before NOT NULL). */
523
- org_id: ColumnType<string | null, string | null | undefined, string | null>;
522
+ /** Owning org, enforced by the composite foreign key to conversations. */
523
+ org_id: string;
524
524
  seq: Int8;
525
525
  type: string;
526
526
  run_id: string | null;
@@ -708,8 +708,6 @@ export interface ConnectorToolsTable {
708
708
  spec_hash: string;
709
709
  status: "enabled" | "disabled" | "pending_review";
710
710
  default_policy: "allow" | "ask" | "deny";
711
- /** Retained for the rc.157 rollout. The next contract drops this column. */
712
- declaration_policy: ColumnType<null, never, never>;
713
711
  reviewed_at: TsNullable;
714
712
  /** 0013:工具来源(`resources` = 内核为支持 resources 的连接器补上的两个工具)。 */
715
713
  source: Generated<"connector" | "resources">;
@@ -1302,6 +1300,51 @@ export interface DeviceSiteGrantsTable {
1302
1300
  expires_at: ColumnType<Date, Date | string, Date | string>;
1303
1301
  revoked_at: TsNullable;
1304
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
+ }
1305
1348
  /** 0088_environments.sql, renamed in 0105: the device a member's new conversations use by default. */
1306
1349
  export interface DeviceDefaultsTable {
1307
1350
  org_id: string;
@@ -2055,6 +2098,9 @@ export interface KernelDatabase {
2055
2098
  device_conversation_notices: DeviceConversationNoticesTable;
2056
2099
  device_loopback_grants: DeviceLoopbackGrantsTable;
2057
2100
  device_site_grants: DeviceSiteGrantsTable;
2101
+ device_host_services: DeviceHostServicesTable;
2102
+ device_service_events: DeviceServiceEventsTable;
2103
+ device_service_event_cursors: DeviceServiceEventCursorsTable;
2058
2104
  background_tasks: BackgroundTasksTable;
2059
2105
  automations: AutomationsTable;
2060
2106
  automation_runs: AutomationRunsTable;
@@ -1,4 +1,5 @@
1
1
  import { type QueryExecutorProvider } from "kysely";
2
+ import pg from "pg";
2
3
  /** 迁移文件名:`NNNN_<snake_desc>.sql`(其他文件忽略)。 */
3
4
  export declare const MIGRATION_FILE_RE: RegExp;
4
5
  /** 迁移器所有者:目标 schema 与迁移文件目录。 */
@@ -6,6 +7,9 @@ export interface MigrationOwner {
6
7
  schema: string;
7
8
  dir: string;
8
9
  }
10
+ export declare function lockMigrationSchema(client: pg.ClientBase, schema: string, scope: "session" | "transaction"): Promise<void>;
11
+ /** A held two-key lock conflicts only with sessions in the same database. */
12
+ export declare function assertSameMigrationDatabase(owner: pg.ClientBase, extension: pg.ClientBase): Promise<void>;
9
13
  export declare function canMigrateKernel(db: QueryExecutorProvider): Promise<boolean>;
10
14
  /** Verify the files expected by this binary without taking a migration lock or writing the journal.
11
15
  * Extra entries are valid when a newer release has already migrated a shared database.
@@ -25,6 +29,8 @@ export declare function verifyMigrations(db: QueryExecutorProvider, { schema, di
25
29
  export declare function migrate(connectionString: string, owner: MigrationOwner, opts?: {
26
30
  connectTimeoutMs?: number | undefined;
27
31
  signal?: AbortSignal | undefined;
32
+ /** Verify the effective PostgreSQL role before running an isolated extension migration. */
33
+ extensionLogin?: string | undefined;
28
34
  /** 迁移会话的 `statement_timeout`(毫秒);不给不设。 */
29
35
  statementTimeoutMs?: number | undefined;
30
36
  /** 迁移会话的 `lock_timeout`(毫秒,含按 schema 的咨询锁);不给不设。 */
@@ -1,13 +1,30 @@
1
- import { createHash } from "node:crypto";
1
+ import { createHash, randomBytes } from "node:crypto";
2
2
  import { readdir, readFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { sql } from "kysely";
5
5
  import pg from "pg";
6
+ import { assertExtensionSchemaOwner, assertExtensionSession } from "./extension-db.js";
7
+ import { EXTENSION_RLS_PREDICATE } from "./extension-rls-predicate.js";
6
8
  import { pgConnectOptions } from "./pool.js";
7
9
  /** 迁移文件名:`NNNN_<snake_desc>.sql`(其他文件忽略)。 */
8
10
  export const MIGRATION_FILE_RE = /^\d{4}_[a-z0-9_]+\.sql$/;
9
11
  const ident = (s) => `"${s.replaceAll('"', '""')}"`;
10
12
  const num = (name) => Number.parseInt(name.slice(0, 4), 10);
13
+ export async function lockMigrationSchema(client, schema, scope) {
14
+ const lock = scope === "session" ? "pg_advisory_lock" : "pg_advisory_xact_lock";
15
+ await client.query(`select pg_catalog.${lock}(pg_catalog.hashtext($1))`, [
16
+ `capybara-migrate:${schema}`,
17
+ ]);
18
+ }
19
+ /** A held two-key lock conflicts only with sessions in the same database. */
20
+ export async function assertSameMigrationDatabase(owner, extension) {
21
+ const challenge = randomBytes(8);
22
+ const keys = [challenge.readInt32BE(0), challenge.readInt32BE(4)];
23
+ await owner.query("select pg_catalog.pg_advisory_xact_lock($1::int, $2::int)", keys);
24
+ const { rows: [lock], } = await extension.query("select pg_catalog.pg_try_advisory_xact_lock($1::int, $2::int) as acquired", keys);
25
+ if (lock?.acquired !== false)
26
+ throw new Error("The extension URL points to another database");
27
+ }
11
28
  async function migrationFiles(dir) {
12
29
  const names = (await readdir(dir)).filter((file) => MIGRATION_FILE_RE.test(file)).sort();
13
30
  return Promise.all(names.map(async (name) => {
@@ -16,9 +33,10 @@ async function migrationFiles(dir) {
16
33
  }));
17
34
  }
18
35
  // Use the effective login on the actual connection, including when a URL sets a role.
36
+ // Roles are cluster-wide, so the schema owner in this database identifies a split installation.
19
37
  const kernelMigrationPrivileges = `
20
38
  select pg_catalog.has_database_privilege(current_user, current_database(), 'CREATE') as can_create,
21
- exists (select from pg_catalog.pg_roles where rolname = 'capybara_owner') as has_owner_role,
39
+ coalesce(n.nspowner = pg_catalog.to_regrole('capybara_owner'), false) as split_identity,
22
40
  current_user = pg_catalog.pg_get_userbyid(n.nspowner) as owns_schema
23
41
  from (values ('capybara'::name)) as target(schema_name)
24
42
  left join pg_catalog.pg_namespace n on n.nspname = target.schema_name
@@ -27,7 +45,7 @@ export async function canMigrateKernel(db) {
27
45
  const { rows: [privileges], } = await sql.raw(kernelMigrationPrivileges).execute(db);
28
46
  if (privileges === undefined)
29
47
  throw new Error("Could not read kernel migration privileges");
30
- return privileges.can_create && (privileges.owns_schema ?? !privileges.has_owner_role);
48
+ return privileges.can_create && (privileges.owns_schema ?? true);
31
49
  }
32
50
  const migrateHint = "Run capybara migrate with CAPYBARA_DB__MIGRATION_URL set to the schema owner URL for split roles.";
33
51
  /** Verify the files expected by this binary without taking a migration lock or writing the journal.
@@ -121,18 +139,21 @@ export async function migrate(connectionString, owner, opts = {}) {
121
139
  signal?.addEventListener("abort", onAbort, { once: true });
122
140
  try {
123
141
  await client.connect();
142
+ if (opts.extensionLogin !== undefined)
143
+ await assertExtensionSession(client, opts.extensionLogin);
124
144
  if (opts.statementTimeoutMs !== undefined) {
125
145
  await client.query(`set statement_timeout = ${Math.max(1, Math.floor(opts.statementTimeoutMs))}`);
126
146
  }
127
147
  if (opts.lockTimeoutMs !== undefined) {
128
148
  await client.query(`set lock_timeout = ${Math.max(1, Math.floor(opts.lockTimeoutMs))}`);
129
149
  }
130
- await client.query("select pg_catalog.pg_advisory_lock(pg_catalog.hashtext($1))", [
131
- `capybara-migrate:${schema}`,
132
- ]);
150
+ await lockMigrationSchema(client, schema, "session");
151
+ if (opts.extensionLogin !== undefined) {
152
+ await assertExtensionSchemaOwner(client, schema, opts.extensionLogin);
153
+ }
133
154
  if (schema === "capybara") {
134
155
  const { rows: [privileges], } = await client.query(kernelMigrationPrivileges);
135
- if (privileges?.has_owner_role && !privileges.owns_schema) {
156
+ if (privileges?.split_identity && !privileges.owns_schema) {
136
157
  throw new Error(`The migration login must own the capybara schema. ${migrateHint}`);
137
158
  }
138
159
  }
@@ -163,6 +184,13 @@ export async function migrate(connectionString, owner, opts = {}) {
163
184
  try {
164
185
  await client.query("begin");
165
186
  await client.query(`set local search_path to ${ident(schema)}, public`);
187
+ if (opts.extensionLogin !== undefined) {
188
+ await client.query(`select pg_catalog.set_config('capybara.scope', 'platform', true),
189
+ pg_catalog.set_config('capybara.org_id', '', true),
190
+ pg_catalog.set_config('capybara.rls', 'off', true)`);
191
+ if (applied.length === 0)
192
+ await client.query(EXTENSION_RLS_PREDICATE);
193
+ }
166
194
  await client.query(f.content);
167
195
  await client.query(`insert into ${table} (name, checksum) values ($1, $2)`, [
168
196
  f.name,
package/dist/db/pool.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Kysely } from "kysely";
2
+ import pg from "pg";
2
3
  import { type RlsMode } from "../infra/database/scoped-dialect.js";
3
4
  /** 内核连接池的 PG `application_name`(便于在 pg_stat_activity 中识别)。 */
4
5
  export declare const KERNEL_APPLICATION_NAME = "capybara-kernel";
@@ -30,8 +31,11 @@ export declare function createDb(url: string, poolMax: number, onError?: (err: E
30
31
  */
31
32
  onClientError?: ((err: Error) => void) | undefined;
32
33
  /**
33
- * `db.rls`: whether every connection carries the org scope of its caller (RLS spec §5.2;
34
- * `scoped-dialect.ts`). Unset = `off`, a plain pool.
34
+ * `db.rls` controls the scope carried by each PostgreSQL transaction (RLS spec §5.2).
35
+ * Unset uses a plain pool.
35
36
  */
36
37
  rls?: RlsMode | undefined;
38
+ onConnect?: (client: pg.ClientBase) => Promise<void>;
39
+ /** The owner has already drained callers and may close any connection they still hold. */
40
+ closeActiveOnDestroy?: boolean;
37
41
  }): Kysely<any>;
package/dist/db/pool.js CHANGED
@@ -20,6 +20,7 @@ export function pgConnectOptions(cfg) {
20
20
  * `opts.connectTimeoutMs` 为建立连接的超时(不设则 pg 无限等待)。
21
21
  */
22
22
  export function createDb(url, poolMax, onError = (err) => console.error("[db] idle client error:", err), opts = {}) {
23
+ const rls = opts.rls ?? "off";
23
24
  const pool = new pg.Pool({
24
25
  connectionString: url,
25
26
  max: poolMax,
@@ -27,12 +28,46 @@ export function createDb(url, poolMax, onError = (err) => console.error("[db] id
27
28
  ...(opts.idleTimeoutMs !== undefined && { idleTimeoutMillis: opts.idleTimeoutMs }),
28
29
  // a client kept idle longer must notice a dead peer (a dropped VPN, a NAT timeout) by itself
29
30
  keepAlive: true,
31
+ ...(opts.onConnect && { onConnect: opts.onConnect }),
30
32
  });
31
33
  pool.on("error", onError);
32
34
  pool.on("connect", (client) => client.on("error", opts.onClientError ?? onError));
33
- const rls = opts.rls ?? "off";
34
35
  return new Kysely({
35
- dialect: new ScopedPostgresDialect({ pool }, rls),
36
+ dialect: new ScopedPostgresDialect({
37
+ pool: opts.closeActiveOnDestroy ? disposablePool(pool) : pool,
38
+ }, rls, rls !== "off"),
36
39
  plugins: rls !== "off" && unscopedQueryCheck() ? [captureUnscopedQueryOrigins] : [],
37
40
  });
38
41
  }
42
+ // pg.Pool.end waits for every checkout. After the host's drain, release remaining clients with
43
+ // an error so PostgreSQL closes their sessions. Late transaction cleanup can release safely.
44
+ function disposablePool(pool) {
45
+ const active = new Set();
46
+ let closing;
47
+ return {
48
+ Client: pg.Client,
49
+ options: pool.options,
50
+ async connect() {
51
+ const client = await pool.connect();
52
+ if (closing) {
53
+ client.release(true);
54
+ throw new Error("Extension database pool is closing");
55
+ }
56
+ const release = client.release.bind(client);
57
+ client.release = (error) => {
58
+ if (active.delete(client))
59
+ release(error);
60
+ };
61
+ active.add(client);
62
+ return client;
63
+ },
64
+ end() {
65
+ if (!closing) {
66
+ closing = pool.end();
67
+ for (const client of active)
68
+ client.release(true);
69
+ }
70
+ return closing;
71
+ },
72
+ };
73
+ }
@@ -5,6 +5,9 @@
5
5
  export type SqlStatement = {
6
6
  text: string;
7
7
  line: number;
8
+ /** Source range from the first token through the terminator, if present. */
9
+ startOffset: number;
10
+ endOffset: number;
8
11
  /** 语句里美元引用字符串的原文(不含定界符),按出现顺序;`DO $$ … $$` 的块体在这里。 */
9
12
  bodies: string[];
10
13
  /**
@@ -13,17 +13,27 @@ export function splitSqlStatements(src) {
13
13
  let text = "";
14
14
  let line = 1;
15
15
  let startLine = 0;
16
+ let startOffset = 0;
16
17
  let bodies = [];
17
18
  let quoted = [];
18
19
  let i = 0;
19
20
  const push = (chunk) => {
20
- if (startLine === 0 && chunk.trim() !== "")
21
+ if (startLine === 0 && chunk.trim() !== "") {
21
22
  startLine = line;
23
+ startOffset = i;
24
+ }
22
25
  text += chunk;
23
26
  };
24
- const flush = () => {
27
+ const flush = (endOffset) => {
25
28
  if (text.trim() !== "") {
26
- out.push({ text: text.replace(/\s+/g, " ").trim(), line: startLine, bodies, quoted });
29
+ out.push({
30
+ text: text.replace(/\s+/g, " ").trim(),
31
+ line: startLine,
32
+ startOffset,
33
+ endOffset,
34
+ bodies,
35
+ quoted,
36
+ });
27
37
  }
28
38
  text = "";
29
39
  startLine = 0;
@@ -113,7 +123,7 @@ export function splitSqlStatements(src) {
113
123
  }
114
124
  }
115
125
  if (c === ";") {
116
- flush();
126
+ flush(i + 1);
117
127
  i++;
118
128
  continue;
119
129
  }
@@ -122,7 +132,7 @@ export function splitSqlStatements(src) {
122
132
  line++;
123
133
  i++;
124
134
  }
125
- flush();
135
+ flush(src.length);
126
136
  return out;
127
137
  }
128
138
  /**
@@ -7,10 +7,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  import { Module } from "@nestjs/common";
8
8
  import { DevicesModule } from "../devices/devices.module.js";
9
9
  import { ExtensionRegistryModule } from "../extensions/registry.js";
10
+ import { PermissionAuthorityModule } from "../sandbox/permission-authority.module.js";
11
+ import { PermissionFactsModule } from "../sandbox/permission-facts.module.js";
10
12
  import { SandboxProviderRegistryModule } from "../sandbox/providers.module.js";
11
13
  import { SandboxModule } from "../sandbox/sandbox.module.js";
12
14
  import { ToolsModule } from "../tools/tools.module.js";
13
15
  import { DeviceAccessService } from "./device-access.service.js";
16
+ import { HostServiceGate } from "./host-gate.js";
17
+ import { HostServiceAccess } from "./host-services.js";
14
18
  import { DeviceSiteGrantsModule } from "./site-grants.module.js";
15
19
  import { DEVICE_ACCESS_BACKEND } from "./token.js";
16
20
  /**
@@ -24,7 +28,9 @@ ExtensionDeviceAccessModule = __decorate([
24
28
  Module({
25
29
  // SandboxModule: device services and the command review; DevicesModule: the conversation's
26
30
  // device, who may use it and its allowlist write; ToolsModule: the questions;
27
- // ExtensionRegistryModule: an extension's approved manifest when a viewer opens
31
+ // ExtensionRegistryModule: an extension's approved manifest when a viewer opens;
32
+ // PermissionFactsModule: the host gate's device sandbox; PermissionAuthorityModule: the locks and
33
+ // the published config its admission reads under
28
34
  imports: [
29
35
  SandboxModule,
30
36
  SandboxProviderRegistryModule,
@@ -32,12 +38,16 @@ ExtensionDeviceAccessModule = __decorate([
32
38
  ToolsModule,
33
39
  ExtensionRegistryModule,
34
40
  DeviceSiteGrantsModule,
41
+ PermissionFactsModule,
42
+ PermissionAuthorityModule,
35
43
  ],
36
44
  providers: [
45
+ HostServiceGate,
46
+ HostServiceAccess,
37
47
  DeviceAccessService,
38
48
  { provide: DEVICE_ACCESS_BACKEND, useExisting: DeviceAccessService },
39
49
  ],
40
- exports: [DeviceAccessService, DEVICE_ACCESS_BACKEND],
50
+ exports: [DeviceAccessService, HostServiceAccess, DEVICE_ACCESS_BACKEND],
41
51
  })
42
52
  ], ExtensionDeviceAccessModule);
43
53
  export { ExtensionDeviceAccessModule };