@capybara-hq/kernel 0.1.0-rc.112 → 0.1.0-rc.114

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 (72) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/channels/actions.js +2 -0
  3. package/dist/channels/cards.d.ts +4 -3
  4. package/dist/channels/cards.js +18 -3
  5. package/dist/channels/phrases.d.ts +15 -0
  6. package/dist/channels/phrases.js +9 -0
  7. package/dist/conversations/conversations.service.js +19 -5
  8. package/dist/conversations/events.d.ts +13 -0
  9. package/dist/conversations/events.js +24 -3
  10. package/dist/ctx/create-ctx.d.ts +1 -1
  11. package/dist/ctx/create-ctx.js +6 -1
  12. package/dist/db/kernel-schema.d.ts +26 -0
  13. package/dist/device-access/device-access.service.d.ts +74 -3
  14. package/dist/device-access/device-access.service.js +221 -7
  15. package/dist/devices/devices.service.js +3 -0
  16. package/dist/errors.d.ts +6 -0
  17. package/dist/errors.js +6 -0
  18. package/dist/extensions/permission-set.d.ts +11 -1
  19. package/dist/extensions/permission-set.js +15 -1
  20. package/dist/extensions/permission-view.d.ts +3 -2
  21. package/dist/extensions/permission-view.js +15 -2
  22. package/dist/infra/outbox/registry.d.ts +14 -0
  23. package/dist/infra/outbox/registry.js +14 -0
  24. package/dist/orgs/offboarding.js +5 -1
  25. package/dist/platform/ops/agent-skills.ops.js +6 -2
  26. package/dist/roles/worker.module.js +3 -0
  27. package/dist/runtime/maintenance.d.ts +4 -2
  28. package/dist/runtime/maintenance.js +14 -4
  29. package/dist/sandbox/device-sandbox.d.ts +12 -0
  30. package/dist/sandbox/device-sandbox.js +2 -0
  31. package/dist/sandbox/device-services.d.ts +42 -2
  32. package/dist/sandbox/device-services.js +74 -14
  33. package/dist/sandbox/loopback-expiry.job.d.ts +21 -0
  34. package/dist/sandbox/loopback-expiry.job.js +50 -0
  35. package/dist/sandbox/loopback-grant-records.d.ts +143 -0
  36. package/dist/sandbox/loopback-grant-records.js +239 -0
  37. package/dist/sandbox/loopback-grants.d.ts +119 -0
  38. package/dist/sandbox/loopback-grants.js +454 -0
  39. package/dist/sandbox/loopback-live-ports.d.ts +12 -0
  40. package/dist/sandbox/loopback-live-ports.js +43 -0
  41. package/dist/sandbox/permission-call-types.d.ts +3 -2
  42. package/dist/sandbox/permission-ceiling-writes.js +13 -1
  43. package/dist/sandbox/permission-facts.d.ts +4 -0
  44. package/dist/sandbox/permission-facts.js +4 -0
  45. package/dist/sandbox/review/classifier.d.ts +26 -4
  46. package/dist/sandbox/review/classifier.js +31 -4
  47. package/dist/sandbox/review/index.d.ts +3 -3
  48. package/dist/sandbox/review/index.js +2 -2
  49. package/dist/sandbox/review/permission-candidate.d.ts +5 -4
  50. package/dist/sandbox/review/permission-candidate.js +6 -5
  51. package/dist/sandbox/review/review.service.d.ts +69 -0
  52. package/dist/sandbox/review/review.service.js +117 -0
  53. package/dist/sandbox/sandbox.module.d.ts +1 -1
  54. package/dist/sandbox/sandbox.module.js +13 -2
  55. package/dist/skills/invocable.controller.d.ts +4 -0
  56. package/dist/skills/invocable.controller.js +5 -1
  57. package/dist/skills/invoke.d.ts +68 -2
  58. package/dist/skills/invoke.js +128 -13
  59. package/dist/skills/skills.schemas.d.ts +7 -1
  60. package/dist/skills/skills.schemas.js +11 -2
  61. package/dist/tools/approvals.service.d.ts +82 -6
  62. package/dist/tools/approvals.service.js +233 -11
  63. package/dist/tools/call-scope.d.ts +9 -1
  64. package/dist/tools/loopback-asks.d.ts +52 -0
  65. package/dist/tools/loopback-asks.js +70 -0
  66. package/dist/tools/network-asks.d.ts +2 -1
  67. package/dist/tools/network-asks.js +10 -5
  68. package/dist/tools/pipeline.d.ts +59 -3
  69. package/dist/tools/pipeline.js +403 -40
  70. package/dist/tools/tools.module.js +3 -0
  71. package/package.json +2 -2
  72. package/src/migrations/0199_device_loopback_grants.sql +59 -0
