@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
@@ -1,24 +1,22 @@
1
1
  import { setTimeout as sleep } from "node:timers/promises";
2
- import { isSandboxGoneError, rootsOf, ToolError, } from "@capybara-hq/plugin-sdk";
2
+ import { isSandboxGoneError, ToolError } from "@capybara-hq/plugin-sdk";
3
3
  import { finishedEventKey } from "../../../background/finish.js";
4
- import { TASK_ID_RE, TASKS_DIR, taskOutputFile } from "../../../background/launch.js";
4
+ import { TASK_ID_RE, taskOutputFile } from "../../../background/launch.js";
5
5
  import { exactRefOf, lastLinesByRef, ManagedRefError, onManagedInstance, readerOf, statusEnd, summaryLines, } from "../../../background/managed.js";
6
6
  import { assembleTaskOutput, ManagedOutputCapacityError, ManagedOutputUnavailableError, } from "../../../background/managed-output.js";
7
- import { formatElapsed, lostReasonText } from "../../../background/render.js";
8
- import { actingAs, SID_RE, taskActor } from "../../../background/session.js";
9
- import { parsePollOutput, polledAs, pollScript, } from "../../../background/status.js";
7
+ import { formatElapsed, taskReasonText } from "../../../background/render.js";
10
8
  import { notRunningAs, RECREATED } from "../../../background/stop.js";
11
9
  import { isManagedTask } from "../../../background/store.js";
10
+ import { RetirementPendingError, retirementPending, } from "../../../sandbox/sandbox.service.js";
12
11
  import { clip, display, mapSandboxError, noSandboxError, runTimeLeftMs, sandboxBaseTimeoutMs, sandboxConversationOf, sandboxUsable, unavailableWhenNoSandbox, } from "./common.js";
13
12
  import { parseDeviceCode } from "./device-code.js";
13
+ import { assertDeviceOfRunAccount } from "./device-owner.js";
14
14
  /** How long `TaskOutput` waits with `block` when `timeout` is not given (ms). */
15
15
  export const TASK_OUTPUT_DEFAULT_TIMEOUT_MS = 30_000;
16
16
  /** The longest `TaskOutput` wait (ms). */
17
17
  export const TASK_OUTPUT_MAX_TIMEOUT_MS = 600_000;
18
- /** How often a blocking `TaskOutput` checks the task (each check a short exec of its own). */
18
+ /** How often a blocking `TaskOutput` checks the task (each check an exact status read). */
19
19
  export const TASK_CHECK_INTERVAL_MS = 2000;
20
- /** The time limit of one check or read exec. */
21
- const READ_EXEC_TIMEOUT_MS = 30_000;
22
20
  const SPEC = {
23
21
  name: "TaskOutput",
24
22
  // Display only (the tool row; not in the fingerprint, never sent to the model).
@@ -125,21 +123,6 @@ export async function recheckDevice(env, ctx) {
125
123
  throw mapSandboxError(e, env.log);
126
124
  }
127
125
  }
