@capybara-hq/kernel 0.1.0-rc.89 → 0.1.0-rc.90
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/background/poll.job.d.ts +10 -0
- package/dist/background/poll.job.js +41 -10
- package/dist/background/stop.d.ts +39 -7
- package/dist/background/stop.js +107 -19
- package/dist/background/store.d.ts +25 -3
- package/dist/background/store.js +32 -2
- package/dist/background/tasks.service.d.ts +16 -2
- package/dist/background/tasks.service.js +11 -2
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +1 -0
- package/dist/config/schema.js +11 -1
- package/dist/conversations/events.d.ts +5 -0
- package/dist/conversations/events.js +11 -0
- package/dist/db/kernel-schema.d.ts +4 -0
- package/dist/device-access/device-access.service.d.ts +4 -1
- package/dist/device-access/device-access.service.js +40 -11
- package/dist/device-access/viewer.js +3 -2
- package/dist/dial-in/gateway.d.ts +7 -0
- package/dist/dial-in/gateway.js +43 -4
- package/dist/dial-in/relay.d.ts +27 -5
- package/dist/dial-in/relay.js +83 -21
- package/dist/dial-in/streams.d.ts +13 -5
- package/dist/dial-in/streams.js +43 -30
- package/dist/overrides.d.ts +4 -0
- package/dist/overrides.js +2 -0
- package/dist/platform/ops/background.ops.js +5 -2
- package/dist/sandbox/device-services.d.ts +4 -2
- package/dist/sandbox/device-services.js +9 -7
- package/dist/sandbox/review/review.service.d.ts +5 -0
- package/dist/sandbox/review/review.service.js +1 -0
- package/dist/sandbox/review/rules.js +24 -0
- package/dist/sandbox/review/types.d.ts +6 -0
- package/dist/sandbox/sandbox.service.d.ts +23 -0
- package/dist/sandbox/sandbox.service.js +57 -9
- package/dist/tools/builtins/sandbox/common.js +6 -1
- package/dist/tools/builtins/sandbox/task-stop.d.ts +2 -1
- package/dist/tools/builtins/sandbox/task-stop.js +21 -3
- package/dist/tools/call-scope.d.ts +21 -0
- package/dist/tools/call-scope.js +25 -0
- package/dist/tools/pipeline.d.ts +20 -0
- package/dist/tools/pipeline.js +67 -5
- package/dist/tools/questions.service.d.ts +6 -0
- package/dist/tools/questions.service.js +1 -0
- package/dist/tools/registry.d.ts +15 -8
- package/dist/tools/registry.js +21 -10
- package/package.json +3 -3
- package/src/migrations/0184_background_cancel_failure.sql +10 -0
package/dist/dial-in/streams.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { DeviceOfflineError, DIAL_IN_STREAM_INITIAL_CREDIT, } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { DeviceOfflineError, DIAL_IN_STREAM_INITIAL_CREDIT, encodeDialInStreamData, } from "@capybara-hq/plugin-sdk";
|
|
3
3
|
/**
|
|
4
4
|
* The `code` of the error a stream's `send` rejects with when a message does not fit one frame
|
|
5
|
-
*
|
|
5
|
+
* (base64-encoded, or binary with its header; the viewer endpoint answers it with 1009).
|
|
6
6
|
*/
|
|
7
7
|
export const DEVICE_STREAM_MESSAGE_TOO_BIG = "device.stream_message_too_big";
|
|
8
8
|
/** Whether a machine frame belongs to a stream (routed to {@link DialInStreams.onFrame}). */
|
|
@@ -28,7 +28,7 @@ class Stream {
|
|
|
28
28
|
sendCredit = DIAL_IN_STREAM_INITIAL_CREDIT;
|
|
29
29
|
/** Messages the machine may still send (granted by the kernel). */
|
|
30
30
|
recvCredit = DIAL_IN_STREAM_INITIAL_CREDIT;
|
|
31
|
-
/** Sends waiting for credit, in call order (each frame
|
|
31
|
+
/** Sends waiting for credit, in call order (each frame already checked to fit). */
|
|
32
32
|
waiting = [];
|
|
33
33
|
/** Messages received and not consumed yet (at most the credit the kernel granted). */
|
|
34
34
|
inbox = [];
|
|
@@ -79,18 +79,21 @@ class Stream {
|
|
|
79
79
|
return Promise.reject(new TypeError("A stream message must be a Uint8Array"));
|
|
80
80
|
if (this.endedWith !== undefined)
|
|
81
81
|
return Promise.reject(new Error(`The stream is closed: ${this.endedWith}`));
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
82
|
+
const binary = this.transport.binaryStreamData();
|
|
83
|
+
const frame = binary
|
|
84
|
+
? encodeDialInStreamData(this.id, message)
|
|
85
|
+
: JSON.stringify({
|
|
86
|
+
type: "stream-data",
|
|
87
|
+
streamId: this.id,
|
|
88
|
+
data: Buffer.from(message.buffer, message.byteOffset, message.byteLength).toString("base64"),
|
|
89
|
+
});
|
|
90
|
+
const size = typeof frame === "string" ? Buffer.byteLength(frame) : frame.byteLength;
|
|
88
91
|
const cap = this.transport.maxFrameBytes();
|
|
89
92
|
// a message is never split: one that does not fit one frame is refused
|
|
90
|
-
if (
|
|
91
|
-
return Promise.reject(Object.assign(new Error(`A stream message of ${message.byteLength} bytes does not fit the connection's frame capacity of ${cap} bytes once base64-encoded; send smaller messages`), { code: DEVICE_STREAM_MESSAGE_TOO_BIG }));
|
|
93
|
+
if (size > cap)
|
|
94
|
+
return Promise.reject(Object.assign(new Error(`A stream message of ${message.byteLength} bytes does not fit the connection's frame capacity of ${cap} bytes ${binary ? "with its header" : "once base64-encoded"}; send smaller messages`), { code: DEVICE_STREAM_MESSAGE_TOO_BIG }));
|
|
92
95
|
return new Promise((resolve, reject) => {
|
|
93
|
-
this.waiting.push({
|
|
96
|
+
this.waiting.push({ frame, resolve, reject });
|
|
94
97
|
this.flush();
|
|
95
98
|
});
|
|
96
99
|
}
|
|
@@ -110,27 +113,32 @@ class Stream {
|
|
|
110
113
|
this.flush();
|
|
111
114
|
}
|
|
112
115
|
else if (frame.type === "stream-data") {
|
|
113
|
-
|
|
114
|
-
// the machine sent beyond the credit the kernel granted: the stream ends, the connection
|
|
115
|
-
// and its other streams go on
|
|
116
|
-
this.close("credit exceeded");
|
|
117
|
-
return;
|
|
118
|
-
}
|
|
119
|
-
this.recvCredit--;
|
|
120
|
-
const m = new Uint8Array(Buffer.from(frame.data, "base64"));
|
|
121
|
-
const reader = this.reader;
|
|
122
|
-
if (reader) {
|
|
123
|
-
this.reader = undefined;
|
|
124
|
-
this.consumed();
|
|
125
|
-
reader({ value: m, done: false });
|
|
126
|
-
}
|
|
127
|
-
else
|
|
128
|
-
this.inbox.push(m);
|
|
116
|
+
this.onData(new Uint8Array(Buffer.from(frame.data, "base64")));
|
|
129
117
|
}
|
|
130
118
|
else if (frame.type === "stream-close") {
|
|
131
119
|
this.end(frame.reason);
|
|
132
120
|
}
|
|
133
121
|
}
|
|
122
|
+
/** One message of this stream from the machine (a JSON or a binary `stream-data`). */
|
|
123
|
+
onData(m) {
|
|
124
|
+
if (this.endedWith !== undefined)
|
|
125
|
+
return;
|
|
126
|
+
if (this.recvCredit <= 0) {
|
|
127
|
+
// the machine sent beyond the credit the kernel granted: the stream ends, the connection
|
|
128
|
+
// and its other streams go on
|
|
129
|
+
this.close("credit exceeded");
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
this.recvCredit--;
|
|
133
|
+
const reader = this.reader;
|
|
134
|
+
if (reader) {
|
|
135
|
+
this.reader = undefined;
|
|
136
|
+
this.consumed();
|
|
137
|
+
reader({ value: m, done: false });
|
|
138
|
+
}
|
|
139
|
+
else
|
|
140
|
+
this.inbox.push(m);
|
|
141
|
+
}
|
|
134
142
|
/** The stream ended (either side, or the socket): waiting sends fail, the reader ends. */
|
|
135
143
|
end(reason) {
|
|
136
144
|
if (this.endedWith !== undefined)
|
|
@@ -154,7 +162,7 @@ class Stream {
|
|
|
154
162
|
flush() {
|
|
155
163
|
while (this.sendCredit > 0 && this.waiting.length > 0 && this.endedWith === undefined) {
|
|
156
164
|
const w = this.waiting.shift();
|
|
157
|
-
if (!this.transport.send(w.
|
|
165
|
+
if (!this.transport.send(w.frame)) {
|
|
158
166
|
w.reject(new Error(`The stream is closed: ${STREAM_OFFLINE_REASON}`));
|
|
159
167
|
continue;
|
|
160
168
|
}
|
|
@@ -168,7 +176,8 @@ class Stream {
|
|
|
168
176
|
* spec §6.1): opened with `stream-open`, carried as `stream-data` frames straight over the socket
|
|
169
177
|
* (never through Redis or PG), each side sending only while it holds credit
|
|
170
178
|
* ({@link DIAL_IN_STREAM_INITIAL_CREDIT} at the open, one more per message the other side
|
|
171
|
-
* consumed). A data frame carries one whole message in base64
|
|
179
|
+
* consumed). A data frame carries one whole message, in base64 inside JSON or, when hello and
|
|
180
|
+
* ready agreed on it, as a binary message (raw bytes); a message that does not fit the
|
|
172
181
|
* connection's frame capacity is refused, never split. The table is the connection's own state and
|
|
173
182
|
* lives exactly as long as the socket: its close ends every stream with
|
|
174
183
|
* {@link STREAM_OFFLINE_REASON}.
|
|
@@ -266,6 +275,10 @@ export class DialInStreams {
|
|
|
266
275
|
// a frame racing the stream's close (or of a stream never opened here) has nothing to reach
|
|
267
276
|
this.open.get(frame.streamId)?.onFrame(frame);
|
|
268
277
|
}
|
|
278
|
+
/** A binary `stream-data` message from the machine; one of a stream not open is dropped. */
|
|
279
|
+
onData(streamId, data) {
|
|
280
|
+
this.open.get(streamId)?.onData(data);
|
|
281
|
+
}
|
|
269
282
|
/** The socket closed: every stream ends, every opening fails. */
|
|
270
283
|
closeAll() {
|
|
271
284
|
if (this.ended)
|
package/dist/overrides.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { NestInterceptor } from "@nestjs/common";
|
|
2
2
|
import { APP_INTERCEPTOR } from "@nestjs/core";
|
|
3
3
|
import { ADMIN_USAGE_TIMINGS, type AdminUsageTimings } from "./admin/usage.service.js";
|
|
4
|
+
import { BACKGROUND_STOP_ATTEMPT_MS } from "./background/stop.js";
|
|
4
5
|
import { SCOPE_ORG_CHUNK_SIZE } from "./catalog/scope-jobs.js";
|
|
5
6
|
import { CHANNEL_WEBHOOK_TIMINGS, type ChannelWebhookTimings } from "./channels/webhook.js";
|
|
6
7
|
import { PROMPT_SUGGESTION_TIMEOUT } from "./conversations/prompt-suggestions.js";
|
|
@@ -60,6 +61,8 @@ import { EMBED_TOKEN_CLOCK } from "./ui/embed-token.js";
|
|
|
60
61
|
* read (a test shortens it for one run);
|
|
61
62
|
* - `PUSH_SEND_TIMEOUT_MS`: one push send's time limit, read at every send (a test shortens it
|
|
62
63
|
* for a hanging provider);
|
|
64
|
+
* - `BACKGROUND_STOP_ATTEMPT_MS`: one exact background task stop attempt's time limit, read at
|
|
65
|
+
* every attempt (a test shortens it for a machine that never answers);
|
|
63
66
|
* - `PROMPT_SUGGESTION_TIMEOUT`: the prompt suggestion call's time limit, read at every call (a test
|
|
64
67
|
* shortens it for one call);
|
|
65
68
|
* - `PLUGIN_PUBLIC_WRITE_LIMIT`: a lower limit for unsafe methods on `public` extension routes;
|
|
@@ -97,6 +100,7 @@ interface KernelSeams {
|
|
|
97
100
|
[PROJECT_KNOWLEDGE_TIMEOUT]: () => number;
|
|
98
101
|
[PROMPT_SUGGESTION_TIMEOUT]: () => number;
|
|
99
102
|
[PUSH_SEND_TIMEOUT_MS]: () => number;
|
|
103
|
+
[BACKGROUND_STOP_ATTEMPT_MS]: () => number;
|
|
100
104
|
[PLUGIN_PUBLIC_WRITE_LIMIT]: number;
|
|
101
105
|
[EXTENSION_NET_SEAMS]: ExtensionNetSeams;
|
|
102
106
|
[APP_INTERCEPTOR]: NestInterceptor;
|
package/dist/overrides.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { APP_INTERCEPTOR } from "@nestjs/core";
|
|
2
2
|
import { ADMIN_USAGE_TIMINGS } from "./admin/usage.service.js";
|
|
3
|
+
import { BACKGROUND_STOP_ATTEMPT_MS } from "./background/stop.js";
|
|
3
4
|
import { SCOPE_ORG_CHUNK_SIZE } from "./catalog/scope-jobs.js";
|
|
4
5
|
import { CHANNEL_WEBHOOK_TIMINGS } from "./channels/webhook.js";
|
|
5
6
|
import { PROMPT_SUGGESTION_TIMEOUT } from "./conversations/prompt-suggestions.js";
|
|
@@ -55,6 +56,7 @@ const SEAM_TOKENS = [
|
|
|
55
56
|
PROJECT_KNOWLEDGE_TIMEOUT,
|
|
56
57
|
PROMPT_SUGGESTION_TIMEOUT,
|
|
57
58
|
PUSH_SEND_TIMEOUT_MS,
|
|
59
|
+
BACKGROUND_STOP_ATTEMPT_MS,
|
|
58
60
|
PLUGIN_PUBLIC_WRITE_LIMIT,
|
|
59
61
|
EXTENSION_NET_SEAMS,
|
|
60
62
|
APP_INTERCEPTOR,
|
|
@@ -30,6 +30,9 @@ const row = (t) => ({
|
|
|
30
30
|
command: t.command.length > COMMAND_MAX ? `${t.command.slice(0, COMMAND_MAX)}…` : t.command,
|
|
31
31
|
subagentId: t.subagentId,
|
|
32
32
|
stopping: t.stopping,
|
|
33
|
+
// the stop is recorded and is delivered once the device answers (offline or not answering now)
|
|
34
|
+
...(t.stopWaiting && { stopWaiting: true }),
|
|
35
|
+
...(t.stopFailure !== null && { stopFailure: t.stopFailure }),
|
|
33
36
|
});
|
|
34
37
|
/**
|
|
35
38
|
* Background task operations of the `Platform` tool (the conversation domain): list the
|
|
@@ -47,7 +50,7 @@ let BackgroundOperations = class BackgroundOperations {
|
|
|
47
50
|
this.registry.register([
|
|
48
51
|
defineOperation({
|
|
49
52
|
id: "conversations.background-tasks",
|
|
50
|
-
description: "List the background commands of one of your conversations and of its sub-agents, newest first: description, state (running, finished, failed, stopped, lost), the command
|
|
53
|
+
description: "List the background commands of one of your conversations and of its sub-agents, newest first: description, state (running, finished, failed, stopped, lost), the command, whether a stop is under way, whether it is recorded and waits for the device (stopWaiting) and why its last attempt did not settle (stopFailure: unreachable or failed). Pages by 50: pass the returned next as params.cursor.",
|
|
51
54
|
input: z.object({ conversationId: ConversationId, cursor: Cursor.optional() }).strict(),
|
|
52
55
|
example: { conversationId: "3f2b8a40-6c1d-4e0b-9a77-5d1e2c8b9f10" },
|
|
53
56
|
authz: { orgAction: "agents.use" },
|
|
@@ -65,7 +68,7 @@ let BackgroundOperations = class BackgroundOperations {
|
|
|
65
68
|
}),
|
|
66
69
|
defineOperation({
|
|
67
70
|
id: "conversations.stop-background-task",
|
|
68
|
-
description: "Stop one background command of one of your conversations, as the stop button does: the command is killed. Takes the task id from conversations.background-tasks. A task already stopping or finished is returned as it is.",
|
|
71
|
+
description: "Stop one background command of one of your conversations, as the stop button does: the command is killed. Takes the task id from conversations.background-tasks. A task already stopping or finished is returned as it is; a stop the device has not applied yet is recorded (stopWaiting, with stopFailure saying why its last attempt did not settle) and attempted again automatically.",
|
|
69
72
|
input: z.object({ conversationId: ConversationId, taskId: TaskId }).strict(),
|
|
70
73
|
example: {
|
|
71
74
|
conversationId: "3f2b8a40-6c1d-4e0b-9a77-5d1e2c8b9f10",
|
|
@@ -10,7 +10,9 @@ export declare const POST_APPLY_ENSURE_TIMEOUT_MS = 30000;
|
|
|
10
10
|
* ({@link SandboxService.withDeviceServices}: a suspended instance is resumed); stopping never
|
|
11
11
|
* starts or resumes one. A provider without the service methods is refused with
|
|
12
12
|
* `DeviceAccessError("capability_missing")` before the device is touched. The command review of a
|
|
13
|
-
* launch and the extension's permission are the caller's (`ctx.deviceAccess`).
|
|
13
|
+
* launch and the extension's permission are the caller's (`ctx.deviceAccess`). Every name here is
|
|
14
|
+
* a service id (`<extension>.<name>`, `DEVICE_SERVICE_ID_RE`): the caller namespaces the
|
|
15
|
+
* extension's service names, so the provider never sees a bare name two extensions could share.
|
|
14
16
|
*/
|
|
15
17
|
export declare class DeviceServices {
|
|
16
18
|
private readonly sandbox;
|
|
@@ -60,7 +62,7 @@ export declare class DeviceServices {
|
|
|
60
62
|
*/
|
|
61
63
|
export declare function nameOnlySpec(name: string): DeviceServiceSpec;
|
|
62
64
|
/**
|
|
63
|
-
* Why a service spec is refused, or null (browser use spec §5): a valid
|
|
65
|
+
* Why a service spec is refused, or null (browser use spec §5): a valid service id; `entry` and every
|
|
64
66
|
* `files` key relative inside the state directory (no absolute path, no `.` / `..` / empty
|
|
65
67
|
* segment, no backslash, no NUL); `entry` one of the files; no env variable that changes what
|
|
66
68
|
* runs or that the provider sets (`NODE_*`, `PATH`, `SSL_CERT_FILE`, `SSL_CERT_DIR`,
|
|
@@ -7,7 +7,7 @@ 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 {
|
|
10
|
+
import { DEVICE_SERVICE_ID_RE, DeviceAccessError, } from "@capybara-hq/plugin-sdk";
|
|
11
11
|
import { Inject, Injectable } from "@nestjs/common";
|
|
12
12
|
import { SandboxService } from "./sandbox.service.js";
|
|
13
13
|
/** The budget of the `ifRunning` ensure after a refresh applied new limits (a service restart). */
|
|
@@ -19,7 +19,9 @@ export const POST_APPLY_ENSURE_TIMEOUT_MS = 30_000;
|
|
|
19
19
|
* ({@link SandboxService.withDeviceServices}: a suspended instance is resumed); stopping never
|
|
20
20
|
* starts or resumes one. A provider without the service methods is refused with
|
|
21
21
|
* `DeviceAccessError("capability_missing")` before the device is touched. The command review of a
|
|
22
|
-
* launch and the extension's permission are the caller's (`ctx.deviceAccess`).
|
|
22
|
+
* launch and the extension's permission are the caller's (`ctx.deviceAccess`). Every name here is
|
|
23
|
+
* a service id (`<extension>.<name>`, `DEVICE_SERVICE_ID_RE`): the caller namespaces the
|
|
24
|
+
* extension's service names, so the provider never sees a bare name two extensions could share.
|
|
23
25
|
*/
|
|
24
26
|
let DeviceServices = class DeviceServices {
|
|
25
27
|
sandbox;
|
|
@@ -148,7 +150,7 @@ function servicePathIssue(path) {
|
|
|
148
150
|
return null;
|
|
149
151
|
}
|
|
150
152
|
/**
|
|
151
|
-
* Why a service spec is refused, or null (browser use spec §5): a valid
|
|
153
|
+
* Why a service spec is refused, or null (browser use spec §5): a valid service id; `entry` and every
|
|
152
154
|
* `files` key relative inside the state directory (no absolute path, no `.` / `..` / empty
|
|
153
155
|
* segment, no backslash, no NUL); `entry` one of the files; no env variable that changes what
|
|
154
156
|
* runs or that the provider sets (`NODE_*`, `PATH`, `SSL_CERT_FILE`, `SSL_CERT_DIR`,
|
|
@@ -156,8 +158,8 @@ function servicePathIssue(path) {
|
|
|
156
158
|
* a value. So the reviewed command is the one that runs.
|
|
157
159
|
*/
|
|
158
160
|
export function serviceSpecIssue(spec) {
|
|
159
|
-
if (typeof spec?.name !== "string" || !
|
|
160
|
-
return `the service
|
|
161
|
+
if (typeof spec?.name !== "string" || !DEVICE_SERVICE_ID_RE.test(spec.name))
|
|
162
|
+
return `the service id ${JSON.stringify(spec?.name)} must be <extension>.<name> (${DEVICE_SERVICE_ID_RE})`;
|
|
161
163
|
if (typeof spec.entry !== "string")
|
|
162
164
|
return "entry must be a string";
|
|
163
165
|
const files = spec.files ?? {};
|
|
@@ -190,8 +192,8 @@ export function assertServiceSpec(spec) {
|
|
|
190
192
|
throw new TypeError(`Invalid device service spec: ${why}.`);
|
|
191
193
|
}
|
|
192
194
|
function assertServiceName(name) {
|
|
193
|
-
if (!
|
|
194
|
-
throw new Error(`Invalid device service
|
|
195
|
+
if (!DEVICE_SERVICE_ID_RE.test(name))
|
|
196
|
+
throw new Error(`Invalid device service id ${JSON.stringify(name)}: use <extension>.<name> (${DEVICE_SERVICE_ID_RE}).`);
|
|
195
197
|
}
|
|
196
198
|
/** Refuses a provider that lacks any of the methods a service needs (`openStream` is optional). */
|
|
197
199
|
function requireServices(p) {
|
|
@@ -83,6 +83,11 @@ export interface ReviewInput {
|
|
|
83
83
|
deviceHome?: string | null | undefined;
|
|
84
84
|
/** Whether a person is present to answer an `ask` (rules may read it; the pipeline decides). */
|
|
85
85
|
attended: boolean;
|
|
86
|
+
/**
|
|
87
|
+
* A device service launch (`ctx.deviceAccess.ensureService`): the absolute entry the command
|
|
88
|
+
* runs, the kernel's own fact ({@link ReviewFacts.serviceEntry}). Absent for every tool call.
|
|
89
|
+
*/
|
|
90
|
+
serviceEntry?: string | undefined;
|
|
86
91
|
/** Hook payload facts (optional: without enough of them no model hook fires). */
|
|
87
92
|
agentId?: string | undefined;
|
|
88
93
|
agentVersion?: number | undefined;
|
|
@@ -329,6 +329,7 @@ let CommandReviewService = class CommandReviewService {
|
|
|
329
329
|
deviceHome: input.deviceHome ?? null,
|
|
330
330
|
mode: input.mode,
|
|
331
331
|
attended: input.attended,
|
|
332
|
+
...(input.serviceEntry !== undefined && { serviceEntry: input.serviceEntry }),
|
|
332
333
|
};
|
|
333
334
|
// running a file this conversation wrote is not a development command (hardening spec R1)
|
|
334
335
|
const result = isWrite
|
|
@@ -835,6 +835,7 @@ function resolveFacts(facts) {
|
|
|
835
835
|
home: reported ?? derived ?? deviceHome,
|
|
836
836
|
homes: [...new Set([reported, derived, deviceHome].filter((h) => h !== null))],
|
|
837
837
|
written: new Set((facts.written ?? []).map((p) => p.endsWith("/**") ? `${normalizePath(p.slice(0, -3))}/**` : normalizePath(p))),
|
|
838
|
+
serviceEntry: facts.serviceEntry?.startsWith("/") ? normalizePath(facts.serviceEntry) : null,
|
|
838
839
|
};
|
|
839
840
|
}
|
|
840
841
|
function normalizePath(path) {
|
|
@@ -4315,6 +4316,24 @@ const RULES = [
|
|
|
4315
4316
|
: null;
|
|
4316
4317
|
},
|
|
4317
4318
|
},
|
|
4319
|
+
{
|
|
4320
|
+
// a device service launch as the kernel runs it (`node <entry> …`, browser use spec §5):
|
|
4321
|
+
// the extension's declared service from its code directory, not a build of the project
|
|
4322
|
+
id: "allow.service",
|
|
4323
|
+
outcome: "allow",
|
|
4324
|
+
check: (ctx) => {
|
|
4325
|
+
const entry = ctx.facts.serviceEntry;
|
|
4326
|
+
if (entry === null)
|
|
4327
|
+
return null;
|
|
4328
|
+
const matched = eachInvocation(ctx.commands, (inv) => inv.program === "node" && inv.args[0] === entry);
|
|
4329
|
+
return matched.length > 0
|
|
4330
|
+
? {
|
|
4331
|
+
reason: "Starts a device service declared by the extension, from its code directory.",
|
|
4332
|
+
commands: matched,
|
|
4333
|
+
}
|
|
4334
|
+
: null;
|
|
4335
|
+
},
|
|
4336
|
+
},
|
|
4318
4337
|
{
|
|
4319
4338
|
id: "allow.dev",
|
|
4320
4339
|
outcome: "allow",
|
|
@@ -4322,6 +4341,11 @@ const RULES = [
|
|
|
4322
4341
|
const matched = eachInvocation(ctx.commands, (inv, command) => {
|
|
4323
4342
|
if (credentialProducer(inv))
|
|
4324
4343
|
return false;
|
|
4344
|
+
// a device service launch is `allow.service`'s, never a development command
|
|
4345
|
+
if (ctx.facts.serviceEntry !== null &&
|
|
4346
|
+
inv.program === "node" &&
|
|
4347
|
+
inv.args[0] === ctx.facts.serviceEntry)
|
|
4348
|
+
return false;
|
|
4325
4349
|
// code the review cannot read is not a development command (`unsure.interpreter`)
|
|
4326
4350
|
if (interpreterRisk(inv, command, ctx) !== null)
|
|
4327
4351
|
return false;
|
|
@@ -64,6 +64,12 @@ export interface ReviewFacts {
|
|
|
64
64
|
* development command but code the run itself produced (hardening spec R1).
|
|
65
65
|
*/
|
|
66
66
|
written?: readonly string[];
|
|
67
|
+
/**
|
|
68
|
+
* The absolute entry a device service launch runs (`ctx.deviceAccess.ensureService`): the
|
|
69
|
+
* kernel's own fact, never the model's. `node <serviceEntry> …` is then the extension's declared
|
|
70
|
+
* service, allowed by `allow.service` instead of read as a development command.
|
|
71
|
+
*/
|
|
72
|
+
serviceEntry?: string;
|
|
67
73
|
}
|
|
68
74
|
/** One shell redirection of a simple command. */
|
|
69
75
|
export interface Redirect {
|
|
@@ -141,6 +141,23 @@ export declare const sandboxOpenNetworkRefused: () => ApiError;
|
|
|
141
141
|
* provider's own error goes only to the log.
|
|
142
142
|
*/
|
|
143
143
|
export declare const sandboxCreateFailed: () => ApiError;
|
|
144
|
+
/**
|
|
145
|
+
* What a failed `createFileSystem` / `create` / `update` of a cloud provider becomes: an abort,
|
|
146
|
+
* a gone error, an unreachable provider and a kernel error stay as they are (their callers and the
|
|
147
|
+
* tools handle them); any other error is logged (warn, redacted) and replaced by
|
|
148
|
+
* {@link sandboxOpenNetworkRefused} when `limits` ask for the open public network (the only
|
|
149
|
+
* network a provider's config refuses), else (a create) by {@link sandboxCreateFailed}; a failed
|
|
150
|
+
* `update` below the open network stays as it is. A dial-in device that is offline keeps its
|
|
151
|
+
* error (the tools tell the person to connect its machine), and so does a machine that did not
|
|
152
|
+
* finish or answer in time (`DialInAnswerTimeoutError`, `SandboxOperationOutcomeUnknownError`,
|
|
153
|
+
* `DeviceRequestNotSentError`): a slow machine is never reported as a refused network or a
|
|
154
|
+
* failed create.
|
|
155
|
+
*/
|
|
156
|
+
export declare function providerRefusal(log: Pick<KernelLogger, "warn">, err: unknown, facts: {
|
|
157
|
+
deviceId: string;
|
|
158
|
+
provider: string;
|
|
159
|
+
op: "createFileSystem" | "create" | "update";
|
|
160
|
+
}, limits: SandboxLimits, signal: AbortSignal): unknown;
|
|
144
161
|
/**
|
|
145
162
|
* The row still records the instance `gone` (same handle and same `created_at`). Handles compare
|
|
146
163
|
* canonically: a jsonb round trip reorders a multi-key handle's keys (final review m9).
|
|
@@ -927,6 +944,12 @@ export declare class SandboxService {
|
|
|
927
944
|
* instance would run wider than the record claims.
|
|
928
945
|
*/
|
|
929
946
|
private applyLimits;
|
|
947
|
+
/**
|
|
948
|
+
* One lifecycle step on the provider (resume, create, recreate), logged when it ends with its
|
|
949
|
+
* duration and outcome: `ok`, `aborted` (the use's signal, e.g. a tool call's time limit) or
|
|
950
|
+
* `failed` (the error itself is thrown on, and logged by whoever handles it).
|
|
951
|
+
*/
|
|
952
|
+
private lifecycleStep;
|
|
930
953
|
/**
|
|
931
954
|
* After a failed `update` that cannot be repaired by a recreate: best effort, with fresh short
|
|
932
955
|
* signals (the use's own may be aborted), suspends the instance (or revokes its operations) and
|
|
@@ -40,7 +40,7 @@ const backgroundBinding = (args, instanceId) => ({
|
|
|
40
40
|
instanceId,
|
|
41
41
|
});
|
|
42
42
|
import { randomUUID } from "node:crypto";
|
|
43
|
-
import { isFileSystemGoneError, isSandboxGoneError, isSandboxOperationOutcomeUnknownError, isStaleFenceError, rootsOf, } from "@capybara-hq/plugin-sdk";
|
|
43
|
+
import { isDialInAnswerTimeoutError, isFileSystemGoneError, isSandboxGoneError, isSandboxOperationOutcomeUnknownError, isStaleFenceError, rootsOf, } from "@capybara-hq/plugin-sdk";
|
|
44
44
|
import { Inject, Injectable, Optional } from "@nestjs/common";
|
|
45
45
|
import { sql, } from "kysely";
|
|
46
46
|
import { MANAGED_STOP_GRACE_MS } from "../background/managed.js";
|
|
@@ -162,11 +162,18 @@ export const sandboxCreateFailed = () => new ApiError("sandbox.create_failed", "
|
|
|
162
162
|
* {@link sandboxOpenNetworkRefused} when `limits` ask for the open public network (the only
|
|
163
163
|
* network a provider's config refuses), else (a create) by {@link sandboxCreateFailed}; a failed
|
|
164
164
|
* `update` below the open network stays as it is. A dial-in device that is offline keeps its
|
|
165
|
-
* error (the tools tell the person to connect its machine)
|
|
165
|
+
* error (the tools tell the person to connect its machine), and so does a machine that did not
|
|
166
|
+
* finish or answer in time (`DialInAnswerTimeoutError`, `SandboxOperationOutcomeUnknownError`,
|
|
167
|
+
* `DeviceRequestNotSentError`): a slow machine is never reported as a refused network or a
|
|
168
|
+
* failed create.
|
|
166
169
|
*/
|
|
167
|
-
function providerRefusal(log, err, facts, limits, signal) {
|
|
170
|
+
export function providerRefusal(log, err, facts, limits, signal) {
|
|
168
171
|
if (signal.aborted ||
|
|
169
172
|
isDeviceOfflineError(err) ||
|
|
173
|
+
// a machine that did not finish (or never answered) in time: an outcome, not a refusal
|
|
174
|
+
isDialInAnswerTimeoutError(err) ||
|
|
175
|
+
isSandboxOperationOutcomeUnknownError(err) ||
|
|
176
|
+
isDeviceRequestNotSent(err) ||
|
|
170
177
|
isSandboxGoneError(err) ||
|
|
171
178
|
isFileSystemGoneError(err) ||
|
|
172
179
|
err instanceof SandboxProviderUnreachableError ||
|
|
@@ -1546,7 +1553,8 @@ let SandboxService = class SandboxService {
|
|
|
1546
1553
|
*/
|
|
1547
1554
|
async enter(ctx, p, signal, gone, wantNow) {
|
|
1548
1555
|
const env = ctx.deviceId;
|
|
1549
|
-
const
|
|
1556
|
+
const waitStart = Date.now();
|
|
1557
|
+
const deadline = waitStart + this.config.get().sandbox.lockWaitSeconds * 1000;
|
|
1550
1558
|
const token = randomUUID();
|
|
1551
1559
|
let intent = false;
|
|
1552
1560
|
let want = await wantNow();
|
|
@@ -1593,9 +1601,24 @@ let SandboxService = class SandboxService {
|
|
|
1593
1601
|
if (lease)
|
|
1594
1602
|
return await this.asExclusive(ctx, p, lease, gone, signal);
|
|
1595
1603
|
}
|
|
1596
|
-
if (Date.now() + this.pollMs > deadline)
|
|
1604
|
+
if (Date.now() + this.pollMs > deadline) {
|
|
1605
|
+
this.log.info("sandbox lease wait gave up: the device stayed busy", {
|
|
1606
|
+
deviceId: env,
|
|
1607
|
+
waitedMs: Date.now() - waitStart,
|
|
1608
|
+
});
|
|
1597
1609
|
throw sandboxBusy();
|
|
1598
|
-
|
|
1610
|
+
}
|
|
1611
|
+
try {
|
|
1612
|
+
await sleep(this.pollMs + Math.floor(Math.random() * this.pollMs), signal);
|
|
1613
|
+
}
|
|
1614
|
+
catch (err) {
|
|
1615
|
+
if (signal.aborted)
|
|
1616
|
+
this.log.info("sandbox lease wait aborted", {
|
|
1617
|
+
deviceId: env,
|
|
1618
|
+
waitedMs: Date.now() - waitStart,
|
|
1619
|
+
});
|
|
1620
|
+
throw err;
|
|
1621
|
+
}
|
|
1599
1622
|
}
|
|
1600
1623
|
}
|
|
1601
1624
|
catch (err) {
|
|
@@ -3056,7 +3079,9 @@ let SandboxService = class SandboxService {
|
|
|
3056
3079
|
}
|
|
3057
3080
|
if (handle && row.status === "suspended") {
|
|
3058
3081
|
// the retirement gate may have resumed it already, to cancel revoked starts exactly (B-22)
|
|
3059
|
-
const r = gate.resumed
|
|
3082
|
+
const r = gate.resumed
|
|
3083
|
+
? "resumed"
|
|
3084
|
+
: await this.lifecycleStep("resume", id, p, signal, () => p.impl.resume(handle, signal));
|
|
3060
3085
|
if (r === "resumed") {
|
|
3061
3086
|
const incarnation = { provider: p.plugin, generation: String(createdAt) };
|
|
3062
3087
|
// the new limits first: the row says running only once the instance runs with them
|
|
@@ -3144,7 +3169,7 @@ let SandboxService = class SandboxService {
|
|
|
3144
3169
|
* got the desired limits at `create`.
|
|
3145
3170
|
*/
|
|
3146
3171
|
async createSettled(ctx, p, held, row, fence, signal, want) {
|
|
3147
|
-
const created = await this.create(ctx, p, held, row, fence, signal, want);
|
|
3172
|
+
const created = await this.lifecycleStep(row.had_instance ? "recreate" : "create", ctx.deviceId, p, signal, () => this.create(ctx, p, held, row, fence, signal, want));
|
|
3148
3173
|
if (p.impl.limitsApplyAt !== "fileSystem")
|
|
3149
3174
|
return created;
|
|
3150
3175
|
// the row as the create committed it (its new instance generation and record)
|
|
@@ -3383,7 +3408,30 @@ let SandboxService = class SandboxService {
|
|
|
3383
3408
|
});
|
|
3384
3409
|
}
|
|
3385
3410
|
}
|
|
3386
|
-
return await this.create(ctx, p, held, row, fence, signal, want);
|
|
3411
|
+
return await this.lifecycleStep("recreate", id, p, signal, () => this.create(ctx, p, held, row, fence, signal, want));
|
|
3412
|
+
}
|
|
3413
|
+
/**
|
|
3414
|
+
* One lifecycle step on the provider (resume, create, recreate), logged when it ends with its
|
|
3415
|
+
* duration and outcome: `ok`, `aborted` (the use's signal, e.g. a tool call's time limit) or
|
|
3416
|
+
* `failed` (the error itself is thrown on, and logged by whoever handles it).
|
|
3417
|
+
*/
|
|
3418
|
+
async lifecycleStep(step, deviceId, p, signal, fn) {
|
|
3419
|
+
const started = Date.now();
|
|
3420
|
+
const done = (outcome, extra = {}) => this.log.info(`sandbox ${step} ${outcome}`, {
|
|
3421
|
+
deviceId,
|
|
3422
|
+
provider: p.plugin,
|
|
3423
|
+
durationMs: Date.now() - started,
|
|
3424
|
+
...extra,
|
|
3425
|
+
});
|
|
3426
|
+
try {
|
|
3427
|
+
const r = await fn();
|
|
3428
|
+
done("ok", typeof r === "string" ? { answer: r } : {});
|
|
3429
|
+
return r;
|
|
3430
|
+
}
|
|
3431
|
+
catch (err) {
|
|
3432
|
+
done(signal.aborted ? "aborted" : "failed", signal.aborted ? {} : { error: err instanceof Error ? err.name : typeof err });
|
|
3433
|
+
throw err;
|
|
3434
|
+
}
|
|
3387
3435
|
}
|
|
3388
3436
|
/**
|
|
3389
3437
|
* After a failed `update` that cannot be repaired by a recreate: best effort, with fresh short
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DEFAULT_SANDBOX_ROOTS, isDeviceOfflineError, isDeviceRequestNotSent, isFileSystemGoneError, isSandboxOperationOutcomeUnknownError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, isSandboxScopeValidationError, isSandboxWorkUnsettledError, SandboxScopeDeniedError, ToolError, validateSandboxPath, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import { DEFAULT_SANDBOX_ROOTS, isDeviceOfflineError, isDeviceRequestNotSent, isDialInAnswerTimeoutError, isFileSystemGoneError, isSandboxOperationOutcomeUnknownError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, isSandboxScopeValidationError, isSandboxWorkUnsettledError, SandboxScopeDeniedError, ToolError, validateSandboxPath, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import { DeviceProtocolError } from "@capybara-hq/plugin-sdk/device-protocol";
|
|
3
3
|
import { ANONYMOUS_NO_DEVICE, NO_DEVICE, } from "../../../devices/conversation-devices.js";
|
|
4
4
|
import { canonicalRoot, workingRootOf } from "../../../devices/working-root.js";
|
|
@@ -365,6 +365,11 @@ export function mapSandboxError(e, log) {
|
|
|
365
365
|
log?.warn("sandbox operation outcome unknown", { err: e });
|
|
366
366
|
return new ToolError(OUTCOME_UNKNOWN_TOOL_TEXT, { kind: "unavailable" });
|
|
367
367
|
}
|
|
368
|
+
// a connected dial-in machine that never answered (the relay's give-up): it may have acted
|
|
369
|
+
if (isDialInAnswerTimeoutError(e)) {
|
|
370
|
+
log?.warn("dial-in machine did not answer in time", { err: e });
|
|
371
|
+
return new ToolError(OUTCOME_UNKNOWN_TOOL_TEXT, { kind: "unavailable" });
|
|
372
|
+
}
|
|
368
373
|
// a dial-in provider's machine is not connected (the SDK's error, from any provider)
|
|
369
374
|
if (isDeviceOfflineError(e))
|
|
370
375
|
return new ToolError(DEVICE_OFFLINE_TEXT);
|
|
@@ -5,6 +5,7 @@ import { type SandboxToolDeps } from "./common.js";
|
|
|
5
5
|
* conversation's background tasks through `BackgroundTaskStopper` (by its exact ref, with the device's
|
|
6
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
|
-
* stopping. A stop
|
|
8
|
+
* stopping. A stop the device cannot apply now (its machine offline or silent, the device's stop
|
|
9
|
+
* failed) is recorded and reported as requested, with why: the poller attempts it again.
|
|
9
10
|
*/
|
|
10
11
|
export declare function taskStopTool(deps: SandboxToolDeps): BuiltinTool;
|
|
@@ -72,12 +72,28 @@ function text(task, body) {
|
|
|
72
72
|
display: display(`停止后台任务:${d}`, `Stop background task: ${d}`),
|
|
73
73
|
};
|
|
74
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* The result of a stop that is recorded but not applied yet (`cancel-pending`): why the last
|
|
77
|
+
* attempt did not settle, and how the recorded stop proceeds.
|
|
78
|
+
*/
|
|
79
|
+
function owedStopText(task) {
|
|
80
|
+
const head = `Background task ${task.id} ("${task.description}") stop requested`;
|
|
81
|
+
const why = task.cancelFailure === "unreachable"
|
|
82
|
+
? `the device did not confirm it (${clip(task.cancelFailureDetail ?? "its machine is offline or not answering", 300)})`
|
|
83
|
+
: task.cancelFailure === "failed"
|
|
84
|
+
? `the device's stop failed (${clip(task.cancelFailureDetail ?? "no detail", 300)})`
|
|
85
|
+
: "the device recorded the cancellation and has not applied it yet";
|
|
86
|
+
return (`${head}: ${why}. The stop is recorded and attempted again automatically until the device ` +
|
|
87
|
+
"applies it; another TaskStop call changes nothing. The task's own time limit still ends it on " +
|
|
88
|
+
"the device. TaskOutput shows when it has ended.");
|
|
89
|
+
}
|
|
75
90
|
/**
|
|
76
91
|
* Built-in `TaskStop` (spec 2026-11-05-background-bash-design §2.3): stops one of this
|
|
77
92
|
* conversation's background tasks through `BackgroundTaskStopper` (by its exact ref, with the device's
|
|
78
93
|
* five-second grace, never creating or resuming a sandbox). A task that had already finished is not an
|
|
79
94
|
* error; a reservation still launching, or a task another stop already claimed, is reported as
|
|
80
|
-
* stopping. A stop
|
|
95
|
+
* stopping. A stop the device cannot apply now (its machine offline or silent, the device's stop
|
|
96
|
+
* failed) is recorded and reported as requested, with why: the poller attempts it again.
|
|
81
97
|
*/
|
|
82
98
|
export function taskStopTool(deps) {
|
|
83
99
|
return {
|
|
@@ -100,7 +116,9 @@ export function taskStopTool(deps) {
|
|
|
100
116
|
after = await env.tasks.stopper.stop(task, "tool", ctx.signal);
|
|
101
117
|
}
|
|
102
118
|
catch (e) {
|
|
103
|
-
// a
|
|
119
|
+
// a managed task's stop never throws for the device (it stays owed): what is left is a
|
|
120
|
+
// running legacy task's retirement refusal, in its own words, a malformed recorded ref or
|
|
121
|
+
// a failed write that recorded nothing
|
|
104
122
|
const mapped = retirementRefusal(e, env);
|
|
105
123
|
if (mapped instanceof ToolError)
|
|
106
124
|
throw mapped;
|
|
@@ -108,7 +126,7 @@ export function taskStopTool(deps) {
|
|
|
108
126
|
throw new ToolError(`Background task ${task.id} could not be stopped (${clip(why, 300)}); it keeps running. Retry TaskStop, or check the sandbox with Bash.`);
|
|
109
127
|
}
|
|
110
128
|
if (after.status === "running" && after.launchState === "cancel-pending") {
|
|
111
|
-
return text(after,
|
|
129
|
+
return text(after, owedStopText(after));
|
|
112
130
|
}
|
|
113
131
|
if (after.status === "running") {
|
|
114
132
|
return text(after, `Background task ${after.id} ("${after.description}") is stopping: it is still starting, or another stop is in progress. Call TaskOutput to see when it has ended.`);
|
|
@@ -53,8 +53,29 @@ export interface CallScope {
|
|
|
53
53
|
hosts: Set<string>;
|
|
54
54
|
url: string | null;
|
|
55
55
|
} | null;
|
|
56
|
+
/**
|
|
57
|
+
* How many device starts of this call are in progress now (`ctx.deviceAccess.ensureService`:
|
|
58
|
+
* the instance created or resumed, the service launched): a timeout that lands while one is
|
|
59
|
+
* says the device was still starting, not that the target failed.
|
|
60
|
+
*/
|
|
61
|
+
starting: number;
|
|
62
|
+
/**
|
|
63
|
+
* Whether this call sent a request to a device service (`ctx.deviceAccess.request`): its target
|
|
64
|
+
* may have acted, so a timeout never claims otherwise.
|
|
65
|
+
*/
|
|
66
|
+
reached: boolean;
|
|
56
67
|
}
|
|
57
68
|
/** Attaches a fresh scope to the call's context (the pipeline, before the handler runs). */
|
|
58
69
|
export declare function attachCallScope(ctx: ToolCallContext, facts?: CallFacts): CallScope;
|
|
59
70
|
/** The call's scope, or null for a context the pipeline did not make (no scope attached). */
|
|
60
71
|
export declare function callScopeOf(ctx: ToolCallContext): CallScope | null;
|
|
72
|
+
/**
|
|
73
|
+
* Runs `fn` as a device start of the call ({@link CallScope.starting}); a context without a scope
|
|
74
|
+
* runs it as it is.
|
|
75
|
+
*/
|
|
76
|
+
export declare function whileDeviceStarting<T>(ctx: ToolCallContext, fn: () => Promise<T>): Promise<T>;
|
|
77
|
+
/**
|
|
78
|
+
* Whether a timeout of this call happened while its device was still starting and before it sent
|
|
79
|
+
* anything to a device service (the only case the pipeline's "still starting" text may describe).
|
|
80
|
+
*/
|
|
81
|
+
export declare function stillStartingUnsent(scope: CallScope | undefined | null): boolean;
|