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

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 (65) hide show
  1. package/bootstrap.json +29 -29
  2. package/dist/admin/outbox-dead.service.js +133 -120
  3. package/dist/background/store.js +78 -67
  4. package/dist/background/tasks.service.d.ts +6 -0
  5. package/dist/background/tasks.service.js +3 -0
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/plugin-import.js +45 -40
  8. package/dist/catalog/scope-sync-workers.js +3 -0
  9. package/dist/channels/inbound.d.ts +6 -1
  10. package/dist/channels/inbound.js +18 -1
  11. package/dist/client/client-reports.service.js +9 -6
  12. package/dist/config/schema.d.ts +5 -0
  13. package/dist/config/schema.js +6 -0
  14. package/dist/conversations/attachments.service.js +101 -96
  15. package/dist/conversations/events.d.ts +7 -0
  16. package/dist/conversations/events.js +9 -0
  17. package/dist/ctx/bus.js +5 -3
  18. package/dist/ctx/queue.js +4 -2
  19. package/dist/db/pool.d.ts +6 -0
  20. package/dist/db/pool.js +3 -2
  21. package/dist/devices/legacy-cleanup.job.js +73 -70
  22. package/dist/dial-in/gateway.d.ts +8 -0
  23. package/dist/dial-in/gateway.js +22 -2
  24. package/dist/extensions/admin-ops.js +22 -19
  25. package/dist/extensions/lifecycle-hooks.js +3 -1
  26. package/dist/http/app.js +3 -1
  27. package/dist/http/plugin-dispatch.js +8 -0
  28. package/dist/identity/auth.guard.js +13 -3
  29. package/dist/index.d.ts +2 -0
  30. package/dist/index.js +1 -0
  31. package/dist/infra/database/database.module.js +1 -0
  32. package/dist/infra/database/org-scope.d.ts +59 -0
  33. package/dist/infra/database/org-scope.js +68 -0
  34. package/dist/infra/database/rls-role.d.ts +11 -0
  35. package/dist/infra/database/rls-role.js +33 -0
  36. package/dist/infra/database/scoped-dialect.d.ts +18 -0
  37. package/dist/infra/database/scoped-dialect.js +245 -0
  38. package/dist/infra/outbox/outbox.dispatcher.js +98 -90
  39. package/dist/infra/outbox/outbox.service.js +29 -26
  40. package/dist/infra/queue/run-job.d.ts +8 -2
  41. package/dist/infra/queue/run-job.js +16 -3
  42. package/dist/infra/schedule/locked-tick.js +12 -4
  43. package/dist/infra/schedule/scheduled-runs.js +3 -1
  44. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -0
  45. package/dist/lifecycle/kernel-lifecycle.js +16 -1
  46. package/dist/orgs/org.guard.js +4 -0
  47. package/dist/platform/sealed-reveals.js +9 -6
  48. package/dist/runtime/maintenance.js +6 -1
  49. package/dist/runtime/run-execution.d.ts +1 -0
  50. package/dist/runtime/run-execution.js +5 -0
  51. package/dist/runtime/run-orphan-check.job.js +20 -15
  52. package/dist/sandbox/legacy-retirement.js +438 -397
  53. package/dist/sandbox/modes.d.ts +10 -0
  54. package/dist/sandbox/modes.js +23 -0
  55. package/dist/sandbox/operation-reconcile.job.d.ts +14 -1
  56. package/dist/sandbox/operation-reconcile.job.js +35 -3
  57. package/dist/sandbox/permission-config-publication.js +83 -77
  58. package/dist/sandbox/sandbox.service.d.ts +24 -0
  59. package/dist/sandbox/sandbox.service.js +159 -62
  60. package/dist/schedules/store.js +17 -14
  61. package/dist/tools/builtins/sandbox/bash.js +16 -1
  62. package/dist/tools/drift.js +31 -24
  63. package/dist/tools/outputs.js +20 -17
  64. package/package.json +2 -2
  65. package/src/migrations/0182_rls_policies.sql +202 -0