128
- /**
129
- * `ifRunning` on the task's own device instance (its execs act for the task's trigger in its
130
- * conversation); sandbox errors become the tools' errors. A task from before devices has no
131
- * instance (`not_running`).
132
- */
133
- export async function onTaskInstance(env, task, fn, signal) {
134
- if (task.deviceId === null)
135
- return { kind: "not_running", status: "gone" };
136
- try {
137
- return await env.ifRunning(task.deviceId, { createdAt: task.sandboxCreatedAt }, (p, h, sig) => fn(actingAs(p, taskActor(task)), h, sig), signal);
138
- }
139
- catch (e) {
140
- throw mapSandboxError(e, env.log);
141
- }
142
- }
143
126
  /**
144
127
  * The task's status line: `Status: running (2m05s)`, `Status: failed, exit code 3, after 4m12s`,
145
128
  * `Status: stopped after 1m00s`, `Status: lost (the sandbox was suspended) after 3s`.
@@ -151,7 +134,7 @@ export function statusLine(task, now = new Date()) {
151
134
  return `Status: running (${elapsed})`;
152
135
  let s = `Status: ${task.status === "timed_out" ? "timed out" : task.status}`;
153
136
  if (task.lostReason !== null)
154
- s += ` (${lostReasonText(task.lostReason)})`;
137
+ s += ` (${taskReasonText(task)})`;
155
138
  if (task.exitCode !== null)
156
139
  return `${s}, exit code ${task.exitCode}, after ${elapsed}`;
157
140
  return `${s} after ${elapsed}`;
@@ -165,111 +148,6 @@ export function unavailableText(task, r) {
165
148
  }
166
149
  return "[Output unavailable: the sandbox that ran this task is gone, and its output with it.]";
167
150
  }
168
- // ---- reading a task ----
169
- /**
170
- * The exec that checks and reads task `t` (relative to the workspace root): for a running task first
171
- * its status line (the poller's, {@link pollScript}: liveness, then the exit file), then
172
- * `size <bytes>` and `out <base64>`, at most `cap` bytes of the output from byte `offset` on.
173
- * The file is never read whole: `tail -c +<offset+1> | head -c <cap>`. Without `read` only the
174
- * status line.
175
- */
176
- export function taskReadScript(t, offset, cap, read = true) {
177
- if (!TASK_ID_RE.test(t.id))
178
- throw new Error(`invalid background task id: ${t.id}`);
179
- const lines = [];
180
- if (t.running && t.sid !== null)
181
- lines.push(pollScript([{ id: t.id, sid: t.sid }]));
182
- if (read) {
183
- const f = `${TASKS_DIR}/${t.id}.out`;
184
- const from = Math.max(0, Math.floor(offset)) + 1;
185
- const n = Math.max(1, Math.floor(cap));
186
- lines.push(`s=$({ wc -c < ${f}; } 2>/dev/null | tr -d ' '); echo "size \${s:-0}"`);
187
- lines.push(`printf 'out '; { tail -c +${from} ${f} 2>/dev/null | head -c ${n} | base64 | tr -d '\\n'; }; echo`);
188
- }
189
- return lines.join("\n");
190
- }
191
- function parseRead(id, stdout) {
192
- const size = /^size ([0-9]+)$/m.exec(stdout);
193
- const out = /^out ?([A-Za-z0-9+/=]*)$/m.exec(stdout);
194
- return {
195
- report: parsePollOutput(stdout).get(id),
196
- size: size ? Number(size[1]) : 0,
197
- data: Buffer.from(out?.[1] ?? "", "base64"),
198
- };
199
- }
200
- /**
201
- * How many bytes before the read offset a `TaskOutput` read also reads again, so a prompt split
202
- * across reads still matches: `gh auth login --web` prints its one-time code and its URL line
203
- * separately, and a read that lands between them (or a read cap that splits them) otherwise sees
204
- * only one half, and no later read sees both. The tail only ever holds this many already-delivered
205
- * bytes, whatever the task's output size: a read's buffer stays bounded.
206
- */
207
- export const READ_TAIL_BYTES = 4096;
208
- /**
209
- * The window of a read at `offset` (the output bytes already delivered) with `cap` new bytes: it
210
- * starts up to {@link READ_TAIL_BYTES} earlier, and the first `skip` bytes of what it returns were
211
- * delivered already, so the parser can match a pattern spanning the boundary. Bounded: the window
212
- * is `cap + READ_TAIL_BYTES` bytes at most, never more as the output grows.
213
- */
214
- export function readWindow(offset, cap) {
215
- const start = Math.max(0, offset - READ_TAIL_BYTES);
216
- const skip = offset - start;
217
- return { offset: start, cap: cap + skip, skip };
218
- }
219
- /**
220
- * The bytes of `buf` up to its last whole UTF-8 character: a character cut by the read's cap is
221
- * left for the next read.
222
- */
223
- export function wholeUtf8Length(buf) {
224
- let i = buf.length - 1;
225
- let back = 0;
226
- while (i >= 0 && back < 3 && (buf[i] & 0xc0) === 0x80) {
227
- i--;
228
- back++;
229
- }
230
- if (i < 0)
231
- return buf.length;
232
- const b = buf[i];
233
- const need = b >= 0xf0 ? 4 : b >= 0xe0 ? 3 : b >= 0xc0 ? 2 : 1;
234
- return i + need > buf.length ? i : buf.length;
235
- }
236
- /** Checks (and with `read`, reads) the task in its sandbox instance; never creates or resumes one. */
237
- async function look(env, task, read, signal) {
238
- if (task.sid !== null && !SID_RE.test(task.sid)) {
239
- throw new Error(`invalid background task session: ${task.sid}`);
240
- }
241
- const script = taskReadScript({ id: task.id, sid: task.sid, running: task.status === "running" }, read?.offset ?? 0, read?.cap ?? 1, read !== null);
242
- const maxBytes = Math.ceil((read?.cap ?? 0) / 3) * 4 + 64 * 1024;
243
- return onTaskInstance(env, task, async (p, h, sig) => {
244
- const r = await p.exec(h, {
245
- command: script,
246
- cwd: rootsOf(h).workspace,
247
- timeoutMs: READ_EXEC_TIMEOUT_MS,
248
- maxOutputBytes: maxBytes,
249
- signal: sig,
250
- });
251
- if (r.exitCode !== 0 || r.truncated) {
252
- throw new ToolError(`Background task ${task.id} could not be read (exit ${r.exitCode}${r.truncated ? ", output truncated" : ""}); retry TaskOutput, or Read ${outputFile(task)}.`);
253
- }
254
- return parseRead(task.id, r.stdout);
255
- }, signal);
256
- }
257
- /**
258
- * How `seen` shows the running `task` ended (an exit file, no process left, its sandbox instance
259
- * not running), or null while it runs (or when the row is no longer running).
260
- */
261
- function endOf(task, seen) {
262
- if (task.status !== "running")
263
- return null;
264
- if (seen.kind === "not_running") {
265
- return { to: notRunningAs(seen.status, seen.status === "suspended"), lastLines: "" };
266
- }
267
- if (seen.kind === "other_instance")
268
- return { to: RECREATED, lastLines: "" };
269
- const r = seen.value.report;
270
- const to = r ? polledAs(task, r, new Date()) : null;
271
- return to === null ? null : { to, lastLines: r?.lastLines ?? "" };
272
- }
273
151
  /**
274
152
  * Finishes the task as `end` says, marked reported: called only once nothing can fail before the
275
153
  * result reaches the model, so a reported finish is one the model saw. A task a stop claimed is
@@ -281,26 +159,15 @@ async function settle(env, task, end) {
281
159
  await env.tasks.finisher.finish(task, end.to, end.lastLines, true, { unclaimed: true });
282
160
  return (await env.store.get(task.id)) ?? task;
283
161
  }
284
- /** {@link look}, with a `SandboxGoneError` from the exec as null (the instance is gone). */
285
- async function lookOrGone(env, task, read, signal) {
286
- try {
287
- return await look(env, task, read, signal);
288
- }
289
- catch (e) {
290
- if (isSandboxGoneError(e))
291
- return null;
292
- throw e;
293
- }
294
- }
295
162
  /**
296
163
  * Built-in `TaskOutput` (spec 2026-11-05-background-bash-design §2.2): a task's status and the
297
- * output since this conversation's last read of it. Every check is a short exec through
298
- * `SandboxService.ifRunning` on the task's own sandbox instance: it never creates or resumes a
299
- * sandbox, so a suspended or rebuilt one means the task is lost (its output unavailable). With
300
- * `block`, checks every {@link TASK_CHECK_INTERVAL_MS}, each under a lease of its own, until the
301
- * task ends or the wait (at most `timeout` and the run's time left) is over; the checks only
302
- * detect the end, and the one read that makes the result finishes the task (reported). The output
303
- * read is capped at `tools.outputSpillChars` bytes; the pipeline spills the result beyond that.
164
+ * output since this conversation's last read of it, by the task's exact ref only (no exec, no
165
+ * path) through `SandboxService.ifRunning` on the task's own instance: it never creates or
166
+ * resumes a sandbox, so a suspended or rebuilt one means the task is lost (its output
167
+ * unavailable). With `block`, checks every {@link TASK_CHECK_INTERVAL_MS}, each under a lease of
168
+ * its own, until the task ends or the wait (at most `timeout` and the run's time left) is over.
169
+ * The output read is capped at `tools.outputSpillChars` bytes; the pipeline spills the result
170
+ * beyond that. A legacy (SID) task is never read live ({@link legacyTaskOutput}).
304
171
  */
