@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.
- package/dist/admin/admin.schemas.d.ts +0 -6
- package/dist/background/launch.d.ts +7 -61
- package/dist/background/launch.js +8 -133
- package/dist/background/poll.job.d.ts +19 -23
- package/dist/background/poll.job.js +30 -66
- package/dist/background/render.d.ts +9 -0
- package/dist/background/render.js +19 -0
- package/dist/background/session.d.ts +3 -66
- package/dist/background/session.js +3 -114
- package/dist/background/stop.d.ts +26 -33
- package/dist/background/stop.js +59 -90
- package/dist/background/store.d.ts +26 -60
- package/dist/background/store.js +23 -108
- package/dist/background/tasks.service.d.ts +9 -29
- package/dist/background/tasks.service.js +18 -115
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/cards.d.ts +3 -0
- package/dist/channels/cards.js +29 -2
- package/dist/channels/phrases.d.ts +35 -0
- package/dist/channels/phrases.js +32 -0
- package/dist/config/load.d.ts +3 -10
- package/dist/config/load.js +26 -21
- package/dist/config/schema.js +3 -3
- package/dist/conversations/events.d.ts +45 -2
- package/dist/conversations/events.js +44 -4
- package/dist/db/kernel-schema.d.ts +9 -4
- package/dist/devices/devices.service.js +1 -1
- package/dist/devices/errors.d.ts +5 -0
- package/dist/devices/errors.js +5 -0
- package/dist/devices/project-rules.d.ts +2 -2
- package/dist/errors.d.ts +9 -11
- package/dist/errors.js +9 -11
- package/dist/identity/settings.d.ts +4 -17
- package/dist/identity/settings.js +9 -32
- package/dist/infra/config/kernel-config.service.js +2 -9
- package/dist/infra/outbox/registry.d.ts +13 -0
- package/dist/infra/outbox/registry.js +8 -0
- package/dist/local-devices/device-auth.controller.d.ts +1 -1
- package/dist/local-devices/device-auth.controller.js +1 -1
- package/dist/local-devices/device-auth.d.ts +4 -3
- package/dist/local-devices/device-auth.js +1 -1
- package/dist/local-devices/device-policy.service.d.ts +6 -6
- package/dist/local-devices/device-routes.d.ts +4 -2
- package/dist/local-devices/device-routes.js +7 -6
- package/dist/local-devices/instance-bindings.d.ts +4 -4
- package/dist/local-devices/instance-bindings.js +2 -2
- package/dist/local-devices/local-device-gateway.d.ts +12 -12
- package/dist/local-devices/local-device-gateway.js +94 -129
- package/dist/local-devices/local-device-provider.d.ts +19 -87
- package/dist/local-devices/local-device-provider.js +43 -158
- package/dist/local-devices/local-devices.module.d.ts +4 -5
- package/dist/local-devices/local-devices.module.js +6 -9
- package/dist/local-devices/machines.d.ts +6 -6
- package/dist/local-devices/machines.js +4 -4
- package/dist/local-devices/owner-report.d.ts +3 -3
- package/dist/local-devices/owner-report.js +4 -4
- package/dist/local-devices/owner-reports.js +2 -2
- package/dist/local-devices/policy-summary.js +2 -2
- package/dist/local-devices/relay.d.ts +12 -25
- package/dist/local-devices/relay.js +17 -31
- package/dist/orgs/settings.controller.d.ts +1 -4
- package/dist/orgs/settings.controller.js +3 -3
- package/dist/orgs/settings.service.d.ts +7 -21
- package/dist/orgs/settings.service.js +16 -40
- package/dist/overrides.d.ts +3 -3
- package/dist/platform/ops/admin.ops.js +6 -8
- package/dist/platform/ops/org-settings.ops.js +4 -4
- package/dist/platform/ops/orgs.ops.js +0 -1
- package/dist/runtime/maintenance.d.ts +1 -1
- package/dist/runtime/maintenance.js +7 -1
- package/dist/runtime/run-steps.js +2 -2
- package/dist/sandbox/held-operations.d.ts +7 -0
- package/dist/sandbox/held-operations.js +25 -1
- package/dist/sandbox/leases.d.ts +6 -3
- package/dist/sandbox/leases.js +16 -10
- package/dist/sandbox/legacy-retirement.d.ts +0 -19
- package/dist/sandbox/legacy-retirement.js +6 -37
- package/dist/sandbox/managed-device-context.d.ts +12 -0
- package/dist/sandbox/managed-device-context.js +49 -1
- package/dist/sandbox/modes.d.ts +9 -8
- package/dist/sandbox/modes.js +4 -15
- package/dist/sandbox/operation-authority-types.d.ts +18 -1
- package/dist/sandbox/operation-authority-types.js +20 -1
- package/dist/sandbox/operation-authority.d.ts +14 -0
- package/dist/sandbox/operation-authority.js +120 -18
- package/dist/sandbox/operation-intents.d.ts +43 -0
- package/dist/sandbox/operation-intents.js +107 -4
- package/dist/sandbox/operation-reconcile.job.d.ts +12 -1
- package/dist/sandbox/operation-reconcile.job.js +53 -6
- package/dist/sandbox/permission-call-grants.d.ts +4 -0
- package/dist/sandbox/permission-call-grants.js +32 -3
- package/dist/sandbox/permission-call-types.d.ts +27 -2
- package/dist/sandbox/permission-ceiling-writes.js +2 -1
- package/dist/sandbox/permission-context-types.d.ts +2 -2
- package/dist/sandbox/permission-context-types.js +2 -2
- package/dist/sandbox/permission-facts.js +10 -2
- package/dist/sandbox/platform-full-access.d.ts +8 -26
- package/dist/sandbox/platform-full-access.js +8 -20
- package/dist/sandbox/review/classifier.d.ts +2 -2
- package/dist/sandbox/review/classifier.js +18 -5
- package/dist/sandbox/review/permission-candidate.d.ts +59 -3
- package/dist/sandbox/review/permission-candidate.js +192 -25
- package/dist/sandbox/review/review.service.d.ts +18 -0
- package/dist/sandbox/review/review.service.js +158 -12
- package/dist/sandbox/sandbox.service.d.ts +71 -47
- package/dist/sandbox/sandbox.service.js +234 -133
- package/dist/tools/approvals.service.d.ts +6 -1
- package/dist/tools/approvals.service.js +10 -0
- package/dist/tools/builtins/builtin-tools.d.ts +1 -4
- package/dist/tools/builtins/builtin-tools.js +13 -18
- package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
- package/dist/tools/builtins/sandbox/bash.js +92 -270
- package/dist/tools/builtins/sandbox/common.d.ts +15 -9
- package/dist/tools/builtins/sandbox/common.js +55 -19
- package/dist/tools/builtins/sandbox/device-owner.d.ts +13 -0
- package/dist/tools/builtins/sandbox/device-owner.js +14 -0
- package/dist/tools/builtins/sandbox/task-list.js +2 -2
- package/dist/tools/builtins/sandbox/task-output.d.ts +14 -57
- package/dist/tools/builtins/sandbox/task-output.js +88 -210
- package/dist/tools/builtins/sandbox/task-stop.d.ts +2 -2
- package/dist/tools/builtins/sandbox/task-stop.js +15 -26
- package/dist/tools/pipeline.d.ts +31 -2
- package/dist/tools/pipeline.js +273 -43
- package/dist/tools/registry.d.ts +7 -0
- package/package.json +4 -4
- package/src/migrations/0162_permission_call_escalation.sql +9 -0
- package/dist/background/status.d.ts +0 -35
- package/dist/background/status.js +0 -57
|
@@ -1,70 +1,7 @@
|
|
|
1
|
-
import { type SandboxActor, type SandboxHandle } from "@capybara-hq/plugin-sdk";
|
|
2
|
-
import { type HeldProvider, type TaggedProvider } from "../sandbox/sandbox.service.js";
|
|
3
1
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* Linux). macOS has no `setsid` and its `pgrep` / `pkill` no `-s`: there the task is the process
|
|
8
|
-
* group the launch made (`launchScript`), signalled with `kill -- -<sid>` ({@link SESSION_MODE_SCRIPT}).
|
|
2
|
+
* What a background task's finish keeps of its output (spec 2026-11-05-background-bash-design
|
|
3
|
+
* §2.4). A task is reached only by its exact execution ref (permission runtime cutover phase 8.3):
|
|
4
|
+
* no session id, process group or shell script identifies it.
|
|
9
5
|
*/
|
|
10
|
-
/**
|
|
11
|
-
* Whether a legacy (SID) task may still be driven by a raw exec: only while the one activation
|
|
12
|
-
* gate is off (`activation`: the injected gate, else the production state). Once it is on, a
|
|
13
|
-
* legacy row is the retirement gate's (8.5): no SID poll, read or stop runs, and its device stays
|
|
14
|
-
* unavailable until the old incarnation is confirmed gone (permission activation W3-L).
|
|
15
|
-
*/
|
|
16
|
-
export declare const legacyBackgroundAllowed: (activation?: boolean) => boolean;
|
|
17
|
-
/**
|
|
18
|
-
* `p` with every `exec` carrying `actor` (`SandboxService.ifRunning` tags execs but leaves the
|
|
19
|
-
* actor to the caller): the provider then reads like a `withSandbox` holder's. Once the
|
|
20
|
-
* activation gate is on ({@link legacyBackgroundAllowed}) every exec refuses before reaching the
|
|
21
|
-
* provider with the retirement refusal: a legacy task is never driven by a raw exec then.
|
|
22
|
-
*/
|
|
23
|
-
export declare function actingAs(p: TaggedProvider, actor: SandboxActor, activation?: boolean): HeldProvider;
|
|
24
|
-
/** Who a background task's own execs (poll, stop, reads) act for: its trigger and its owner. */
|
|
25
|
-
export declare const taskActor: (task: {
|
|
26
|
-
triggerAccountId: string;
|
|
27
|
-
conversationId: string;
|
|
28
|
-
}) => SandboxActor;
|
|
29
|
-
/** A session id (the pid `setsid` started). */
|
|
30
|
-
export declare const SID_RE: RegExp;
|
|
31
|
-
/** The time limit of one kill of a session ({@link killSession}). */
|
|
32
|
-
export declare const KILL_SESSION_TIMEOUT_MS = 10000;
|
|
33
|
-
/** Throws unless `id` is a task id and `sid` a session id (both go into scripts unquoted). */
|
|
34
|
-
export declare function assertTaskRef(id: string, sid: string): void;
|
|
35
|
-
/**
|
|
36
|
-
* A shell fragment that kills every process of the session `sid` with SIGKILL, repeated until the
|
|
37
|
-
* session is empty (pkill exits 1: no process left): a process may fork between pkill's listing
|
|
38
|
-
* and its signals, and the child would live on. Sets `ks` to 0 when the session was confirmed
|
|
39
|
-
* empty, else to pkill's failing status (3 when it was still not empty after 10 tries). Uses only
|
|
40
|
-
* the variables and functions of {@link SESSION_MODE_SCRIPT} (it starts with it), `ks`, `kc` and `ki`. `sid` must be
|
|
41
|
-
* a session id.
|
|
42
|
-
*/
|
|
43
|
-
export declare function killSessionScript(sid: string): string;
|
|
44
|
-
/**
|
|
45
|
-
* Kills every process of the session `sid` ({@link killSessionScript}) in an exec of its own. Any
|
|
46
|
-
* pkill status other than 0 and 1 is a failure. Runs with a fresh signal of its own (a command
|
|
47
|
-
* must be killed even when the caller was just aborted). True when the session was confirmed
|
|
48
|
-
* empty; false when it could not be (an error is never thrown). Once the activation gate is on
|
|
49
|
-
* ({@link legacyBackgroundAllowed}) nothing runs and the session is not confirmed empty.
|
|
50
|
-
*/
|
|
51
|
-
export declare function killSession(p: Pick<HeldProvider, "exec">, h: SandboxHandle, sid: string, activation?: boolean): Promise<boolean>;
|
|
52
|
-
/** How long a stop waits after SIGTERM before SIGKILL (spec §2.3). */
|
|
53
|
-
export declare const STOP_GRACE_MS = 5000;
|
|
54
|
-
/** The time limit of the SIGTERM exec: the grace period plus some room. */
|
|
55
|
-
export declare const TERM_EXEC_TIMEOUT_MS: number;
|
|
56
|
-
/**
|
|
57
|
-
* Exit code 0 with `exited <code>` when the task had already finished (its exit file exists),
|
|
58
|
-
* else sends SIGTERM to the session and waits up to {@link STOP_GRACE_MS} for it to empty, then
|
|
59
|
-
* prints `term`. Relative to the workspace root.
|
|
60
|
-
*/
|
|
61
|
-
export declare function termScript(id: string, sid: string): string;
|
|
62
6
|
/** The longest `lastLines` of a finished task (spec §2.4). */
|
|
63
7
|
export declare const LAST_LINES_MAX_CHARS = 4000;
|
|
64
|
-
/**
|
|
65
|
-
* A shell pipeline printing the last 20 lines of task `id`'s output (at most {@link TAIL_BYTES}),
|
|
66
|
-
* base64 on one line (empty when there is no output file). Relative to the workspace root.
|
|
67
|
-
*/
|
|
68
|
-
export declare function tailCommand(id: string): string;
|
|
69
|
-
/** Decodes a {@link tailCommand} result into `lastLines`: its end, at most 4 000 characters. */
|
|
70
|
-
export declare function decodeTail(b64: string): string;
|
|
@@ -1,118 +1,7 @@
|
|
|
1
|
-
import { rootsOf } from "@capybara-hq/plugin-sdk";
|
|
2
|
-
import { permissionContextActive } from "../sandbox/permission-context-types.js";
|
|
3
|
-
import { retirementPending, } from "../sandbox/sandbox.service.js";
|
|
4
|
-
import { SESSION_MODE_SCRIPT, TASK_ID_RE, TASKS_DIR } from "./launch.js";
|
|
5
1
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* Linux). macOS has no `setsid` and its `pgrep` / `pkill` no `-s`: there the task is the process
|
|
10
|
-
* group the launch made (`launchScript`), signalled with `kill -- -<sid>` ({@link SESSION_MODE_SCRIPT}).
|
|
2
|
+
* What a background task's finish keeps of its output (spec 2026-11-05-background-bash-design
|
|
3
|
+
* §2.4). A task is reached only by its exact execution ref (permission runtime cutover phase 8.3):
|
|
4
|
+
* no session id, process group or shell script identifies it.
|
|
11
5
|
*/
|
|
12
|
-
/**
|
|
13
|
-
* Whether a legacy (SID) task may still be driven by a raw exec: only while the one activation
|
|
14
|
-
* gate is off (`activation`: the injected gate, else the production state). Once it is on, a
|
|
15
|
-
* legacy row is the retirement gate's (8.5): no SID poll, read or stop runs, and its device stays
|
|
16
|
-
* unavailable until the old incarnation is confirmed gone (permission activation W3-L).
|
|
17
|
-
*/
|
|
18
|
-
export const legacyBackgroundAllowed = (activation) => !permissionContextActive(activation);
|
|
19
|
-
/**
|
|
20
|
-
* `p` with every `exec` carrying `actor` (`SandboxService.ifRunning` tags execs but leaves the
|
|
21
|
-
* actor to the caller): the provider then reads like a `withSandbox` holder's. Once the
|
|
22
|
-
* activation gate is on ({@link legacyBackgroundAllowed}) every exec refuses before reaching the
|
|
23
|
-
* provider with the retirement refusal: a legacy task is never driven by a raw exec then.
|
|
24
|
-
*/
|
|
25
|
-
export function actingAs(p, actor, activation) {
|
|
26
|
-
const wrapped = Object.create(p);
|
|
27
|
-
Object.defineProperty(wrapped, "exec", {
|
|
28
|
-
value: async (h, args) => {
|
|
29
|
-
if (!legacyBackgroundAllowed(activation))
|
|
30
|
-
throw retirementPending();
|
|
31
|
-
return p.exec(h, { ...args, actor });
|
|
32
|
-
},
|
|
33
|
-
});
|
|
34
|
-
return wrapped;
|
|
35
|
-
}
|
|
36
|
-
/** Who a background task's own execs (poll, stop, reads) act for: its trigger and its owner. */
|
|
37
|
-
export const taskActor = (task) => ({ accountId: task.triggerAccountId, conversationId: task.conversationId });
|
|
38
|
-
/** A session id (the pid `setsid` started). */
|
|
39
|
-
export const SID_RE = /^[1-9][0-9]*$/;
|
|
40
|
-
/** The time limit of one kill of a session ({@link killSession}). */
|
|
41
|
-
export const KILL_SESSION_TIMEOUT_MS = 10_000;
|
|
42
|
-
/** Throws unless `id` is a task id and `sid` a session id (both go into scripts unquoted). */
|
|
43
|
-
export function assertTaskRef(id, sid) {
|
|
44
|
-
if (!TASK_ID_RE.test(id))
|
|
45
|
-
throw new Error(`invalid background task id: ${JSON.stringify(id)}`);
|
|
46
|
-
if (!SID_RE.test(sid))
|
|
47
|
-
throw new Error(`invalid background task session: ${JSON.stringify(sid)}`);
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* A shell fragment that kills every process of the session `sid` with SIGKILL, repeated until the
|
|
51
|
-
* session is empty (pkill exits 1: no process left): a process may fork between pkill's listing
|
|
52
|
-
* and its signals, and the child would live on. Sets `ks` to 0 when the session was confirmed
|
|
53
|
-
* empty, else to pkill's failing status (3 when it was still not empty after 10 tries). Uses only
|
|
54
|
-
* the variables and functions of {@link SESSION_MODE_SCRIPT} (it starts with it), `ks`, `kc` and `ki`. `sid` must be
|
|
55
|
-
* a session id.
|
|
56
|
-
*/
|
|
57
|
-
export function killSessionScript(sid) {
|
|
58
|
-
if (!SID_RE.test(sid))
|
|
59
|
-
throw new Error(`invalid background task session: ${JSON.stringify(sid)}`);
|
|
60
|
-
return `${SESSION_MODE_SCRIPT}\nks=3; for ki in 1 2 3 4 5 6 7 8 9 10; do tk_kill KILL ${sid}; kc=$?; if [ "$kc" -eq 1 ]; then ks=0; break; fi; if [ "$kc" -ne 0 ]; then ks=$kc; break; fi; sleep 0.2; done`;
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Kills every process of the session `sid` ({@link killSessionScript}) in an exec of its own. Any
|
|
64
|
-
* pkill status other than 0 and 1 is a failure. Runs with a fresh signal of its own (a command
|
|
65
|
-
* must be killed even when the caller was just aborted). True when the session was confirmed
|
|
66
|
-
* empty; false when it could not be (an error is never thrown). Once the activation gate is on
|
|
67
|
-
* ({@link legacyBackgroundAllowed}) nothing runs and the session is not confirmed empty.
|
|
68
|
-
*/
|
|
69
|
-
export async function killSession(p, h, sid, activation) {
|
|
70
|
-
if (!SID_RE.test(sid) || !legacyBackgroundAllowed(activation))
|
|
71
|
-
return false;
|
|
72
|
-
const r = await p
|
|
73
|
-
.exec(h, {
|
|
74
|
-
command: `${killSessionScript(sid)}; exit "$ks"`,
|
|
75
|
-
cwd: rootsOf(h).workspace,
|
|
76
|
-
timeoutMs: KILL_SESSION_TIMEOUT_MS,
|
|
77
|
-
maxOutputBytes: 4096,
|
|
78
|
-
signal: AbortSignal.timeout(KILL_SESSION_TIMEOUT_MS),
|
|
79
|
-
})
|
|
80
|
-
.catch(() => undefined);
|
|
81
|
-
return r?.exitCode === 0;
|
|
82
|
-
}
|
|
83
|
-
/** How long a stop waits after SIGTERM before SIGKILL (spec §2.3). */
|
|
84
|
-
export const STOP_GRACE_MS = 5000;
|
|
85
|
-
/** The time limit of the SIGTERM exec: the grace period plus some room. */
|
|
86
|
-
export const TERM_EXEC_TIMEOUT_MS = STOP_GRACE_MS + 5000;
|
|
87
|
-
/**
|
|
88
|
-
* Exit code 0 with `exited <code>` when the task had already finished (its exit file exists),
|
|
89
|
-
* else sends SIGTERM to the session and waits up to {@link STOP_GRACE_MS} for it to empty, then
|
|
90
|
-
* prints `term`. Relative to the workspace root.
|
|
91
|
-
*/
|
|
92
|
-
export function termScript(id, sid) {
|
|
93
|
-
const f = `${TASKS_DIR}/${id}`;
|
|
94
|
-
const tries = Math.ceil(STOP_GRACE_MS / 200);
|
|
95
|
-
return [
|
|
96
|
-
`if [ -s ${f}.exit ]; then echo "exited $(cat ${f}.exit)"; exit 0; fi`,
|
|
97
|
-
SESSION_MODE_SCRIPT,
|
|
98
|
-
`tk_kill TERM ${sid} >/dev/null 2>&1`,
|
|
99
|
-
`i=0; while [ "$i" -lt ${tries} ] && tk_alive ${sid}; do sleep 0.2; i=$((i+1)); done`,
|
|
100
|
-
"echo term",
|
|
101
|
-
].join("\n");
|
|
102
|
-
}
|
|
103
|
-
/** The most bytes of a task's output end a tail reads (the event keeps at most 4 000 characters). */
|
|
104
|
-
const TAIL_BYTES = 12_000;
|
|
105
6
|
/** The longest `lastLines` of a finished task (spec §2.4). */
|
|
106
7
|
export const LAST_LINES_MAX_CHARS = 4000;
|
|
107
|
-
/**
|
|
108
|
-
* A shell pipeline printing the last 20 lines of task `id`'s output (at most {@link TAIL_BYTES}),
|
|
109
|
-
* base64 on one line (empty when there is no output file). Relative to the workspace root.
|
|
110
|
-
*/
|
|
111
|
-
export function tailCommand(id) {
|
|
112
|
-
return `{ tail -n 20 ${TASKS_DIR}/${id}.out 2>/dev/null | tail -c ${TAIL_BYTES} | base64 | tr -d '\\n'; }`;
|
|
113
|
-
}
|
|
114
|
-
/** Decodes a {@link tailCommand} result into `lastLines`: its end, at most 4 000 characters. */
|
|
115
|
-
export function decodeTail(b64) {
|
|
116
|
-
const text = Buffer.from(b64.trim(), "base64").toString("utf8");
|
|
117
|
-
return text.length > LAST_LINES_MAX_CHARS ? text.slice(-LAST_LINES_MAX_CHARS) : text;
|
|
118
|
-
}
|
|
@@ -8,20 +8,17 @@ import { type BackgroundTaskRow, BackgroundTaskStore } from "./store.js";
|
|
|
8
8
|
* conversation, unless a stop asked for it before: that asker's rule holds).
|
|
9
9
|
*/
|
|
10
10
|
export type StopReason = "tool" | "person" | "subagent_end" | "conversation_deleted" | "revoked";
|
|
11
|
-
/** How a task that exited by itself ends (spec §4.3): exit 137 past its deadline timed out. */
|
|
12
|
-
export declare function exitedAs(task: BackgroundTaskRow, code: number, now: Date): BackgroundFinish;
|
|
13
11
|
/** How a task whose sandbox is not running ends (`ifRunning`'s `not_running` status). */
|
|
14
12
|
export declare function notRunningAs(status: string, killPending: boolean): BackgroundFinish;
|
|
15
13
|
/** A task found in another sandbox instance (a rebuild): its processes are gone with the old one. */
|
|
16
14
|
export declare const RECREATED: BackgroundFinish;
|
|
17
15
|
/**
|
|
18
|
-
* Stops background tasks (spec 2026-11-05-background-bash-design §2.3, §4.3
|
|
19
|
-
*
|
|
20
|
-
* `SandboxService.ifRunning` (it never creates or resumes a sandbox)
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* already exited left running are killed as well.
|
|
16
|
+
* Stops background tasks (spec 2026-11-05-background-bash-design §2.3, §4.3, permission runtime
|
|
17
|
+
* cutover phase 8.3): a managed task by its exact ref on its exact instance only, through
|
|
18
|
+
* `SandboxService.ifRunning` (it never creates or resumes a sandbox). A legacy (SID) task is never
|
|
19
|
+
* signalled: while its instance runs it belongs to the retirement gate (`RetireLegacyTasksJob`),
|
|
20
|
+
* and its stop is refused with that gate's actionable refusal; once its instance is gone or
|
|
21
|
+
* replaced it finishes `lost` without any exec or signal.
|
|
25
22
|
*/
|
|
26
23
|
export declare class BackgroundTaskStopper {
|
|
27
24
|
private readonly store;
|
|
@@ -29,30 +26,17 @@ export declare class BackgroundTaskStopper {
|
|
|
29
26
|
private readonly sandbox;
|
|
30
27
|
private readonly db;
|
|
31
28
|
private readonly log;
|
|
32
|
-
|
|
33
|
-
* The paired activation gate: once on, a legacy (SID) task's stop refuses with the retirement
|
|
34
|
-
* refusal exactly when it would run an exec (its instance runs); one whose instance is gone
|
|
35
|
-
* or replaced still finishes without one. A managed task always stops by its exact ref.
|
|
36
|
-
*/
|
|
37
|
-
private readonly activation?;
|
|
38
|
-
constructor(store: Pick<BackgroundTaskStore, "get" | "runningOwnedBy" | "runningIn" | "claimStop" | "releaseStop" | "requestCancel" | "noteCancelAttempt">, finisher: BackgroundTaskFinisher, sandbox: Pick<SandboxService, "ifRunning">, db: KernelDb, log: Pick<KernelLogger, "warn">,
|
|
39
|
-
/**
|
|
40
|
-
* The paired activation gate: once on, a legacy (SID) task's stop refuses with the retirement
|
|
41
|
-
* refusal exactly when it would run an exec (its instance runs); one whose instance is gone
|
|
42
|
-
* or replaced still finishes without one. A managed task always stops by its exact ref.
|
|
43
|
-
*/
|
|
44
|
-
activation?: boolean | undefined);
|
|
29
|
+
constructor(store: Pick<BackgroundTaskStore, "get" | "runningOwnedBy" | "runningIn" | "claimStop" | "releaseStop" | "requestCancel" | "noteCancelAttempt">, finisher: BackgroundTaskFinisher, sandbox: Pick<SandboxService, "ifRunning">, db: KernelDb, log: Pick<KernelLogger, "warn">);
|
|
45
30
|
/**
|
|
46
31
|
* Stops `task` and returns its row afterwards. A task that is no longer running, or that another
|
|
47
32
|
* live stop already claimed, is returned as it is now.
|
|
48
33
|
*
|
|
49
|
-
* The stop first claims the task (`stopping_at`), so the poller leaves it alone while the
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
* finish (a managed task's cancellation settled from a TaskOutput read).
|
|
34
|
+
* The stop first claims the task (`stopping_at`), so the poller leaves it alone while the stop
|
|
35
|
+
* takes effect and the stop's finish is its only one. A legacy reservation that never started
|
|
36
|
+
* (no instance) is only claimed: the poller fails it as abandoned. When the stop fails while the
|
|
37
|
+
* sandbox runs (busy, a provider error, a legacy task's retirement refusal), the claim is given
|
|
38
|
+
* up, the task stays `running` and the error is thrown. `how.reported`: the caller's own result
|
|
39
|
+
* tells the model this finish (a managed task's cancellation settled from a TaskOutput read).
|
|
56
40
|
*/
|
|
57
41
|
stop(task: BackgroundTaskRow, why: StopReason, signal?: AbortSignal, how?: {
|
|
58
42
|
reported?: boolean;
|
|
@@ -68,12 +52,19 @@ export declare class BackgroundTaskStopper {
|
|
|
68
52
|
* running (never resumed) or was replaced leaves the cancellation owed. Who asked is recorded,
|
|
69
53
|
* so a later finish keeps their wake rule.
|
|
70
54
|
*/
|
|
55
|
+
/**
|
|
56
|
+
* `conversation_deleted` when the task's conversation, its tree's root (the device's
|
|
57
|
+
* conversation, a sub-agent's root) or its org is deleted or gone, else null.
|
|
58
|
+
*/
|
|
59
|
+
private deletedConversationStop;
|
|
71
60
|
private stopManaged;
|
|
72
61
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
62
|
+
* A legacy task's own instance, never signalled: a running one refuses with the retirement
|
|
63
|
+
* gate's refusal before any provider call (the gate retires it and its processes whole); one
|
|
64
|
+
* that is not running or was replaced is reported, so the task finishes without any exec or
|
|
65
|
+
* signal. A task from before devices has none.
|
|
75
66
|
*/
|
|
76
|
-
private
|
|
67
|
+
private legacyInstance;
|
|
77
68
|
/**
|
|
78
69
|
* After a sub-agent run ended (spec §4.3): stops the running tasks of `conversationId` when it
|
|
79
70
|
* is a sub-agent's conversation; any other conversation is left alone. With `runId`, only the
|
|
@@ -90,7 +81,9 @@ export declare class BackgroundTaskStopper {
|
|
|
90
81
|
stopForDeletedConversation(conversationId: string): Promise<void>;
|
|
91
82
|
/**
|
|
92
83
|
* Stops `tasks` side by side. A stop that fails while the sandbox runs leaves its task running
|
|
93
|
-
* (logged):
|
|
84
|
+
* (logged): a managed task stays owed to the poller and ends at its own deadline at the latest;
|
|
85
|
+
* a legacy task stays with the retirement gate until its instance is destroyed or quarantined
|
|
86
|
+
* (no deadline ends it in the kernel's view).
|
|
94
87
|
*/
|
|
95
88
|
private stopAll;
|
|
96
89
|
}
|
package/dist/background/stop.js
CHANGED
|
@@ -7,27 +7,13 @@ 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 {
|
|
11
|
-
import { Inject, Injectable, Optional } from "@nestjs/common";
|
|
10
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
11
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
13
12
|
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
14
|
-
import {
|
|
15
|
-
import { SandboxService } from "../sandbox/sandbox.service.js";
|
|
13
|
+
import { retirementPending, SandboxService, } from "../sandbox/sandbox.service.js";
|
|
16
14
|
import { BackgroundTaskFinisher, } from "./finish.js";
|
|
17
15
|
import { exactRefOf, lastLinesByRef, MANAGED_STOP_GRACE_MS, onManagedInstance, stopEnd, summaryLines, } from "./managed.js";
|
|
18
|
-
import { actingAs, assertTaskRef, decodeTail, killSession, TERM_EXEC_TIMEOUT_MS, tailCommand, taskActor, termScript, } from "./session.js";
|
|
19
16
|
import { BackgroundTaskStore, isManagedTask, } from "./store.js";
|
|
20
|
-
/** The time limit of reading the last lines after a stop. */
|
|
21
|
-
const TAIL_EXEC_TIMEOUT_MS = 10_000;
|
|
22
|
-
/** How a task that exited by itself ends (spec §4.3): exit 137 past its deadline timed out. */
|
|
23
|
-
export function exitedAs(task, code, now) {
|
|
24
|
-
if (code === 0)
|
|
25
|
-
return { status: "completed", exitCode: 0 };
|
|
26
|
-
if (code === 137 && now.getTime() >= task.deadlineAt.getTime()) {
|
|
27
|
-
return { status: "timed_out", exitCode: 137 };
|
|
28
|
-
}
|
|
29
|
-
return { status: "failed", exitCode: code };
|
|
30
|
-
}
|
|
31
17
|
/** How a task whose sandbox is not running ends (`ifRunning`'s `not_running` status). */
|
|
32
18
|
export function notRunningAs(status, killPending) {
|
|
33
19
|
return {
|
|
@@ -43,13 +29,12 @@ export const RECREATED = {
|
|
|
43
29
|
killPending: false,
|
|
44
30
|
};
|
|
45
31
|
/**
|
|
46
|
-
* Stops background tasks (spec 2026-11-05-background-bash-design §2.3, §4.3
|
|
47
|
-
*
|
|
48
|
-
* `SandboxService.ifRunning` (it never creates or resumes a sandbox)
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
* already exited left running are killed as well.
|
|
32
|
+
* Stops background tasks (spec 2026-11-05-background-bash-design §2.3, §4.3, permission runtime
|
|
33
|
+
* cutover phase 8.3): a managed task by its exact ref on its exact instance only, through
|
|
34
|
+
* `SandboxService.ifRunning` (it never creates or resumes a sandbox). A legacy (SID) task is never
|
|
35
|
+
* signalled: while its instance runs it belongs to the retirement gate (`RetireLegacyTasksJob`),
|
|
36
|
+
* and its stop is refused with that gate's actionable refusal; once its instance is gone or
|
|
37
|
+
* replaced it finishes `lost` without any exec or signal.
|
|
53
38
|
*/
|
|
54
39
|
let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
55
40
|
store;
|
|
@@ -57,46 +42,35 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
57
42
|
sandbox;
|
|
58
43
|
db;
|
|
59
44
|
log;
|
|
60
|
-
|
|
61
|
-
constructor(store, finisher, sandbox, db, log,
|
|
62
|
-
/**
|
|
63
|
-
* The paired activation gate: once on, a legacy (SID) task's stop refuses with the retirement
|
|
64
|
-
* refusal exactly when it would run an exec (its instance runs); one whose instance is gone
|
|
65
|
-
* or replaced still finishes without one. A managed task always stops by its exact ref.
|
|
66
|
-
*/
|
|
67
|
-
activation) {
|
|
45
|
+
constructor(store, finisher, sandbox, db, log) {
|
|
68
46
|
this.store = store;
|
|
69
47
|
this.finisher = finisher;
|
|
70
48
|
this.sandbox = sandbox;
|
|
71
49
|
this.db = db;
|
|
72
50
|
this.log = log;
|
|
73
|
-
this.activation = activation;
|
|
74
51
|
}
|
|
75
52
|
/**
|
|
76
53
|
* Stops `task` and returns its row afterwards. A task that is no longer running, or that another
|
|
77
54
|
* live stop already claimed, is returned as it is now.
|
|
78
55
|
*
|
|
79
|
-
* The stop first claims the task (`stopping_at`), so the poller leaves it alone while the
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* finish (a managed task's cancellation settled from a TaskOutput read).
|
|
56
|
+
* The stop first claims the task (`stopping_at`), so the poller leaves it alone while the stop
|
|
57
|
+
* takes effect and the stop's finish is its only one. A legacy reservation that never started
|
|
58
|
+
* (no instance) is only claimed: the poller fails it as abandoned. When the stop fails while the
|
|
59
|
+
* sandbox runs (busy, a provider error, a legacy task's retirement refusal), the claim is given
|
|
60
|
+
* up, the task stays `running` and the error is thrown. `how.reported`: the caller's own result
|
|
61
|
+
* tells the model this finish (a managed task's cancellation settled from a TaskOutput read).
|
|
86
62
|
*/
|
|
87
63
|
async stop(task, why, signal, how = {}) {
|
|
88
64
|
if (!(await this.store.claimStop(task.id)))
|
|
89
65
|
return (await this.store.get(task.id)) ?? task;
|
|
90
|
-
// read after the claim:
|
|
91
|
-
// recording it after sees the claim (both are single-row updates of the same row)
|
|
66
|
+
// read after the claim: an acknowledgement recording the ref before the claim is seen here,
|
|
67
|
+
// one recording it after sees the claim (both are single-row updates of the same row)
|
|
92
68
|
const cur = (await this.store.get(task.id)) ?? task;
|
|
93
69
|
if (isManagedTask(cur))
|
|
94
70
|
return this.stopManaged(cur, why, signal, how.reported);
|
|
95
|
-
if (cur.status !== "running" || cur.
|
|
71
|
+
if (cur.status !== "running" || cur.sandboxCreatedAt === null)
|
|
96
72
|
return cur;
|
|
97
73
|
const started = { ...cur, sandboxCreatedAt: cur.sandboxCreatedAt };
|
|
98
|
-
const sid = cur.sid;
|
|
99
|
-
assertTaskRef(cur.id, sid);
|
|
100
74
|
const reported = why === "tool";
|
|
101
75
|
// a person's stop never wakes the conversation (background Bash §3, fix round 1), nor does
|
|
102
76
|
// the stop of a conversation being deleted or of a sub-agent that ended (agent map spec §5.3)
|
|
@@ -110,7 +84,7 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
110
84
|
const opts = stoppedBy === undefined ? {} : { stoppedBy };
|
|
111
85
|
let r;
|
|
112
86
|
try {
|
|
113
|
-
r = await this.
|
|
87
|
+
r = await this.legacyInstance(started, signal);
|
|
114
88
|
}
|
|
115
89
|
catch (err) {
|
|
116
90
|
await this.store
|
|
@@ -118,13 +92,10 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
118
92
|
.catch((e) => this.log.warn("cannot release a background task stop", { taskId: cur.id, err: e }));
|
|
119
93
|
throw err;
|
|
120
94
|
}
|
|
121
|
-
if (r.kind === "
|
|
122
|
-
await this.finisher.finish(cur, r.value.to, r.value.lastLines, reported, opts);
|
|
123
|
-
}
|
|
124
|
-
else if (r.kind === "not_running") {
|
|
95
|
+
if (r.kind === "not_running") {
|
|
125
96
|
await this.finisher.finish(cur, notRunningAs(r.status, true), "", reported, opts);
|
|
126
97
|
}
|
|
127
|
-
else {
|
|
98
|
+
else if (r.kind === "other_instance") {
|
|
128
99
|
await this.finisher.finish(cur, RECREATED, "", reported, opts);
|
|
129
100
|
}
|
|
130
101
|
return (await this.store.get(cur.id)) ?? cur;
|
|
@@ -140,12 +111,37 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
140
111
|
* running (never resumed) or was replaced leaves the cancellation owed. Who asked is recorded,
|
|
141
112
|
* so a later finish keeps their wake rule.
|
|
142
113
|
*/
|
|
114
|
+
/**
|
|
115
|
+
* `conversation_deleted` when the task's conversation, its tree's root (the device's
|
|
116
|
+
* conversation, a sub-agent's root) or its org is deleted or gone, else null.
|
|
117
|
+
*/
|
|
118
|
+
async deletedConversationStop(cur) {
|
|
119
|
+
const ids = [...new Set([cur.conversationId, cur.sandboxConversationId])];
|
|
120
|
+
const [conversations, org] = await Promise.all([
|
|
121
|
+
this.db.db
|
|
122
|
+
.selectFrom("conversations")
|
|
123
|
+
.select(["id", "deleted_at"])
|
|
124
|
+
.where("id", "in", ids)
|
|
125
|
+
.execute(),
|
|
126
|
+
this.db.db
|
|
127
|
+
.selectFrom("orgs")
|
|
128
|
+
.select("deleted_at")
|
|
129
|
+
.where("id", "=", cur.orgId)
|
|
130
|
+
.executeTakeFirst(),
|
|
131
|
+
]);
|
|
132
|
+
const live = conversations.filter((c) => c.deleted_at === null).length;
|
|
133
|
+
return live < ids.length || org === undefined || org.deleted_at !== null
|
|
134
|
+
? "conversation_deleted"
|
|
135
|
+
: null;
|
|
136
|
+
}
|
|
143
137
|
async stopManaged(cur, why, signal, reportedHere) {
|
|
144
138
|
if (cur.status !== "running")
|
|
145
139
|
return cur;
|
|
146
140
|
const asker = why === "revoked" ? null : why;
|
|
147
|
-
// the first asker's wake rule holds for the finish, whoever applies the stop
|
|
148
|
-
|
|
141
|
+
// the first asker's wake rule holds for the finish, whoever applies the stop; a revocation
|
|
142
|
+
// that wins the race against its conversation's deletion stop is still the deletion's (its
|
|
143
|
+
// finish must never wake anything)
|
|
144
|
+
const by = cur.cancelRequestedBy ?? asker ?? (await this.deletedConversationStop(cur));
|
|
149
145
|
if (cur.executionRef === null) {
|
|
150
146
|
if (asker !== null)
|
|
151
147
|
await this.store.requestCancel(cur.id, asker, false);
|
|
@@ -200,43 +196,16 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
200
196
|
return (await this.store.get(cur.id)) ?? cur;
|
|
201
197
|
}
|
|
202
198
|
/**
|
|
203
|
-
*
|
|
204
|
-
*
|
|
199
|
+
* A legacy task's own instance, never signalled: a running one refuses with the retirement
|
|
200
|
+
* gate's refusal before any provider call (the gate retires it and its processes whole); one
|
|
201
|
+
* that is not running or was replaced is reported, so the task finishes without any exec or
|
|
202
|
+
* signal. A task from before devices has none.
|
|
205
203
|
*/
|
|
206
|
-
async
|
|
204
|
+
async legacyInstance(cur, signal) {
|
|
207
205
|
if (cur.deviceId === null)
|
|
208
206
|
return { kind: "not_running", status: "gone" };
|
|
209
|
-
return this.sandbox.ifRunning(cur.deviceId, { createdAt: cur.sandboxCreatedAt }, async (
|
|
210
|
-
|
|
211
|
-
const p = actingAs(tp, taskActor(cur), this.activation);
|
|
212
|
-
const term = await p.exec(h, {
|
|
213
|
-
command: termScript(cur.id, sid),
|
|
214
|
-
cwd: rootsOf(h).workspace,
|
|
215
|
-
timeoutMs: TERM_EXEC_TIMEOUT_MS,
|
|
216
|
-
maxOutputBytes: 4096,
|
|
217
|
-
signal: sig,
|
|
218
|
-
});
|
|
219
|
-
const exited = /^exited (-?[0-9]+)$/.exec(term.stdout.trim());
|
|
220
|
-
if (term.exitCode !== 0 || (!exited && term.stdout.trim() !== "term")) {
|
|
221
|
-
throw new Error(`the stop of background task ${cur.id} failed (${term.exitCode})`);
|
|
222
|
-
}
|
|
223
|
-
// also after an exit: processes the command left running are stopped with the task
|
|
224
|
-
if (!(await killSession(p, h, sid, this.activation))) {
|
|
225
|
-
throw new Error(`background task ${cur.id} could not be confirmed stopped`);
|
|
226
|
-
}
|
|
227
|
-
const tail = await p.exec(h, {
|
|
228
|
-
command: tailCommand(cur.id),
|
|
229
|
-
cwd: rootsOf(h).workspace,
|
|
230
|
-
timeoutMs: TAIL_EXEC_TIMEOUT_MS,
|
|
231
|
-
maxOutputBytes: 64 * 1024,
|
|
232
|
-
signal: sig,
|
|
233
|
-
});
|
|
234
|
-
const lastLines = tail.exitCode === 0 ? decodeTail(tail.stdout) : "";
|
|
235
|
-
// a task that had exited before the signal ends as its exit says
|
|
236
|
-
const to = exited
|
|
237
|
-
? exitedAs(cur, Number(exited[1]), new Date())
|
|
238
|
-
: { status: "stopped" };
|
|
239
|
-
return { to, lastLines };
|
|
207
|
+
return this.sandbox.ifRunning(cur.deviceId, { createdAt: cur.sandboxCreatedAt }, async () => {
|
|
208
|
+
throw retirementPending();
|
|
240
209
|
}, signal);
|
|
241
210
|
}
|
|
242
211
|
/**
|
|
@@ -284,7 +253,9 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
284
253
|
}
|
|
285
254
|
/**
|
|
286
255
|
* Stops `tasks` side by side. A stop that fails while the sandbox runs leaves its task running
|
|
287
|
-
* (logged):
|
|
256
|
+
* (logged): a managed task stays owed to the poller and ends at its own deadline at the latest;
|
|
257
|
+
* a legacy task stays with the retirement gate until its instance is destroyed or quarantined
|
|
258
|
+
* (no deadline ends it in the kernel's view).
|
|
288
259
|
*/
|
|
289
260
|
async stopAll(tasks, why) {
|
|
290
261
|
await Promise.all(tasks.map(async (t) => {
|
|
@@ -303,8 +274,6 @@ BackgroundTaskStopper = __decorate([
|
|
|
303
274
|
__param(1, Inject(BackgroundTaskFinisher)),
|
|
304
275
|
__param(2, Inject(SandboxService)),
|
|
305
276
|
__param(3, Inject(KernelDb)),
|
|
306
|
-
__param(4, Inject(KERNEL_LOGGER))
|
|
307
|
-
__param(5, Optional()),
|
|
308
|
-
__param(5, Inject(PERMISSION_CONTEXT_ACTIVATION))
|
|
277
|
+
__param(4, Inject(KERNEL_LOGGER))
|
|
309
278
|
], BackgroundTaskStopper);
|
|
310
279
|
export { BackgroundTaskStopper };
|