@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
@@ -7,6 +7,10 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
+ import { createHash } from "node:crypto";
11
+ import { closeSync, constants, fstatSync, openSync, readdirSync, readFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
10
14
  import { Inject, Injectable } from "@nestjs/common";
11
15
  import pg from "pg";
12
16
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -28,19 +32,99 @@ ConfiguredExtensionDbIdentity = __decorate([
28
32
  __param(0, Inject(KernelConfigService))
29
33
  ], ConfiguredExtensionDbIdentity);
30
34
  export { ConfiguredExtensionDbIdentity };
35
+ function readExtensionPassword(directory, name) {
36
+ if (!EXTENSION_NAME_RE.test(name))
37
+ throw new Error(`Invalid extension name: ${name}`);
38
+ let fd;
39
+ try {
40
+ fd = openSync(join(directory, `${name}.password`), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
41
+ }
42
+ catch {
43
+ throw new Error(`Cannot open database credential for extension ${name} in db.extensionCredentialsDir`);
44
+ }
45
+ try {
46
+ const info = fstatSync(fd);
47
+ if (!info.isFile() || (info.mode & 0o7777) !== 0o600)
48
+ throw new Error(`Database credential for extension ${name} must be a regular file with mode 0600`);
49
+ const password = readFileSync(fd, "utf8").replace(/\r?\n$/, "");
50
+ if (!password ||
51
+ [...password].some((character) => {
52
+ const code = character.charCodeAt(0);
53
+ return code < 32 || code > 126;
54
+ })) {
55
+ throw new Error(`Database credential for extension ${name} must contain a printable ASCII password`);
56
+ }
57
+ return password;
58
+ }
59
+ finally {
60
+ closeSync(fd);
61
+ }
62
+ }
63
+ function credentialNames(directory) {
64
+ try {
65
+ return readdirSync(directory)
66
+ .filter((file) => file.endsWith(".password"))
67
+ .map((file) => file.slice(0, -".password".length))
68
+ .sort();
69
+ }
70
+ catch {
71
+ throw new Error("Cannot read db.extensionCredentialsDir");
72
+ }
73
+ }
74
+ export function validateExtensionCredentials(db) {
75
+ if (db.extensionsUrl === undefined)
76
+ return;
77
+ const directory = db.extensionCredentialsDir;
78
+ if (!directory)
79
+ throw new Error("db.extensionsUrl requires db.extensionCredentialsDir");
80
+ const seen = new Map();
81
+ for (const name of credentialNames(directory)) {
82
+ const fingerprint = createHash("sha256")
83
+ .update(readExtensionPassword(directory, name))
84
+ .digest("hex");
85
+ const other = seen.get(fingerprint);
86
+ if (other)
87
+ throw new Error(`Database credentials for extensions ${other} and ${name} must use distinct passwords`);
88
+ seen.set(fingerprint, name);
89
+ }
90
+ }
31
91
  export function extensionDbIdentity(db) {
32
92
  const url = db.extensionsUrl ?? db.url;
33
93
  const separate = db.extensionsUrl !== undefined;
34
- let login;
94
+ let endpoint;
35
95
  try {
36
- login = new pg.Client({ connectionString: url }).user;
96
+ endpoint = new pg.Client({ connectionString: url });
37
97
  }
38
98
  catch {
39
99
  throw new Error("Invalid PostgreSQL connection URL for extensions");
40
100
  }
101
+ const { user: login, database } = endpoint;
41
102
  if (!login)
42
103
  throw new Error("PostgreSQL connection needs a login");
43
- return { sharedLogin: separate ? login : undefined, resolve: () => ({ login, url, separate }) };
104
+ const directory = db.extensionCredentialsDir;
105
+ if (!separate)
106
+ return { resolve: () => ({ login, url, separate: false }) };
107
+ if (!directory)
108
+ throw new Error("db.extensionsUrl requires db.extensionCredentialsDir");
109
+ if (!database)
110
+ throw new Error("Dedicated extension connections need a PostgreSQL database");
111
+ if (!URL.canParse(url))
112
+ throw new Error("db.extensionsUrl must be a PostgreSQL URL");
113
+ return {
114
+ sharedLogin: login,
115
+ provisionedNames: () => credentialNames(directory),
116
+ resolve(name) {
117
+ const password = readExtensionPassword(directory, name);
118
+ const hash = createHash("sha256").update(database).update("\0").update(name).digest("hex");
119
+ const username = `cap_ext_${hash.slice(0, 40)}`;
120
+ const target = new URL(url);
121
+ target.searchParams.delete("user");
122
+ target.searchParams.delete("password");
123
+ target.username = username;
124
+ target.password = encodeURIComponent(password);
125
+ return { login: username, url: target.toString(), separate: true, dedicated: true };
126
+ },
127
+ };
44
128
  }
45
129
  export function pluginSchemaName(name) {
46
130
  return `plugin_${name.replaceAll("-", "_")}`;
@@ -58,17 +142,33 @@ const extensionLoginCheck = `
58
142
  ), false) as isolated
59
143
  from pg_catalog.pg_roles r where r.rolname = $1
60
144
  `;
61
- export async function assertExtensionSession(client, login) {
145
+ export async function assertExtensionSession(client, login, dedicatedSchema) {
62
146
  const { rows: [actual], } = await client.query("select current_user as login");
63
147
  const { rows: [role], } = await client.query(extensionLoginCheck, [login]);
64
148
  if (actual?.login !== login || !role?.isolated) {
65
149
  throw new Error("db.extensionsUrl must authenticate as a restricted extension login with no access to capybara");
66
150
  }
151
+ if (dedicatedSchema !== undefined) {
152
+ const { rows: [privileges], } = await client.query(`select pg_catalog.has_database_privilege(current_database(), 'CREATE') as can_create,
153
+ exists (
154
+ select from pg_catalog.pg_shdepend d
155
+ cross join lateral pg_catalog.pg_identify_object(d.classid, d.objid, d.objsubid) obj
156
+ where d.dbid = (select oid from pg_catalog.pg_database where datname = current_database())
157
+ and d.refclassid = 'pg_catalog.pg_authid'::regclass
158
+ and d.refobjid = current_user::regrole and d.deptype = 'o'
159
+ and coalesce(obj.schema, case when obj.type = 'schema' then obj.name end) <> $1
160
+ ) as foreign_owner`, [dedicatedSchema]);
161
+ if (!privileges || privileges.can_create || privileges.foreign_owner)
162
+ throw new Error(`Extension login ${login} has database CREATE or owns objects outside its schema`);
163
+ }
67
164
  }
68
165
  /** A missing schema is normal before a plugin's first migration. */
69
- export async function assertExtensionSchemaOwner(client, schema, login) {
166
+ export async function assertExtensionSchemaOwner(client, schema, login, required = false) {
70
167
  const { rows: [namespace], } = await client.query(`select pg_catalog.pg_get_userbyid(nspowner) as owner
71
168
  from pg_catalog.pg_namespace where nspname = $1`, [schema]);
169
+ if (required && !namespace) {
170
+ throw new Error(`Missing extension schema ${schema}. Run the one-shot extension database provisioner.`);
171
+ }
72
172
  if (namespace && namespace.owner !== login) {
73
173
  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
174
  }
@@ -85,8 +185,8 @@ export function extensionDbPool(identity, name, config, onError) {
85
185
  onConnect: async (client) => {
86
186
  if (!identity.separate)
87
187
  return;
88
- await assertExtensionSession(client, identity.login);
89
- await assertExtensionSchemaOwner(client, schema, identity.login);
188
+ await assertExtensionSession(client, identity.login, identity.dedicated ? schema : undefined);
189
+ await assertExtensionSchemaOwner(client, schema, identity.login, identity.dedicated);
90
190
  await client.query("select pg_catalog.set_config('search_path', $1, false)", [searchPath]);
91
191
  },
92
192
  });
@@ -0,0 +1,9 @@
1
+ import pg from "pg";
2
+ import type { KernelConfig } from "../config/schema.js";
3
+ import type { ExtensionDbConnection } from "./extension-db.js";
4
+ export declare const EMPTY_EXTENSION_SCHEMA_COMMENT = "Capybara provisioned empty extension schema";
5
+ export declare function createProvisionedExtensionSchema(admin: pg.ClientBase, schema: string, login: string): Promise<void>;
6
+ type ExtensionLimits = Pick<KernelConfig["db"], "extensionConnectionLimit" | "extensionStatementTimeoutMs" | "extensionIdleTransactionTimeoutMs" | "extensionTempFileLimitKb">;
7
+ /** Runs in the operator transaction under the extension provisioning lock. */
8
+ export declare function provisionExtensionRole(admin: pg.ClientBase, name: string, identity: ExtensionDbConnection, limits: ExtensionLimits): Promise<boolean>;
9
+ export {};
@@ -0,0 +1,89 @@
1
+ import { createHash, createHmac, pbkdf2Sync, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import pg from "pg";
3
+ export const EMPTY_EXTENSION_SCHEMA_COMMENT = "Capybara provisioned empty extension schema";
4
+ export async function createProvisionedExtensionSchema(admin, schema, login) {
5
+ const identifier = pg.escapeIdentifier(schema);
6
+ await admin.query(`create schema ${identifier} authorization ${pg.escapeIdentifier(login)}`);
7
+ await admin.query(`comment on schema ${identifier} is ${pg.escapeLiteral(EMPTY_EXTENSION_SCHEMA_COMMENT)}`);
8
+ }
9
+ const scramIterations = 4096;
10
+ function scramVerifier(password, salt, iterations) {
11
+ const salted = pbkdf2Sync(password, salt, iterations, 32, "sha256");
12
+ const client = createHmac("sha256", salted).update("Client Key").digest();
13
+ const stored = createHash("sha256").update(client).digest("base64");
14
+ const server = createHmac("sha256", salted).update("Server Key").digest("base64");
15
+ return `SCRAM-SHA-256$${iterations}:${salt.toString("base64")}$${stored}:${server}`;
16
+ }
17
+ function matchesCredential(password, stored) {
18
+ const match = stored?.match(/^SCRAM-SHA-256\$(\d+):([A-Za-z0-9+/]+=*)\$/);
19
+ if (!match || !stored)
20
+ return false;
21
+ const iterations = Number(match[1]);
22
+ if (iterations < 1 || iterations > 100_000)
23
+ return false;
24
+ const expected = Buffer.from(scramVerifier(password, Buffer.from(match[2], "base64"), iterations));
25
+ const actual = Buffer.from(stored);
26
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
27
+ }
28
+ /** Runs in the operator transaction under the extension provisioning lock. */
29
+ export async function provisionExtensionRole(admin, name, identity, limits) {
30
+ if (!identity.dedicated)
31
+ throw new Error("Extension provisioning requires a dedicated login");
32
+ const client = new pg.Client({ connectionString: identity.url });
33
+ if (!client.database || !client.password) {
34
+ throw new Error(`Missing PostgreSQL database or credential for extension ${name}`);
35
+ }
36
+ const database = await admin.query("select current_database() as db");
37
+ if (database.rows[0]?.db !== client.database)
38
+ throw new Error(`The provisioner and extension ${name} must use the same PostgreSQL database`);
39
+ const login = pg.escapeIdentifier(identity.login);
40
+ const defaults = {
41
+ statement_timeout: `${limits.extensionStatementTimeoutMs}ms`,
42
+ idle_in_transaction_session_timeout: `${limits.extensionIdleTransactionTimeoutMs}ms`,
43
+ temp_file_limit: `${limits.extensionTempFileLimitKb}kB`,
44
+ search_path: "public",
45
+ };
46
+ const marker = `Capybara extension login for ${client.database}/${name}`;
47
+ const { rows: [existing], } = await admin.query(`select pg_catalog.shobj_description(r.oid, 'pg_authid') as marker,
48
+ exists (select from pg_catalog.pg_stat_activity where usename = r.rolname) as active,
49
+ r.rolcanlogin and not (r.rolsuper or r.rolcreatedb or r.rolcreaterole
50
+ or r.rolreplication or r.rolbypassrls or r.rolinherit)
51
+ and r.rolconnlimit = $2 and coalesce(r.rolvaliduntil, 'infinity') = 'infinity' as restricted,
52
+ r.rolpassword as verifier, settings.setconfig as defaults
53
+ from pg_catalog.pg_authid r
54
+ left join pg_catalog.pg_db_role_setting settings on settings.setrole = r.oid and settings.setdatabase = 0
55
+ where r.rolname = $1`, [identity.login, limits.extensionConnectionLimit]);
56
+ if (existing && existing.marker !== marker) {
57
+ throw new Error(`Refusing to take over unexpected extension login ${identity.login}`);
58
+ }
59
+ const sameCredential = existing && matchesCredential(client.password, existing.verifier);
60
+ if (existing?.restricted &&
61
+ sameCredential &&
62
+ Object.entries(defaults).every(([key, value]) => existing.defaults?.includes(`${key}=${value}`))) {
63
+ return false;
64
+ }
65
+ if (existing?.active) {
66
+ throw new Error(`Drain sessions for extension ${name} before provisioning its database login`);
67
+ }
68
+ if (!existing) {
69
+ await admin.query(`create role ${login} nologin`);
70
+ await admin.query(`comment on role ${login} is ${pg.escapeLiteral(marker)}`);
71
+ }
72
+ if (!sameCredential) {
73
+ try {
74
+ const verifier = scramVerifier(client.password, randomBytes(16), scramIterations);
75
+ await admin.query(`alter role ${login} password ${pg.escapeLiteral(verifier)}`);
76
+ }
77
+ catch {
78
+ throw new Error(`Could not set the PostgreSQL password for extension ${name}`);
79
+ }
80
+ }
81
+ await admin.query(`alter role ${login} login nosuperuser nocreatedb nocreaterole noreplication nobypassrls noinherit
82
+ connection limit ${limits.extensionConnectionLimit} valid until 'infinity'`);
83
+ for (const [key, value] of Object.entries(defaults)) {
84
+ await admin.query(`alter role ${login} set ${key} = ${pg.escapeLiteral(value)}`);
85
+ }
86
+ await admin.query(`grant connect on database ${pg.escapeIdentifier(client.database)} to ${login}`);
87
+ await admin.query(`grant usage on schema public to ${login}`);
88
+ return true;
89
+ }
@@ -1,6 +1,7 @@
1
+ import type { KernelConfig } from "../config/schema.js";
1
2
  import { type ExtensionDbIdentity } from "./extension-db.js";
2
3
  /**
3
4
  * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
4
5
  * to transfer ownership. Run before starting replicas with the new extension identity.
5
6
  */
6
- export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number, runtimeLogin?: string): Promise<void>;
7
+ export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number, provisioning?: KernelConfig["db"]): Promise<void>;
@@ -3,14 +3,18 @@ import pg from "pg";
3
3
  import { EXTENSION_EFFECT_HANDOFF } from "../infra/database/extension-handoff.js";
4
4
  import { assertExtensionSession, pluginSchemaName, } from "./extension-db.js";
5
5
  import { provisionExtensionHandoff } from "./extension-handoff-schema.js";
6
+ import { createProvisionedExtensionSchema, provisionExtensionRole, } from "./extension-role-provision.js";
6
7
  import { assertSameMigrationDatabase, lockMigrationSchema } from "./migrator.js";
7
8
  import { pgConnectOptions } from "./pool.js";
8
- async function transferExtensionSchema(client, schema, target, sources) {
9
+ async function transferExtensionSchema(client, schema, target, sources, dedicated = false) {
9
10
  await lockMigrationSchema(client, schema, "transaction");
10
11
  const { rows: [namespace], } = await client.query(`select oid, pg_catalog.pg_get_userbyid(nspowner) as owner
11
12
  from pg_catalog.pg_namespace where nspname = $1`, [schema]);
12
- if (!namespace)
13
+ if (!namespace) {
14
+ if (dedicated)
15
+ await createProvisionedExtensionSchema(client, schema, target);
13
16
  return;
17
+ }
14
18
  if (namespace.owner !== target && !sources.has(namespace.owner)) {
15
19
  throw new Error(`Unexpected owner ${namespace.owner} for extension schema ${schema}`);
16
20
  }
@@ -73,7 +77,22 @@ async function transferExtensionSchema(client, schema, target, sources) {
73
77
  }
74
78
  }
75
79
  }
76
- async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
80
+ async function revokeForeignSchemaGrants(client, schema, relayLogin) {
81
+ const { rows } = await client.query(`select distinct case when acl.grantee = 0 then null else pg_get_userbyid(acl.grantee) end as grantee,
82
+ acl.privilege_type as privilege
83
+ from pg_namespace n cross join lateral aclexplode(n.nspacl) acl
84
+ where n.nspname = $1 and acl.grantee <> n.nspowner
85
+ and not (acl.grantee = to_regrole($2) and acl.privilege_type = 'USAGE')
86
+ order by grantee, privilege`, [schema, relayLogin]);
87
+ const revoked = [];
88
+ for (const { grantee, privilege } of rows) {
89
+ const recipient = grantee === null ? "PUBLIC" : pg.escapeIdentifier(grantee);
90
+ await client.query(`revoke ${privilege} on schema ${pg.escapeIdentifier(schema)} from ${recipient} cascade`);
91
+ revoked.push(`Revoked foreign ${privilege} on schema ${pg.escapeIdentifier(schema)} from ${recipient}`);
92
+ }
93
+ return revoked;
94
+ }
95
+ async function confirmTargetDatabase(owner, target, schema, connectTimeoutMs) {
77
96
  const client = new pg.Client({
78
97
  connectionString: target.url,
79
98
  ...pgConnectOptions({ connectTimeoutMs }),
@@ -81,7 +100,7 @@ async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
81
100
  client.on("error", () => { });
82
101
  try {
83
102
  await client.connect();
84
- await assertExtensionSession(client, target.login);
103
+ await assertExtensionSession(client, target.login, target.dedicated ? schema : undefined);
85
104
  await assertSameMigrationDatabase(owner, client);
86
105
  }
87
106
  catch (cause) {
@@ -95,7 +114,7 @@ async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
95
114
  * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
96
115
  * to transfer ownership. Run before starting replicas with the new extension identity.
97
116
  */
98
- export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs, runtimeLogin) {
117
+ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs, provisioning) {
99
118
  const owner = new pg.Client({
100
119
  connectionString: bootstrapUrl,
101
120
  ...pgConnectOptions({ connectTimeoutMs }),
@@ -103,44 +122,109 @@ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, decl
103
122
  owner.on("error", () => { });
104
123
  try {
105
124
  await owner.connect();
125
+ if (provisioning) {
126
+ const { rows: [role], } = await owner.query("select rolsuper from pg_catalog.pg_roles where rolname = current_user");
127
+ if (!role?.rolsuper)
128
+ throw new Error("db.extensionProvisioningUrl must authenticate as a PostgreSQL superuser");
129
+ await lockMigrationSchema(owner, "extension-provisioning", "session");
130
+ }
106
131
  await owner.query("begin");
107
132
  try {
108
133
  await owner.query("set local search_path = pg_catalog");
109
134
  await owner.query("set local lock_timeout = '30s'");
110
135
  const { rows: [legacy], } = await owner.query(`
111
- select current_user as login,
112
- pg_catalog.has_database_privilege(pg_catalog.current_database(), 'CREATE') as can_create
136
+ select current_user as login, pg_get_userbyid(nspowner) as kernel_owner
137
+ from pg_catalog.pg_namespace where nspname = 'capybara'
113
138
  `);
114
139
  if (!legacy)
115
140
  throw new Error("Could not verify the schema transfer login");
116
141
  const { rows: registered } = await owner.query(`select name from capybara.extension_name_owners
117
142
  union select name from capybara.extension_installs`);
118
- const names = new Set([...declaredNames, ...registered.map((row) => row.name)]);
143
+ const names = new Set([
144
+ ...declaredNames,
145
+ ...registered.map((row) => row.name),
146
+ ...(provisioning ? (identity.provisionedNames?.() ?? []) : []),
147
+ ]);
119
148
  const resolved = [...names].sort().map((name) => {
120
149
  if (!EXTENSION_NAME_RE.test(name))
121
150
  throw new Error(`Invalid extension name: ${name}`);
122
- return { schema: pluginSchemaName(name), target: identity.resolve(name) };
151
+ return { name, schema: pluginSchemaName(name), target: identity.resolve(name) };
123
152
  });
124
- const sources = new Set([legacy.login, ...resolved.map(({ target }) => target.login)]);
153
+ const legacySources = new Set([legacy.login, legacy.kernel_owner]);
125
154
  if (identity.sharedLogin !== undefined)
126
- sources.add(identity.sharedLogin);
155
+ legacySources.add(identity.sharedLogin);
156
+ const sources = new Set([...legacySources, ...resolved.map(({ target }) => target.login)]);
127
157
  const targets = resolved.filter(({ target }) => target.separate);
158
+ const unchanged = new Set();
159
+ const revoked = [];
160
+ if (provisioning) {
161
+ const { rows: owned } = await owner.query(`select nspname as schema, pg_get_userbyid(nspowner) as login
162
+ from pg_namespace where nspname = any($1::text[])`, [targets.map(({ schema }) => schema)]);
163
+ const owners = new Map(owned.map(({ schema, login }) => [schema, login]));
164
+ if (identity.sharedLogin && owned.some(({ login }) => login === identity.sharedLogin)) {
165
+ const stale = await owner.query(`select 1 from pg_catalog.pg_stat_activity where usename = $1 and datname = current_database()`, [identity.sharedLogin]);
166
+ if (stale.rows.length) {
167
+ throw new Error("Drain shared extension database sessions before transferring ownership");
168
+ }
169
+ }
170
+ const runtime = new pg.Client({ connectionString: provisioning.url });
171
+ runtime.on("error", () => { });
172
+ try {
173
+ await runtime.connect();
174
+ await assertSameMigrationDatabase(owner, runtime);
175
+ }
176
+ finally {
177
+ await runtime.end();
178
+ }
179
+ const { rows: [database], } = await owner.query("select current_database() as name");
180
+ if (!database)
181
+ throw new Error("Could not verify the extension provisioning database");
182
+ await owner.query(`revoke create, temporary on database ${pg.escapeIdentifier(database.name)} from public`);
183
+ for (const { name, schema, target } of targets) {
184
+ const changed = await provisionExtensionRole(owner, name, target, provisioning);
185
+ if (!changed && owners.get(schema) === target.login)
186
+ unchanged.add(schema);
187
+ }
188
+ await owner.query("commit");
189
+ await owner.query("begin");
190
+ await owner.query("set local search_path = pg_catalog");
191
+ await owner.query("set local lock_timeout = '30s'");
192
+ }
128
193
  const validated = new Set();
129
- for (const { target } of targets) {
130
- if (validated.has(target.url))
194
+ for (const { target, schema } of targets) {
195
+ if (unchanged.has(schema) || validated.has(target.url))
131
196
  continue;
132
- await confirmTargetDatabase(owner, target, connectTimeoutMs);
197
+ await confirmTargetDatabase(owner, target, schema, connectTimeoutMs);
133
198
  validated.add(target.url);
134
199
  }
135
200
  for (const { schema, target } of targets) {
136
- await transferExtensionSchema(owner, schema, target.login, sources);
137
- // Repeated migrations may use the restricted runtime login. Only the one-shot
138
- // provisioner can create the contract table and grant access to it.
139
- if (runtimeLogin !== undefined && legacy.can_create) {
140
- await provisionExtensionHandoff(owner, schema, target.login, runtimeLogin);
201
+ await transferExtensionSchema(owner, schema, target.login, target.dedicated ? legacySources : sources, target.dedicated);
202
+ if (provisioning && target.dedicated) {
203
+ const relayLogin = provisioning.extensionEffectRelayLogin ?? "capybara_runtime";
204
+ await provisionExtensionHandoff(owner, schema, target.login, relayLogin);
205
+ revoked.push(...(await revokeForeignSchemaGrants(owner, schema, relayLogin)));
206
+ }
207
+ if (target.dedicated && identity.sharedLogin) {
208
+ const namespace = pg.escapeIdentifier(schema);
209
+ const old = pg.escapeIdentifier(identity.sharedLogin);
210
+ const { rows } = await owner.query("select 1 from pg_catalog.pg_roles where rolname = $1", [identity.sharedLogin]);
211
+ if (rows.length) {
212
+ await owner.query(`revoke all on schema ${namespace} from ${old}`);
213
+ await owner.query(`revoke all on all tables in schema ${namespace} from ${old}`);
214
+ await owner.query(`revoke all on all sequences in schema ${namespace} from ${old}`);
215
+ await owner.query(`revoke all on all routines in schema ${namespace} from ${old}`);
216
+ }
217
+ }
218
+ }
219
+ if (provisioning && identity.sharedLogin) {
220
+ const { rows: [old], } = await owner.query(`select current_database() as db from pg_catalog.pg_roles where rolname = $1`, [identity.sharedLogin]);
221
+ if (old) {
222
+ await owner.query(`revoke create on database ${pg.escapeIdentifier(old.db)} from ${pg.escapeIdentifier(identity.sharedLogin)}`);
141
223
  }
142
224
  }
143
225
  await owner.query("commit");
226
+ for (const message of revoked)
227
+ process.stderr.write(`${JSON.stringify(message)}\n`);
144
228
  }
145
229
  catch (error) {
146
230
  await owner.query("rollback").catch(() => { });
@@ -1,4 +1,4 @@
1
- import type { CacheWriteByTtl, ConversationSource, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SiteAccessAction, SkillInvocation, TriggerFactValue, TriggerSubject } from "@capybara-hq/plugin-sdk";
1
+ import type { CacheWriteByTtl, ConversationSource, ExternalConversationState, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SiteAccessAction, SkillInvocation, TriggerFactValue, TriggerSubject } from "@capybara-hq/plugin-sdk";
2
2
  import type { ColumnType, Generated, Kysely } from "kysely";
3
3
  import type { ModelRef } from "../agents/definition.js";
4
4
  import type { AutomationChat, AutomationEventMarker, AutomationMode, AutomationOrigin, AutomationPauseReason, AutomationPrincipal, AutomationStatus, AutomationTrigger, AutomationUnattendedAsk, ScheduleMarker, TaskRunSkipReason, TaskRunStatus } from "../automations/types.js";
@@ -399,7 +399,8 @@ export interface ConversationsTable {
399
399
  create_request_hash: ColumnType<string | null, string | null | undefined, string | null>;
400
400
  id: string;
401
401
  org_id: string;
402
- agent_id: string;
402
+ /** 0227: null exactly when `kind` is 'external' (`conversations_external_shape`). */
403
+ agent_id: string | null;
403
404
  account_id: string;
404
405
  title: string | null;
405
406
  last_seq: Int8;
@@ -455,6 +456,29 @@ export interface ConversationsTable {
455
456
  project_name: ColumnType<string | null, string | null | undefined, never>;
456
457
  /** 0133: the absolute path the bound project resolved to at creation; null: free mode. */
457
458
  project_path: ColumnType<string | null, string | null | undefined, never>;
459
+ /** 0227: the target an external conversation is held with (set once); null for other kinds. */
460
+ external: ColumnType<ExternalRef | null, string | null | undefined, never>;
461
+ /** 0227: what the target last reported (external conversations; 'idle' for the others). */
462
+ external_state: ColumnType<ExternalConversationState, ExternalConversationState | undefined, ExternalConversationState>;
463
+ /**
464
+ * 0227: the highest `external_user_message.deliverySeq` handed to the target; -1 (written only
465
+ * by the kernel) once the conversation's `start` was dropped after its retries.
466
+ */
467
+ external_delivered_seq: Int8;
468
+ }
469
+ /** `conversations.external` (0227): the `conversation-target@1` target of an external conversation. */
470
+ export interface ExternalRef {
471
+ /** The extension that provides the target. */
472
+ extension: string;
473
+ targetKey: string;
474
+ /** The target's label as written at creation. */
475
+ label: string;
476
+ /** The options chosen for the start on the new conversation page (absent: none recorded). */
477
+ options?: {
478
+ model?: string;
479
+ effort?: string;
480
+ mode?: string;
481
+ };
458
482
  }
459
483
  /** 0060: an org's order of file-preview@1 previewers (UI refresh B Task 11). */
460
484
  export interface FilePreviewersTable {
@@ -514,8 +538,11 @@ export interface ConversationSubject {
514
538
  id: string;
515
539
  title: string;
516
540
  }
517
- /** chat; eval (a hidden full-run replay conversation); subagent (0053: a sub-agent's conversation). */
518
- export type ConversationKind = "chat" | "eval" | "subagent";
541
+ /**
542
+ * chat; eval (a hidden full-run replay conversation); subagent (0053: a sub-agent's conversation);
543
+ * external (0227: mirrored from a `conversation-target@1` target; no agent, never a run).
544
+ */
545
+ export type ConversationKind = "chat" | "eval" | "subagent" | "external";
519
546
  /** 0006_conversations.sql: append-only conversation event log. */
520
547
  export interface ConversationEventsTable {
521
548
  conversation_id: string;
@@ -31,6 +31,8 @@ export declare function migrate(connectionString: string, owner: MigrationOwner,
31
31
  signal?: AbortSignal | undefined;
32
32
  /** Verify the effective PostgreSQL role before running an isolated extension migration. */
33
33
  extensionLogin?: string | undefined;
34
+ /** Dedicated logins own a pre-provisioned schema and cannot create schemas. */
35
+ extensionDedicated?: boolean | undefined;
34
36
  /** 迁移会话的 `statement_timeout`(毫秒);不给不设。 */
35
37
  statementTimeoutMs?: number | undefined;
36
38
  /** 迁移会话的 `lock_timeout`(毫秒,含按 schema 的咨询锁);不给不设。 */
@@ -140,7 +140,7 @@ export async function migrate(connectionString, owner, opts = {}) {
140
140
  try {
141
141
  await client.connect();
142
142
  if (opts.extensionLogin !== undefined)
143
- await assertExtensionSession(client, opts.extensionLogin);
143
+ await assertExtensionSession(client, opts.extensionLogin, opts.extensionDedicated ? schema : undefined);
144
144
  if (opts.statementTimeoutMs !== undefined) {
145
145
  await client.query(`set statement_timeout = ${Math.max(1, Math.floor(opts.statementTimeoutMs))}`);
146
146
  }
@@ -149,7 +149,7 @@ export async function migrate(connectionString, owner, opts = {}) {
149
149
  }
150
150
  await lockMigrationSchema(client, schema, "session");
151
151
  if (opts.extensionLogin !== undefined) {
152
- await assertExtensionSchemaOwner(client, schema, opts.extensionLogin);
152
+ await assertExtensionSchemaOwner(client, schema, opts.extensionLogin, opts.extensionDedicated);
153
153
  }
154
154
  if (schema === "capybara") {
155
155
  const { rows: [privileges], } = await client.query(kernelMigrationPrivileges);
@@ -157,7 +157,8 @@ export async function migrate(connectionString, owner, opts = {}) {
157
157
  throw new Error(`The migration login must own the capybara schema. ${migrateHint}`);
158
158
  }
159
159
  }
160
- await client.query(`create schema if not exists ${ident(schema)}`);
160
+ if (!opts.extensionDedicated)
161
+ await client.query(`create schema if not exists ${ident(schema)}`);
161
162
  await client.query(`create table if not exists ${table} (
162
163
  name text primary key,
163
164
  checksum text not null,
@@ -74,9 +74,10 @@ function resolveAt(at) {
74
74
  return { orgId: call.orgId, accountId: call.accountId, deviceId, call };
75
75
  }
76
76
  const person = personOf(at.person);
77
- if (person === null)
77
+ // a handle bound to one device (a conversation target's call) reaches that device only
78
+ if (person === null || (person.deviceId !== undefined && person.deviceId !== deviceId))
78
79
  throw new DeviceAccessError("invalid_request", HOST_SCOPE_TEXT);
79
- return { ...person, deviceId, call: null };
80
+ return { orgId: person.orgId, accountId: person.accountId, deviceId, call: null };
80
81
  }
81
82
  /**
82
83
  * Host device services (local agents spec, Part 1): a service of a platform-trusted extension that
@@ -1,10 +1,19 @@
1
1
  import type { DevicePersonHandle } from "@capybara-hq/plugin-sdk";
2
- /** A new handle for `accountId` in `orgId`, live until {@link revokePersonHandle}. */
3
- export declare function issuePersonHandle(orgId: string, accountId: string): DevicePersonHandle;
4
- /** Ends the handle: later host service calls with it are refused. */
5
- export declare function revokePersonHandle(handle: DevicePersonHandle): void;
6
- /** The org and account of a live handle the kernel issued; null for anything else. */
7
- export declare function personOf(handle: unknown): {
2
+ /**
3
+ * What a live handle stands for; `deviceId` only for a handle bound to one device (null: bound to
4
+ * none, so no device is reached with it).
5
+ */
6
+ export interface PersonHandleScope {
8
7
  orgId: string;
9
8
  accountId: string;
10
- } | null;
9
+ deviceId?: string | null;
10
+ }
11
+ /**
12
+ * A new handle for `accountId` in `orgId`, live until {@link revokePersonHandle}; with `deviceId`,
13
+ * valid for that device only (null: for no device).
14
+ */
15
+ export declare function issuePersonHandle(orgId: string, accountId: string, deviceId?: string | null): DevicePersonHandle;
16
+ /** Ends the handle: later host service calls with it are refused. */
17
+ export declare function revokePersonHandle(handle: DevicePersonHandle): void;
18
+ /** The org, account (and bound device) of a live handle the kernel issued; null for anything else. */
19
+ export declare function personOf(handle: unknown): PersonHandleScope | null;
@@ -1,23 +1,28 @@
1
1
  /**
2
2
  * Kernel-issued person handles (`DevicePersonHandle`, local agents spec, call 6): the kernel puts
3
- * one on the args of each org `ctx.ui.action` / `ctx.ui.query` handler call, for the person the
4
- * call runs for, and revokes it when the handler settles. A host service call with a person scope
5
- * is admitted only for a live handle, and the org and account come from it, never from the
6
- * extension. Per call and per process like a tool call's scope (`tools/call-scope.ts`): the handle
7
- * never leaves the process that issued it, and nothing is shared across replicas.
3
+ * one on the args of each org `ctx.ui.action` / `ctx.ui.query` handler call and of each
4
+ * `conversation-target@1` call, for the person the call runs for, and revokes it when the call
5
+ * settles. A host service call with a person scope is admitted only for a live handle, and the org
6
+ * and account come from it, never from the extension; a handle bound to a device (a call about an
7
+ * external conversation: its device) is admitted for that device only. Per call and per process
8
+ * like a tool call's scope (`tools/call-scope.ts`): the handle never leaves the process that issued
9
+ * it, and nothing is shared across replicas.
8
10
  */
9
11
  const persons = new WeakMap();
10
- /** A new handle for `accountId` in `orgId`, live until {@link revokePersonHandle}. */
11
- export function issuePersonHandle(orgId, accountId) {
12
+ /**
13
+ * A new handle for `accountId` in `orgId`, live until {@link revokePersonHandle}; with `deviceId`,
14
+ * valid for that device only (null: for no device).
15
+ */
16
+ export function issuePersonHandle(orgId, accountId, deviceId) {
12
17
  const handle = Object.freeze({ kind: "device-person" });
13
- persons.set(handle, { orgId, accountId });
18
+ persons.set(handle, { orgId, accountId, ...(deviceId !== undefined && { deviceId }) });
14
19
  return handle;
15
20
  }
16
21
  /** Ends the handle: later host service calls with it are refused. */
17
22
  export function revokePersonHandle(handle) {
18
23
  persons.delete(handle);
19
24
  }
20
- /** The org and account of a live handle the kernel issued; null for anything else. */
25
+ /** The org, account (and bound device) of a live handle the kernel issued; null for anything else. */
21
26
  export function personOf(handle) {
22
27
  if (typeof handle !== "object" || handle === null)
23
28
  return null;