@capybara-hq/kernel 0.1.0-rc.49 → 0.1.0-rc.50

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 (128) hide show
  1. package/dist/admin/admin.schemas.d.ts +0 -6
  2. package/dist/background/launch.d.ts +7 -61
  3. package/dist/background/launch.js +8 -133
  4. package/dist/background/poll.job.d.ts +19 -23
  5. package/dist/background/poll.job.js +30 -66
  6. package/dist/background/render.d.ts +9 -0
  7. package/dist/background/render.js +19 -0
  8. package/dist/background/session.d.ts +3 -66
  9. package/dist/background/session.js +3 -114
  10. package/dist/background/stop.d.ts +26 -33
  11. package/dist/background/stop.js +59 -90
  12. package/dist/background/store.d.ts +26 -60
  13. package/dist/background/store.js +23 -108
  14. package/dist/background/tasks.service.d.ts +9 -29
  15. package/dist/background/tasks.service.js +18 -115
  16. package/dist/catalog/marketplaces.service.d.ts +1 -1
  17. package/dist/channels/cards.d.ts +3 -0
  18. package/dist/channels/cards.js +29 -2
  19. package/dist/channels/phrases.d.ts +35 -0
  20. package/dist/channels/phrases.js +32 -0
  21. package/dist/config/load.d.ts +3 -10
  22. package/dist/config/load.js +26 -21
  23. package/dist/config/schema.js +3 -3
  24. package/dist/conversations/events.d.ts +45 -2
  25. package/dist/conversations/events.js +44 -4
  26. package/dist/db/kernel-schema.d.ts +9 -4
  27. package/dist/devices/devices.service.js +1 -1
  28. package/dist/devices/errors.d.ts +5 -0
  29. package/dist/devices/errors.js +5 -0
  30. package/dist/devices/project-rules.d.ts +2 -2
  31. package/dist/errors.d.ts +9 -11
  32. package/dist/errors.js +9 -11
  33. package/dist/identity/settings.d.ts +4 -17
  34. package/dist/identity/settings.js +9 -32
  35. package/dist/infra/config/kernel-config.service.js +2 -9
  36. package/dist/infra/outbox/registry.d.ts +13 -0
  37. package/dist/infra/outbox/registry.js +8 -0
  38. package/dist/local-devices/device-auth.controller.d.ts +1 -1
  39. package/dist/local-devices/device-auth.controller.js +1 -1
  40. package/dist/local-devices/device-auth.d.ts +4 -3
  41. package/dist/local-devices/device-auth.js +1 -1
  42. package/dist/local-devices/device-policy.service.d.ts +6 -6
  43. package/dist/local-devices/device-routes.d.ts +4 -2
  44. package/dist/local-devices/device-routes.js +7 -6
  45. package/dist/local-devices/instance-bindings.d.ts +4 -4
  46. package/dist/local-devices/instance-bindings.js +2 -2
  47. package/dist/local-devices/local-device-gateway.d.ts +12 -12
  48. package/dist/local-devices/local-device-gateway.js +94 -129
  49. package/dist/local-devices/local-device-provider.d.ts +19 -87
  50. package/dist/local-devices/local-device-provider.js +43 -158
  51. package/dist/local-devices/local-devices.module.d.ts +4 -5
  52. package/dist/local-devices/local-devices.module.js +6 -9
  53. package/dist/local-devices/machines.d.ts +6 -6
  54. package/dist/local-devices/machines.js +4 -4
  55. package/dist/local-devices/owner-report.d.ts +3 -3
  56. package/dist/local-devices/owner-report.js +4 -4
  57. package/dist/local-devices/owner-reports.js +2 -2
  58. package/dist/local-devices/policy-summary.js +2 -2
  59. package/dist/local-devices/relay.d.ts +12 -25
  60. package/dist/local-devices/relay.js +17 -31
  61. package/dist/orgs/settings.controller.d.ts +1 -4
  62. package/dist/orgs/settings.controller.js +3 -3
  63. package/dist/orgs/settings.service.d.ts +7 -21
  64. package/dist/orgs/settings.service.js +16 -40
  65. package/dist/overrides.d.ts +3 -3
  66. package/dist/platform/ops/admin.ops.js +6 -8
  67. package/dist/platform/ops/org-settings.ops.js +4 -4
  68. package/dist/platform/ops/orgs.ops.js +0 -1
  69. package/dist/runtime/maintenance.d.ts +1 -1
  70. package/dist/runtime/maintenance.js +7 -1
  71. package/dist/runtime/run-steps.js +2 -2
  72. package/dist/sandbox/held-operations.d.ts +7 -0
  73. package/dist/sandbox/held-operations.js +25 -1
  74. package/dist/sandbox/leases.d.ts +6 -3
  75. package/dist/sandbox/leases.js +16 -10
  76. package/dist/sandbox/legacy-retirement.d.ts +0 -19
  77. package/dist/sandbox/legacy-retirement.js +6 -37
  78. package/dist/sandbox/managed-device-context.d.ts +12 -0
  79. package/dist/sandbox/managed-device-context.js +49 -1
  80. package/dist/sandbox/modes.d.ts +9 -8
  81. package/dist/sandbox/modes.js +4 -15
  82. package/dist/sandbox/operation-authority-types.d.ts +18 -1
  83. package/dist/sandbox/operation-authority-types.js +20 -1
  84. package/dist/sandbox/operation-authority.d.ts +14 -0
  85. package/dist/sandbox/operation-authority.js +120 -18
  86. package/dist/sandbox/operation-intents.d.ts +43 -0
  87. package/dist/sandbox/operation-intents.js +107 -4
  88. package/dist/sandbox/operation-reconcile.job.d.ts +12 -1
  89. package/dist/sandbox/operation-reconcile.job.js +53 -6
  90. package/dist/sandbox/permission-call-grants.d.ts +4 -0
  91. package/dist/sandbox/permission-call-grants.js +32 -3
  92. package/dist/sandbox/permission-call-types.d.ts +27 -2
  93. package/dist/sandbox/permission-ceiling-writes.js +2 -1
  94. package/dist/sandbox/permission-context-types.d.ts +2 -2
  95. package/dist/sandbox/permission-context-types.js +2 -2
  96. package/dist/sandbox/permission-facts.js +10 -2
  97. package/dist/sandbox/platform-full-access.d.ts +8 -26
  98. package/dist/sandbox/platform-full-access.js +8 -20
  99. package/dist/sandbox/review/classifier.d.ts +2 -2
  100. package/dist/sandbox/review/classifier.js +18 -5
  101. package/dist/sandbox/review/permission-candidate.d.ts +59 -3
  102. package/dist/sandbox/review/permission-candidate.js +192 -25
  103. package/dist/sandbox/review/review.service.d.ts +18 -0
  104. package/dist/sandbox/review/review.service.js +158 -12
  105. package/dist/sandbox/sandbox.service.d.ts +71 -47
  106. package/dist/sandbox/sandbox.service.js +234 -133
  107. package/dist/tools/approvals.service.d.ts +6 -1
  108. package/dist/tools/approvals.service.js +10 -0
  109. package/dist/tools/builtins/builtin-tools.d.ts +1 -4
  110. package/dist/tools/builtins/builtin-tools.js +13 -18
  111. package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
  112. package/dist/tools/builtins/sandbox/bash.js +92 -270
  113. package/dist/tools/builtins/sandbox/common.d.ts +15 -9
  114. package/dist/tools/builtins/sandbox/common.js +55 -19
  115. package/dist/tools/builtins/sandbox/device-owner.d.ts +13 -0
  116. package/dist/tools/builtins/sandbox/device-owner.js +14 -0
  117. package/dist/tools/builtins/sandbox/task-list.js +2 -2
  118. package/dist/tools/builtins/sandbox/task-output.d.ts +14 -57
  119. package/dist/tools/builtins/sandbox/task-output.js +88 -210
  120. package/dist/tools/builtins/sandbox/task-stop.d.ts +2 -2
  121. package/dist/tools/builtins/sandbox/task-stop.js +15 -26
  122. package/dist/tools/pipeline.d.ts +31 -2
  123. package/dist/tools/pipeline.js +273 -43
  124. package/dist/tools/registry.d.ts +7 -0
  125. package/package.json +4 -4
  126. package/src/migrations/0162_permission_call_escalation.sql +9 -0
  127. package/dist/background/status.d.ts +0 -35
  128. package/dist/background/status.js +0 -57
