@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
@@ -64,12 +64,6 @@ export declare const DeploymentSettingsBody: z.ZodObject<{
64
64
  off: "off";
65
65
  }>>;
66
66
  }, z.core.$strict>>;
67
- devicesAutoMode: z.ZodOptional<z.ZodObject<{
68
- mode: z.ZodNullable<z.ZodEnum<{
69
- allowed: "allowed";
70
- off: "off";
71
- }>>;
72
- }, z.core.$strict>>;
73
67
  attribution: z.ZodOptional<z.ZodObject<{
74
68
  commit: z.ZodOptional<z.ZodNullable<z.ZodString>>;
75
69
  pr: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -1,12 +1,12 @@
1
1
  import { type SandboxOperationScope } from "@capybara-hq/plugin-sdk";
2
2
  import type { KernelConfig } from "../config/schema.js";
3
3
  /**
4
- * Launching a background Bash task (spec 2026-11-05-background-bash-design §4.2): the task id, the
5
- * one short exec that starts the command detached from the exec, and the model-visible result.
6
- * Every path is relative to the instance's workspace root (the launch exec's `cwd`), so the
7
- * script is the same whatever the instance's roots are.
4
+ * Launching a background Bash task (spec 2026-11-05-background-bash-design §4.2, permission
5
+ * runtime cutover phase 8.2): the task id, the managed artifact placement and the model-visible
6
+ * result. A task starts only through the device's exact `backgroundStart` operation; no shell
7
+ * script launches, polls or stops a task.
8
8
  */
9
- /** The launch exec's own time limit: it only writes a file and forks. */
9
+ /** The time limit of the start itself (the task's own time limit runs on the device). */
10
10
  export declare const LAUNCH_EXEC_TIMEOUT_MS = 30000;
11
11
  /**
12
12
  * The longest a background task may run, in seconds: `sandbox.background.maxSeconds`, at most
@@ -18,72 +18,18 @@ export declare const TASKS_DIR = ".capybara/tasks";
18
18
  /** A task's output file, relative to the workspace root (`output_path` while reserved). */
19
19
  export declare const taskOutputPath: (id: string) => string;
20
20
  /**
21
- * The absolute output file of a task from its `output_path`: absolute once the task started (the
22
- * launch records `<workspace>/.capybara/tasks/<id>.out` of its instance); a reservation's relative
23
- * path is read under the default workspace.
21
+ * The absolute output file of a task from its `output_path`: a managed task's is always absolute;
22
+ * a legacy row reserved but never started kept a relative one, read under the default workspace.
24
23
  */
25
24
  export declare const taskOutputFile: (outputPath: string) => string;
26
- /** The file the launch writes the session id to, relative to the workspace root. */
27
- export declare const taskSidPath: (id: string) => string;
28
25
  /** A new task id: `bt_` plus 6 lowercase base32 characters. */
29
26
  export declare function newTaskId(): string;
30
27
  /** A task id ({@link newTaskId}). */
31
28
  export declare const TASK_ID_RE: RegExp;
32
- /**
33
- * A shell fragment that sets how a task's processes are found and signalled by its sid, defining
34
- * `tk_alive <sid>` (status 0 while the task has a process) and `tk_kill <SIGNAL> <sid>` (0: sent,
35
- * 1: no process left, anything else: a failure), and `pg` to the mode:
36
- * - `-s`, the session, where `pgrep` has `-s` (Linux procps and busybox, the sandbox-fake shims:
37
- * `pgrep -s 0`, the own session, exits 0 or 1): `pgrep -s` and `pkill -s`;
38
- * - `-g`, the process group, elsewhere (macOS). Its `pgrep` has no `-s`, and inside the OS sandbox
39
- * (Seatbelt) a command can neither list processes nor signal those of another command. So the
40
- * task's process group (its id is the sid) is watched by its launcher ({@link GROUP_LAUNCHER}),
41
- * which signals it on request: `tk_kill` appends the signal to `.capybara/tasks/g<sid>.ctl`, and
42
- * `tk_alive` asks `kill(0, -sid)`, where "not permitted" (another command's group) still means
43
- * the group exists. A group signal is one system call, so it misses no process forked meanwhile.
44
- * Relative to the workspace root. Every script that asks for or signals a task's processes starts
45
- * with it; the launch picks its launcher with the same test.
46
- */
47
- export declare const SESSION_MODE_SCRIPT: string;
48
- /**
49
- * The process group launcher (macOS: {@link SESSION_MODE_SCRIPT}'s `-g`), a perl program run as
50
- * `perl -e <this> <seconds> <task path>` from the workspace root. It makes a session of its own
51
- * (leaving the launch exec's process group), starts `bash <task>.sh` as the leader of a new process
52
- * group (the task; its id, the sid, goes to `<task>.sid` through a rename) and watches it every
53
- * 0.1 s, outside the group:
54
- * - the command exits: its status as the shell gives it (`128 + signal` when killed) goes to
55
- * `<task>.exit`, and what it left running in the group is SIGKILLed (the task ends when its
56
- * command exits, as the poll does on Linux);
57
- * - the time limit passes: 137 goes to `<task>.exit`, then the group is SIGKILLed (as
58
- * `timeout -s KILL`);
59
- * - a signal is requested in `g<sid>.ctl` ({@link SESSION_MODE_SCRIPT}'s `tk_kill`, read through
60
- * a rename): the group gets it, and no exit file is written any more (a stop, as on Linux).
61
- * It exits once the group is empty. Contains no single quote (it goes between single quotes).
62
- */
63
- export declare const GROUP_LAUNCHER: string;
64
- /**
65
- * The shell of the launch exec: writes `command` (base64 in the script, so nothing is quoted by
66
- * hand) to `.capybara/tasks/<id>.sh` and starts it with bash (the shell a foreground `Bash` call
67
- * runs its command in), detached from the exec under a hard time limit of `seconds` that SIGKILLs
68
- * every process of the task, with its exit status written to `<id>.exit` and its output to
69
- * `<id>.out`; the task's sid goes to `<id>.sid` and is printed. Where `pgrep` has `-s`
70
- * ({@link SESSION_MODE_SCRIPT}) the command runs in a session of its own under
71
- * `setsid nohup sh -c 'timeout -s KILL <seconds> …'` and the sid is `$!`, the pid `setsid` started;
72
- * elsewhere (macOS: no `setsid`, no `timeout`, no `pgrep -s`) {@link GROUP_LAUNCHER} runs it in a
73
- * process group of its own, watched by the launcher, and writes the sid (the group id) itself,
74
- * which the launch waits for (up to 10 s). The script starts with `BACKGROUND_LAUNCH_LINE`, so a
75
- * local device, which kills what any other exec leaves running, leaves the task alone. An
76
- * environment without one of the needed programs fails with a readable error on stderr and exit
77
- * code 127, before anything starts. `id` must be a task id and `seconds` a positive integer (both
78
- * go into the script unquoted).
79
- */
80
- export declare function launchScript(id: string, command: string, seconds: number): string;
81
29
  /**
82
30
  * The launch result's last line: how the task's end is reported and how to read and stop it.
83
31
  */
84
32
  export declare const LAUNCH_NEXT_STEP = "You will be told when it finishes. Read its output with TaskOutput (or Read), stop it with TaskStop.";
85
- /** The model-visible result of a launch (spec §2.1); `workspace`: the instance's workspace root. */
86
- export declare function startedText(id: string, description: string, workspace?: string): string;
87
33
  /**
88
34
  * The artifact of a managed task (permission runtime cutover §"Artifact location decision"):
89
35
  * `${workingRoot}/.capybara/tasks/${taskId}.out`, where the working root is the trusted root the
@@ -1,12 +1,12 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { BACKGROUND_LAUNCH_LINE, DEFAULT_SANDBOX_ROOTS, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
2
+ import { DEFAULT_SANDBOX_ROOTS, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
3
3
  /**
4
- * Launching a background Bash task (spec 2026-11-05-background-bash-design §4.2): the task id, the
5
- * one short exec that starts the command detached from the exec, and the model-visible result.
6
- * Every path is relative to the instance's workspace root (the launch exec's `cwd`), so the
7
- * script is the same whatever the instance's roots are.
4
+ * Launching a background Bash task (spec 2026-11-05-background-bash-design §4.2, permission
5
+ * runtime cutover phase 8.2): the task id, the managed artifact placement and the model-visible
6
+ * result. A task starts only through the device's exact `backgroundStart` operation; no shell
7
+ * script launches, polls or stops a task.
8
8
  */
9
- /** The launch exec's own time limit: it only writes a file and forks. */
9
+ /** The time limit of the start itself (the task's own time limit runs on the device). */
10
10
  export const LAUNCH_EXEC_TIMEOUT_MS = 30_000;
11
11
  /**
12
12
  * The longest a background task may run, in seconds: `sandbox.background.maxSeconds`, at most
@@ -18,13 +18,10 @@ export const TASKS_DIR = ".capybara/tasks";
18
18
  /** A task's output file, relative to the workspace root (`output_path` while reserved). */
19
19
  export const taskOutputPath = (id) => `${TASKS_DIR}/${id}.out`;
20
20
  /**
21
- * The absolute output file of a task from its `output_path`: absolute once the task started (the
22
- * launch records `<workspace>/.capybara/tasks/<id>.out` of its instance); a reservation's relative
23
- * path is read under the default workspace.
21
+ * The absolute output file of a task from its `output_path`: a managed task's is always absolute;
22
+ * a legacy row reserved but never started kept a relative one, read under the default workspace.
24
23
  */
25
24
  export const taskOutputFile = (outputPath) => outputPath.startsWith("/") ? outputPath : `${DEFAULT_SANDBOX_ROOTS.workspace}/${outputPath}`;
26
- /** The file the launch writes the session id to, relative to the workspace root. */
27
- export const taskSidPath = (id) => `${TASKS_DIR}/${id}.sid`;
28
25
  const BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
29
26
  /** A new task id: `bt_` plus 6 lowercase base32 characters. */
30
27
  export function newTaskId() {
@@ -34,134 +31,12 @@ export function newTaskId() {
34
31
  out += BASE32[b & 31];
35
32
  return out;
36
33
  }
37
- /** The programs a session launch and the later polls and stops need (Linux, sandbox-fake). */
38
- const REQUIRED_SESSION = ["bash", "setsid", "nohup", "timeout", "pgrep", "pkill", "base64"];
39
- /** The programs a process group launch and the later polls and stops need (macOS). */
40
- const REQUIRED_GROUP = ["bash", "perl", "nohup", "base64"];
41
34
  /** A task id ({@link newTaskId}). */
42
35
  export const TASK_ID_RE = /^bt_[a-z2-7]{6}$/;
43
- /**
44
- * A shell fragment that sets how a task's processes are found and signalled by its sid, defining
45
- * `tk_alive <sid>` (status 0 while the task has a process) and `tk_kill <SIGNAL> <sid>` (0: sent,
46
- * 1: no process left, anything else: a failure), and `pg` to the mode:
47
- * - `-s`, the session, where `pgrep` has `-s` (Linux procps and busybox, the sandbox-fake shims:
48
- * `pgrep -s 0`, the own session, exits 0 or 1): `pgrep -s` and `pkill -s`;
49
- * - `-g`, the process group, elsewhere (macOS). Its `pgrep` has no `-s`, and inside the OS sandbox
50
- * (Seatbelt) a command can neither list processes nor signal those of another command. So the
51
- * task's process group (its id is the sid) is watched by its launcher ({@link GROUP_LAUNCHER}),
52
- * which signals it on request: `tk_kill` appends the signal to `.capybara/tasks/g<sid>.ctl`, and
53
- * `tk_alive` asks `kill(0, -sid)`, where "not permitted" (another command's group) still means
54
- * the group exists. A group signal is one system call, so it misses no process forked meanwhile.
55
- * Relative to the workspace root. Every script that asks for or signals a task's processes starts
56
- * with it; the launch picks its launcher with the same test.
57
- */
58
- export const SESSION_MODE_SCRIPT = [
59
- 'if pgrep -s 0 >/dev/null 2>&1 || [ "$?" -eq 1 ]; then pg=-s',
60
- 'tk_alive() { pgrep -s "$1" >/dev/null 2>&1; }',
61
- 'tk_kill() { pkill -"$1" -s "$2"; }',
62
- "else pg=-g",
63
- `tk_alive() { perl -e 'exit((kill(0, -$ARGV[0]) || $!{EPERM}) ? 0 : 1)' "$1"; }`,
64
- `tk_kill() { tk_alive "$2" || return 1; echo "$1" >> ${TASKS_DIR}/g"$2".ctl || return 2; }`,
65
- "fi",
66
- ].join("\n");
67
- /**
68
- * The process group launcher (macOS: {@link SESSION_MODE_SCRIPT}'s `-g`), a perl program run as
69
- * `perl -e <this> <seconds> <task path>` from the workspace root. It makes a session of its own
70
- * (leaving the launch exec's process group), starts `bash <task>.sh` as the leader of a new process
71
- * group (the task; its id, the sid, goes to `<task>.sid` through a rename) and watches it every
72
- * 0.1 s, outside the group:
73
- * - the command exits: its status as the shell gives it (`128 + signal` when killed) goes to
74
- * `<task>.exit`, and what it left running in the group is SIGKILLed (the task ends when its
75
- * command exits, as the poll does on Linux);
76
- * - the time limit passes: 137 goes to `<task>.exit`, then the group is SIGKILLed (as
77
- * `timeout -s KILL`);
78
- * - a signal is requested in `g<sid>.ctl` ({@link SESSION_MODE_SCRIPT}'s `tk_kill`, read through
79
- * a rename): the group gets it, and no exit file is written any more (a stop, as on Linux).
80
- * It exits once the group is empty. Contains no single quote (it goes between single quotes).
81
- */
82
- export const GROUP_LAUNCHER = [
83
- "use POSIX;",
84
- "my ($n, $t) = @ARGV;",
85
- "my ($d) = $t =~ m{^(.*)/};",
86
- 'sub put { my ($f, $v) = @_; open(my $h, ">", "$f.tmp") or return; print $h "$v\\n"; close($h); rename("$f.tmp", $f) }',
87
- 'POSIX::setsid() or die "setsid: $!\\n";',
88
- "my $c = fork();",
89
- 'defined $c or die "fork: $!\\n";',
90
- 'if ($c == 0) { setpgid(0, 0); exec("bash", "$t.sh") or POSIX::_exit(127) }',
91
- "setpgid($c, $c);",
92
- 'put("$t.sid", $c);',
93
- 'my $ctl = "$d/g$c.ctl";',
94
- "my $end = time() + $n;",
95
- "my ($code, $done);",
96
- 'sub fin { put("$t.exit", $_[0]) unless $done; $done = 1 }',
97
- "while (1) {",
98
- ' if (rename($ctl, "$ctl.$$")) { open(my $h, "<", "$ctl.$$"); my @s = grep { /^[A-Z0-9]+$/ } map { s/\\s+//gr } <$h>; close($h); unlink("$ctl.$$"); $done = 1; kill($_, -$c) for @s }',
99
- ' if (!defined $code && waitpid($c, WNOHANG) == $c) { $code = ($? & 127) ? 128 + ($? & 127) : $? >> 8; fin($code); kill("KILL", -$c) }',
100
- ' if (!defined $code && time() >= $end) { fin(137); kill("KILL", -$c) }',
101
- " last if defined $code && !kill(0, -$c);",
102
- " select(undef, undef, undef, 0.1);",
103
- "}",
104
- ].join(" ");
105
- /**
106
- * The shell of the launch exec: writes `command` (base64 in the script, so nothing is quoted by
107
- * hand) to `.capybara/tasks/<id>.sh` and starts it with bash (the shell a foreground `Bash` call
108
- * runs its command in), detached from the exec under a hard time limit of `seconds` that SIGKILLs
109
- * every process of the task, with its exit status written to `<id>.exit` and its output to
110
- * `<id>.out`; the task's sid goes to `<id>.sid` and is printed. Where `pgrep` has `-s`
111
- * ({@link SESSION_MODE_SCRIPT}) the command runs in a session of its own under
112
- * `setsid nohup sh -c 'timeout -s KILL <seconds> …'` and the sid is `$!`, the pid `setsid` started;
113
- * elsewhere (macOS: no `setsid`, no `timeout`, no `pgrep -s`) {@link GROUP_LAUNCHER} runs it in a
114
- * process group of its own, watched by the launcher, and writes the sid (the group id) itself,
115
- * which the launch waits for (up to 10 s). The script starts with `BACKGROUND_LAUNCH_LINE`, so a
116
- * local device, which kills what any other exec leaves running, leaves the task alone. An
117
- * environment without one of the needed programs fails with a readable error on stderr and exit
118
- * code 127, before anything starts. `id` must be a task id and `seconds` a positive integer (both
119
- * go into the script unquoted).
120
- */
121
- export function launchScript(id, command, seconds) {
122
- if (!TASK_ID_RE.test(id))
123
- throw new Error(`invalid background task id: ${JSON.stringify(id)}`);
124
- if (!Number.isSafeInteger(seconds) || seconds < 1) {
125
- throw new Error(`invalid background task seconds: ${seconds}`);
126
- }
127
- const b64 = Buffer.from(command, "utf8").toString("base64");
128
- const t = `${TASKS_DIR}/${id}`;
129
- const need = (list) => `for c in ${list.join(" ")}; do command -v "$c" >/dev/null 2>&1 || { echo "Background tasks need ${list.join(", ")} in this environment; $c is missing." >&2; exit 127; }; done`;
130
- return [
131
- // first: a local device kills what an exec leaves running, except a launch's detached task
132
- BACKGROUND_LAUNCH_LINE,
133
- "set -e",
134
- SESSION_MODE_SCRIPT,
135
- `if [ "$pg" = -s ]; then ${need(REQUIRED_SESSION)}; else ${need(REQUIRED_GROUP)}; fi`,
136
- `mkdir -p ${TASKS_DIR}`,
137
- `printf '%s' '${b64}' | base64 -d > ${t}.sh`,
138
- `if [ "$pg" = -s ]; then`,
139
- `setsid nohup sh -c 'timeout -s KILL ${seconds} bash ${t}.sh; echo $? > ${t}.exit' > ${t}.out 2>&1 < /dev/null &`,
140
- // the session id goes to a file first: a launch that ends before its output comes back
141
- // (aborted, timed out) still leaves the id of what it started
142
- `echo $! > ${t}.sid`,
143
- "else",
144
- `rm -f ${t}.sid`,
145
- `nohup perl -e '${GROUP_LAUNCHER}' ${seconds} ${t} > ${t}.out 2>&1 < /dev/null &`,
146
- // the launcher writes the group id once the group exists
147
- `i=0; while [ ! -s ${t}.sid ] && [ "$i" -lt 200 ]; do sleep 0.05; i=$((i+1)); done`,
148
- `[ -s ${t}.sid ] || { echo "The background task did not start: no process group id after 10 s." >&2; exit 1; }`,
149
- "fi",
150
- `cat ${t}.sid`,
151
- ].join("\n");
152
- }
153
36
  /**
154
37
  * The launch result's last line: how the task's end is reported and how to read and stop it.
155
38
  */
156
39
  export const LAUNCH_NEXT_STEP = "You will be told when it finishes. Read its output with TaskOutput (or Read), stop it with TaskStop.";
157
- /** The model-visible result of a launch (spec §2.1); `workspace`: the instance's workspace root. */
158
- export function startedText(id, description, workspace = DEFAULT_SANDBOX_ROOTS.workspace) {
159
- return [
160
- `Started background task ${id} ("${description}").`,
161
- `Output: ${workspace}/${taskOutputPath(id)}`,
162
- LAUNCH_NEXT_STEP,
163
- ].join("\n");
164
- }
165
40
  /**
166
41
  * The artifact of a managed task (permission runtime cutover §"Artifact location decision"):
167
42
  * `${workingRoot}/.capybara/tasks/${taskId}.out`, where the working root is the trusted root the
@@ -15,7 +15,8 @@ export declare const BACKGROUND_PRUNE_JOB = "background-task-prune";
15
15
  /** The most owed managed cancellations one poll applies (each a lease and up to a 5 s grace). */
16
16
  export declare const MANAGED_STOPS_PER_TICK = 8;
17
17
  /**
18
- * A reservation (`sid` null) older than this has lost its launch. The slowest legitimate launch
18
+ * A reservation that never dispatched (a managed `pending` row, or a legacy row without an
19
+ * instance) older than this has lost its launch. The slowest legitimate launch
19
20
  * is the pipeline's own limit for a background `Bash` call ({@link LAUNCH_EXEC_TIMEOUT_MS} plus
20
21
  * {@link sandboxBaseTimeoutMs}: the tool timeout, `sandbox.lockWaitSeconds` and the setup margin),
21
22
  * so twice that (never under 2 minutes) leaves a wide margin: only a launching process that died
@@ -25,12 +26,13 @@ export declare const launchAbandonedAfterMs: (cfg: KernelConfig) => number;
25
26
  /**
26
27
  * The worker's background task jobs (spec 2026-11-05-background-bash-design §4.3), each once per
27
28
  * tick across replicas:
28
- * - `background-task-poll` (every `sandbox.background.pollSeconds`): for every device
29
- * instance with running tasks (of any conversation using it), one exec through
30
- * `SandboxService.ifRunning` (which never creates or resumes an instance) reports each task's
31
- * exit file and liveness; ended tasks finish through {@link BackgroundTaskFinisher}. Each poll
29
+ * - `background-task-poll` (every `sandbox.background.pollSeconds`): every managed task by its
30
+ * exact ref on its exact instance (through `SandboxService.ifRunning`, which never creates or
31
+ * resumes an instance); ended tasks finish through {@link BackgroundTaskFinisher}. Each poll
32
32
  * takes and releases a lease, so `last_used_at` stays fresh and an instance with running tasks
33
- * is never idle-suspended;
33
+ * is never idle-suspended. A running legacy (SID) task is never polled by any exec: while its
34
+ * instance runs it is left to the retirement gate (`RetireLegacyTasksJob`); once that instance
35
+ * is gone or replaced it finishes `lost` without any exec or signal;
34
36
  * - `background-task-prune` (daily): deletes finished tasks older than `tools.outputRetentionDays`.
35
37
  */
36
38
  export declare class BackgroundTaskPollJob {
@@ -42,20 +44,10 @@ export declare class BackgroundTaskPollJob {
42
44
  readonly lockService: LockService;
43
45
  readonly log: KernelLogger;
44
46
  private readonly stopper;
45
- /**
46
- * The paired activation gate: once on, a legacy (SID) task is never polled by a raw exec;
47
- * its instance's poll is refused for the retirement gate ({@link pollSandbox}).
48
- */
49
- private readonly activation?;
50
- /** The marker that logs a refused legacy poll once per instance across the replicas. */
47
+ /** The marker that logs a left-alone legacy instance once across the replicas. */
51
48
  private readonly redis?;
52
- constructor(store: Pick<BackgroundTaskStore, "runningStarted" | "runningManaged" | "owedCancels" | "pruneFinished" | "failAbandonedLaunches">, finisher: BackgroundTaskFinisher, eventLog: Pick<EventLog, "publishChanged">, sandbox: Pick<SandboxService, "cloudAvailable" | "availableFor" | "ifRunning">, config: KernelConfigService, lockService: LockService, log: KernelLogger, stopper: Pick<BackgroundTaskStopper, "stop">,
53
- /**
54
- * The paired activation gate: once on, a legacy (SID) task is never polled by a raw exec;
55
- * its instance's poll is refused for the retirement gate ({@link pollSandbox}).
56
- */
57
- activation?: boolean | undefined,
58
- /** The marker that logs a refused legacy poll once per instance across the replicas. */
49
+ constructor(store: Pick<BackgroundTaskStore, "runningLegacy" | "runningManaged" | "owedCancels" | "pruneFinished" | "failAbandonedLaunches">, finisher: BackgroundTaskFinisher, eventLog: Pick<EventLog, "publishChanged">, sandbox: Pick<SandboxService, "cloudAvailable" | "availableFor" | "ifRunning">, config: KernelConfigService, lockService: LockService, log: KernelLogger, stopper: Pick<BackgroundTaskStopper, "stop">,
50
+ /** The marker that logs a left-alone legacy instance once across the replicas. */
59
51
  redis?: Pick<Redis, "set"> | undefined);
60
52
  poll(signal?: AbortSignal): Promise<void>;
61
53
  /**
@@ -76,15 +68,19 @@ export declare class BackgroundTaskPollJob {
76
68
  private pollManaged;
77
69
  /** The exact statuses of one instance's acknowledged managed tasks; returns how many finished. */
78
70
  private pollManagedInstance;
79
- /** Polls the tasks of one device instance; returns how many finished. */
80
- private pollSandbox;
71
+ /**
72
+ * The legacy tasks of one device instance, without any exec or signal; returns how many
73
+ * finished. A running instance is the retirement gate's: its tasks stay as they are until it
74
+ * destroys or quarantines that incarnation (said once per instance, not a warning every tick).
75
+ * An instance that is not running finishes them `lost` (a suspended one may keep their processes:
76
+ * `kill_pending`, settled by the retirement), a replaced one `sandbox_recreated`.
77
+ */
78
+ private pollLegacy;
81
79
  /**
82
80
  * Logs at `info`, once per legacy instance across the replicas (a Redis marker; every time
83
81
  * without one), that its tasks are left to the retirement gate. A Redis failure logs anyway.
84
82
  */
85
83
  private noteRetirementOnce;
86
- /** The poll exec of one instance: each task's report by id. */
87
- private pollExec;
88
84
  /** Deletes the finished tasks older than `tools.outputRetentionDays` (their rows only). */
89
85
  prune(): Promise<void>;
90
86
  }
@@ -7,7 +7,6 @@ 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 { rootsOf } from "@capybara-hq/plugin-sdk";
11
10
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
11
  import { EventLog } from "../conversations/event-log.js";
13
12
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -15,14 +14,11 @@ import { LockService } from "../infra/lock/lock.service.js";
15
14
  import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
16
15
  import { LockedInterval } from "../infra/schedule/locked-interval.js";
17
16
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
18
- import { PERMISSION_CONTEXT_ACTIVATION } from "../sandbox/permission-context-types.js";
19
17
  import { RetirementPendingError, SandboxService, } from "../sandbox/sandbox.service.js";
20
18
  import { sandboxBaseTimeoutMs } from "../tools/builtins/sandbox/common.js";
21
19
  import { BackgroundTaskFinisher } from "./finish.js";
22
20
  import { LAUNCH_EXEC_TIMEOUT_MS } from "./launch.js";
23
21
  import { exactRefOf, lastLinesByRef, onManagedInstance, statusEnd, summaryLines, } from "./managed.js";
24
- import { actingAs, taskActor } from "./session.js";
25
- import { parsePollOutput, polledAs, pollScript } from "./status.js";
26
22
  import { BackgroundTaskStopper, notRunningAs, RECREATED } from "./stop.js";
27
23
  import { BackgroundTaskStore } from "./store.js";
28
24
  /** The poll of the running background tasks (`@LockedInterval`, every `pollSeconds`). */
@@ -34,26 +30,24 @@ export const MANAGED_STOPS_PER_TICK = 8;
34
30
  /** The least age at which a reservation counts as abandoned, whatever the config. */
35
31
  const LAUNCH_ABANDONED_FLOOR_MS = 120_000;
36
32
  /**
37
- * A reservation (`sid` null) older than this has lost its launch. The slowest legitimate launch
33
+ * A reservation that never dispatched (a managed `pending` row, or a legacy row without an
34
+ * instance) older than this has lost its launch. The slowest legitimate launch
38
35
  * is the pipeline's own limit for a background `Bash` call ({@link LAUNCH_EXEC_TIMEOUT_MS} plus
39
36
  * {@link sandboxBaseTimeoutMs}: the tool timeout, `sandbox.lockWaitSeconds` and the setup margin),
40
37
  * so twice that (never under 2 minutes) leaves a wide margin: only a launching process that died
41
38
  * leaves a reservation this old.
42
39
  */
43
40
  export const launchAbandonedAfterMs = (cfg) => Math.max(LAUNCH_ABANDONED_FLOOR_MS, 2 * (LAUNCH_EXEC_TIMEOUT_MS + sandboxBaseTimeoutMs(cfg)));
44
- /** The time limit of one sandbox's poll exec. */
45
- const POLL_EXEC_TIMEOUT_MS = 30_000;
46
- /** The most output one poll exec keeps (a line per task, with a tail when it ended). */
47
- const POLL_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
48
41
  /**
49
42
  * The worker's background task jobs (spec 2026-11-05-background-bash-design §4.3), each once per
50
43
  * tick across replicas:
51
- * - `background-task-poll` (every `sandbox.background.pollSeconds`): for every device
52
- * instance with running tasks (of any conversation using it), one exec through
53
- * `SandboxService.ifRunning` (which never creates or resumes an instance) reports each task's
54
- * exit file and liveness; ended tasks finish through {@link BackgroundTaskFinisher}. Each poll
44
+ * - `background-task-poll` (every `sandbox.background.pollSeconds`): every managed task by its
45
+ * exact ref on its exact instance (through `SandboxService.ifRunning`, which never creates or
46
+ * resumes an instance); ended tasks finish through {@link BackgroundTaskFinisher}. Each poll
55
47
  * takes and releases a lease, so `last_used_at` stays fresh and an instance with running tasks
56
- * is never idle-suspended;
48
+ * is never idle-suspended. A running legacy (SID) task is never polled by any exec: while its
49
+ * instance runs it is left to the retirement gate (`RetireLegacyTasksJob`); once that instance
50
+ * is gone or replaced it finishes `lost` without any exec or signal;
57
51
  * - `background-task-prune` (daily): deletes finished tasks older than `tools.outputRetentionDays`.
58
52
  */
59
53
  let BackgroundTaskPollJob = class BackgroundTaskPollJob {
@@ -65,15 +59,9 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
65
59
  lockService;
66
60
  log;
67
61
  stopper;
68
- activation;
69
62
  redis;
70
63
  constructor(store, finisher, eventLog, sandbox, config, lockService, log, stopper,
71
- /**
72
- * The paired activation gate: once on, a legacy (SID) task is never polled by a raw exec;
73
- * its instance's poll is refused for the retirement gate ({@link pollSandbox}).
74
- */
75
- activation,
76
- /** The marker that logs a refused legacy poll once per instance across the replicas. */
64
+ /** The marker that logs a left-alone legacy instance once across the replicas. */
77
65
  redis) {
78
66
  this.store = store;
79
67
  this.finisher = finisher;
@@ -83,7 +71,6 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
83
71
  this.lockService = lockService;
84
72
  this.log = log;
85
73
  this.stopper = stopper;
86
- this.activation = activation;
87
74
  this.redis = redis;
88
75
  }
89
76
  async poll(signal) {
@@ -107,10 +94,10 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
107
94
  await this.eventLog.publishChanged(c, "background");
108
95
  }
109
96
  const groups = new Map();
110
- for (const t of await this.store.runningStarted()) {
111
- if (t.sid === null || t.sandboxCreatedAt === null)
97
+ for (const t of await this.store.runningLegacy()) {
98
+ if (t.sandboxCreatedAt === null)
112
99
  continue;
113
- // one exec per instance: the tasks of every conversation sharing the device
100
+ // one look per instance: the tasks of every conversation sharing the device
114
101
  const key = `${t.deviceId} ${t.sandboxCreatedAt.getTime()}`;
115
102
  groups.set(key, [...(groups.get(key) ?? []), t]);
116
103
  }
@@ -125,12 +112,12 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
125
112
  if (env === null ? !this.sandbox.cloudAvailable : !(await this.sandbox.availableFor(env))) {
126
113
  continue;
127
114
  }
128
- finished += await this.pollSandbox(tasks, signal);
115
+ finished += await this.pollLegacy(tasks, signal);
129
116
  }
130
117
  catch (err) {
131
118
  if (signal.aborted)
132
119
  break;
133
- this.log.warn("cannot poll background tasks; retrying next tick", {
120
+ this.log.warn("cannot check legacy background tasks; retrying next tick", {
134
121
  deviceId: tasks[0]?.deviceId,
135
122
  err,
136
123
  });
@@ -252,8 +239,14 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
252
239
  }
253
240
  return n;
254
241
  }
255
- /** Polls the tasks of one device instance; returns how many finished. */
256
- async pollSandbox(tasks, signal) {
242
+ /**
243
+ * The legacy tasks of one device instance, without any exec or signal; returns how many
244
+ * finished. A running instance is the retirement gate's: its tasks stay as they are until it
245
+ * destroys or quarantines that incarnation (said once per instance, not a warning every tick).
246
+ * An instance that is not running finishes them `lost` (a suspended one may keep their processes:
247
+ * `kill_pending`, settled by the retirement), a replaced one `sandbox_recreated`.
248
+ */
249
+ async pollLegacy(tasks, signal) {
257
250
  const [first] = tasks;
258
251
  // a task from before devices has no instance any more
259
252
  let r;
@@ -261,36 +254,23 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
261
254
  r =
262
255
  first.deviceId === null
263
256
  ? { kind: "not_running", status: "gone" }
264
- : await this.sandbox.ifRunning(first.deviceId, { createdAt: first.sandboxCreatedAt }, (p, h, sig) => this.pollExec(actingAs(p, taskActor(first), this.activation), h, tasks, sig), signal);
257
+ : await this.sandbox.ifRunning(first.deviceId, { createdAt: first.sandboxCreatedAt }, async () => "running", signal);
265
258
  }
266
259
  catch (err) {
267
- // once activated, a running legacy instance is the retirement gate's: its tasks stay as
268
- // they are until it retires them; said once per instance, not as a warning every tick
260
+ // the lifecycle gate refuses the instance itself: the same retirement owns it
269
261
  if (!(err instanceof RetirementPendingError))
270
262
  throw err;
263
+ r = { kind: "ran", value: "running" };
264
+ }
265
+ if (r.kind === "ran") {
271
266
  await this.noteRetirementOnce(first);
272
267
  return 0;
273
268
  }
274
- const now = new Date();
275
269
  let n = 0;
276
270
  for (const t of tasks) {
277
- let to;
278
- let lastLines = "";
279
- if (r.kind === "ran") {
280
- const report = r.value.get(t.id);
281
- // a task the exec did not report is checked again next tick
282
- to = report ? polledAs(t, report, now) : null;
283
- lastLines = report?.lastLines ?? "";
284
- }
285
- else if (r.kind === "not_running") {
286
- // a suspended sandbox may keep the processes (E2B's pause): killed after its next resume
287
- to = notRunningAs(r.status, r.status === "suspended");
288
- }
289
- else {
290
- to = RECREATED;
291
- }
271
+ const to = r.kind === "not_running" ? notRunningAs(r.status, r.status === "suspended") : RECREATED;
292
272
  // a stop that claimed the task after the read above finishes it itself
293
- if (to && (await this.finisher.finish(t, to, lastLines, false, { unclaimed: true })))
273
+ if (await this.finisher.finish(t, to, "", false, { unclaimed: true }))
294
274
  n++;
295
275
  }
296
276
  return n;
@@ -314,20 +294,6 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
314
294
  instanceGeneration: first.sandboxCreatedAt?.getTime(),
315
295
  });
316
296
  }
317
- /** The poll exec of one instance: each task's report by id. */
318
- async pollExec(p, h, tasks, signal) {
319
- const res = await p.exec(h, {
320
- command: pollScript(tasks.map((t) => ({ id: t.id, sid: t.sid }))),
321
- cwd: rootsOf(h).workspace,
322
- timeoutMs: POLL_EXEC_TIMEOUT_MS,
323
- maxOutputBytes: POLL_MAX_OUTPUT_BYTES,
324
- signal,
325
- });
326
- if (res.exitCode !== 0 || res.truncated) {
327
- throw new Error(`the poll exec failed (exit ${res.exitCode}${res.truncated ? ", truncated" : ""}): ${res.stderr.slice(0, 500)}`);
328
- }
329
- return parsePollOutput(res.stdout);
330
- }
331
297
  /** Deletes the finished tasks older than `tools.outputRetentionDays` (their rows only). */
332
298
  async prune() {
333
299
  const days = this.config.get().tools.outputRetentionDays;
@@ -353,8 +319,6 @@ BackgroundTaskPollJob = __decorate([
353
319
  __param(6, Inject(KERNEL_LOGGER)),
354
320
  __param(7, Inject(BackgroundTaskStopper)),
355
321
  __param(8, Optional()),
356
- __param(8, Inject(PERMISSION_CONTEXT_ACTIVATION)),
357
- __param(9, Optional()),
358
- __param(9, Inject(REDIS))
322
+ __param(8, Inject(REDIS))
359
323
  ], BackgroundTaskPollJob);
360
324
  export { BackgroundTaskPollJob };
@@ -3,6 +3,15 @@ import type { EventPayload } from "../conversations/events.js";
3
3
  export declare function formatElapsed(ms: number): string;
4
4
  /** Why a task was lost, as the model reads it (an unknown reason as is). */
5
5
  export declare const lostReasonText: (reason: string) => string;
6
+ /**
7
+ * A task's lost or failure reason as the model reads it (`TaskOutput`, `TaskList`): kernel text
8
+ * only. A managed task's reasons are the kernel's own; a legacy row's unknown reason is the old
9
+ * launcher's raw text and is replaced.
10
+ */
11
+ export declare function taskReasonText(task: {
12
+ lostReason: string | null;
13
+ launchState: string;
14
+ }): string;
6
15
  type Finished = EventPayload<"background_task_finished">;
7
16
  /**
8
17
  * The model-visible text of a `background_task_finished` event, rendered as a system message (spec
@@ -15,9 +15,28 @@ const LOST_REASONS = {
15
15
  process_gone: "its processes ended without an exit code",
16
16
  launch_abandoned: "its launch was interrupted",
17
17
  supervision_lost: "its supervision was lost",
18
+ launch_unknown: "whether its launch started could not be confirmed; any process it started is being stopped",
19
+ launch_revoked: "its launch was revoked before its start was confirmed; any process it started is being stopped",
18
20
  };
19
21
  /** Why a task was lost, as the model reads it (an unknown reason as is). */
20
22
  export const lostReasonText = (reason) => LOST_REASONS[reason] ?? reason;
23
+ /**
24
+ * Why a legacy (SID) launch failed is recorded in the old launcher's raw words (a provider's
25
+ * stderr): never shown, the model gets this instead.
26
+ */
27
+ const LEGACY_LAUNCH_FAILED = "its launch failed under an earlier version of the device runtime; call Bash with run_in_background again to start it";
28
+ /**
29
+ * A task's lost or failure reason as the model reads it (`TaskOutput`, `TaskList`): kernel text
30
+ * only. A managed task's reasons are the kernel's own; a legacy row's unknown reason is the old
31
+ * launcher's raw text and is replaced.
32
+ */
33
+ export function taskReasonText(task) {
34
+ const reason = task.lostReason ?? "";
35
+ const known = lostReasonText(reason);
36
+ if (known !== reason || task.launchState !== "legacy")
37
+ return known;
38
+ return LEGACY_LAUNCH_FAILED;
39
+ }
21
40
  const statusWord = (status) => status === "timed_out" ? "timed out" : status;
22
41
  /**
23
42
  * The model-visible text of a `background_task_finished` event, rendered as a system message (spec