305
172
  export function taskOutputTool(deps) {
306
173
  return {
@@ -316,6 +183,8 @@ export function taskOutputTool(deps) {
316
183
  },
317
184
  async run(input, ctx) {
318
185
  const { task_id, block = true, timeout } = input;
186
+ // another account's run never reads or stops on the owner's device (activated)
187
+ assertDeviceOfRunAccount(deps.managedDeviceContextRequired, ctx);
319
188
  const env = await taskEnv(deps, ctx);
320
189
  // A sub-agent's agentId is answered, not refused: where its report arrives is the answer
321
190
  // (acceptance 2026-11-13: guidance the model is expected to follow is not a failed call).
@@ -328,75 +197,84 @@ export function taskOutputTool(deps) {
328
197
  display: display(`查看子智能体:${id}`, `Checked sub-agent: ${id}`),
329
198
  };
330
199
  }
331
- let task = await ownedTask(env, ctx, task_id);
200
+ const task = await ownedTask(env, ctx, task_id);
332
201
  await recheckDevice(env, ctx);
333
202
  if (isManagedTask(task))
334
203
  return managedTaskOutput(deps, env, ctx, task, block, timeout);
335
- if (block && task.status === "running") {
336
- const wait = Math.max(0, Math.min(timeout ?? TASK_OUTPUT_DEFAULT_TIMEOUT_MS, TASK_OUTPUT_MAX_TIMEOUT_MS, runTimeLeftMs(ctx.runDeadline)));
337
- const until = Date.now() + wait;
338
- // no check right before the final read: the loop ends when the wait does
339
- while (task.status === "running" && Date.now() < until) {
340
- if (task.sandboxCreatedAt !== null) {
341
- const seen = await lookOrGone(env, task, null, ctx.signal);
342
- if (seen === null || endOf(task, seen) !== null)
343
- break;
344
- }
345
- const left = until - Date.now();
346
- if (left <= 0)
347
- break;
348
- await sleep(Math.min(TASK_CHECK_INTERVAL_MS, left), undefined, { signal: ctx.signal });
349
- task = (await env.store.get(task.id)) ?? task;
350
- }
351
- }
352
- if (task.sandboxCreatedAt === null) {
353
- // a reservation still launching, or a launch that failed: nothing ran
354
- return result(task, [
355
- statusLine(task),
356
- task.status === "running"
357
- ? "[The task is still starting; no output yet.]"
358
- : "[No output: the command never started.]",
359
- ]);
360
- }
361
- const offset = task.readOffset;
362
- const cap = deps.config.get().tools.outputSpillChars;
363
- const window = readWindow(offset, cap);
364
- const seen = await lookOrGone(env, task, { offset: window.offset, cap: window.cap }, ctx.signal);
365
- if (seen === null) {
366
- return result(task, [statusLine(task), unavailableText(task, { kind: "other_instance" })]);
367
- }
368
- const end = endOf(task, seen);
369
- if (seen.kind !== "ran") {
370
- task = await settle(env, task, end);
371
- return result(task, [statusLine(task), unavailableText(task, seen)]);
372
- }
373
- const { data, size } = seen.value;
374
- // the window's first bytes were delivered already: only the rest is new output
375
- const fresh = data.subarray(window.skip);
376
- // an ended task's output is complete: only a read cut by the cap can end inside a character
377
- const ended = task.status !== "running" || end !== null;
378
- const used = ended && data.length < window.cap ? fresh.length : wholeUtf8Length(fresh);
379
- if (used > 0)
380
- await env.store.advanceOffset(task.id, offset + used);
381
- task = await settle(env, task, end);
382
- const parts = [];
383
- const more = size - (offset + used);
384
- if (more > 0) {
385
- parts.push(`[${more} more bytes of output after this; call TaskOutput again to read them, or Read ${outputFile(task)}.]`);
386
- }
387
- const text = used === 0 ? "" : fresh.subarray(0, used).toString("utf8");
388
- parts.push(used === 0 ? "[No new output.]" : text);
389
- // A background command that waits for a person (`gh auth login --web`, any interactive
390
- // login) prints its prompt while TaskOutput reads it (auto mode spec §6, P-D13): this is
391
- // the path that shows the device-code card while the login is still pending. The parser sees
392
- // the tail the window re-read plus the new bytes, so a prompt split across reads matches; it
393
- // takes the newest prompt in the window, so a retried login's code is not hidden by an older
394
- // prompt sitting in the tail.
395
- const loginCode = used > 0 ? parseDeviceCode(data.toString("utf8")) : null;
396
- return result(task, [statusLine(task), ...parts], loginCode);
204
+ return legacyTaskOutput(deps, env, task);
397
205
  },
398
206
  };