package/bootstrap.json CHANGED
@@ -3,103 +3,103 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "03a53c895cc9993306203fc0d41a6cc71acc3107"
6
+ "commit": "727f62bd821702a1b9d6ce0fb672d998dbb9d6d5"
7
7
  },
8
8
  "plugins": [
9
9
  {
10
10
  "name": "openai-compatible",
11
11
  "source": "npm",
12
12
  "npm": "@capybara-hq/plugin-openai-compatible",
13
- "version": "0.1.0-rc.11",
14
- "integrity": "sha512-xhLYmzgzC6I8VAx/xzGSrW53On9hVT9aXrNJaeLYBMVr84lY765MZ6P6qt5hDhHIH13sxyfaCf+3FQ6muc4U/w==",
13
+ "version": "0.1.0-rc.12",
14
+ "integrity": "sha512-4bO5W4xw97s1SPCfgWunqNzCiCoUUE35YdGX9GX+0CJ8bBRLQDZi6XaYHvOt1qZ+zQdwh8gRl9ILavwn4prEEw==",
15
15
  "required": false
16
16
  },
17
17
  {
18
18
  "name": "object-store-s3",
19
19
  "source": "npm",
20
20
  "npm": "@capybara-hq/plugin-object-store-s3",
21
- "version": "0.1.0-rc.11",
22
- "integrity": "sha512-1wwQSxvlGVYc7ZxtTBNN7VPHjtoa6rvzx4x3Qir2I39ILh/D9FxhlgEoSGXZ//Gt7L7Mos/hIvs7//QGf/vZPg==",
21
+ "version": "0.1.0-rc.12",
22
+ "integrity": "sha512-hPKfoH25RbEB8aA/Feqwfvbs2OR6B/MrXfj1DngBWEhSYvBoPfcezEC+LJDr35nRmfzsnqLc+Ho9Y4pT02tcyw==",
23
23
  "required": true
24
24
  },
25
25
  {
26
26
  "name": "anthropic",
27
27
  "source": "npm",
28
28
  "npm": "@capybara-hq/plugin-anthropic",
29
- "version": "0.1.0-rc.9",
30
- "integrity": "sha512-tLrZk/37U/6OX4rFWFmqsAHpizWT6Q4lqeXtx8O0t1WmfiX9UR9osfuA+atwdGNTAlyIZx8bGEALrMEZPjtyBw==",
29
+ "version": "0.1.0-rc.10",
30
+ "integrity": "sha512-fOZuAzmJLRdHj/IwsVA71jyu45FmK3VSQYKlOZk6JYv6WbCX5cUrieduN+PGHwszFysQ4QxFj4XQ23QltQMh+g==",
31
31
  "required": false
32
32
  },
33
33
  {
34
34
  "name": "openai",
35
35
  "source": "npm",
36
36
  "npm": "@capybara-hq/plugin-openai",
37
- "version": "0.1.0-rc.11",
38
- "integrity": "sha512-vFV/CgyPyRdE2OJ2JO+esoDeJ2jP+6jMqIautSOHyCMvpWkrg3UGnUH1iBN1z1Dy0cp293ddwo2CZAmlS6FI7w==",
37
+ "version": "0.1.0-rc.12",
38
+ "integrity": "sha512-bh4ydAdf7cJwod2crmd6q9mbAFYULtoSXm/FAWf5xOUvwfYCo6OWY+JD5fQGNZQDuD+0MV3wQbvSpYBA2/poNQ==",
39
39
  "required": false
40
40
  },
41
41
  {
42
42
  "name": "deepseek",
43
43
  "source": "npm",
44
44
  "npm": "@capybara-hq/plugin-deepseek",
45
- "version": "0.1.0-rc.10",
46
- "integrity": "sha512-sTlLjNWdGLTCFKJXYX0H9803zHq6ANU9TS/HG56McUqYxyay+/iWxbXhmP6h/8H4ditzxKLTcuerYNJLh6hxRw==",
45
+ "version": "0.1.0-rc.11",
46
+ "integrity": "sha512-AUgib6r+8sdNEu9Fs8NvatbYTe/eihW3Zo6zILzTIUxgCHRkvIJ/QKoWcH4O32gaiyvlsmYBocIlD3m0ntUhyA==",
47
47
  "required": false
48
48
  },
49
49
  {
50
50
  "name": "bailian",
51
51
  "source": "npm",
52
52
  "npm": "@capybara-hq/plugin-bailian",
53
- "version": "0.1.0-rc.10",
54
- "integrity": "sha512-yXDrvaJh3DtGg/hHpYFSJkoRxQdJCJQM6Y+mNLL1Cff53FraGYAZZi7ZIc1FnK9jFEp6nfHgnsuCJcvRmvpqqg==",
53
+ "version": "0.1.0-rc.11",
54
+ "integrity": "sha512-3LYmVw1KQL6qXYgU7XeymBvnRRZy8PM5OIP5CeUtypqMkBXHo1wR8leuwucLLLpRR5EgTJOWMdZNx5D99fp+rw==",
55
55
  "required": false
56
56
  },
57
57
  {
58
58
  "name": "ark",
59
59
  "source": "npm",
60
60
  "npm": "@capybara-hq/plugin-ark",
61
- "version": "0.1.0-rc.11",
62
- "integrity": "sha512-rE0tPudbL0AjY9f6cTdM0wSFtyhWsKOaEFy6GOZ79wISw9F5Y0ap3RVaiaeW9c0lZPxKdhqIzi18xARu/A1jVQ==",
61
+ "version": "0.1.0-rc.12",
62
+ "integrity": "sha512-8yrnD2AKpsqT7RKrokyH95xW8z8un5z4c3rgsxtgW49kVZ9Y+rOpsf+mNGW/XM/rEATSvQTj3LMPDBGPPZdPyw==",
63
63
  "required": false
64
64
  },
65
65
  {
66
66
  "name": "connector-mcp",
67
67
  "source": "npm",
68
68
  "npm": "@capybara-hq/plugin-connector-mcp",
69
- "version": "0.1.0-rc.11",
70
- "integrity": "sha512-n1V9BMlU5JVQfTUFoWsOXOi0huE8XTsbU9MULLXSESCrEc0a5RjgvhvoSuk3SXE4jxJoVV4WB6g2BVin8E/dMg==",
69
+ "version": "0.1.0-rc.12",
70
+ "integrity": "sha512-AMUljGAoaFN8NZo5A6vkAz+PYF0QooqBPCz+OThLHjFZhej1qhYkwNqDkQU8DQKpVLhQ/Z0dUg8OprSnGMtGsw==",
71
71
  "required": false
72
72
  },
73
73
  {
74
74
  "name": "connector-openapi",
75
75
  "source": "npm",
76
76
  "npm": "@capybara-hq/plugin-connector-openapi",
77
- "version": "0.1.0-rc.12",
78
- "integrity": "sha512-qIYknFj7V6xSl4lbTYpSXpu8f+FFLAwWxOhJq9HzH3RSAAq80emp4WPdXbIoJ2nzfg2mXNs0lTkgCuR38oxhQw==",
77
+ "version": "0.1.0-rc.13",
78
+ "integrity": "sha512-3kI76wL9WL8dPkjLxpXliRzQzI66Xs2fp/mYT6t5svCobJpoan/b6X72h46TeDO9SsXiT+5X9licvRxwSWf6Sw==",
79
79
  "required": false
80
80
  },
81
81
  {
82
82
  "name": "jina",
83
83
  "source": "npm",
84
84
  "npm": "@capybara-hq/plugin-jina",
85
- "version": "0.1.0-rc.9",
86
- "integrity": "sha512-c0DFvKKQrO3qDkwAEBoBbFhDDfktucjWCIPyh+wRWGAbrXLwz69zX8C0f6MHI0YmlM68EW+NxVM3f1w8bDHOQg==",
85
+ "version": "0.1.0-rc.10",
86
+ "integrity": "sha512-Sxsg2qMz//QcZMqRCGvK7o8CqFDS5XMXpESmiyJasCoNYRE/cb/Q7v4XcSIc/WXccVTN9kWUBPJDU6c6gpiAjA==",
87
87
  "required": false
88
88
  },
89
89
  {
90
90
  "name": "device-docker",
91
91
  "source": "npm",
92
92
  "npm": "@capybara-hq/plugin-device-docker",
93
- "version": "0.1.0-rc.25",
94
- "integrity": "sha512-2ooWuxVKvGoXWNQTpEwwFRZP2/qUiPvihP/858VDwiRqkEU9DY3zsf2QrcIOUeL6NcjGhNRWsz6r5ReKdXUc8w==",
93
+ "version": "0.1.0-rc.28",
94
+ "integrity": "sha512-AMmRgf+D8Aap5RKdrhNvPH+1ItvTtQohOCzr6B0xaSzOYD78BbYZxKniOZzEqphGxOymoZe+LCqfTSnKGdKRWg==",
95
95
  "required": false
96
96
  },
97
97
  {
98
98
  "name": "device-local",
99
99
  "source": "npm",
100
100
  "npm": "@capybara-hq/plugin-device-local",
101
- "version": "0.1.0-rc.7",
102
- "integrity": "sha512-IGhfG42LMy8Rf95vHEjGKkEHHhASClFvPZZnLZAHjdHr6fqox6z2q1c4Kn1BRee2kSVT31AOw8hiTurfIXyalA==",
101
+ "version": "0.1.0-rc.8",
102
+ "integrity": "sha512-TA84YgBO3gpzZUumpR3ZdwFVa1Vytre9oaDWslFN9J3tE4ch3F1HdDKCstNgxhgogwHRLAyy6nwOIiGn7XXurw==",
103
103
  "required": false,
104
104
  "scope": "all"
105
105
  },
@@ -107,8 +107,8 @@
107
107
  "name": "todo",
108
108
  "source": "npm",
109
109
  "npm": "@capybara-hq/plugin-todo",
110
- "version": "0.1.0-rc.12",
111
- "integrity": "sha512-tTQKRoBAlN3tz6eC0ZqFpfwwm0j/dte4ZJ6EOB8hSXzaQLagPIwutNsr3pTFA1xoFhFLKo13ZPdQbv8ONq06Ww==",
110
+ "version": "0.1.0-rc.13",
111
+ "integrity": "sha512-QApBFqo6PrFJlmR7Pokbkx6AmLZ8dIGApl+EneshGw6dpJbDYvyUaoRyvk2Os1pYyfQOTHnCc0FUEae5mrVj6g==",
112
112
  "required": false
113
113
  },