@@ -0,0 +1,454 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { randomUUID } from "node:crypto";
11
+ import { DeviceAccessError, LOOPBACK_MAX_PORTS_PER_SERVICE, } from "@capybara-hq/plugin-sdk";
12
+ import { Inject, Injectable } from "@nestjs/common";
13
+ import { sql } from "kysely";
14
+ import { ApiError } from "../errors.js";
15
+ import { audit } from "../identity/audit.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { asPlatform } from "../infra/database/org-scope.js";
18
+ import { TransactionHost } from "../infra/database/transaction-host.js";
19
+ import { Transactional } from "../infra/database/transactional.decorator.js";
20
+ import { XactLock } from "../infra/database/xact-lock.js";
21
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
22
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
23
+ import { DeviceServices } from "./device-services.js";
24
+ import { endedGrants, isDatabasePort, knownLoopbackRefusal, LOOPBACK_GRANT_TTL_HOURS, LoopbackLimitError, loopbackRefusal, oweLoopbackFollowUp, oweRefresh, rowOf, } from "./loopback-grant-records.js";
25
+ import { LoopbackLivePorts } from "./loopback-live-ports.js";
26
+ import { runtimeReportVerdict } from "./permission-availability.js";
27
+ import { PermissionFacts } from "./permission-facts.js";
28
+ import { escalationCeilingWhy, escalationRuntimeWhy } from "./review/permission-candidate.js";
29
+ // the constants, types and plain functions live in a leaf module (no services imported), so
30
+ // conversation deletion and ceiling writes import them without an import cycle
31
+ export * from "./loopback-grant-records.js";
32
+ /** How long an ended grant row is kept before the expiry pass deletes it (the audit log stays). */
33
+ export const LOOPBACK_ENDED_RETENTION_DAYS = 30;
34
+ /** The rows one retention batch deletes. */
35
+ export const LOOPBACK_PURGE_BATCH = 500;
36
+ /** The retention batches one expiry pass runs at most. */
37
+ export const LOOPBACK_PURGE_MAX_BATCHES = 20;
38
+ /**
39
+ * The lock of one (device, service)'s live set (decision R9: one provider per
40
+ * transaction-scoped lock): serializes grants of the service, so the count of its live ports
41
+ * checked against {@link LOOPBACK_MAX_PORTS_PER_SERVICE} and the insert are one step. Joins the
42
+ * caller's transaction (`mandatory`), which holds it until it ends.
43
+ */
44
+ let LoopbackGrantLock = class LoopbackGrantLock {
45
+ xactLock;
46
+ txHost;
47
+ constructor(xactLock, txHost) {
48
+ this.xactLock = xactLock;
49
+ this.txHost = txHost;
50
+ }
51
+ async lock(deviceId, serviceId) {
52
+ await this.xactLock.lock(`capybara.loopback-grants:${deviceId}:${serviceId}`);
53
+ }
54
+ };
55
+ __decorate([
56
+ Transactional({ propagation: "mandatory" })
57
+ ], LoopbackGrantLock.prototype, "lock", null);
58
+ LoopbackGrantLock = __decorate([
59
+ Injectable(),
60
+ __param(0, Inject(XactLock)),
61
+ __param(1, Inject(TransactionHost))
62
+ ], LoopbackGrantLock);
63
+ export { LoopbackGrantLock };
64
+ /** The grant records: issue, revoke, read, refresh and expiry (see the file header). */
65
+ let LoopbackGrants = class LoopbackGrants {
66
+ db;
67
+ txHost;
68
+ outbox;
69
+ locks;
70
+ live;
71
+ facts;
72
+ services;
73
+ log;
74
+ constructor(db, txHost, outbox, locks, live, facts, services, log) {
75
+ this.db = db;
76
+ this.txHost = txHost;
77
+ this.outbox = outbox;
78
+ this.locks = locks;
79
+ this.live = live;
80
+ this.facts = facts;
81
+ this.services = services;
82
+ this.log = log;
83
+ }
84
+ /**
85
+ * In the caller's transaction (`propagation: "mandatory"`): expires stale rows of the key,
86
+ * inserts the grant (or returns the live row, with no second audit or refresh), audits
87
+ * `device.loopback_granted` and owes the refresh. Throws {@link LoopbackLimitError} when the
88
+ * port would be the service's 33rd live one. The caller checked the person, the device and the
89
+ * ceilings ({@link loopbackRefusal}).
90
+ */
91
+ async grantIn(key, by) {
92
+ if ((by.source === "owner-panel") !== (by.call === undefined))
93
+ throw new Error("A loopback grant names its call unless the owner's panel made it");
94
+ const db = this.db.db;
95
+ // the root must be a live root conversation, read FOR SHARE: a deletion that commits first is
96
+ // seen here (the row is re-checked after its lock), and one that comes later waits for this
97
+ // transaction and then revokes the grant with the conversation's other grants
98
+ const root = await db
99
+ .selectFrom("conversations")
100
+ .select("id")
101
+ .where("id", "=", key.rootConversationId)
102
+ .where("org_id", "=", key.orgId)
103
+ .where("deleted_at", "is", null)
104
+ .where("parent_conversation_id", "is", null)
105
+ .forShare()
106
+ .executeTakeFirst();
107
+ if (!root)
108
+ throw new ApiError("conversation.not_found", "The conversation was deleted or is not a root conversation; a loopback port is granted to a live root conversation");
109
+ await this.locks.lock(key.deviceId, key.serviceId);
110
+ const stale = await db
111
+ .updateTable("device_loopback_grants")
112
+ .set({ revoked_at: sql `now()`, revoke_reason: "expired" })
113
+ .where("org_id", "=", key.orgId)
114
+ .where("device_id", "=", key.deviceId)
115
+ .where("service_id", "=", key.serviceId)
116
+ .where("conversation_id", "=", key.rootConversationId)
117
+ .where("port", "=", key.port)
118
+ .where("revoked_at", "is", null)
119
+ .where("expires_at", "<=", sql `now()`)
120
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
121
+ .execute();
122
+ for (const r of stale)
123
+ await audit(db, {
124
+ actorAccountId: null,
125
+ orgId: r.org_id,
126
+ action: "device.loopback_revoked",
127
+ target: r.device_id,
128
+ detail: {
129
+ grantId: r.id,
130
+ deviceId: r.device_id,
131
+ serviceId: r.service_id,
132
+ conversationId: r.conversation_id,
133
+ port: r.port,
134
+ reason: "expired",
135
+ },
136
+ });
137
+ const existing = await db
138
+ .selectFrom("device_loopback_grants")
139
+ .selectAll()
140
+ .where("org_id", "=", key.orgId)
141
+ .where("device_id", "=", key.deviceId)
142
+ .where("service_id", "=", key.serviceId)
143
+ .where("conversation_id", "=", key.rootConversationId)
144
+ .where("port", "=", key.port)
145
+ .where("revoked_at", "is", null)
146
+ .executeTakeFirst();
147
+ if (existing)
148
+ return rowOf(existing);
149
+ const ports = await this.live.livePorts(key.orgId, key.deviceId, key.serviceId);
150
+ if (!ports.includes(key.port) && ports.length >= LOOPBACK_MAX_PORTS_PER_SERVICE)
151
+ throw new LoopbackLimitError();
152
+ const inserted = await db
153
+ .insertInto("device_loopback_grants")
154
+ .values({
155
+ id: randomUUID(),
156
+ org_id: key.orgId,
157
+ device_id: key.deviceId,
158
+ service_id: key.serviceId,
159
+ conversation_id: key.rootConversationId,
160
+ port: key.port,
161
+ source: by.source,
162
+ ...(by.approvalId !== undefined && { approval_id: by.approvalId }),
163
+ ...(by.call !== undefined && {
164
+ run_id: by.call.runId,
165
+ call_id: by.call.callId,
166
+ attempt: by.call.attempt,
167
+ }),
168
+ expires_at: sql `now() + make_interval(hours => ${LOOPBACK_GRANT_TTL_HOURS})`,
169
+ })
170
+ .returningAll()
171
+ .executeTakeFirstOrThrow();
172
+ const row = rowOf(inserted);
173
+ await audit(db, {
174
+ actorAccountId: by.actorAccountId,
175
+ orgId: key.orgId,
176
+ action: "device.loopback_granted",
177
+ target: key.deviceId,
178
+ detail: {
179
+ grantId: row.id,
180
+ deviceId: key.deviceId,
181
+ serviceId: key.serviceId,
182
+ conversationId: key.rootConversationId,
183
+ port: key.port,
184
+ database: isDatabasePort(key.port),
185
+ source: by.source,
186
+ expiresAt: row.expiresAt,
187
+ ...(by.approvalId !== undefined && { approvalId: by.approvalId }),
188
+ ...(by.call !== undefined && { ...by.call }),
189
+ },
190
+ });
191
+ await oweRefresh(this.outbox, { orgId: key.orgId, deviceId: key.deviceId, serviceId: key.serviceId }, `g${row.id}`);
192
+ return row;
193
+ }
194
+ /**
195
+ * Revokes the key's live grant (reason `revoked`, audited `device.loopback_revoked`) and owes the
196
+ * refresh; false when there was none.
197
+ */
198
+ async revoke(key, actorAccountId) {
199
+ const rows = await this.db
200
+ .updateTable("device_loopback_grants")
201
+ .set({ revoked_at: sql `now()`, revoke_reason: "revoked" })
202
+ .where("org_id", "=", key.orgId)
203
+ .where("device_id", "=", key.deviceId)
204
+ .where("service_id", "=", key.serviceId)
205
+ .where("conversation_id", "=", key.rootConversationId)
206
+ .where("port", "=", key.port)
207
+ .where("revoked_at", "is", null)
208
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
209
+ .execute();
210
+ await endedGrants(this.db.db, this.outbox, rows, "revoked", actorAccountId);
211
+ return rows.length > 0;
212
+ }
213
+ /** The live ports of one (device, service): sorted, unique, not revoked, not expired. */
214
+ livePorts(orgId, deviceId, serviceId) {
215
+ return this.live.livePorts(orgId, deviceId, serviceId);
216
+ }
217
+ /**
218
+ * In the caller's transaction (`propagation: "mandatory"`): the key's live grant read
219
+ * `FOR SHARE`, or null. A revoke committed first is not seen; one that comes later waits for the
220
+ * caller's transaction.
221
+ */
222
+ async liveLockedIn(key) {
223
+ const row = await this.db
224
+ .selectFrom("device_loopback_grants")
225
+ .selectAll()
226
+ .where("org_id", "=", key.orgId)
227
+ .where("device_id", "=", key.deviceId)
228
+ .where("service_id", "=", key.serviceId)
229
+ .where("conversation_id", "=", key.rootConversationId)
230
+ .where("port", "=", key.port)
231
+ .where("revoked_at", "is", null)
232
+ .where("expires_at", ">", sql `now()`)
233
+ .forShare()
234
+ .executeTakeFirst();
235
+ return row === undefined ? null : rowOf(row);
236
+ }
237
+ /** The live grants of one (device, service) held by the root, by port. */
238
+ async liveForRoot(orgId, deviceId, serviceId, rootConversationId) {
239
+ const rows = await this.db
240
+ .selectFrom("device_loopback_grants")
241
+ .selectAll()
242
+ .where("org_id", "=", orgId)
243
+ .where("device_id", "=", deviceId)
244
+ .where("service_id", "=", serviceId)
245
+ .where("conversation_id", "=", rootConversationId)
246
+ .where("revoked_at", "is", null)
247
+ .where("expires_at", ">", sql `now()`)
248
+ .orderBy("port")
249
+ .execute();
250
+ return rows.map(rowOf);
251
+ }
252
+ /**
253
+ * The live grant the call made (a rerun after a crash resumes from it), or null when it made
254
+ * none or the grant ended since.
255
+ */
256
+ async forCall(runId, callId) {
257
+ // org-filter: the runtime's own run and call ids name the grant; the run was claimed under its
258
+ // org, and run ids are unique across orgs
259
+ const row = await this.db
260
+ .selectFrom("device_loopback_grants")
261
+ .selectAll()
262
+ .where("run_id", "=", runId)
263
+ .where("call_id", "=", callId)
264
+ .where("revoked_at", "is", null)
265
+ .where("expires_at", ">", sql `now()`)
266
+ .orderBy("created_at", "desc")
267
+ .limit(1)
268
+ .executeTakeFirst();
269
+ return row ? rowOf(row) : null;
270
+ }
271
+ /**
272
+ * Why a loopback grant on the device is refused now for an attended decision (a person's click
273
+ * or approval; an unattended run is refused before), in the note's words ({@link loopbackRefusal});
274
+ * null when grantable. The escalation refusal is previewCall's for an attended call: the runtime
275
+ * cannot run anything outside its sandbox now, else the device's outside-sandbox ceiling. Read
276
+ * outside the grant's transaction: a ceiling switched off meanwhile owes a refresh whose job
277
+ * revokes the grant ({@link refresh}), so the window is bounded.
278
+ */
279
+ async refusalNow(orgId, deviceId) {
280
+ const facts = await this.facts.deviceSandboxFacts(orgId, deviceId);
281
+ const runtime = runtimeWhy(facts.availability);
282
+ const escalation = runtime !== null
283
+ ? escalationRuntimeWhy(runtime)
284
+ : facts.box.outsideSandbox
285
+ ? null
286
+ : escalationCeilingWhy({
287
+ layer: facts.box.layer.outsideSandbox,
288
+ boundary: facts.box.boundary,
289
+ description: facts.description,
290
+ changeHint: facts.changeHint,
291
+ });
292
+ return loopbackRefusal(facts.box, facts.support, escalation);
293
+ }
294
+ /**
295
+ * The refresh job. First it revokes the (device, service)'s live grants (reason
296
+ * `outside-sandbox-off`, audited) when the device refuses loopback grants now: a ceiling layer
297
+ * keeps running outside the sandbox off, or the provider's known support lacks
298
+ * `network.loopbackPorts` (a provider that lost it; {@link knownLoopbackRefusal}). A support
299
+ * not known (none stored, a failed read, or a closed one with an `unavailableReason`, as while a
300
+ * device re-binds) revokes nothing: grants are consents, and new ones are refused meanwhile.
301
+ * Then it sends the live set to an `ifRunning` ensure of the service
302
+ * (`DeviceServices.refreshLoopback`), always, so a revocation already recorded reaches the
303
+ * machine whatever the support says. A stopped service or instance needs nothing: its
304
+ * next ensure sends the set. A failed send owes a delayed follow-up
305
+ * ({@link oweLoopbackFollowUp}), so a narrowing never stays on a machine the kernel records as
306
+ * running because one send failed.
307
+ */
308
+ async refresh(data, signal) {
309
+ const refused = knownLoopbackRefusal(await this.facts.deviceSandboxFacts(data.orgId, data.deviceId));
310
+ if (refused !== null)
311
+ await this.revokeRefused(data, refused);
312
+ signal.throwIfAborted();
313
+ try {
314
+ await this.services.refreshLoopback(data.orgId, data.deviceId, data.serviceId, signal);
315
+ }
316
+ catch (err) {
317
+ // a provider without services runs none, so nothing holds a port there
318
+ if (err instanceof DeviceAccessError && err.code === "capability_missing")
319
+ return;
320
+ const owed = await this.followUp(data);
321
+ this.log.warn("loopback refresh failed", {
322
+ deviceId: data.deviceId,
323
+ serviceId: data.serviceId,
324
+ followUp: owed ? (data.followUp ?? 0) + 1 : null,
325
+ err,
326
+ });
327
+ }
328
+ }
329
+ followUp(data) {
330
+ return oweLoopbackFollowUp(this.outbox, data);
331
+ }
332
+ async revokeRefused(data, cause) {
333
+ const rows = await this.db
334
+ .updateTable("device_loopback_grants")
335
+ .set({ revoked_at: sql `now()`, revoke_reason: "outside-sandbox-off" })
336
+ .where("org_id", "=", data.orgId)
337
+ .where("device_id", "=", data.deviceId)
338
+ .where("service_id", "=", data.serviceId)
339
+ .where("revoked_at", "is", null)
340
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
341
+ .execute();
342
+ // audited only: this job is the refresh their revocation would owe
343
+ for (const r of rows)
344
+ await audit(this.db.db, {
345
+ actorAccountId: null,
346
+ orgId: r.org_id,
347
+ action: "device.loopback_revoked",
348
+ target: r.device_id,
349
+ detail: {
350
+ grantId: r.id,
351
+ deviceId: r.device_id,
352
+ serviceId: r.service_id,
353
+ conversationId: r.conversation_id,
354
+ port: r.port,
355
+ reason: "outside-sandbox-off",
356
+ cause,
357
+ },
358
+ });
359
+ }
360
+ /**
361
+ * The expiry pass: marks every live grant past its `expires_at` revoked (reason `expired`,
362
+ * audited) and owes one refresh per (device, service). Returns how many it ended. Then it
363
+ * deletes the grant rows that ended more than {@link LOOPBACK_ENDED_RETENTION_DAYS} days ago
364
+ * ({@link purgeEnded}; the audit log keeps every grant and its end).
365
+ */
366
+ async expireDue() {
367
+ const ended = await asPlatform("loopback grant expiry sweep over every org", () => this.expireDueIn());
368
+ await this.purgeEnded();
369
+ return ended;
370
+ }
371
+ /**
372
+ * Deletes ended grant rows older than the retention, in batches of
373
+ * {@link LOOPBACK_PURGE_BATCH} (each its own transaction), at most
374
+ * {@link LOOPBACK_PURGE_MAX_BATCHES} per pass: the next pass takes the rest. Returns how many.
375
+ */
376
+ async purgeEnded() {
377
+ let total = 0;
378
+ for (let i = 0; i < LOOPBACK_PURGE_MAX_BATCHES; i++) {
379
+ const n = await asPlatform("loopback grant retention sweep over every org", () => this.purgeEndedBatch());
380
+ total += n;
381
+ if (n < LOOPBACK_PURGE_BATCH)
382
+ break;
383
+ }
384
+ return total;
385
+ }
386
+ async purgeEndedBatch() {
387
+ // org-filter: the retention sweep over every org's ended grants, entered under asPlatform by
388
+ // purgeEnded; nothing live is touched
389
+ const r = await this.db
390
+ .deleteFrom("device_loopback_grants")
391
+ .where("id", "in", this.db
392
+ .selectFrom("device_loopback_grants")
393
+ .select("id")
394
+ .where("revoked_at", "is not", null)
395
+ .where("revoked_at", "<", sql `now() - make_interval(days => ${LOOPBACK_ENDED_RETENTION_DAYS})`)
396
+ .limit(LOOPBACK_PURGE_BATCH))
397
+ .executeTakeFirst();
398
+ return Number(r.numDeletedRows);
399
+ }
400
+ async expireDueIn() {
401
+ // org-filter: the expiry sweep over every org's grants, entered under asPlatform by
402
+ // expireDue; each row keeps its org
403
+ const rows = await this.db
404
+ .updateTable("device_loopback_grants")
405
+ .set({ revoked_at: sql `now()`, revoke_reason: "expired" })
406
+ .where("revoked_at", "is", null)
407
+ .where("expires_at", "<=", sql `now()`)
408
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
409
+ .execute();
410
+ await endedGrants(this.db.db, this.outbox, rows, "expired", null);
411
+ return rows.length;
412
+ }
413
+ };
414
+ __decorate([
415
+ Transactional({ propagation: "mandatory" })
416
+ ], LoopbackGrants.prototype, "grantIn", null);
417
+ __decorate([
418
+ Transactional()
419
+ ], LoopbackGrants.prototype, "revoke", null);
420
+ __decorate([
421
+ Transactional({ propagation: "mandatory" })
422
+ ], LoopbackGrants.prototype, "liveLockedIn", null);
423
+ __decorate([
424
+ Transactional()
425
+ ], LoopbackGrants.prototype, "followUp", null);
426
+ __decorate([
427
+ Transactional()
428
+ ], LoopbackGrants.prototype, "revokeRefused", null);
429
+ __decorate([
430
+ Transactional()
431
+ ], LoopbackGrants.prototype, "purgeEndedBatch", null);
432
+ __decorate([
433
+ Transactional()
434
+ ], LoopbackGrants.prototype, "expireDueIn", null);
435
+ LoopbackGrants = __decorate([
436
+ Injectable(),
437
+ __param(0, Inject(KernelDb)),
438
+ __param(1, Inject(TransactionHost)),
439
+ __param(2, Inject(OutboxService)),
440
+ __param(3, Inject(LoopbackGrantLock)),
441
+ __param(4, Inject(LoopbackLivePorts)),
442
+ __param(5, Inject(PermissionFacts)),
443
+ __param(6, Inject(DeviceServices)),
444
+ __param(7, Inject(KERNEL_LOGGER))
445
+ ], LoopbackGrants);
446
+ export { LoopbackGrants };
447
+ /** Why the device's runtime cannot run anything outside its sandbox now; null when it can. */
448
+ function runtimeWhy(availability) {
449
+ if (availability.state === "unsupported")
450
+ return availability.reason;
451
+ if (availability.state === "supported")
452
+ return runtimeReportVerdict(availability.report);
453
+ return null;
454
+ }
@@ -0,0 +1,12 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ /**
3
+ * The live ports of one (device, service): what every ensure of the service sends its provider.
4
+ * A provider of its own so `DeviceServices` reads it without depending on `LoopbackGrants`
5
+ * (`sandbox/loopback-grants.ts`, whose refresh calls `DeviceServices`).
6
+ */
7
+ export declare class LoopbackLivePorts {
8
+ private readonly db;
9
+ constructor(db: KernelDb);
10
+ /** Sorted, unique, not revoked and not expired. */
11
+ livePorts(orgId: string, deviceId: string, serviceId: string): Promise<number[]>;
12
+ }
@@ -0,0 +1,43 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ /**
14
+ * The live ports of one (device, service): what every ensure of the service sends its provider.
15
+ * A provider of its own so `DeviceServices` reads it without depending on `LoopbackGrants`
16
+ * (`sandbox/loopback-grants.ts`, whose refresh calls `DeviceServices`).
17
+ */
18
+ let LoopbackLivePorts = class LoopbackLivePorts {
19
+ db;
20
+ constructor(db) {
21
+ this.db = db;
22
+ }
23
+ /** Sorted, unique, not revoked and not expired. */
24
+ async livePorts(orgId, deviceId, serviceId) {
25
+ const rows = await this.db
26
+ .selectFrom("device_loopback_grants")
27
+ .select("port")
28
+ .distinct()
29
+ .where("org_id", "=", orgId)
30
+ .where("device_id", "=", deviceId)
31
+ .where("service_id", "=", serviceId)
32
+ .where("revoked_at", "is", null)
33
+ .where("expires_at", ">", sql `now()`)
34
+ .orderBy("port")
35
+ .execute();
36
+ return rows.map((r) => r.port);
37
+ }
38
+ };
39
+ LoopbackLivePorts = __decorate([
40
+ Injectable(),
41
+ __param(0, Inject(KernelDb))
42
+ ], LoopbackLivePorts);
43
+ export { LoopbackLivePorts };
@@ -56,9 +56,10 @@ export type PermissionFullAccessGrantDecision = {
56
56
  export type PermissionGrantSource = PermissionGrantDecision["source"];
57
57
  /**
58
58
  * The kind of one boundary crossing, as `ReviewRecord.crossing` records it: a directory outside the
59
- * scope, a new host on an allowlist, running one call outside the sandbox, or a sensitive command.
59
+ * scope, a new host on an allowlist, running one call outside the sandbox, a sensitive command, or
60
+ * a device service (the browser) reaching one loopback port on the person's own device.
60
61
  */
61
- export type PermissionCrossingKind = "directory" | "host" | "outside-sandbox" | "sensitive";
62
+ export type PermissionCrossingKind = "directory" | "host" | "outside-sandbox" | "sensitive" | "loopback-port";
62
63
  /**
63
64
  * What a call grant authorizes: an exact directory and host expansion of the restricted scope, or
64
65
  * one Bash call run outside the OS sandbox (per-call sandbox escalation: full execution for that
@@ -12,6 +12,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
12
12
  import { TransactionHost } from "../infra/database/transaction-host.js";
13
13
  import { Transactional } from "../infra/database/transactional.decorator.js";
14
14
  import { OutboxService } from "../infra/outbox/outbox.service.js";
15
+ import { oweLoopbackRefreshes } from "./loopback-grant-records.js";
15
16
  import { coversHost } from "./modes.js";
16
17
  import { isExecutionMethod, isFullExecutionScope, usesOpenNetwork, } from "./operation-authority-types.js";
17
18
  import { PermissionAuthorityEpochStore } from "./permission-authority-epochs.js";
@@ -81,7 +82,7 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
81
82
  throw new Error("Ceiling publication requires its actual subject");
82
83
  this.locks.assertHeld(level, id, true);
83
84
  const vector = await this.epochs.readLocked(subject);
84
- await this.epochs.bumpLocked(level, id, required(vector[level]));
85
+ const epoch = await this.epochs.bumpLocked(level, id, required(vector[level]));
85
86
  if (invalidateFullConsent) {
86
87
  await this.db
87
88
  .updateTable("permission_authority_epochs")
@@ -103,6 +104,17 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
103
104
  for (const root of await roots.orderBy("org_id").orderBy("id").forUpdate().execute())
104
105
  await this.resetRoot(root, subject, level);
105
106
  }
107
+ // every revoking writer may have narrowed the outside-sandbox ceiling: the refresh of each
108
+ // live loopback grant set under the subject decides, and revokes the grants it now refuses
109
+ if (revoke !== false)
110
+ await oweLoopbackRefreshes(this.db.db, this.outbox, {
111
+ level,
112
+ ...(subject.orgId !== undefined && { orgId: subject.orgId }),
113
+ ...(subject.deviceId !== undefined && { deviceId: subject.deviceId }),
114
+ ...(subject.rootConversationId !== undefined && {
115
+ rootConversationId: subject.rootConversationId,
116
+ }),
117
+ }, `c${level}-${id}-${epoch}`);
106
118
  if (!revoke)
107
119
  return;
108
120
  // Acknowledged background starts stay revocable by every actual revoking writer (deletion is
@@ -78,6 +78,10 @@ export declare class PermissionFacts {
78
78
  */
79
79
  layer?: "ceilings" | "lifecycle"): Promise<{
80
80
  box: DeviceSandbox;
81
+ /** The provider's support the box was computed with (null: none known yet, or `lifecycle`). */
82
+ support: import("@capybara-hq/plugin-sdk").SandboxPermissionSupport | null;
83
+ /** The device's permission availability the support was read from. */
84
+ availability: PermissionAvailability;
81
85
  hostCeiling: HostGrantCeiling;
82
86
  /** The org's effective hosts: what a device's own host list may narrow, never add to. */
83
87
  orgHosts: string[];
@@ -137,6 +137,10 @@ let PermissionFacts = class PermissionFacts {
137
137
  const hostCeiling = hostGrantCeiling(box, platform, orgLayer);
138
138
  return {
139
139
  box,
140
+ /** The provider's support the box was computed with (null: none known yet, or `lifecycle`). */
141
+ support,
142
+ /** The device's permission availability the support was read from. */
143
+ availability: current,
140
144
  hostCeiling,
141
145
  /** The org's effective hosts: what a device's own host list may narrow, never add to. */
142
146
  orgHosts: orgHostsOf(platform, orgLayer),
@@ -28,6 +28,12 @@ export declare const REVIEW_PURPOSE = "review";
28
28
  * prompt sent is {@link reviewSystemPrompt}, which names the call's data tag.
29
29
  */
30
30
  export declare const REVIEW_SYSTEM_PROMPT: string;
31
+ /**
32
+ * The fixed start of the system prompt of a loopback port review (`kind: "loopback-port"`; model
33
+ * facing, English): the request is a device service's to reach one port of the person's own
34
+ * machine, not a command. Command, write and read reviews keep {@link REVIEW_SYSTEM_PROMPT}.
35
+ */
36
+ export declare const LOOPBACK_REVIEW_SYSTEM_PROMPT: string;
31
37
  /** The answer cap of the classifier call (one sentence is far less). */
32
38
  export declare const REVIEW_MAX_OUTPUT_TOKENS = 300;
33
39
  /** The marker a command (or path) cut to fit the review model's context ends with. */
@@ -38,16 +44,22 @@ export declare const REVIEW_TRUNCATED_ASK_REASON = "The command is too long for
38
44
  export declare const REVIEW_ASK_REASON = "The command review could not decide; this command needs the person's approval.";
39
45
  /** The reason prefix when a `model.request` policy hook denies the classifier call. */
40
46
  export declare const REVIEW_UNAVAILABLE_PREFIX = "Command review is unavailable: ";
41
- /** The system prompt of one classifier call: {@link REVIEW_SYSTEM_PROMPT} naming its data tag. */
42
- export declare function reviewSystemPrompt(tag: string): string;
47
+ /**
48
+ * The system prompt of one classifier call: {@link REVIEW_SYSTEM_PROMPT} naming its data tag, or
49
+ * for a loopback port review {@link LOOPBACK_REVIEW_SYSTEM_PROMPT}.
50
+ */
51
+ export declare function reviewSystemPrompt(tag: string, kind?: ReviewClassifierInput["kind"]): string;
43
52
  /** A fresh data tag (`review-` and 16 hex digits): text inside the tags cannot forge the structure. */
44
53
  export declare function newReviewTag(): string;
45
54
  /** What the classifier is asked about. */
46
55
  export interface ReviewClassifierInput {
47
56
  permissionCandidate?: PermissionCandidate;
48
57
  mode: "auto" | "sandbox";
49
- /** The command for `Bash`, the path for a file write or a file read. */
50
- kind: "command" | "write" | "read";
58
+ /**
59
+ * The command for `Bash`, the path for a file write or a file read, or a device service's
60
+ * request to reach a loopback port on the person's own device (`loopback`).
61
+ */
62
+ kind: "command" | "write" | "read" | "loopback-port";
51
63
  text: string;
52
64
  /** The directory the command runs in (the workspace for a file write). */
53
65
  cwd: string;
@@ -64,6 +76,16 @@ export interface ReviewClassifierInput {
64
76
  subAgent?: true;
65
77
  credential?: true;
66
78
  };
79
+ /**
80
+ * A loopback port request (`kind: "loopback-port"`): the device service, the port, the page it
81
+ * asked for (null when none was given) and whether the port is a well-known database port.
82
+ */
83
+ loopback?: {
84
+ service: string;
85
+ port: number;
86
+ url: string | null;
87
+ database: boolean;
88
+ };
67
89
  }
68
90
  /**
69
91
  * The user message of the classifier call: the facts, the untrusted command or path, the rule