@capybara-hq/kernel 0.1.0-rc.80 → 0.1.0-rc.81

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 (64) hide show
  1. package/dist/admin/outbox-dead.service.js +133 -120
  2. package/dist/background/store.js +78 -67
  3. package/dist/background/tasks.service.d.ts +6 -0
  4. package/dist/background/tasks.service.js +3 -0
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/catalog/plugin-import.js +45 -40
  7. package/dist/catalog/scope-sync-workers.js +3 -0
  8. package/dist/channels/inbound.d.ts +6 -1
  9. package/dist/channels/inbound.js +18 -1
  10. package/dist/client/client-reports.service.js +9 -6
  11. package/dist/config/schema.d.ts +5 -0
  12. package/dist/config/schema.js +6 -0
  13. package/dist/conversations/attachments.service.js +101 -96
  14. package/dist/conversations/events.d.ts +7 -0
  15. package/dist/conversations/events.js +9 -0
  16. package/dist/ctx/bus.js +5 -3
  17. package/dist/ctx/queue.js +4 -2
  18. package/dist/db/pool.d.ts +6 -0
  19. package/dist/db/pool.js +3 -2
  20. package/dist/devices/legacy-cleanup.job.js +73 -70
  21. package/dist/dial-in/gateway.d.ts +8 -0
  22. package/dist/dial-in/gateway.js +22 -2
  23. package/dist/extensions/admin-ops.js +22 -19
  24. package/dist/extensions/lifecycle-hooks.js +3 -1
  25. package/dist/http/app.js +3 -1
  26. package/dist/http/plugin-dispatch.js +8 -0
  27. package/dist/identity/auth.guard.js +13 -3
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.js +1 -0
  30. package/dist/infra/database/database.module.js +1 -0
  31. package/dist/infra/database/org-scope.d.ts +59 -0
  32. package/dist/infra/database/org-scope.js +68 -0
  33. package/dist/infra/database/rls-role.d.ts +11 -0
  34. package/dist/infra/database/rls-role.js +33 -0
  35. package/dist/infra/database/scoped-dialect.d.ts +18 -0
  36. package/dist/infra/database/scoped-dialect.js +245 -0
  37. package/dist/infra/outbox/outbox.dispatcher.js +98 -90
  38. package/dist/infra/outbox/outbox.service.js +29 -26
  39. package/dist/infra/queue/run-job.d.ts +8 -2
  40. package/dist/infra/queue/run-job.js +16 -3
  41. package/dist/infra/schedule/locked-tick.js +12 -4
  42. package/dist/infra/schedule/scheduled-runs.js +3 -1
  43. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -0
  44. package/dist/lifecycle/kernel-lifecycle.js +16 -1
  45. package/dist/orgs/org.guard.js +4 -0
  46. package/dist/platform/sealed-reveals.js +9 -6
  47. package/dist/runtime/maintenance.js +6 -1
  48. package/dist/runtime/run-execution.d.ts +1 -0
  49. package/dist/runtime/run-execution.js +5 -0
  50. package/dist/runtime/run-orphan-check.job.js +20 -15
  51. package/dist/sandbox/legacy-retirement.js +438 -397
  52. package/dist/sandbox/modes.d.ts +10 -0
  53. package/dist/sandbox/modes.js +23 -0
  54. package/dist/sandbox/operation-reconcile.job.d.ts +14 -1
  55. package/dist/sandbox/operation-reconcile.job.js +35 -3
  56. package/dist/sandbox/permission-config-publication.js +83 -77
  57. package/dist/sandbox/sandbox.service.d.ts +24 -0
  58. package/dist/sandbox/sandbox.service.js +159 -62
  59. package/dist/schedules/store.js +17 -14
  60. package/dist/tools/builtins/sandbox/bash.js +16 -1
  61. package/dist/tools/drift.js +31 -24
  62. package/dist/tools/outputs.js +20 -17
  63. package/package.json +2 -2
  64. package/src/migrations/0182_rls_policies.sql +202 -0
@@ -32,6 +32,7 @@ import { SuperAdminLock } from "../identity/super-admin.js";
32
32
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
33
33
  import { afterCommit } from "../infra/database/after-commit.js";