114
114
  {
@@ -124,8 +124,8 @@
124
124
  "name": "file-preview",
125
125
  "source": "npm",
126
126
  "npm": "@capybara-hq/plugin-file-preview",
127
- "version": "0.1.0-rc.3",
128
- "integrity": "sha512-4GMeq6gpjloCmTrEidiUHX5v6PN4oTfRDWcx+sLb5NlUoSk5DaJVVtJDc5oNDzow09OSm62DJchDOBJItLdwrA==",
127
+ "version": "0.1.0-rc.4",
128
+ "integrity": "sha512-TBIUsqB2ZNpKPc8ddBh9e2KdT9SV/+ZNSBYqrDRv8SazVmN3q7lgbVk5QaiLioI2EPt5Kfs4DSY+YIrKlzwCcA==",
129
129
  "required": false,
130
130
  "builtin": true
131
131
  }
@@ -14,6 +14,7 @@ import { audit } from "../identity/audit.js";
14
14
  import { SuperAdminLock } from "../identity/super-admin.js";
15
15
  import { afterCommit } from "../infra/database/after-commit.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { asPlatform } from "../infra/database/org-scope.js";
17
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
18
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
19
20
  import { OUTBOX_FAST_PATH } from "../infra/outbox/outbox.service.js";
@@ -48,62 +49,66 @@ let OutboxDeadService = class OutboxDeadService {
48
49
  * first by `(dead_at, id)`; one extra row tells `next`. A malformed cursor is a validation error.
49
50
  */
50
51
  async list(q = {}) {
51
- const limit = Math.min(q.limit ?? OUTBOX_DEAD_LIST_MAX, OUTBOX_DEAD_LIST_MAX);
52
- const cursor = q.after === undefined ? null : decodeOutboxDeadCursor(q.after);
53
- if (q.after !== undefined && cursor === null) {
54
- throw new ApiError("validation_failed", "after must be a cursor from a previous page");
55
- }
56
- let query = this.db.db
57
- .selectFrom("outbox")
58
- .select([
59
- "id",
60
- "queue",
61
- "job_name",
62
- "job_id",
63
- "org_id",
64
- "attempts",
65
- "last_error",
66
- "dead_at",
67
- "created_at",
68
- // PG's own text keeps the microseconds a JS Date would cut
69
- sql `dead_at::text`.as("dead_at_text"),
70
- ])
71
- .where("dead_at", "is not", null);
72
- if (cursor !== null) {
73
- query = query.where(sql `(dead_at, id) > (${cursor.deadAt}::timestamptz, ${cursor.id}::bigint)`);
74
- }
75
- const rows = await query
76
- .orderBy("dead_at")
77
- .orderBy("id")
78
- .limit(limit + 1)
79
- .execute();
80
- const page = rows.slice(0, limit);
81
- const last = page.at(-1);
82
- return {
83
- next: rows.length > limit && last !== undefined
84
- ? encodeOutboxDeadCursor({ deadAt: last.dead_at_text, id: String(last.id) })
85
- : null,
86
- items: page.map((r) => ({
87
- id: String(r.id),
88
- queue: r.queue,
89
- jobName: r.job_name,
90
- jobId: r.job_id,
91
- orgId: r.org_id,
92
- attempts: r.attempts,
93
- lastError: r.last_error,
94
- deadAt: r.dead_at.toISOString(),
95
- createdAt: r.created_at.toISOString(),
96
- })),
97
- };
52
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
53
+ const limit = Math.min(q.limit ?? OUTBOX_DEAD_LIST_MAX, OUTBOX_DEAD_LIST_MAX);
54
+ const cursor = q.after === undefined ? null : decodeOutboxDeadCursor(q.after);
55
+ if (q.after !== undefined && cursor === null) {
56
+ throw new ApiError("validation_failed", "after must be a cursor from a previous page");
57
+ }
58
+ let query = this.db.db
59
+ .selectFrom("outbox")
60
+ .select([
61
+ "id",
62
+ "queue",
63
+ "job_name",
64
+ "job_id",
65
+ "org_id",
66
+ "attempts",
67
+ "last_error",
68
+ "dead_at",
69
+ "created_at",
70
+ // PG's own text keeps the microseconds a JS Date would cut
71
+ sql `dead_at::text`.as("dead_at_text"),
72
+ ])
73
+ .where("dead_at", "is not", null);
74
+ if (cursor !== null) {
75
+ query = query.where(sql `(dead_at, id) > (${cursor.deadAt}::timestamptz, ${cursor.id}::bigint)`);
76
+ }
77
+ const rows = await query
78
+ .orderBy("dead_at")
79
+ .orderBy("id")
80
+ .limit(limit + 1)
81
+ .execute();
82
+ const page = rows.slice(0, limit);
83
+ const last = page.at(-1);
84
+ return {
85
+ next: rows.length > limit && last !== undefined
86
+ ? encodeOutboxDeadCursor({ deadAt: last.dead_at_text, id: String(last.id) })
87
+ : null,
88
+ items: page.map((r) => ({
89
+ id: String(r.id),
90
+ queue: r.queue,
91
+ jobName: r.job_name,
92
+ jobId: r.job_id,
93
+ orgId: r.org_id,
94
+ attempts: r.attempts,
95
+ lastError: r.last_error,
96
+ deadAt: r.dead_at.toISOString(),
97
+ createdAt: r.created_at.toISOString(),
98
+ })),
99
+ };
100
+ });
98
101
  }