399
207
  }
208
+ /**
209
+ * A legacy task's own instance, never signalled or read (as `BackgroundTaskStopper` checks it):
210
+ * a running one refuses with the retirement gate's own text before any provider call; one that is
211
+ * not running or was replaced is returned. A task from before devices has none.
212
+ */
213
+ async function legacyInstance(env, task) {
214
+ if (task.deviceId === null || task.sandboxCreatedAt === null)
215
+ return { kind: "not_running", status: "gone" };
216
+ let r;
217
+ try {
218
+ r = await env.ifRunning(task.deviceId, { createdAt: task.sandboxCreatedAt }, async () => {
219
+ throw retirementPending();
220
+ }, AbortSignal.timeout(30_000));
221
+ }
222
+ catch (e) {
223
+ throw retirementRefusal(e, env);
224
+ }
225
+ if (r.kind === "ran")
226
+ throw retirementRefusal(retirementPending(), env);
227
+ return r;
228
+ }
229
+ /**
230
+ * The retirement gate's refusal as the tool's error (the generic `device.unavailable` text would
231
+ * name an inactive provider); anything else mapped as usual.
232
+ */
233
+ export function retirementRefusal(e, env) {
234
+ if (e instanceof RetirementPendingError) {
235
+ return new ToolError("This task's device is unavailable: background work started by an earlier version may still run on its previous instance, which has not been confirmed destroyed yet (for a local device, restarting its computer confirms it). The task cannot be read or stopped until then; continue without it, or start the work again with Bash on another device.");
236
+ }
237
+ return mapSandboxError(e, env.log);
238
+ }
239
+ /**
240
+ * `TaskOutput` of a legacy (SID) task: never read by an exec (permission activation W5-P2). A
241
+ * running one whose instance still runs belongs to the retirement gate, so the call is refused
242
+ * with its actionable text; one whose instance is gone, suspended or replaced is settled lost; a
243
+ * finished one answers with its status and the last lines its finish kept.
244
+ */
245
+ async function legacyTaskOutput(deps, env, task) {
246
+ if (task.sandboxCreatedAt === null) {
247
+ // a reservation that never started: nothing ran
248
+ return result(task, [
249
+ statusLine(task),
250
+ task.status === "running"
251
+ ? "[The task is still starting; no output yet.]"
252
+ : "[No output: the command never started.]",
253
+ ]);
254
+ }
255
+ if (task.status === "running") {
256
+ // the instance first: only a running one belongs to the retirement gate; a gone, suspended
257
+ // or replaced one settles the task lost (its processes went with it, or wait for retirement)
258
+ const seen = await legacyInstance(env, task);
259
+ const end = {
260
+ to: seen.kind === "not_running"
261
+ ? notRunningAs(seen.status, seen.status === "suspended")
262
+ : RECREATED,
263
+ lastLines: "",
264
+ };
265
+ const after = await settle(env, task, end);
266
+ return result(after, [statusLine(after), unavailableText(after, seen)]);
267
+ }
268
+ const lines = [
269
+ statusLine(task),
270
+ "[Output unavailable: this task was started by an earlier version of the device runtime, whose output is not read live.]",
271
+ ];
272
+ const summary = await finishSummary(deps, task);
273
+ if (summary !== null) {
274
+ lines.push(`Last lines recorded when the task finished (not new output):\n${summary}`);
275
+ }
276
+ return result(task, lines);
277
+ }
400
278
  /** A managed task's ref or provider failure as the tool's error (never a fallback read). */