34
34
  import { KernelDb } from "../infra/database/kernel-db.js";
35
+ import { asPlatform } from "../infra/database/org-scope.js";
35
36
  import { TransactionHost } from "../infra/database/transaction-host.js";
36
37
  import { Transactional } from "../infra/database/transactional.decorator.js";
37
38
  import { OutboxService } from "../infra/outbox/outbox.service.js";
@@ -1284,33 +1285,35 @@ let PluginImport = class PluginImport {
1284
1285
  /** The expired staging rows, batch by batch; returns the rows deleted. */
1285
1286
  // org-filter: deployment-wide expiry sweep (maintenance job) over every org's staging rows
1286
1287
  async cleanupStagingRows() {
1287
- let total = 0;
1288
- for (;;) {
1289
- const batch = await this.db
1290
- .selectFrom("plugin_import_staging")
1291
- .select(["id", "object_prefix"])
1292
- .where("expires_at", "<=", sql `now()`)
1293
- .orderBy("expires_at")
1294
- .limit(CLEANUP_BATCH)
1295
- .execute();
1296
- if (batch.length === 0)
1297
- return total;
1298
- let progressed = 0;
1299
- for (const r of batch) {
1300
- try {
1301
- const done = await this.cleanupOne(r);
1302
- if (done) {
1303
- total++;
1304
- progressed++;
1288
+ return asPlatform("deployment-wide expiry sweep", async () => {
1289
+ let total = 0;
1290
+ for (;;) {
1291
+ const batch = await this.db
1292
+ .selectFrom("plugin_import_staging")
1293
+ .select(["id", "object_prefix"])
1294
+ .where("expires_at", "<=", sql `now()`)
1295
+ .orderBy("expires_at")
1296
+ .limit(CLEANUP_BATCH)
1297
+ .execute();
1298
+ if (batch.length === 0)
1299
+ return total;
1300
+ let progressed = 0;
1301
+ for (const r of batch) {
1302
+ try {
1303
+ const done = await this.cleanupOne(r);
1304
+ if (done) {
1305
+ total++;
1306
+ progressed++;
1307
+ }
1308
+ }
1309
+ catch (err) {
1310
+ this.log.warn("cannot clean up an expired plugin import", { stagingId: r.id, err });
1305
1311
  }
1306
1312
  }
1307
- catch (err) {
1308
- this.log.warn("cannot clean up an expired plugin import", { stagingId: r.id, err });
1309
- }
1313
+ if (progressed === 0 || batch.length < CLEANUP_BATCH)
1314
+ return total;
1310
1315
  }
1311
- if (progressed === 0 || batch.length < CLEANUP_BATCH)
1312
- return total;
1313
- }
1316
+ });
1314
1317
  }
1315
1318
  /**
1316
1319
  * One expired staging row (row lock, `SKIP LOCKED`): its objects, then the row; false when another
@@ -1318,22 +1321,24 @@ let PluginImport = class PluginImport {
1318
1321
  */
1319
1322
  // org-filter: deployment-wide expiry sweep; the row id comes from the sweep's own read
1320
1323
  async cleanupOne(r) {
1321
- const t = this.db;
1322
- const locked = await t
1323
- .selectFrom("plugin_import_staging")
1324
- .select(["id", "org_id", "review", "manifest"])
1325
- .where("id", "=", r.id)
1326
- .where("expires_at", "<=", sql `now()`)
1327
- .forUpdate()
1328
- .skipLocked()
1329
- .executeTakeFirst();
1330
- if (!locked)
1331
- return false;
1332
- if (r.object_prefix)
1333
- await this.files.deployment().deletePrefix(r.object_prefix);
1334
- await t.deleteFrom("plugin_import_staging").where("id", "=", r.id).execute();
1335
- await this.dropOrgPackage(locked);
1336
- return true;
1324
+ return asPlatform("deployment-wide expiry sweep", async () => {
1325
+ const t = this.db;
1326
+ const locked = await t
1327
+ .selectFrom("plugin_import_staging")
1328
+ .select(["id", "org_id", "review", "manifest"])
1329
+ .where("id", "=", r.id)
1330
+ .where("expires_at", "<=", sql `now()`)
1331
+ .forUpdate()
1332
+ .skipLocked()
1333
+ .executeTakeFirst();
1334
+ if (!locked)
1335
+ return false;
1336
+ if (r.object_prefix)
1337
+ await this.files.deployment().deletePrefix(r.object_prefix);
1338
+ await t.deleteFrom("plugin_import_staging").where("id", "=", r.id).execute();
1339
+ await this.dropOrgPackage(locked);
1340
+ return true;
1341
+ });
1337
1342
  }
1338
1343
  /**
1339
1344
  * An expired org staging's extension package (an org upload stores it at prepare, P3-10): removed
@@ -41,6 +41,9 @@ let PluginScopeSyncProcessor = class PluginScopeSyncProcessor extends WorkerHost
41
41
  finalAttempt: job.attemptsMade + 1 >= (job.opts.attempts ?? 1),
42
42
  signal: this.stopping.signal,
43
43
  });
44
+ }, {
45
+ // an item or chunk job spans the orgs of a platform item; an org job carries its orgId
46
+ platform: "plugin scope sync of a platform item",
44
47
  });
45
48
  }
46
49
  /** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
@@ -71,8 +71,13 @@ export declare class ChannelInbound {
71
71
  * not create a second run; it means a redelivery is never acked before the job is really queued.
72
72
  */
73
73
  private dedupeAndEnqueue;
74
- /** 入站任务的处理(worker 上执行;失败抛错由队列重试)。 */
74
+ /**
75
+ * Handles one inbound job (on a worker; a throw makes the queue retry). The event works in the
76
+ * org of its connection (RLS spec §5.3: each inbound event enters its org once resolved); the
77
+ * job itself runs in the platform scope, since its data names only the connection.
78
+ */
75
79
  handle(connectionId: string, e: InboundEvent): Promise<void>;
80
+ private handleInOrg;
76
81
  private message;
77
82
  /**
78
83
  * Direct-message `/device` (environments spec §4.2 item 8): lists the person's usable devices,
@@ -20,6 +20,7 @@ import { IdentityBinding } from "../identity/binding.js";
20
20
  import { ExternalIdentities } from "../identity/external.js";
21
21
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
22
22
  import { KernelDb } from "../infra/database/kernel-db.js";
23
+ import { asPlatform, withOrgScope, withoutOrgScope } from "../infra/database/org-scope.js";
23
24
  import { LockService } from "../infra/lock/lock.service.js";
24
25
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
25
26
  import { DirectorySync } from "../orgs/directory-sync.js";
@@ -187,8 +188,24 @@ let ChannelInbound = class ChannelInbound {
187
188
  }
188
189
  await this.redis.set(key, DEDUPE_DONE, "EX", MESSAGE_DEDUPE_TTL_SECONDS);
189
190
  }
190
- /** 入站任务的处理(worker 上执行;失败抛错由队列重试)。 */
191
+ /**
192
+ * Handles one inbound job (on a worker; a throw makes the queue retry). The event works in the
193
+ * org of its connection (RLS spec §5.3: each inbound event enters its org once resolved); the
194
+ * job itself runs in the platform scope, since its data names only the connection.
195
+ */
191
196
  async handle(connectionId, e) {
197
+ // org-filter: resolves the org of a kernel-held connection id (the inbound job's own), the
198
+ // one lookup made before the event's org scope is known
199
+ const conn = await asPlatform("inbound event: resolve the connection's org", () => this.kdb
200
+ .selectFrom("channel_connections")
201
+ .select("org_id")
202
+ .where("id", "=", connectionId)
203
+ .executeTakeFirst());
204
+ const run = () => this.handleInOrg(connectionId, e);
205
+ // a connection gone meanwhile: nothing to scope to, and no platform fallback
206
+ return conn ? withOrgScope(conn.org_id, run) : withoutOrgScope(run);
207
+ }
208
+ async handleInOrg(connectionId, e) {
192
209
  if (e.type === "directory_changed") {
193
210
  const row = await this.connections.row(connectionId);
194
211
  if (row?.status === "active" && row.pluginEnabled) {
@@ -12,6 +12,7 @@ import { sql } from "kysely";
12
12
  import { ApiError } from "../errors.js";
13
13
  import { enabledExtensionsQuery } from "../extensions/enabled.js";
14
14
  import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { asPlatform } from "../infra/database/org-scope.js";
15
16
  import { TransactionHost } from "../infra/database/transaction-host.js";
16
17
  import { Transactional } from "../infra/database/transactional.decorator.js";
17
18
  import { ClientAccess } from "./client-access.service.js";
@@ -82,12 +83,14 @@ let ClientReports = class ClientReports {
82
83
  }
83
84
  /** Deletes the reports last seen more than {@link REPORT_RETENTION_DAYS} days ago; the count. */
84
85
  async prune() {
85
- // org-filter: deployment-wide retention sweep over every org's reports (maintenance job)
86
- const r = await this.db.db
87
- .deleteFrom("extension_client_reports")
88
- .where("last_at", "<", sql `now() - make_interval(days => ${REPORT_RETENTION_DAYS})`)
89
- .executeTakeFirst();
90
- return Number(r.numDeletedRows);
86
+ return asPlatform("deployment-wide retention sweep over every org's reports", async () => {
87
+ // org-filter: deployment-wide retention sweep over every org's reports (maintenance job)
88
+ const r = await this.db.db
89
+ .deleteFrom("extension_client_reports")
90
+ .where("last_at", "<", sql `now() - make_interval(days => ${REPORT_RETENTION_DAYS})`)
91
+ .executeTakeFirst();
92
+ return Number(r.numDeletedRows);
93
+ });
91
94
  }
92
95
  };
93
96
  __decorate([
@@ -70,6 +70,11 @@ export declare const KernelConfigSchema: z.ZodObject<{
70
70
  poolMax: z.ZodDefault<z.ZodNumber>;
71
71
  connectTimeoutMs: z.ZodDefault<z.ZodNumber>;
72
72
  idleTimeoutMs: z.ZodDefault<z.ZodNumber>;
73
+ rls: z.ZodDefault<z.ZodEnum<{
74
+ enforce: "enforce";
75
+ off: "off";
76
+ scoped: "scoped";
77
+ }>>;
73
78
  }, z.core.$strict>>;
74
79
  redis: z.ZodPrefault<z.ZodObject<{
75
80
  url: z.ZodString;
@@ -345,6 +345,12 @@ export const KernelConfigSchema = z.strictObject({
345
345
  .meta(meta({
346
346
  description: "How long an idle PostgreSQL connection stays in the pool, in milliseconds",
347
347
  })),
348
+ rls: z
349
+ .enum(["off", "scoped", "enforce"])
350
+ .default("off")
351
+ .meta(meta({
352
+ description: "Row level security (RLS spec, issue #115): off sends nothing; scoped sets the caller's org scope on every PostgreSQL connection (one extra round trip per pool query and per transaction) while the policies admit every row; enforce makes the policies filter every org-scoped table by that scope once row level security is enabled on the tables (RLS spec phase 5; until then the kernel warns at start and nothing is filtered). Needs a session-capable connection (no PgBouncer transaction pooling) unless off; PostgreSQL applies no policy to a superuser or BYPASSRLS role",
353
+ })),
348
354
  })
349
355
  .prefault({}),
350
356
  redis: z
@@ -15,6 +15,7 @@ import { ApiError } from "../errors.js";
15
15
  import { CacheService } from "../infra/cache/cache.service.js";
16
16
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
17
17
  import { KernelDb } from "../infra/database/kernel-db.js";
18
+ import { asPlatform } from "../infra/database/org-scope.js";
18
19
  import { TransactionHost } from "../infra/database/transaction-host.js";
19
20
  import { Transactional } from "../infra/database/transactional.decorator.js";
20
21
  import { LockService } from "../infra/lock/lock.service.js";
@@ -1017,20 +1018,21 @@ let AttachmentsService = class AttachmentsService {
1017
1018
  // org-filter: deployment-wide cleanup job across all orgs; each claimed row is deleted by its
1018
1019
  // own id and handled in its own org (r.org_id)
1019
1020
  async purgeRead() {
1020
- if (!this.storage.available)
1021
- return 0;
1022
- const hours = this.config.get().attachments.readPurgeAfterHours;
1023
- let deleted = 0;
1024
- const failed = [];
1025
- for (;;) {
1026
- const claimed = await this.db
1027
- .updateTable("attachments")
1028
- .set({ status: "deleting" })
1029
- .where("id", "in", this.db
1030
- .selectFrom("attachments")
1031
- .select("id")
1032
- .where("purpose", "=", "read")
1033
- .where("conversation_id", "in", sql `(
1021
+ return asPlatform("deployment-wide cleanup job across all orgs", async () => {
1022
+ if (!this.storage.available)
1023
+ return 0;
1024
+ const hours = this.config.get().attachments.readPurgeAfterHours;
1025
+ let deleted = 0;
1026
+ const failed = [];
1027
+ for (;;) {
1028
+ const claimed = await this.db
1029
+ .updateTable("attachments")
1030
+ .set({ status: "deleting" })
1031
+ .where("id", "in", this.db
1032
+ .selectFrom("attachments")
1033
+ .select("id")
1034
+ .where("purpose", "=", "read")
1035
+ .where("conversation_id", "in", sql `(
1034
1036
  WITH RECURSIVE gone(id, level) AS (
1035
1037
  SELECT c.id, 0 FROM capybara.conversations c
1036
1038
  WHERE c.deleted_at < now() - make_interval(hours => ${hours})
@@ -1041,37 +1043,38 @@ let AttachmentsService = class AttachmentsService {
1041
1043
  )
1042
1044
  SELECT id FROM gone
1043
1045
  )`)
1044
- .$if(failed.length > 0, (q) => q.where("id", "not in", failed))
1045
- .orderBy("created_at")
1046
- .limit(READ_PURGE_BATCH)
1047
- .forUpdate()
1048
- .skipLocked())
1049
- .returning(["id", "org_id", "object_key"])
1050
- .execute();
1051
- if (claimed.length === 0)
1052
- return deleted;
1053
- for (const r of claimed) {
1054
- try {
1055
- await this.storage.kernel(r.org_id).delete(r.object_key);
1056
- await this.db
1057
- .deleteFrom("attachments")
1058
- .where("id", "=", r.id)
1059
- .where("purpose", "=", "read")
1060
- .execute();
1061
- deleted++;
1062
- }
1063
- catch (err) {
1064
- failed.push(r.id);
1065
- this.log.warn("cannot purge read attachment; will retry", {
1066
- orgId: r.org_id,
1067
- attachmentId: r.id,
1068
- err,
1069
- });
1046
+ .$if(failed.length > 0, (q) => q.where("id", "not in", failed))
1047
+ .orderBy("created_at")
1048
+ .limit(READ_PURGE_BATCH)
1049
+ .forUpdate()
1050
+ .skipLocked())
1051
+ .returning(["id", "org_id", "object_key"])
1052
+ .execute();
1053
+ if (claimed.length === 0)
1054
+ return deleted;
1055
+ for (const r of claimed) {
1056
+ try {
1057
+ await this.storage.kernel(r.org_id).delete(r.object_key);
1058
+ await this.db
1059
+ .deleteFrom("attachments")
1060
+ .where("id", "=", r.id)
1061
+ .where("purpose", "=", "read")
1062
+ .execute();
1063
+ deleted++;
1064
+ }
1065
+ catch (err) {
1066
+ failed.push(r.id);
1067
+ this.log.warn("cannot purge read attachment; will retry", {
1068
+ orgId: r.org_id,
1069
+ attachmentId: r.id,
1070
+ err,
1071
+ });
1072
+ }
1070
1073
  }
1074
+ if (claimed.length < READ_PURGE_BATCH)
1075
+ return deleted;
1071
1076
  }
1072
- if (claimed.length < READ_PURGE_BATCH)
1073
- return deleted;
1074
- }
1077
+ });
1075
1078
  }
1076
1079
  /**
1077
1080
  * 删除过期(`expires_at < now()`)且从未绑定到会话的附件:先把行认领为 `deleting`(`FOR UPDATE SKIP LOCKED`,
@@ -1083,62 +1086,64 @@ let AttachmentsService = class AttachmentsService {
1083
1086
  // org-filter: deployment-wide cleanup job across all orgs; each claimed row is deleted by its
1084
1087
  // own id and handled in its own org (r.org_id)
1085
1088
  async deleteExpired() {
1086
- if (!this.storage.available)
1087
- return 0;
1088
- let deleted = 0;
1089
- const failed = [];
1090
- for (;;) {
1091
- const claimed = await this.db
1092
- .updateTable("attachments")
1093
- .set({ status: "deleting" })
1094
- .where("id", "in", this.db
1095
- .selectFrom("attachments")
1096
- .select("id")
1097
- .where("conversation_id", "is", null)
1098
- .where("expires_at", "<", sql `now()`)
1099
- .$if(failed.length > 0, (q) => q.where("id", "not in", failed))
1100
- .orderBy("expires_at")
1101
- .limit(CLEANUP_BATCH)
1102
- .forUpdate()
1103
- .skipLocked())
1104
- .returning(["id", "org_id", "object_key", "purpose"])
1105
- .execute();
1106
- if (claimed.length === 0)
1107
- return deleted;
1108
- for (const r of claimed) {
1109
- try {
1110
- const store = this.storage.kernel(r.org_id);
1111
- await store.delete(r.object_key);
1112
- if (r.purpose === "skill-package") {
1113
- // 解出的文件没被任何版本引用(处理中途失败、或从未用掉)才删
1114
- const prefix = skillFilesPrefix(r.id);
1115
- const used = await this.db
1116
- .selectFrom("skill_versions")
1117
- .select("skill_id")
1118
- .where("object_prefix", "=", prefix)
1119
- .executeTakeFirst();
1120
- if (!used)
1121
- await store.deletePrefix(prefix);
1089
+ return asPlatform("deployment-wide cleanup job across all orgs", async () => {
1090
+ if (!this.storage.available)
1091
+ return 0;
1092
+ let deleted = 0;
1093
+ const failed = [];
1094
+ for (;;) {
1095
+ const claimed = await this.db
1096
+ .updateTable("attachments")
1097
+ .set({ status: "deleting" })
1098
+ .where("id", "in", this.db
1099
+ .selectFrom("attachments")
1100
+ .select("id")
1101
+ .where("conversation_id", "is", null)
1102
+ .where("expires_at", "<", sql `now()`)
1103
+ .$if(failed.length > 0, (q) => q.where("id", "not in", failed))
1104
+ .orderBy("expires_at")
1105
+ .limit(CLEANUP_BATCH)
1106
+ .forUpdate()
1107
+ .skipLocked())
1108
+ .returning(["id", "org_id", "object_key", "purpose"])
1109
+ .execute();
1110
+ if (claimed.length === 0)
1111
+ return deleted;
1112
+ for (const r of claimed) {
1113
+ try {
1114
+ const store = this.storage.kernel(r.org_id);
1115
+ await store.delete(r.object_key);
1116
+ if (r.purpose === "skill-package") {
1117
+ // delete the unpacked files only when no version references them (a failed or unused upload)
1118
+ const prefix = skillFilesPrefix(r.id);
1119
+ const used = await this.db
1120
+ .selectFrom("skill_versions")
1121
+ .select("skill_id")
1122
+ .where("object_prefix", "=", prefix)
1123
+ .executeTakeFirst();
1124
+ if (!used)
1125
+ await store.deletePrefix(prefix);
1126
+ }
1127
+ await this.db
1128
+ .deleteFrom("attachments")
1129
+ .where("id", "=", r.id)
1130
+ .where("conversation_id", "is", null)
1131
+ .execute();
1132
+ deleted++;
1133
+ }
1134
+ catch (err) {
1135
+ failed.push(r.id);
1136
+ this.log.warn("cannot delete expired attachment; will retry", {
1137
+ orgId: r.org_id,
1138
+ attachmentId: r.id,
1139
+ err,
1140
+ });
1122
1141
  }
1123
- await this.db
1124
- .deleteFrom("attachments")
1125
- .where("id", "=", r.id)
1126
- .where("conversation_id", "is", null)
1127
- .execute();
1128
- deleted++;
1129
- }
1130
- catch (err) {
1131
- failed.push(r.id);
1132
- this.log.warn("cannot delete expired attachment; will retry", {
1133
- orgId: r.org_id,
1134
- attachmentId: r.id,
1135
- err,
1136
- });
1137
1142
  }
1143
+ if (claimed.length < CLEANUP_BATCH)
1144
+ return deleted;
1138
1145
  }
1139
- if (claimed.length < CLEANUP_BATCH)
1140
- return deleted;
1141
- }
1146
+ });
1142
1147
  }
1143
1148
  };
1144
1149
  __decorate([
@@ -509,6 +509,7 @@ export declare const HANDOFF_URL_MAX_CHARS = 2000;
509
509
  * name no tool has (ToolSearch mode, spec 5.5): expected behaviour, the model is told to load it
510
510
  * (or search for it) first. The result
511
511
  * stays `isError: true` for the model; the web shows it as a neutral outcome too.
512
+ * `launch_unconfirmed`: a background `Bash` start whose outcome is being reconciled (see below).
512
513
  * `handoff`: a `Platform` operation whose decision stays with a person on a web page (platform web
513
514
  * parity spec §4.4, §6): the card's title and either a relative web path (`link`, also in the
514
515
  * result text as `reviewUrl`) or a connector to connect (`connect`: the web's Connect button starts
@@ -561,6 +562,9 @@ export declare const ToolViewSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
561
562
  }>;
562
563
  }, z.core.$strip>, z.ZodObject<{
563
564
  kind: z.ZodLiteral<"not_loaded">;
565
+ }, z.core.$strip>, z.ZodObject<{
566
+ kind: z.ZodLiteral<"launch_unconfirmed">;
567
+ taskId: z.ZodString;
564
568
  }, z.core.$strip>, z.ZodObject<{
565
569
  kind: z.ZodLiteral<"reveal">;
566
570
  reveal: z.ZodEnum<{
@@ -1457,6 +1461,9 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1457
1461
  }>;
1458
1462
  }, z.core.$strip>, z.ZodObject<{
1459
1463
  kind: z.ZodLiteral<"not_loaded">;
1464
+ }, z.core.$strip>, z.ZodObject<{
1465
+ kind: z.ZodLiteral<"launch_unconfirmed">;
1466
+ taskId: z.ZodString;
1460
1467
  }, z.core.$strip>, z.ZodObject<{
1461
1468
  kind: z.ZodLiteral<"reveal">;
1462
1469
  reveal: z.ZodEnum<{
@@ -565,6 +565,7 @@ const HANDOFF_PATH = /^\/(?![/\\])[^\\\s]*$/;
565
565
  * name no tool has (ToolSearch mode, spec 5.5): expected behaviour, the model is told to load it
566
566
  * (or search for it) first. The result
567
567
  * stays `isError: true` for the model; the web shows it as a neutral outcome too.
568
+ * `launch_unconfirmed`: a background `Bash` start whose outcome is being reconciled (see below).
568
569
  * `handoff`: a `Platform` operation whose decision stays with a person on a web page (platform web
569
570
  * parity spec §4.4, §6): the card's title and either a relative web path (`link`, also in the
570
571
  * result text as `reviewUrl`) or a connector to connect (`connect`: the web's Connect button starts
@@ -610,6 +611,14 @@ export const ToolViewSchema = z.discriminatedUnion("kind", [
610
611
  reason: z.enum(["not_read", "modified"]),
611
612
  }),
612
613
  z.object({ kind: z.literal("not_loaded") }),
614
+ /**
615
+ * A background `Bash` start the kernel sent but could not confirm (a transport loss after the
616
+ * dispatch): the task may be running, and the kernel reconciles it under its original identity.
617
+ * The result stays `isError: true` for the model with the same text; the web shows the row as
618
+ * reconciling, not failed, until the task is confirmed running, finishes, or is given up
619
+ * (`lost`). Display only.
620
+ */
621
+ z.object({ kind: z.literal("launch_unconfirmed"), taskId: z.string().min(1).max(64) }),
613
622
  /**
614
623
  * A `Platform` operation whose result is shown to the run's person once, read by call (the
615
624
  * initial password, the invitation link; profiles govern every approval, ruling R6): the web
package/dist/ctx/bus.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { withoutOrgScope } from "../infra/database/org-scope.js";
1
2
  import { runOutsideTransaction } from "../infra/database/transaction-host.js";
2
3
  import { withoutLogContext } from "../log-context.js";
3
4
  import { assertNamespace } from "./namespace.js";
@@ -22,12 +23,13 @@ export function createBusSubscriber(subFactory, log = consoleLog) {
22
23
  const c = subFactory();
23
24
  c.on("message", (channel, message) => {
24
25
  // the connection's callbacks carry the async context of the first subscribe (a request's
25
- // log fields, possibly an open transaction): every handler starts from an empty one
26
- runOutsideTransaction(() => withoutLogContext(() => {
26
+ // log fields and org scope, possibly an open transaction): every handler starts from an
27
+ // empty one
28
+ runOutsideTransaction(() => withoutOrgScope(() => withoutLogContext(() => {
27
29
  for (const h of [...(channels.get(channel)?.handlers ?? [])]) {
28
30
  invokeIsolated(log, channel, () => h(message));
29
31
  }
30
- }));
32
+ })));
31
33
  });
32
34
  c.on("error", (err) => log.error("bus subscriber connection error", { err }));
33
35
  conn = c;
package/dist/ctx/queue.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Queue, Worker } from "bullmq";
2
2
  import { Redis } from "ioredis";
3
- import { withJobContext } from "../log-context.js";
3
+ import { runJob } from "../infra/queue/run-job.js";
4
4
  import { assertNamespace } from "./namespace.js";
5
5
  /** 未注入 logger 时的兜底:输出到 stderr。 */
6
6
  const consoleLog = {
@@ -61,7 +61,9 @@ export function createQueue(redisUrl, namespace, opts) {
61
61
  return;
62
62
  const st = { n: 0, idle: [] };
63
63
  active.set(name, st);
64
- const worker = new Worker(queueName(name), (job) => withJobContext(queueName(name), job, async () => {
64
+ const worker = new Worker(queueName(name),
65
+ // runJob: the log context and the org scope of the job (its data's `orgId`, else platform)
66
+ (job) => runJob(queueName(name), job, async () => {
65
67
  st.n += 1;
66
68
  try {
67
69
  await handler(job.data);
package/dist/db/pool.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Kysely } from "kysely";
2
+ import { type RlsMode } from "../infra/database/scoped-dialect.js";
2
3
  /** 内核连接池的 PG `application_name`(便于在 pg_stat_activity 中识别)。 */
3
4
  export declare const KERNEL_APPLICATION_NAME = "capybara-kernel";
4
5
  /**
@@ -28,4 +29,9 @@ export declare function createDb(url: string, poolMax: number, onError?: (err: E
28
29
  * without this a backend killed between two statements is an uncaught exception.
29
30
  */
30
31
  onClientError?: ((err: Error) => void) | undefined;
32
+ /**
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.
35
+ */
36
+ rls?: RlsMode | undefined;
31
37
  }): Kysely<any>;
package/dist/db/pool.js CHANGED
@@ -1,5 +1,6 @@
1
- import { Kysely, PostgresDialect } from "kysely";
1
+ import { Kysely } from "kysely";
2
2
  import pg from "pg";
3
+ import { ScopedPostgresDialect } from "../infra/database/scoped-dialect.js";
3
4
  /** 内核连接池的 PG `application_name`(便于在 pg_stat_activity 中识别)。 */
4
5
  export const KERNEL_APPLICATION_NAME = "capybara-kernel";
5
6
  /**
@@ -28,5 +29,5 @@ export function createDb(url, poolMax, onError = (err) => console.error("[db] id
28
29
  });
29
30
  pool.on("error", onError);
30
31
  pool.on("connect", (client) => client.on("error", opts.onClientError ?? onError));
31
- return new Kysely({ dialect: new PostgresDialect({ pool }) });
32
+ return new Kysely({ dialect: new ScopedPostgresDialect({ pool }, opts.rls ?? "off") });
32
33
  }