99
102
  /** How many rows are dead, and the oldest one's `dead_at`. */
100
103
  async summary() {
101
- const row = await this.db.db
102
- .selectFrom("outbox")
103
- .select([sql `count(*)`.as("count"), sql `min(dead_at)`.as("oldest")])
104
- .where("dead_at", "is not", null)
105
- .executeTakeFirstOrThrow();
106
- return { count: Number(row.count), oldestAt: row.oldest };
104
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
105
+ const row = await this.db.db
106
+ .selectFrom("outbox")
107
+ .select([sql `count(*)`.as("count"), sql `min(dead_at)`.as("oldest")])
108
+ .where("dead_at", "is not", null)
109
+ .executeTakeFirstOrThrow();
110
+ return { count: Number(row.count), oldestAt: row.oldest };
111
+ });
107
112
  }
108
113
  /**
109
114
  * Makes a dead row due again (`dead_at` cleared, no attempts, next attempt now) and hands it to
@@ -132,82 +137,90 @@ let OutboxDeadService = class OutboxDeadService {
132
137
  }
133
138
  }
134
139
  async retryOnce(id, actor, detail) {
135
- await this.adminLock.lockAndAuthorize(actor.accountId);
136
- await this.lockRunRetryIn(id);
137
- const row = await this.lockDead(id);
138
- const owed = await this.db.db
139
- .selectFrom("outbox")
140
- .select("id")
141
- .where("queue", "=", row.queue)
142
- .where("job_id", "=", row.job_id)
143
- .where("dead_at", "is", null)
144
- .executeTakeFirst();
145
- let outcome;
146
- if (owed) {
147
- await this.db.db.deleteFrom("outbox").where("id", "=", id).execute();
148
- outcome = "already_owed";
149
- }
150
- else {
151
- await this.db.db
152
- .updateTable("outbox")
153
- .set({ dead_at: null, attempts: 0, next_attempt_at: sql `now()` })
154
- .where("id", "=", id)
155
- .execute();
156
- outcome = "retried";
157
- afterCommit(() => this.fastPath([id]));
158
- }
159
- await this.audit("outbox.retried", id, row, actor, { ...detail, outcome });
160
- return { outcome };
140
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
141
+ await this.adminLock.lockAndAuthorize(actor.accountId);
142
+ await this.lockRunRetryIn(id);
143
+ const row = await this.lockDead(id);
144
+ const owed = await this.db.db
145
+ .selectFrom("outbox")
146
+ .select("id")
147
+ .where("queue", "=", row.queue)
148
+ .where("job_id", "=", row.job_id)
149
+ .where("dead_at", "is", null)
150
+ .executeTakeFirst();
151
+ let outcome;
152
+ if (owed) {
153
+ await this.db.db.deleteFrom("outbox").where("id", "=", id).execute();
154
+ outcome = "already_owed";
155
+ }
156
+ else {
157
+ await this.db.db
158
+ .updateTable("outbox")
159
+ .set({ dead_at: null, attempts: 0, next_attempt_at: sql `now()` })
160
+ .where("id", "=", id)
161
+ .execute();
162
+ outcome = "retried";
163
+ afterCommit(() => this.fastPath([id]));
164
+ }
165
+ await this.audit("outbox.retried", id, row, actor, { ...detail, outcome });
166
+ return { outcome };
167
+ });
161
168
  }
162
169
  /** A run-job retry is a new delivery generation, serialized with its terminal transition. */