@@ -28,14 +28,13 @@ export interface BackgroundTaskRow {
28
28
  description: string;
29
29
  command: string;
30
30
  /**
31
- * The session id (the pid `setsid` started). Null while the launch is reserved but has not
32
- * started: readers that act on the process (the poller, stops) skip such a row.
31
+ * A legacy row's recorded session id; null on every managed row (a task is never identified by
32
+ * a SID). Kept for the retirement gate's enumeration and display only.
33
33
  */
34
34
  sid: string | null;
35
35
  /**
36
- * The output file: absolute once the task started (`markStarted` records it under its
37
- * instance's workspace root), relative to the workspace root while reserved
38
- * (`taskOutputFile` in launch.ts).
36
+ * The output file: absolute on a managed row; a legacy row reserved but never started kept a
37
+ * relative one (`taskOutputFile` in launch.ts).
39
38
  */
40
39
  outputPath: string;
41
40
  status: BackgroundTaskStatus;
@@ -44,7 +43,7 @@ export interface BackgroundTaskRow {
44
43
  startedAt: Date;
45
44
  finishedAt: Date | null;
46
45
  deadlineAt: Date;
47
- /** The sandbox instance the task started in; null while reserved, like `sid`. */
46
+ /** The sandbox instance the task started in; null until a managed start is acknowledged. */
48
47
  sandboxCreatedAt: Date | null;
49
48
  /** Marked lost while its process may still exist. */
50
49
  killPending: boolean;
@@ -108,8 +107,6 @@ export type ManagedReservation = {
108
107
  kind: "full";
109
108
  };
110
109
  export type BackgroundTaskInsert = Omit<BackgroundTaskRow, "status" | "finishedAt" | "exitCode" | "lostReason" | "killPending" | "readOffset" | "stoppingAt" | "launchState" | "operationId" | "workingRoot" | "retainUntil" | "executionRef" | "instanceId" | "instanceGeneration" | "cancelRequestedAt" | "cancelRequestedBy">;
111
- /** A launch's reservation: the row before the command started (no `sid`, no instance yet). */
112
- export type BackgroundTaskReservation = Omit<BackgroundTaskInsert, "sid" | "sandboxCreatedAt">;
113
110
  /**
114
111
  * How long a stop's claim holds: a claim older than this is abandoned (its stopper died), so the
115
112
  * poller checks the task again and another stop may claim it. Longer than any stop takes (the
@@ -121,24 +118,17 @@ export declare const STOP_CLAIM_TTL_MS: number;
121
118
  * `run_in_background`. The store only reads and writes rows; the launch, the poller and the tools
122
119
  * that drive them are other providers.
123
120
  *
124
- * A launch first reserves its row ({@link BackgroundTaskStore.reserve}: `running`, `sid` null),
125
- * then starts the command and sets `sid` ({@link BackgroundTaskStore.markStarted}), or finishes
126
- * the row as `failed` ({@link BackgroundTaskStore.failLaunch}). A running row with a null `sid`
127
- * counts against `maxTasks` but has no process to check or stop: the poller and stops must skip
128
- * it (the launch that reserved it settles it; one left over by a launch that died is failed by the
129
- * poller, {@link BackgroundTaskStore.failAbandonedLaunches}).
121
+ * A launch reserves its managed row ({@link BackgroundTaskStore.reserveManaged}: `running`,
122
+ * `pending`) before the start is dispatched; the operation facade then moves its durable launch
123
+ * state. No launch writes a legacy (SID) row any more: those left from before are only finished
124
+ * here and retired by `RetireLegacyTasksJob`; a legacy reservation that never started is failed
125
+ * by the poller ({@link BackgroundTaskStore.failAbandonedLaunches}).
130
126
  */
131
127
  export declare class BackgroundTaskStore {
132
128
  private readonly db;
133
129
  readonly txHost: TransactionHost;
134
130
  private readonly launchLock;
135
131
  constructor(db: KernelDb, txHost: TransactionHost, launchLock: BackgroundLaunchLock);
136
- /**
137
- * Reserves a launch: under the root conversation's launch lock, counts the running tasks of
138
- * `row.sandboxConversationId` and inserts `row` as `running` (no `sid`) when fewer than
139
- * `maxTasks` run. False (nothing written) when that conversation tree already runs `maxTasks`.
140
- */
141
- reserve(row: BackgroundTaskReservation, maxTasks: number): Promise<boolean>;
142
132
  /**
143
133
  * Reserves a managed launch (permission runtime cutover phase 8.2) under the root conversation's
144
134
  * launch lock, before anything is dispatched: the task id, its stable operation id, the
@@ -153,21 +143,6 @@ export declare class BackgroundTaskStore {
153
143
  * A dispatched row is never failed here: a null reference is no proof that nothing launched.
154
144
  */
155
145
  failManagedPreEffect(id: string, reason: string, executionId: string): Promise<boolean>;
156
- /**
157
- * Records the started command of a reserved row: `started`, or `stopping` when a stop claimed the
158
- * reservation meanwhile (the launch then kills the command and finishes the row with
159
- * {@link finishStoppedLaunch}); false when the row is no longer running.
160
- */
161
- markStarted(id: string, to: {
162
- sid: string;
163
- sandboxCreatedAt: Date;
164
- outputPath?: string;
165
- }): Promise<"started" | "stopping" | false>;
166
- /**
167
- * Finishes a launch whose reservation a stop claimed, once the launch killed what it started:
168
- * `stopped`. No `background_task_finished` event: the launching call reports it itself.
169
- */
170
- finishStoppedLaunch(id: string): Promise<void>;
171
146
  /**
172
147
  * Claims a running task for a stop (`stopping_at`): false when it is no longer running or another
173
148
  * live stop claimed it ({@link STOP_CLAIM_TTL_MS}). While claimed the poller leaves it alone.
@@ -175,22 +150,16 @@ export declare class BackgroundTaskStore {
175
150
  claimStop(id: string): Promise<boolean>;
176
151
  /** Gives up a stop's claim (the stop failed while the sandbox runs: the task keeps running). */
177
152
  releaseStop(id: string): Promise<void>;
178
- /**
179
- * Finishes a reserved row whose launch failed as `failed`, with `reason` in `lost_reason` (and a
180
- * stop's claim cleared); a row that already has its sid (the command started and is tracked) is
181
- * left as it is. No `background_task_finished` event: the launching call reports the failure
182
- * itself.
183
- */
184
- failLaunch(id: string, reason: string): Promise<void>;
185
153
  /**
186
154
  * Finishes as `failed` (`lost_reason` `launch_abandoned`) every reservation that started before
187
- * `before`, never got its sid and is not claimed by a live stop: the launch that reserved it died
188
- * (a crashed replica). A stop's claim older than {@link STOP_CLAIM_TTL_MS} does not hold it: a
189
- * stop only claims a reservation and leaves the rest to the launch, so a dead launch would keep
190
- * it (and its slot of `maxTasks`) forever. Conditional on `sid` still null, so a launch
191
- * completing at that moment wins. No `background_task_finished` event: the command never
192
- * started and the model never saw its id. Returns the rows it finished (their owner and sandbox
193
- * conversations, for the caller's `changed: "background"` frames).
155
+ * `before`, never dispatched (a managed `pending` row, or a legacy row that never got its sid)
156
+ * and is not claimed by a live stop: the launch that reserved it died (a crashed replica). A
157
+ * stop's claim older than {@link STOP_CLAIM_TTL_MS} does not hold it: a stop only claims a
158
+ * reservation and leaves the rest to the launch, so a dead launch would keep it (and its slot of
159
+ * `maxTasks`) forever. Conditional on `pending`, so a dispatch at that moment wins. No
160
+ * `background_task_finished` event: the command never started and the model never saw its id.
161
+ * Returns the rows it finished (their owner and sandbox conversations, for the caller's
162
+ * `changed: "background"` frames).
194
163
  */
195
164
  failAbandonedLaunches(before: Date): Promise<{
196
165
  id: string;
@@ -198,8 +167,9 @@ export declare class BackgroundTaskStore {
198
167
  sandboxConversationId: string;
199
168
  }[]>;
200
169
  /**
201
- * Inserts a legacy row. `legacyDispatch` (0157) defaults to `unknown`: a row is "never
202
- * dispatched" only when its reservation says so.
170
+ * Inserts a legacy row: no launch writes one any more; only rows from before (and tests of their
171
+ * retirement) exist. `legacyDispatch` (0157) defaults to `unknown`: a row is "never dispatched"
172
+ * only when its reservation says so.
203
173
  */
204
174
  insert(row: BackgroundTaskInsert, legacyDispatch?: "unknown" | "reserved"): Promise<void>;
205
175
  /** The managed task launched by start operation `operationId`, if its row still exists. */
@@ -213,11 +183,12 @@ export declare class BackgroundTaskStore {
213
183
  /** The running tasks of one root conversation's tree, oldest first. */
214
184
  runningIn(sandboxConversationId: string): Promise<BackgroundTaskRow[]>;
215
185
  /**
216
- * Every running task that has started (its `sid` is set) and no live stop claimed, across
217
- * sandboxes, oldest first: what the poller checks. A reservation still launching (`sid` null) is
218
- * left to its launch, a claimed task to its stop.
186
+ * Every running legacy task that started in an instance and no live stop claimed, across
187
+ * sandboxes, oldest first: what the poller finishes once its instance is gone (never by an
188
+ * exec). A legacy reservation that never started is failed as abandoned, a claimed task is left
189
+ * to its stop.
219
190
  */
220
- runningStarted(): Promise<BackgroundTaskRow[]>;
191
+ runningLegacy(): Promise<BackgroundTaskRow[]>;
221
192
  /**
222
193
  * Every running acknowledged managed task with no live stop claim, oldest first: what the
223
194
  * poller checks by exact status.
@@ -269,11 +240,6 @@ export declare class BackgroundTaskStore {
269
240
  }): Promise<boolean>;
270
241
  /** Moves the read offset forward only (a concurrent reader never moves it back). */
271
242
  advanceOffset(id: string, to: number): Promise<void>;
272
- /**
273
- * Finished tasks of a device whose process may still exist (any conversation's: they
274
- * share the instance).
275
- */
276
- pendingKills(deviceId: string): Promise<BackgroundTaskRow[]>;
277
243
  clearKill(ids: string[]): Promise<void>;
278
244
  /**
279
245
  * Deletes finished tasks that ended before `before`; a running one is never deleted, nor a
@@ -63,12 +63,11 @@ const unclaimed = sql `(stopping_at IS NULL OR stopping_at < now() - ${STOP_CLAI
63
63
  * `run_in_background`. The store only reads and writes rows; the launch, the poller and the tools
64
64
  * that drive them are other providers.
65
65
  *
66
- * A launch first reserves its row ({@link BackgroundTaskStore.reserve}: `running`, `sid` null),
67
- * then starts the command and sets `sid` ({@link BackgroundTaskStore.markStarted}), or finishes
68
- * the row as `failed` ({@link BackgroundTaskStore.failLaunch}). A running row with a null `sid`
69
- * counts against `maxTasks` but has no process to check or stop: the poller and stops must skip
70
- * it (the launch that reserved it settles it; one left over by a launch that died is failed by the
71
- * poller, {@link BackgroundTaskStore.failAbandonedLaunches}).
66
+ * A launch reserves its managed row ({@link BackgroundTaskStore.reserveManaged}: `running`,
67
+ * `pending`) before the start is dispatched; the operation facade then moves its durable launch
68
+ * state. No launch writes a legacy (SID) row any more: those left from before are only finished
69
+ * here and retired by `RetireLegacyTasksJob`; a legacy reservation that never started is failed
70
+ * by the poller ({@link BackgroundTaskStore.failAbandonedLaunches}).
72
71
  */
73
72
  let BackgroundTaskStore = class BackgroundTaskStore {
74
73
  db;
@@ -79,19 +78,6 @@ let BackgroundTaskStore = class BackgroundTaskStore {
79
78
  this.txHost = txHost;
80
79
  this.launchLock = launchLock;
81
80
  }
82
- /**
83
- * Reserves a launch: under the root conversation's launch lock, counts the running tasks of
84
- * `row.sandboxConversationId` and inserts `row` as `running` (no `sid`) when fewer than
85
- * `maxTasks` run. False (nothing written) when that conversation tree already runs `maxTasks`.
86
- */
87
- async reserve(row, maxTasks) {
88
- await this.launchLock.lock(row.sandboxConversationId);
89
- if ((await this.countRunning(row.sandboxConversationId)) >= maxTasks)
90
- return false;
91
- // not admitted for dispatch yet (0157): the launch's freeze check marks it `dispatched`
92
- await this.insert({ ...row, sid: null, sandboxCreatedAt: null }, "reserved");
93
- return true;
94
- }
95
81
  /**
96
82
  * Reserves a managed launch (permission runtime cutover phase 8.2) under the root conversation's
97
83
  * launch lock, before anything is dispatched: the task id, its stable operation id, the
@@ -165,41 +151,6 @@ let BackgroundTaskStore = class BackgroundTaskStore {
165
151
  .executeTakeFirst();
166
152
  return Number(r.numUpdatedRows) > 0;
167
153
  }
168
- /**
169
- * Records the started command of a reserved row: `started`, or `stopping` when a stop claimed the
170
- * reservation meanwhile (the launch then kills the command and finishes the row with
171
- * {@link finishStoppedLaunch}); false when the row is no longer running.
172
- */
173
- async markStarted(id, to) {
174
- const r = await this.db
175
- .updateTable("background_tasks")
176
- .set({
177
- sid: to.sid,
178
- sandbox_created_at: to.sandboxCreatedAt,
179
- ...(to.outputPath !== undefined && { output_path: to.outputPath }),
180
- })
181
- .where("id", "=", id)
182
- .where("status", "=", "running")
183
- .where("sid", "is", null)
184
- .where("launch_state", "=", "legacy")
185
- .returning("stopping_at")
186
- .executeTakeFirst();
187
- if (!r)
188
- return false;
189
- return r.stopping_at === null ? "started" : "stopping";
190
- }
191
- /**
192
- * Finishes a launch whose reservation a stop claimed, once the launch killed what it started:
193
- * `stopped`. No `background_task_finished` event: the launching call reports it itself.
194
- */
195
- async finishStoppedLaunch(id) {
196
- await this.db
197
- .updateTable("background_tasks")
198
- .set({ status: "stopped", finished_at: sql `now()`, stopping_at: null })
199
- .where("id", "=", id)
200
- .where("status", "=", "running")
201
- .execute();
202
- }
203
154
  /**
204
155
  * Claims a running task for a stop (`stopping_at`): false when it is no longer running or another
205
156
  * live stop claimed it ({@link STOP_CLAIM_TTL_MS}). While claimed the poller leaves it alone.
@@ -223,38 +174,16 @@ let BackgroundTaskStore = class BackgroundTaskStore {
223
174
  .where("status", "=", "running")
224
175
  .execute();
225
176
  }
226
- /**
227
- * Finishes a reserved row whose launch failed as `failed`, with `reason` in `lost_reason` (and a
228
- * stop's claim cleared); a row that already has its sid (the command started and is tracked) is
229
- * left as it is. No `background_task_finished` event: the launching call reports the failure
230
- * itself.
231
- */
232
- async failLaunch(id, reason) {
233
- await this.db
234
- .updateTable("background_tasks")
235
- .set({
236
- status: "failed",
237
- finished_at: sql `now()`,
238
- lost_reason: reason,
239
- stopping_at: null,
240
- })
241
- .where("id", "=", id)
242
- .where("status", "=", "running")
243
- // only a reservation that never started: a row with its sid is tracked by the poller
244
- .where("sid", "is", null)
245
- // a managed row settles through its durable launch state only
246
- .where("launch_state", "=", "legacy")
247
- .execute();
248
- }
249
177
  /**
250
178
  * Finishes as `failed` (`lost_reason` `launch_abandoned`) every reservation that started before
251
- * `before`, never got its sid and is not claimed by a live stop: the launch that reserved it died
252
- * (a crashed replica). A stop's claim older than {@link STOP_CLAIM_TTL_MS} does not hold it: a
253
- * stop only claims a reservation and leaves the rest to the launch, so a dead launch would keep
254
- * it (and its slot of `maxTasks`) forever. Conditional on `sid` still null, so a launch
255
- * completing at that moment wins. No `background_task_finished` event: the command never
256
- * started and the model never saw its id. Returns the rows it finished (their owner and sandbox
257
- * conversations, for the caller's `changed: "background"` frames).
179
+ * `before`, never dispatched (a managed `pending` row, or a legacy row that never got its sid)
180
+ * and is not claimed by a live stop: the launch that reserved it died (a crashed replica). A
181
+ * stop's claim older than {@link STOP_CLAIM_TTL_MS} does not hold it: a stop only claims a
182
+ * reservation and leaves the rest to the launch, so a dead launch would keep it (and its slot of
183
+ * `maxTasks`) forever. Conditional on `pending`, so a dispatch at that moment wins. No
184
+ * `background_task_finished` event: the command never started and the model never saw its id.
185
+ * Returns the rows it finished (their owner and sandbox conversations, for the caller's
186
+ * `changed: "background"` frames).
258
187
  */
259
188
  async failAbandonedLaunches(before) {
260
189
  const r = await this.db
@@ -283,8 +212,9 @@ let BackgroundTaskStore = class BackgroundTaskStore {
283
212
  }));
284
213
  }
285
214
  /**
286
- * Inserts a legacy row. `legacyDispatch` (0157) defaults to `unknown`: a row is "never
287
- * dispatched" only when its reservation says so.
215
+ * Inserts a legacy row: no launch writes one any more; only rows from before (and tests of their
216
+ * retirement) exist. `legacyDispatch` (0157) defaults to `unknown`: a row is "never dispatched"
217
+ * only when its reservation says so.
288
218
  */
289
219
  async insert(row, legacyDispatch = "unknown") {
290
220
  await this.db
@@ -352,16 +282,18 @@ let BackgroundTaskStore = class BackgroundTaskStore {
352
282
  return rows.map(toRow);
353
283
  }
354
284
  /**
355
- * Every running task that has started (its `sid` is set) and no live stop claimed, across
356
- * sandboxes, oldest first: what the poller checks. A reservation still launching (`sid` null) is
357
- * left to its launch, a claimed task to its stop.
285
+ * Every running legacy task that started in an instance and no live stop claimed, across
286
+ * sandboxes, oldest first: what the poller finishes once its instance is gone (never by an
287
+ * exec). A legacy reservation that never started is failed as abandoned, a claimed task is left
288
+ * to its stop.
358
289
  */
359
- async runningStarted() {
290
+ async runningLegacy() {
360
291
  const rows = await this.db
361
292
  .selectFrom("background_tasks")
362
293
  .selectAll()
363
294
  .where("status", "=", "running")
364
- .where("sid", "is not", null)
295
+ .where("launch_state", "=", "legacy")
296
+ .where("sandbox_created_at", "is not", null)
365
297
  .where(unclaimed)
366
298
  .orderBy("started_at", "asc")
367
299
  .orderBy("id", "asc")
@@ -533,20 +465,6 @@ let BackgroundTaskStore = class BackgroundTaskStore {
533
465
  .where(sql `read_offset < ${to}`)
534
466
  .execute();
535
467
  }
536
- /**
537
- * Finished tasks of a device whose process may still exist (any conversation's: they
538
- * share the instance).
539
- */
540
- async pendingKills(deviceId) {
541
- const rows = await this.db
542
- .selectFrom("background_tasks")
543
- .selectAll()
544
- .where("device_id", "=", deviceId)
545
- .where("kill_pending", "=", true)
546
- .orderBy("started_at", "asc")
547
- .execute();
548
- return rows.map(toRow);
549
- }
550
468
  async clearKill(ids) {
551
469
  if (ids.length === 0)
552
470
  return;
@@ -571,9 +489,6 @@ let BackgroundTaskStore = class BackgroundTaskStore {
571
489
  return Number(r.numDeletedRows);
572
490
  }
573
491
  };
574
- __decorate([
575
- Transactional()
576
- ], BackgroundTaskStore.prototype, "reserve", null);
577
492
  __decorate([
578
493
  Transactional()
579
494
  ], BackgroundTaskStore.prototype, "reserveManaged", null);
@@ -25,13 +25,14 @@ export interface BackgroundTaskView {
25
25
  stopping: boolean;
26
26
  }
27
27
  /**
28
- * Why a task's output cannot be read live: `starting` (the launch has not recorded the task's
29
- * session yet), `not_started` (the launch failed: the task never ran, its `lostReason` says why),
30
- * `device_offline` (the local device's machine is not connected), `suspended` (the instance is
31
- * suspended; reading never resumes it), `rebuilt` (the instance the task ran in is gone, and its
32
- * files with it), `output_missing` (the instance runs but the output file is gone), `no_access`
33
- * (the conversation's owner may no longer use the device), `unavailable` (the device's provider
34
- * is not loaded), `read_failed` (the read command failed).
28
+ * Why a task's output cannot be read live: `starting` (the start has not been acknowledged with
29
+ * the task's exact ref yet), `not_started` (the launch failed: the task never ran, its
30
+ * `lostReason` says why), `device_offline` (the local device's machine is not connected),
31
+ * `suspended` (the instance is suspended; reading never resumes it), `rebuilt` (the instance the
32
+ * task ran in is gone, and its files with it), `output_missing` (the instance runs but the output
33
+ * is gone), `no_access` (the conversation's owner may no longer use the device), `unavailable`
34
+ * (the device's provider is not loaded), `read_failed` (the exact read failed, or the task is a
35
+ * finished legacy one, whose output is never read live).
35
36
  */
36
37
  export type OutputUnavailableReason = "starting" | "not_started" | "device_offline" | "suspended" | "rebuilt" | "output_missing" | "no_access" | "unavailable" | "read_failed";
37
38
  /** Why the live read failed, and where the task ran: a `local` device or a `cloud` sandbox. */
@@ -63,17 +64,7 @@ export declare class BackgroundTasks {
63
64
  private readonly eventLog;
64
65
  private readonly db;
65
66
  private readonly devices;
66
- /**
67
- * The paired activation gate: once on, a legacy (SID) task is never read or stopped by a raw
68
- * exec (the retirement gate owns it); a managed task always goes by its exact ref.
69
- */
70
- private readonly activation?;
71
- constructor(access: Pick<ConversationAccess, "isAccessible">, store: Pick<BackgroundTaskStore, "listFor" | "get">, stopper: Pick<BackgroundTaskStopper, "stop">, sandbox: Pick<SandboxService, "availableFor" | "ifRunning">, eventLog: Pick<EventLog, "findByIdem">, db: KernelDb, devices: Pick<ConversationDevices, "forTool">,
72
- /**
73
- * The paired activation gate: once on, a legacy (SID) task is never read or stopped by a raw
74
- * exec (the retirement gate owns it); a managed task always goes by its exact ref.
75
- */
76
- activation?: boolean | undefined);
67
+ constructor(access: Pick<ConversationAccess, "isAccessible">, store: Pick<BackgroundTaskStore, "listFor" | "get">, stopper: Pick<BackgroundTaskStopper, "stop">, sandbox: Pick<SandboxService, "availableFor" | "ifRunning">, eventLog: Pick<EventLog, "findByIdem">, db: KernelDb, devices: Pick<ConversationDevices, "forTool">);
77
68
  /**
78
69
  * The conversation and every sub-agent conversation below it (grandchildren too: their tasks run
79
70
  * in the root's sandbox, agent map spec §6); `conversation.not_found` when not visible.
@@ -113,14 +104,3 @@ export declare class BackgroundTasks {
113
104
  */
114
105
  private readManaged;
115
106
  }
116
- /**
117
- * Prints `size <bytes>` and `out <base64 of the last `tail` bytes>`, or `missing` when the output
118
- * file is not there. Relative to the workspace root; POSIX tools only (`wc -c`, `tail -c`,
119
- * `base64`, `tr`), so it reads the same on Linux and macOS.
120
- */
121
- export declare function tailScript(id: string, tail: number): string;
122
- /**
123
- * Decodes {@link tailScript}'s output (`missing`: no output file; null: unreadable); a cut that
124
- * splits a UTF-8 character drops its tail bytes.
125
- */
126
- export declare function parseTail(stdout: string, tail: number): Omit<BackgroundTaskOutput, "source"> | "missing" | null;
@@ -7,8 +7,8 @@ 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 { DeviceProtocolError, isSandboxGoneError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, rootsOf, ToolError, } from "@capybara-hq/plugin-sdk";
11
- import { Inject, Injectable, Optional } from "@nestjs/common";
10
+ import { DeviceProtocolError, isSandboxGoneError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, ToolError, } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
12
  import { ConversationAccess } from "../conversations/access.js";
13
13
  import { EventLog } from "../conversations/event-log.js";
14
14
  import { conversationTree } from "../conversations/tree.js";
@@ -17,19 +17,17 @@ import { ApiError } from "../errors.js";
17
17
  import { audit } from "../identity/audit.js";
18
18
  import { KernelDb } from "../infra/database/kernel-db.js";
19
19
  import { rootConversationOf } from "../runtime/subagents/child.js";
20
- import { PERMISSION_CONTEXT_ACTIVATION } from "../sandbox/permission-context-types.js";
21
20
  import { retirementPending, SandboxService } from "../sandbox/sandbox.service.js";
22
21
  import { UUID_RE } from "../ui/registry.js";
23
22
  import { finishedEventKey } from "./finish.js";
24
- import { TASK_ID_RE, TASKS_DIR } from "./launch.js";
23
+ import { TASK_ID_RE } from "./launch.js";
25
24
  import { ManagedInstanceMismatchError, ManagedRefError, onManagedInstance, readerOf, } from "./managed.js";
26
25
  import { assembleOutputSuffix, ManagedOutputCapacityError, ManagedOutputUnavailableError, } from "./managed-output.js";
27
- import { actingAs, legacyBackgroundAllowed } from "./session.js";
28
26
  import { BackgroundTaskStopper } from "./stop.js";
29
27
  import { BackgroundTaskStore, isManagedTask, } from "./store.js";
30
28
  /** The most bytes of output one read returns. */
31
29
  export const OUTPUT_TAIL_MAX_BYTES = 65_536;
32
- /** The time limit of reading an output (the exec and the wait for the sandbox's lease). */
30
+ /** The time limit of reading an output (the exact reads and the wait for the sandbox's lease). */
33
31
  const OUTPUT_READ_TIMEOUT_MS = 30_000;
34
32
  const conversationNotFound = () => new ApiError("conversation.not_found", "Conversation not found");
35
33
  const taskNotFound = () => new ApiError("background_task.not_found", "Background task not found");
@@ -48,13 +46,7 @@ let BackgroundTasks = class BackgroundTasks {
48
46
  eventLog;
49
47
  db;
50
48
  devices;
51
- activation;
52
- constructor(access, store, stopper, sandbox, eventLog, db, devices,
53
- /**
54
- * The paired activation gate: once on, a legacy (SID) task is never read or stopped by a raw
55
- * exec (the retirement gate owns it); a managed task always goes by its exact ref.
56
- */
57
- activation) {
49
+ constructor(access, store, stopper, sandbox, eventLog, db, devices) {
58
50
  this.access = access;
59
51
  this.store = store;
60
52
  this.stopper = stopper;
@@ -62,7 +54,6 @@ let BackgroundTasks = class BackgroundTasks {
62
54
  this.eventLog = eventLog;
63
55
  this.db = db;
64
56
  this.devices = devices;
65
- this.activation = activation;
66
57
  }
67
58
  /**
68
59
  * The conversation and every sub-agent conversation below it (grandchildren too: their tasks run
@@ -114,8 +105,8 @@ let BackgroundTasks = class BackgroundTasks {
114
105
  */
115
106
  async stop(orgId, conversationId, accountId, taskId, actorTokenId, auditDetail) {
116
107
  const task = await this.owned(orgId, conversationId, accountId, taskId);
117
- // once activated, the stopper refuses a legacy task's stop with the retirement refusal
118
- // exactly when it would signal its session (BackgroundTaskStopper's paired gate)
108
+ // the stopper refuses a running legacy task's stop with the retirement refusal while its
109
+ // instance runs (it is never signalled)
119
110
  const after = await this.stopper.stop(task, "person");
120
111
  await audit(this.db.db, {
121
112
  actorAccountId: accountId,
@@ -155,7 +146,7 @@ let BackgroundTasks = class BackgroundTasks {
155
146
  */
156
147
  async output(orgId, conversationId, accountId, taskId, tail) {
157
148
  const task = await this.owned(orgId, conversationId, accountId, taskId);
158
- const read = await this.readLive(orgId, accountId, task, tail);
149
+ const read = await this.readLive(orgId, task, tail);
159
150
  if (read.kind === "ok")
160
151
  return { ...read.value, source: "live" };
161
152
  const unavailable = {
@@ -182,67 +173,17 @@ let BackgroundTasks = class BackgroundTasks {
182
173
  return row?.source === "local" ? "local" : "cloud";
183
174
  }
184
175
  /** Reads the output from the task's running instance, or says why it cannot. */
185
- async readLive(orgId, accountId, task, tail) {
176
+ async readLive(orgId, task, tail) {
186
177
  if (isManagedTask(task))
187
178
  return this.readManaged(orgId, task, tail);
188
- // once activated a legacy task's output is never read by a raw exec: a running one is the
189
- // retirement gate's (its actionable refusal), a finished one answers with its finish summary
190
- if (!legacyBackgroundAllowed(this.activation)) {
191
- if (task.status === "running")
192
- throw retirementPending();
193
- return { kind: "unavailable", reason: "read_failed" };
194
- }
195
- if (task.sid === null || task.sandboxCreatedAt === null || task.deviceId === null) {
196
- // a reservation the launch has not finished, or a launch that failed
197
- return {
198
- kind: "unavailable",
199
- reason: task.status === "running" ? "starting" : "not_started",
200
- };
201
- }
202
- if (!(await this.sandbox.availableFor(task.deviceId))) {
203
- return { kind: "unavailable", reason: "unavailable" };
204
- }
205
- if (!(await this.deviceUsable(orgId, task.conversationId))) {
206
- return { kind: "unavailable", reason: "no_access" };
207
- }
208
- const createdAt = task.sandboxCreatedAt;
209
- // the person reading it acts in the task's conversation
210
- const actor = { accountId, conversationId: task.conversationId };
211
- try {
212
- const r = await this.sandbox.ifRunning(task.deviceId, { createdAt }, async (p, h, signal) => {
213
- const res = await actingAs(p, actor, this.activation).exec(h, {
214
- command: tailScript(task.id, tail),
215
- cwd: rootsOf(h).workspace,
216
- timeoutMs: OUTPUT_READ_TIMEOUT_MS,
217
- maxOutputBytes: 2 * OUTPUT_TAIL_MAX_BYTES + 4096,
218
- signal,
219
- });
220
- return res.exitCode === 0 ? parseTail(res.stdout, tail) : null;
221
- }, AbortSignal.timeout(OUTPUT_READ_TIMEOUT_MS));
222
- if (r.kind === "other_instance")
223
- return { kind: "unavailable", reason: "rebuilt" };
224
- if (r.kind === "not_running") {
225
- // a suspended instance keeps its files; any other state means they went with it
226
- return { kind: "unavailable", reason: r.status === "suspended" ? "suspended" : "rebuilt" };
227
- }
228
- if (r.value === null)
229
- return { kind: "unavailable", reason: "read_failed" };
230
- if (r.value === "missing")
231
- return { kind: "unavailable", reason: "output_missing" };
232
- return { kind: "ok", value: r.value };
233
- }
234
- catch (e) {
235
- if (isSandboxGoneError(e))
236
- return { kind: "unavailable", reason: "rebuilt" };
237
- // a local device's machine: offline, or no longer the owner's (revoked, deleted)
238
- if (e instanceof ApiError && e.code.startsWith("device.")) {
239
- return {
240
- kind: "unavailable",
241
- reason: e.code === "device.offline" ? "device_offline" : "no_access",
242
- };
243
- }
244
- throw e;
245
- }
179
+ // a legacy task's output is never read by an exec: a running one is the retirement gate's
180
+ // (its actionable refusal), a finished one answers with its finish summary
181
+ if (task.status === "running")
182
+ throw retirementPending();
183
+ return {
184
+ kind: "unavailable",
185
+ reason: task.sandboxCreatedAt === null ? "not_started" : "read_failed",
186
+ };
246
187
  }
247
188
  /**
248
189
  * A managed task's live suffix (permission runtime cutover phase 8.3): by its exact ref on its
@@ -318,44 +259,6 @@ BackgroundTasks = __decorate([
318
259
  __param(3, Inject(SandboxService)),
319
260
  __param(4, Inject(EventLog)),
320
261
  __param(5, Inject(KernelDb)),
321
- __param(6, Inject(ConversationDevices)),
322
- __param(7, Optional()),
323
- __param(7, Inject(PERMISSION_CONTEXT_ACTIVATION))
262
+ __param(6, Inject(ConversationDevices))
324
263
  ], BackgroundTasks);
325
264
  export { BackgroundTasks };
326
- /**
327
- * Prints `size <bytes>` and `out <base64 of the last `tail` bytes>`, or `missing` when the output
328
- * file is not there. Relative to the workspace root; POSIX tools only (`wc -c`, `tail -c`,
329
- * `base64`, `tr`), so it reads the same on Linux and macOS.
330
- */
331
- export function tailScript(id, tail) {
332
- if (!TASK_ID_RE.test(id))
333
- throw new Error(`invalid background task id: ${id}`);
334
- const f = `${TASKS_DIR}/${id}.out`;
335
- return [
336
- `if [ ! -f ${f} ]; then echo missing; exit 0; fi`,
337
- `s=$({ wc -c < ${f}; } 2>/dev/null | tr -d ' '); echo "size \${s:-0}"`,
338
- `printf 'out '; { tail -c ${Math.floor(tail)} ${f} 2>/dev/null | base64 | tr -d '\\n'; }; echo`,
339
- ].join("\n");
340
- }
341
- /**
342
- * Decodes {@link tailScript}'s output (`missing`: no output file; null: unreadable); a cut that
343
- * splits a UTF-8 character drops its tail bytes.
344
- */
345
- export function parseTail(stdout, tail) {
346
- if (/^missing$/m.test(stdout))
347
- return "missing";
348
- const size = /^size ([0-9]+)$/m.exec(stdout);
349
- const out = /^out (\S*)$/m.exec(stdout);
350
- if (!size || !out)
351
- return null;
352
- let bytes = Buffer.from(out[1], "base64");
353
- const truncated = Number(size[1]) > tail;
354
- if (truncated) {
355
- let i = 0;
356
- while (i < bytes.length && i < 3 && (bytes[i] & 0xc0) === 0x80)
357
- i++;
358
- bytes = bytes.subarray(i);
359
- }
360
- return { text: bytes.toString("utf8"), truncated };
361
- }
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
188
188
  /** The host versions (an entry's `minKernel` is judged against them). */
189
189
  export declare const HOST_VERSIONS: {
190
190
  readonly kernel: string;
191
- readonly sdk: "0.1.0-rc.35";
191
+ readonly sdk: "0.1.0-rc.36";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -1,5 +1,6 @@
1
1
  import { type ChannelCard, type FormAnswer, type InputForm, type OutboundMessage } from "@capybara-hq/plugin-sdk";
2
2
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ import type { PermissionEscalation } from "../sandbox/permission-call-types.js";
3
4
  import type { ApprovalsService, ApprovalView, CommandAskDetail, GitAskView, NetworkAskView } from "../tools/approvals.service.js";
4
5
  import { type ToolInfo } from "../tools/info.js";
5
6
  import type { ToolRegistry } from "../tools/registry.js";
@@ -76,6 +77,8 @@ export declare function gitCardText(detail: Pick<GitAskView, "host" | "repo" | "
76
77
  */
77
78
  export declare function commandCardText(detail: Pick<CommandAskDetail, "kind" | "command" | "reason"> & {
78
79
  path?: string;
80
+ escalation?: PermissionEscalation;
81
+ workingRoot?: string;
79
82
  }, scopes: readonly string[], locale: ChannelLocale, redact?: (s: string) => string): NetworkCardText;
80
83
  /**
81
84
  * The approval card in the approval's current state; undefined when the approval does not exist.