401
279
  function managedReadError(env, task, e) {
402
280
  if (e instanceof ManagedRefError) {
@@ -2,8 +2,8 @@ import type { BuiltinTool } from "../../registry.js";
2
2
  import { type SandboxToolDeps } from "./common.js";
3
3
  /**
4
4
  * Built-in `TaskStop` (spec 2026-11-05-background-bash-design §2.3): stops one of this
5
- * conversation's background tasks through `BackgroundTaskStopper` (SIGTERM to its session, SIGKILL
6
- * after 5 s, never creating or resuming a sandbox). A task that had already finished is not an
5
+ * conversation's background tasks through `BackgroundTaskStopper` (by its exact ref, with the device's
6
+ * five-second grace, never creating or resuming a sandbox). A task that had already finished is not an
7
7
  * error; a reservation still launching, or a task another stop already claimed, is reported as
8
8
  * stopping. A stop that failed leaves the task running and is an error the model can retry.
9
9
  */
@@ -1,11 +1,9 @@
1
- import { rootsOf, ToolError } from "@capybara-hq/plugin-sdk";
1
+ import { ToolError } from "@capybara-hq/plugin-sdk";
2
2
  import { LAST_LINES_UNAVAILABLE, lastLinesByRef, onManagedInstance, } from "../../../background/managed.js";
3
- import { decodeTail, tailCommand } from "../../../background/session.js";
4
3
  import { isManagedTask } from "../../../background/store.js";
5
4
  import { clip, display, mapSandboxError, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, } from "./common.js";
6
- import { onTaskInstance, ownedTask, recheckDevice, statusLine, taskEnv, } from "./task-output.js";
7
- /** The time limit of reading a stopped task's last lines. */
8
- const TAIL_EXEC_TIMEOUT_MS = 10_000;
5
+ import { assertDeviceOfRunAccount } from "./device-owner.js";
6
+ import { ownedTask, recheckDevice, retirementRefusal, statusLine, taskEnv, } from "./task-output.js";
9
7
  const SPEC = {
10
8
  name: "TaskStop",
11
9
  // Display only (the tool row; not in the fingerprint, never sent to the model).
@@ -27,7 +25,10 @@ const SPEC = {
27
25
  additionalProperties: false,
28
26
  },
29
27
  };
30
- /** The task's last 20 lines, read from its own sandbox instance; null when that is not running. */
28
+ /**
29
+ * The task's last 20 lines, read by its exact ref from its own instance; null when that is not
30
+ * running.
31
+ */
31
32
  async function lastLinesOf(env, task, signal) {
32
33
  if (task.sandboxCreatedAt === null)
33
34
  return null;
@@ -46,23 +47,8 @@ async function lastLinesOf(env, task, signal) {
46
47
  return LAST_LINES_UNAVAILABLE;
47
48
  }
48
49
  }
49
- try {
50
- const r = await onTaskInstance(env, task, async (p, h, sig) => {
51
- const res = await p.exec(h, {
52
- command: tailCommand(task.id),
53
- cwd: rootsOf(h).workspace,
54
- timeoutMs: TAIL_EXEC_TIMEOUT_MS,
55
- maxOutputBytes: 64 * 1024,
56
- signal: sig,
57
- });
58
- return res.exitCode === 0 ? decodeTail(res.stdout) : null;
59
- }, signal);
60
- return r.kind === "ran" ? r.value : null;
61
- }
62
- catch {
63
- // the task is stopped either way; only its last lines are missing
64
- return null;
65
- }
50
+ // a legacy (SID) task's output is never read by an exec: its lines are labelled unavailable
51
+ return LAST_LINES_UNAVAILABLE;
66
52
  }
67
53
  /** The result text: what happened, the status line and the last lines. */
68
54
  async function ended(env, task, what, signal) {
@@ -88,8 +74,8 @@ function text(task, body) {
88
74
  }
89
75
  /**
90
76
  * Built-in `TaskStop` (spec 2026-11-05-background-bash-design §2.3): stops one of this
91
- * conversation's background tasks through `BackgroundTaskStopper` (SIGTERM to its session, SIGKILL
92
- * after 5 s, never creating or resuming a sandbox). A task that had already finished is not an
77
+ * conversation's background tasks through `BackgroundTaskStopper` (by its exact ref, with the device's
78
+ * five-second grace, never creating or resuming a sandbox). A task that had already finished is not an
93
79
  * error; a reservation still launching, or a task another stop already claimed, is reported as
94
80
  * stopping. A stop that failed leaves the task running and is an error the model can retry.
95
81
  */
@@ -101,6 +87,8 @@ export function taskStopTool(deps) {
101
87
  timeoutMs: () => sandboxBaseTimeoutMs(deps.config.get()),
102
88
  async run(input, ctx) {
103
89
  const { task_id } = input;
90
+ // another account's run never reads or stops on the owner's device (activated)
91
+ assertDeviceOfRunAccount(deps.managedDeviceContextRequired, ctx);
104
92
  const env = await taskEnv(deps, ctx);
105
93
  const task = await ownedTask(env, ctx, task_id);
106
94
  await recheckDevice(env, ctx);
@@ -112,7 +100,8 @@ export function taskStopTool(deps) {
112
100
  after = await env.tasks.stopper.stop(task, "tool", ctx.signal);
113
101
  }
114
102
  catch (e) {
115
- const mapped = mapSandboxError(e, env.log);
103
+ // a running legacy task's stop is the retirement gate's refusal, in its own words
104
+ const mapped = retirementRefusal(e, env);
116
105
  if (mapped instanceof ToolError)
117
106
  throw mapped;
118
107
  const why = e instanceof Error ? e.message : String(e);
@@ -21,6 +21,7 @@ import { SandboxOperationAuthority } from "../sandbox/operation-authority.js";
21
21
  import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
22
22
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
23
23
  import { type CommandReview } from "../sandbox/review/index.js";
24
+ import { SandboxService } from "../sandbox/sandbox.service.js";
24
25
  import { type UnattendedRun } from "../schedules/unattended.js";
25
26
  import { ApprovalsService } from "./approvals.service.js";
26
27
  import { Breaker } from "./breaker.js";
@@ -323,6 +324,13 @@ export type ExecOutcome =
323
324
  connectorSlug: string;
324
325
  message: string;
325
326
  };
327
+ /**
328
+ * A call that needs reach beyond the working directory on a device whose permission support is
329
+ * not verified: no approval could let admission run it, so nothing is offered.
330
+ */
331
+ export declare const PERMISSION_SUPPORT_UNVERIFIED_TEXT = "This call needs access outside the working directory, but this device's permission support is not verified yet, so only paths inside the working directory work now. Keep the call inside the working directory, or retry once the device is ready.";
332
+ /** What the model gets when the permission check of its call refused (fail closed). */
333
+ export declare const permissionCheckFailedText: (why: string) => string;
326
334
  /**
327
335
  * 工具执行管线(spec 5.4 / 6.2):每个阶段是独立函数——
328
336
  * `resolveOutputRefs` → `validateInput` → `decidePolicy` → `execute`(超时、熔断)→ `renderResult` / `spillIfLarge`
@@ -336,6 +344,8 @@ export declare class ToolPipeline {
336
344
  private readonly permissionAuthority?;
337
345
  private readonly permissionGrants?;
338
346
  private readonly permissionLocks?;
347
+ /** Starts a cloud device before its first managed call is reviewed (absent: never). */
348
+ private readonly sandboxes?;
339
349
  private readonly decide;
340
350
  private readonly deps;
341
351
  constructor(kdb: KernelDb, eventLog: EventLog,
@@ -350,7 +360,11 @@ export declare class ToolPipeline {
350
360
  /** The command review (auto mode spec §5.4); absent in hand-built pipelines. */
351
361
  review?: CommandReview,
352
362
  /** The reviewed call's device facts; absent in hand-built pipelines. */
353
- devices?: Pick<ConversationDevices, "reviewFacts">, permissionAuthority?: SandboxOperationAuthority | undefined, permissionGrants?: PermissionCallGrants | undefined, permissionLocks?: PermissionAuthorityLock | undefined);
363
+ devices?: Pick<ConversationDevices, "reviewFacts">, permissionAuthority?: SandboxOperationAuthority | undefined, permissionGrants?: PermissionCallGrants | undefined, permissionLocks?: PermissionAuthorityLock | undefined,
364
+ /** The paired activation gate: on, the managed builtins take the permission review. */
365
+ activation?: boolean,
366
+ /** Starts a cloud device before its first managed call is reviewed (absent: never). */
367
+ sandboxes?: Pick<SandboxService, "ensureRunning"> | undefined);
354
368
  /**
355
369
  * tools 节点:按顺序处理本步 assistant 消息里的全部 `tool_call`,每个调用都以一条 `tool_result` 结束
356
370
  * (之后才回到 prepare 构建下一次请求,保持「已记录调用、未记录结果之间不构建请求」的不变式)。
@@ -390,9 +404,23 @@ export declare class ToolPipeline {
390
404
  * asked is the whole truth on a resume: the call is never reviewed twice.
391
405
  */
392
406
  private reviewCall;
407
+ /**
408
+ * Whether this call takes the managed route's permission review: a managed builtin once
409
+ * activated ({@link MANAGED_OPERATION_TOOLS}) whose call enters the device ({@link entersDevice}).
410
+ */
393
411
  private operationScoped;
394
- /** This branch is unreachable for production legacy handlers until the caller cutover. */
412
+ /**
413
+ * The permission review of a managed call, with the escalation state a continued restricted
414
+ * `Bash` call carries to its tool (its sandbox hints: retry with `sandbox: "escalated"` only
415
+ * where this device and org allow it).
416
+ */
395
417
  private reviewPermissionCall;
418
+ private reviewPermissionCallWith;
419
+ /**
420
+ * Whether an execution of this call was admitted outside the sandbox under a restricted profile
421
+ * (a per-call escalation's full reach): an intent past admission, or one revoked after dispatch.
422
+ */
423
+ private admittedOutsideSandbox;
396
424
  private findPermissionGrant;
397
425
  private recordPermissionReview;
398
426
  /** The outcome of a call whose `command` approval was already asked (a resume). */
@@ -435,6 +463,7 @@ export declare class ToolPipeline {
435
463
  execute(tool: ResolvedTool, input: unknown, ctx: ToolStepContext, callId: string, resume?: ToolResume, stepTools?: readonly ResolvedTool[], reviewed?: {
436
464
  workingRoot?: string | undefined;
437
465
  against?: string | undefined;
466
+ escalation?: "available" | "escalated" | undefined;
438
467
  }): Promise<ExecOutcome>;
439
468
  private executeConnector;
440
469
  /** 抛出的错误 → 给模型的结果:ToolError 的消息原样(插件约定为英文、可操作),其他只给错误类名。 */