163
170
  async lockRunRetryIn(id) {
164
- // Read before taking any outbox lock: the lock order is conversation, then outbox. The
165
- // subsequent lockDead rechecks this row, so a concurrent discard/retry rolls this back.
166
- const row = await this.db
167
- .selectFrom("outbox")
168
- .select(["job_name", "job_id", "data"])
169
- .where("id", "=", id)
170
- .where("dead_at", "is not", null)
171
- .executeTakeFirst();
172
- if (row?.job_name !== "run" || row.data === null || typeof row.data !== "object")
173
- return;
174
- const data = row.data;
175
- if (typeof data.conversationId !== "string" || typeof data.runId !== "string")
176
- return;
177
- await this.db
178
- .selectFrom("conversations")
179
- .select("id")
180
- .where("id", "=", data.conversationId)
181
- .forUpdate()
182
- .execute();
183
- await this.db
184
- .updateTable("runs")
185
- .set({ queued_at: sql `clock_timestamp()` })
186
- .where("id", "=", data.runId)
187
- .where("conversation_id", "=", data.conversationId)
188
- .where("status", "=", "queued")
189
- .where(sql `COALESCE(job_id, 'run-' || conversation_id || '-' || trigger_seq::text) = ${row.job_id}`)
190
- .execute();
171
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
172
+ // Read before taking any outbox lock: the lock order is conversation, then outbox. The
173
+ // subsequent lockDead rechecks this row, so a concurrent discard/retry rolls this back.
174
+ const row = await this.db
175
+ .selectFrom("outbox")
176
+ .select(["job_name", "job_id", "data"])
177
+ .where("id", "=", id)
178
+ .where("dead_at", "is not", null)
179
+ .executeTakeFirst();
180
+ if (row?.job_name !== "run" || row.data === null || typeof row.data !== "object")
181
+ return;
182
+ const data = row.data;
183
+ if (typeof data.conversationId !== "string" || typeof data.runId !== "string")
184
+ return;
185
+ await this.db
186
+ .selectFrom("conversations")
187
+ .select("id")
188
+ .where("id", "=", data.conversationId)
189
+ .forUpdate()
190
+ .execute();
191
+ await this.db
192
+ .updateTable("runs")
193
+ .set({ queued_at: sql `clock_timestamp()` })
194
+ .where("id", "=", data.runId)
195
+ .where("conversation_id", "=", data.conversationId)
196
+ .where("status", "=", "queued")
197
+ .where(sql `COALESCE(job_id, 'run-' || conversation_id || '-' || trigger_seq::text) = ${row.job_id}`)
198
+ .execute();
199
+ });
191
200
  }
192
201
  /** Deletes a dead row: its job is never delivered. `outbox.not_found` (404) when none. */
193
202
  async discard(id, actor, detail = {}) {
194
- await this.adminLock.lockAndAuthorize(actor.accountId);
195
- const row = await this.lockDead(id);
196
- await this.db.db.deleteFrom("outbox").where("id", "=", id).execute();
197
- await this.audit("outbox.discarded", id, row, actor, detail);
203
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
204
+ await this.adminLock.lockAndAuthorize(actor.accountId);
205
+ const row = await this.lockDead(id);
206
+ await this.db.db.deleteFrom("outbox").where("id", "=", id).execute();
207
+ await this.audit("outbox.discarded", id, row, actor, detail);
208
+ });
198
209
  }
199
210
  /** The dead row `id`, locked for the transaction; `outbox.not_found` when it is not dead. */
200
211
  async lockDead(id) {
201
- const row = await this.db.db
202
- .selectFrom("outbox")
203
- .select(["queue", "job_name", "job_id", "org_id", "attempts", "last_error"])
204
- .where("id", "=", id)
205
- .where("dead_at", "is not", null)
206
- .forUpdate()
207
- .executeTakeFirst();
208
- if (!row)
209
- throw notFound(id);
210
- return row;
212
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
213
+ const row = await this.db.db
214
+ .selectFrom("outbox")
215
+ .select(["queue", "job_name", "job_id", "org_id", "attempts", "last_error"])
216
+ .where("id", "=", id)
217
+ .where("dead_at", "is not", null)
218
+ .forUpdate()
219
+ .executeTakeFirst();
220
+ if (!row)
221
+ throw notFound(id);
222
+ return row;
223
+ });
211
224
  }
212
225
  /**
213
226
  * A platform-level audit event (no org: the outbox is the deployment's), naming the job. The