@capybara-hq/kernel 0.1.0-rc.97 → 0.1.0-rc.98
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/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/channels.schemas.d.ts +10 -0
- package/dist/channels/channels.schemas.js +7 -0
- package/dist/channels/connections.service.d.ts +7 -0
- package/dist/channels/connections.service.js +4 -0
- package/dist/channels/features.d.ts +18 -1
- package/dist/channels/features.js +22 -0
- package/dist/channels/outbound.d.ts +19 -0
- package/dist/channels/outbound.js +531 -18
- package/dist/channels/phrases.d.ts +10 -0
- package/dist/channels/phrases.js +4 -0
- package/dist/channels/progress.d.ts +75 -0
- package/dist/channels/progress.js +216 -0
- package/dist/conversations/event-log.d.ts +8 -2
- package/dist/conversations/events.d.ts +5 -0
- package/dist/conversations/events.js +5 -1
- package/dist/conversations/prompt-suggestions.js +2 -2
- package/dist/db/kernel-schema.d.ts +16 -0
- package/dist/evals/run-replay.js +2 -2
- package/dist/evals/step-replay.js +2 -2
- package/dist/evals/worker.js +3 -1
- package/dist/extensions/plugin-icons.d.ts +7 -0
- package/dist/extensions/plugin-icons.js +8 -0
- package/dist/models/purposes.js +2 -2
- package/dist/platform/ops/channels.ops.js +24 -5
- package/dist/runtime/model-call.d.ts +23 -2
- package/dist/runtime/model-call.js +64 -9
- package/dist/runtime/run-drafts.d.ts +46 -4
- package/dist/runtime/run-drafts.js +110 -9
- package/dist/runtime/run-steps.d.ts +2 -1
- package/dist/runtime/run-steps.js +6 -2
- package/dist/runtime/runtime.module.js +3 -0
- package/dist/runtime/stream.controller.d.ts +7 -5
- package/dist/runtime/stream.controller.js +10 -6
- package/dist/runtime/stream.js +9 -1
- package/dist/runtime/write-base.d.ts +95 -0
- package/dist/runtime/write-base.js +281 -0
- package/dist/runtime/write-base.service.d.ts +68 -0
- package/dist/runtime/write-base.service.js +184 -0
- package/dist/sandbox/kernel-read.d.ts +39 -9
- package/dist/sandbox/kernel-read.js +33 -3
- package/dist/sandbox/operation-authority.d.ts +16 -12
- package/dist/sandbox/operation-authority.js +33 -20
- package/dist/sandbox/operation-intents.d.ts +10 -4
- package/dist/sandbox/operation-intents.js +31 -11
- package/dist/sandbox/sandbox.service.d.ts +30 -7
- package/dist/sandbox/sandbox.service.js +47 -13
- package/dist/tools/builtins/agent.js +4 -0
- package/dist/tools/builtins/image/generate.js +1 -0
- package/dist/tools/builtins/sandbox/bash.js +1 -0
- package/dist/tools/builtins/sandbox/edit.js +1 -0
- package/dist/tools/builtins/sandbox/write.js +1 -0
- package/dist/tools/builtins/send-message.js +1 -0
- package/dist/tools/info.d.ts +21 -2
- package/dist/tools/info.js +55 -12
- package/dist/tools/pipeline.d.ts +3 -1
- package/dist/tools/pipeline.js +37 -3
- package/dist/tools/registry.d.ts +6 -5
- package/dist/tools/registry.js +6 -5
- package/package.json +3 -3
- package/src/migrations/0185_channel_process_display.sql +13 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { Logger, ToolInputView } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { ResolvedTool } from "../tools/registry.js";
|
|
3
|
+
/**
|
|
4
|
+
* How long an attempt waits for its base reads after aborting them. The abort reaches the lease
|
|
5
|
+
* and provider waits, so a read normally ends at once; a provider that ignores its signal never
|
|
6
|
+
* holds the step (and a Stop) past this bound for a display-only base.
|
|
7
|
+
*/
|
|
8
|
+
export declare const WRITE_BASE_SETTLE_MS = 3000;
|
|
9
|
+
/**
|
|
10
|
+
* Reads the value of one top-level string property of a JSON object streamed in fragments, without
|
|
11
|
+
* re-reading the buffer: each {@link feed} scans only the new fragment with the carried state.
|
|
12
|
+
* The value is known once its closing quote arrived (a half path is not a path). A property of a
|
|
13
|
+
* nested object or array, a non-string value, a top level that is not an object, or a value
|
|
14
|
+
* above {@link VALUE_MAX_CHARS} gives nothing.
|
|
15
|
+
*/
|
|
16
|
+
export declare class TopLevelStringProperty {
|
|
17
|
+
private readonly prop;
|
|
18
|
+
private depth;
|
|
19
|
+
private inString;
|
|
20
|
+
private escaped;
|
|
21
|
+
/** At depth 1, the next string is a key. */
|
|
22
|
+
private expectKey;
|
|
23
|
+
/** What the string being read is. */
|
|
24
|
+
private role;
|
|
25
|
+
/** The raw text of the key or value being read (between its quotes). */
|
|
26
|
+
private raw;
|
|
27
|
+
/** The top-level key read last, until its `:`; null when unknown or too long. */
|
|
28
|
+
private key;
|
|
29
|
+
/** The key whose value comes next at depth 1. */
|
|
30
|
+
private valueOf;
|
|
31
|
+
private result;
|
|
32
|
+
private done;
|
|
33
|
+
constructor(prop: string);
|
|
34
|
+
/** Scans `fragment`; returns the property's value once known, null before (and when none). */
|
|
35
|
+
feed(fragment: string): string | null;
|
|
36
|
+
private step;
|
|
37
|
+
private keep;
|
|
38
|
+
private closeString;
|
|
39
|
+
private stop;
|
|
40
|
+
}
|
|
41
|
+
/** The value of a top-level string property once its closing quote arrived; null before. */
|
|
42
|
+
export declare function closedStringProperty(json: string, prop: string): string | null;
|
|
43
|
+
/**
|
|
44
|
+
* The input view that starts a base read for the step's tool `name` (ruling R7): only the builtin
|
|
45
|
+
* `Write`'s; an extension or connector tool declaring `file_write` gets no base, and a tool whose
|
|
46
|
+
* source is unknown gets none either.
|
|
47
|
+
*/
|
|
48
|
+
export declare function writeBaseViewOf(tools: readonly {
|
|
49
|
+
key: string;
|
|
50
|
+
spec: {
|
|
51
|
+
inputView?: ToolInputView;
|
|
52
|
+
};
|
|
53
|
+
source?: ResolvedTool["source"];
|
|
54
|
+
}[], name: string): ToolInputView | undefined;
|
|
55
|
+
/** A `Write` base: the file's current text and the sha256 (hex) of its bytes. */
|
|
56
|
+
export interface WriteBase {
|
|
57
|
+
text: string;
|
|
58
|
+
sha256: string;
|
|
59
|
+
}
|
|
60
|
+
/** Reads a `Write` base; null whenever there is none to show (never throws for a missing base). */
|
|
61
|
+
export interface WriteBaseReader {
|
|
62
|
+
read(input: {
|
|
63
|
+
conversationId: string;
|
|
64
|
+
path: string;
|
|
65
|
+
signal: AbortSignal;
|
|
66
|
+
}): Promise<WriteBase | null>;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Watches one model stream attempt's tool calls (streaming tool input spec §4.1): a call whose tool
|
|
70
|
+
* declares `inputView.kind: "file_write"` starts one base read once its path property closed, at
|
|
71
|
+
* most one per call id, without blocking the stream. A read that resolves after `signal` aborted
|
|
72
|
+
* (a step reset, the stream's end, the run's abort) emits nothing; a read that throws is logged
|
|
73
|
+
* and dropped. The attempt aborts `signal` and then awaits {@link settle}, so no admission starts
|
|
74
|
+
* after its step moves on (each read checks the signal right before its admission) and a read
|
|
75
|
+
* still running normally ends with it. The wait is bounded ({@link WRITE_BASE_SETTLE_MS}): a read
|
|
76
|
+
* whose provider ignores the abort is logged once and left to end in the background.
|
|
77
|
+
*/
|
|
78
|
+
export declare function writeBaseWatcher(deps: {
|
|
79
|
+
reader: WriteBaseReader;
|
|
80
|
+
inputViewOf(toolName: string): ToolInputView | undefined;
|
|
81
|
+
emit(callId: string, base: WriteBase): void;
|
|
82
|
+
conversationId: string;
|
|
83
|
+
signal: AbortSignal;
|
|
84
|
+
log: Pick<Logger, "warn">;
|
|
85
|
+
/** The bound of {@link settle} in milliseconds (default {@link WRITE_BASE_SETTLE_MS}). */
|
|
86
|
+
settleMs?: number;
|
|
87
|
+
}): {
|
|
88
|
+
onStart(callId: string, name: string): void;
|
|
89
|
+
onInput(callId: string, fragment: string): void;
|
|
90
|
+
/**
|
|
91
|
+
* Resolves once every read started so far has finished, or once the settle bound elapsed
|
|
92
|
+
* (logged once; the reads left keep running in the background). Never rejects.
|
|
93
|
+
*/
|
|
94
|
+
settle(): Promise<void>;
|
|
95
|
+
};
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `Write` base (streaming tool input spec §4.1, D7): while the model streams a call whose tool
|
|
3
|
+
* declares `inputView.kind: "file_write"`, once its path string has closed, the kernel reads the
|
|
4
|
+
* file's current content once, for display only, and publishes it as a `tool_base` so the web can
|
|
5
|
+
* show a live diff. Everything here fails closed: any doubt gives no base, never an error to the
|
|
6
|
+
* run, and nothing reaches the model, the log or a hook. This file holds the stream side (the path
|
|
7
|
+
* scanner and the watcher); the device read is `write-base.service.ts`, kept apart so the model
|
|
8
|
+
* step imports nothing of the sandbox.
|
|
9
|
+
*/
|
|
10
|
+
/** The longest raw (still escaped) top-level key the scanner keeps: longer ones match no property. */
|
|
11
|
+
const KEY_MAX_CHARS = 256;
|
|
12
|
+
/** The longest raw (still escaped) property value the scanner keeps: a longer path gets no base. */
|
|
13
|
+
const VALUE_MAX_CHARS = 8192;
|
|
14
|
+
/**
|
|
15
|
+
* How long an attempt waits for its base reads after aborting them. The abort reaches the lease
|
|
16
|
+
* and provider waits, so a read normally ends at once; a provider that ignores its signal never
|
|
17
|
+
* holds the step (and a Stop) past this bound for a display-only base.
|
|
18
|
+
*/
|
|
19
|
+
export const WRITE_BASE_SETTLE_MS = 3_000;
|
|
20
|
+
/**
|
|
21
|
+
* Reads the value of one top-level string property of a JSON object streamed in fragments, without
|
|
22
|
+
* re-reading the buffer: each {@link feed} scans only the new fragment with the carried state.
|
|
23
|
+
* The value is known once its closing quote arrived (a half path is not a path). A property of a
|
|
24
|
+
* nested object or array, a non-string value, a top level that is not an object, or a value
|
|
25
|
+
* above {@link VALUE_MAX_CHARS} gives nothing.
|
|
26
|
+
*/
|
|
27
|
+
export class TopLevelStringProperty {
|
|
28
|
+
prop;
|
|
29
|
+
depth = 0;
|
|
30
|
+
inString = false;
|
|
31
|
+
escaped = false;
|
|
32
|
+
/** At depth 1, the next string is a key. */
|
|
33
|
+
expectKey = false;
|
|
34
|
+
/** What the string being read is. */
|
|
35
|
+
role = "other";
|
|
36
|
+
/** The raw text of the key or value being read (between its quotes). */
|
|
37
|
+
raw = "";
|
|
38
|
+
/** The top-level key read last, until its `:`; null when unknown or too long. */
|
|
39
|
+
key = null;
|
|
40
|
+
/** The key whose value comes next at depth 1. */
|
|
41
|
+
valueOf = null;
|
|
42
|
+
result = null;
|
|
43
|
+
done = false;
|
|
44
|
+
constructor(prop) {
|
|
45
|
+
this.prop = prop;
|
|
46
|
+
}
|
|
47
|
+
/** Scans `fragment`; returns the property's value once known, null before (and when none). */
|
|
48
|
+
feed(fragment) {
|
|
49
|
+
if (this.done)
|
|
50
|
+
return this.result;
|
|
51
|
+
for (const c of fragment) {
|
|
52
|
+
this.step(c);
|
|
53
|
+
if (this.done)
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
return this.result;
|
|
57
|
+
}
|
|
58
|
+
step(c) {
|
|
59
|
+
if (this.inString) {
|
|
60
|
+
if (this.escaped) {
|
|
61
|
+
this.escaped = false;
|
|
62
|
+
this.keep(c);
|
|
63
|
+
}
|
|
64
|
+
else if (c === "\\") {
|
|
65
|
+
this.escaped = true;
|
|
66
|
+
this.keep(c);
|
|
67
|
+
}
|
|
68
|
+
else if (c === '"') {
|
|
69
|
+
this.closeString();
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
this.keep(c);
|
|
73
|
+
}
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
switch (c) {
|
|
77
|
+
case '"':
|
|
78
|
+
this.inString = true;
|
|
79
|
+
this.raw = "";
|
|
80
|
+
if (this.depth === 1 && this.expectKey)
|
|
81
|
+
this.role = "key";
|
|
82
|
+
else if (this.depth === 1 && this.valueOf === this.prop)
|
|
83
|
+
this.role = "value";
|
|
84
|
+
else
|
|
85
|
+
this.role = "other";
|
|
86
|
+
return;
|
|
87
|
+
case "{":
|
|
88
|
+
case "[":
|
|
89
|
+
// the top level must be an object
|
|
90
|
+
if (this.depth === 0 && c === "[") {
|
|
91
|
+
this.stop();
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (this.depth === 1)
|
|
95
|
+
this.valueOf = null;
|
|
96
|
+
this.depth++;
|
|
97
|
+
if (this.depth === 1)
|
|
98
|
+
this.expectKey = true;
|
|
99
|
+
return;
|
|
100
|
+
case "}":
|
|
101
|
+
case "]":
|
|
102
|
+
this.depth--;
|
|
103
|
+
// the object ended without the property
|
|
104
|
+
if (this.depth <= 0)
|
|
105
|
+
this.stop();
|
|
106
|
+
return;
|
|
107
|
+
case ":":
|
|
108
|
+
if (this.depth === 1) {
|
|
109
|
+
this.valueOf = this.key;
|
|
110
|
+
this.key = null;
|
|
111
|
+
this.expectKey = false;
|
|
112
|
+
}
|
|
113
|
+
return;
|
|
114
|
+
case ",":
|
|
115
|
+
if (this.depth === 1) {
|
|
116
|
+
this.expectKey = true;
|
|
117
|
+
this.valueOf = null;
|
|
118
|
+
}
|
|
119
|
+
return;
|
|
120
|
+
default:
|
|
121
|
+
// a number, literal or whitespace; a non-string value of the property ends the search
|
|
122
|
+
if (this.depth === 1 && !isJsonSpace(c) && this.valueOf === this.prop)
|
|
123
|
+
this.stop();
|
|
124
|
+
else if (this.depth === 0 && !isJsonSpace(c))
|
|
125
|
+
this.stop();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
keep(c) {
|
|
129
|
+
if (this.role === "other")
|
|
130
|
+
return;
|
|
131
|
+
this.raw += c;
|
|
132
|
+
if (this.role === "value" && this.raw.length > VALUE_MAX_CHARS)
|
|
133
|
+
this.stop();
|
|
134
|
+
else if (this.role === "key" && this.raw.length > KEY_MAX_CHARS)
|
|
135
|
+
this.role = "other";
|
|
136
|
+
}
|
|
137
|
+
closeString() {
|
|
138
|
+
this.inString = false;
|
|
139
|
+
const role = this.role;
|
|
140
|
+
this.role = "other";
|
|
141
|
+
if (this.depth !== 1)
|
|
142
|
+
return;
|
|
143
|
+
if (this.expectKey) {
|
|
144
|
+
this.expectKey = false;
|
|
145
|
+
this.key = role === "key" ? decode(this.raw) : null;
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (role === "value") {
|
|
149
|
+
this.result = decode(this.raw);
|
|
150
|
+
this.stop();
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
this.valueOf = null;
|
|
154
|
+
}
|
|
155
|
+
stop() {
|
|
156
|
+
this.done = true;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** JSON whitespace (RFC 8259): space, tab, line feed, carriage return. */
|
|
160
|
+
const isJsonSpace = (c) => c === " " || c === "\n" || c === "\t" || c === "\r";
|
|
161
|
+
/** A JSON string body (between its quotes) decoded; null when it is not valid JSON. */
|
|
162
|
+
function decode(raw) {
|
|
163
|
+
try {
|
|
164
|
+
const v = JSON.parse(`"${raw}"`);
|
|
165
|
+
return typeof v === "string" ? v : null;
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/** The value of a top-level string property once its closing quote arrived; null before. */
|
|
172
|
+
export function closedStringProperty(json, prop) {
|
|
173
|
+
return new TopLevelStringProperty(prop).feed(json);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The input view that starts a base read for the step's tool `name` (ruling R7): only the builtin
|
|
177
|
+
* `Write`'s; an extension or connector tool declaring `file_write` gets no base, and a tool whose
|
|
178
|
+
* source is unknown gets none either.
|
|
179
|
+
*/
|
|
180
|
+
export function writeBaseViewOf(tools, name) {
|
|
181
|
+
const t = tools.find((x) => x.key === name);
|
|
182
|
+
if (t?.source?.kind !== "builtin" || t.source.name !== "Write")
|
|
183
|
+
return undefined;
|
|
184
|
+
return t.spec.inputView?.kind === "file_write" ? t.spec.inputView : undefined;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Watches one model stream attempt's tool calls (streaming tool input spec §4.1): a call whose tool
|
|
188
|
+
* declares `inputView.kind: "file_write"` starts one base read once its path property closed, at
|
|
189
|
+
* most one per call id, without blocking the stream. A read that resolves after `signal` aborted
|
|
190
|
+
* (a step reset, the stream's end, the run's abort) emits nothing; a read that throws is logged
|
|
191
|
+
* and dropped. The attempt aborts `signal` and then awaits {@link settle}, so no admission starts
|
|
192
|
+
* after its step moves on (each read checks the signal right before its admission) and a read
|
|
193
|
+
* still running normally ends with it. The wait is bounded ({@link WRITE_BASE_SETTLE_MS}): a read
|
|
194
|
+
* whose provider ignores the abort is logged once and left to end in the background.
|
|
195
|
+
*/
|
|
196
|
+
export function writeBaseWatcher(deps) {
|
|
197
|
+
const watching = new Map();
|
|
198
|
+
/** The reads in flight (each removes itself when it finishes). */
|
|
199
|
+
const inFlight = new Set();
|
|
200
|
+
/** Call ids already seen: a repeated start never starts a second read. */
|
|
201
|
+
const seen = new Set();
|
|
202
|
+
let warnedStray = false;
|
|
203
|
+
const read = async (callId, path) => {
|
|
204
|
+
try {
|
|
205
|
+
const base = await deps.reader.read({
|
|
206
|
+
conversationId: deps.conversationId,
|
|
207
|
+
path,
|
|
208
|
+
signal: deps.signal,
|
|
209
|
+
});
|
|
210
|
+
if (base === null || deps.signal.aborted)
|
|
211
|
+
return;
|
|
212
|
+
deps.emit(callId, base);
|
|
213
|
+
}
|
|
214
|
+
catch (err) {
|
|
215
|
+
if (deps.signal.aborted)
|
|
216
|
+
return;
|
|
217
|
+
deps.log.warn("write base not shown: the read failed", {
|
|
218
|
+
conversationId: deps.conversationId,
|
|
219
|
+
callId,
|
|
220
|
+
err,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
return {
|
|
225
|
+
onStart(callId, name) {
|
|
226
|
+
if (deps.signal.aborted || seen.has(callId))
|
|
227
|
+
return;
|
|
228
|
+
seen.add(callId);
|
|
229
|
+
const view = deps.inputViewOf(name);
|
|
230
|
+
if (view?.kind !== "file_write")
|
|
231
|
+
return;
|
|
232
|
+
watching.set(callId, new TopLevelStringProperty(view.path));
|
|
233
|
+
},
|
|
234
|
+
onInput(callId, fragment) {
|
|
235
|
+
const scanner = watching.get(callId);
|
|
236
|
+
if (scanner === undefined)
|
|
237
|
+
return;
|
|
238
|
+
if (deps.signal.aborted) {
|
|
239
|
+
watching.delete(callId);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
const path = scanner.feed(fragment);
|
|
243
|
+
if (path === null)
|
|
244
|
+
return;
|
|
245
|
+
// one read per call id, whatever follows
|
|
246
|
+
watching.delete(callId);
|
|
247
|
+
const pending = read(callId, path);
|
|
248
|
+
inFlight.add(pending);
|
|
249
|
+
void pending.finally(() => inFlight.delete(pending));
|
|
250
|
+
},
|
|
251
|
+
async settle() {
|
|
252
|
+
if (inFlight.size === 0)
|
|
253
|
+
return;
|
|
254
|
+
const boundMs = deps.settleMs ?? WRITE_BASE_SETTLE_MS;
|
|
255
|
+
let timer;
|
|
256
|
+
// the attempt's own timer, cleared when the wait ends
|
|
257
|
+
const expired = new Promise((resolve) => {
|
|
258
|
+
timer = setTimeout(() => resolve("expired"), boundMs);
|
|
259
|
+
});
|
|
260
|
+
try {
|
|
261
|
+
while (inFlight.size > 0) {
|
|
262
|
+
const all = Promise.allSettled([...inFlight]).then(() => "done");
|
|
263
|
+
if ((await Promise.race([all, expired])) === "done")
|
|
264
|
+
continue;
|
|
265
|
+
if (!warnedStray) {
|
|
266
|
+
warnedStray = true;
|
|
267
|
+
deps.log.warn("write base read still running after its abort; not waited for", {
|
|
268
|
+
conversationId: deps.conversationId,
|
|
269
|
+
pending: inFlight.size,
|
|
270
|
+
boundMs,
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
clearTimeout(timer);
|
|
278
|
+
}
|
|
279
|
+
},
|
|
280
|
+
};
|
|
281
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { EventLog } from "../conversations/event-log.js";
|
|
2
|
+
import { DeviceAccess } from "../devices/access.js";
|
|
3
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
4
|
+
import type { KernelLogger } from "../log.js";
|
|
5
|
+
import { SandboxService } from "../sandbox/sandbox.service.js";
|
|
6
|
+
import { type ExecutionClaim } from "./run-execution.js";
|
|
7
|
+
import type { WriteBase, WriteBaseReader } from "./write-base.js";
|
|
8
|
+
/** What the run's device read needs to know about the run (the step runs under its claim). */
|
|
9
|
+
export interface WriteBaseRunFacts {
|
|
10
|
+
/** The device the conversation tree is bound to (the root conversation's; never binds one). */
|
|
11
|
+
deviceId: string;
|
|
12
|
+
/** The run's trigger account, the owner of the conversation and its device. */
|
|
13
|
+
accountId: string;
|
|
14
|
+
}
|
|
15
|
+
/** The dependencies of {@link readWriteBase} (the service's, faked in unit tests). */
|
|
16
|
+
export interface WriteBaseReadDeps {
|
|
17
|
+
/** The current execution claim of the step (`currentExecutionClaim`). */
|
|
18
|
+
claim(): Readonly<ExecutionClaim> | undefined;
|
|
19
|
+
/** The run's device and actor, or null when the run may not read one now (never binds). */
|
|
20
|
+
runFacts(claim: Readonly<ExecutionClaim>): Promise<WriteBaseRunFacts | null>;
|
|
21
|
+
eventLog: Pick<EventLog, "latestFileState">;
|
|
22
|
+
sandbox: Pick<SandboxService, "withKernelRead">;
|
|
23
|
+
log: Pick<KernelLogger, "warn" | "debug">;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Reads the base of a streaming `Write` of `rawPath` in `conversationId`, or null (§4.1):
|
|
27
|
+
* 1. The path as `Write` takes it (`checkFilePathShape`, `checkToolPath`, normalized). A relative
|
|
28
|
+
* path gets none here: it resolves against the working root only inside a tool's use.
|
|
29
|
+
* 2. The step's current execution claim, for this conversation. The log's latest recorded state
|
|
30
|
+
* of the path (`lastFileState`): none, or one above `TOOL_VIEW_DIFF_MAX_TEXT_BYTES`, gives none.
|
|
31
|
+
* 3. A `write_base` kernel read (`withKernelRead`: the run `running`, `stat` / `readFile` of exactly
|
|
32
|
+
* the path, never making, waking or resuming an instance, no path lease), at most
|
|
33
|
+
* `TOOL_VIEW_DIFF_MAX_TEXT_BYTES` read (below `TOOL_VIEW_DIFF_MAX_BYTES`). A path in the skills
|
|
34
|
+
* directory (read-only to `Write`), a directory, a missing file, a cut read, a NUL byte, a size
|
|
35
|
+
* or sha256 other than the recorded state's: none. The state check is the guard that the base
|
|
36
|
+
* shows nothing the conversation had not already read unchanged (symlink targets included).
|
|
37
|
+
* Every failure (a refused admission, `KernelReadInstanceNotRunning`, a read error, an abort) gives
|
|
38
|
+
* none; an expected one ({@link expectedNoBase}) is logged at debug, any other as a warning.
|
|
39
|
+
*/
|
|
40
|
+
export declare function readWriteBase(deps: WriteBaseReadDeps, input: {
|
|
41
|
+
conversationId: string;
|
|
42
|
+
path: string;
|
|
43
|
+
signal: AbortSignal;
|
|
44
|
+
}): Promise<WriteBase | null>;
|
|
45
|
+
/**
|
|
46
|
+
* The failures that only mean "no base now": the device's instance is not running, the read was
|
|
47
|
+
* not admitted (the run moved on, the authority refused it) or its runtime cannot enforce a
|
|
48
|
+
* read-only read, the sandbox is busy, the device is gone, its provider off or an earlier instance
|
|
49
|
+
* still awaits retirement, or the model's path is malformed (`Write` refuses it with the same
|
|
50
|
+
* `ToolError`).
|
|
51
|
+
*/
|
|
52
|
+
export declare function expectedNoBase(err: unknown): boolean;
|
|
53
|
+
/**
|
|
54
|
+
* The run worker's {@link WriteBaseReader} (streaming tool input spec §4.1): {@link readWriteBase}
|
|
55
|
+
* over the event log, the sandbox's kernel read and the run's facts read from PG. The device is
|
|
56
|
+
* the one the conversation tree is already bound to (never bound here), used only when the run's
|
|
57
|
+
* trigger account owns the conversation, its root and the device, and the device's provider is
|
|
58
|
+
* on in the org (`DeviceAccess.usable`), as a `Write` call would require.
|
|
59
|
+
*/
|
|
60
|
+
export declare class WriteBaseService implements WriteBaseReader {
|
|
61
|
+
private readonly deps;
|
|
62
|
+
constructor(db: KernelDb, eventLog: EventLog, sandbox: SandboxService, access: DeviceAccess, log: KernelLogger);
|
|
63
|
+
read(input: {
|
|
64
|
+
conversationId: string;
|
|
65
|
+
path: string;
|
|
66
|
+
signal: AbortSignal;
|
|
67
|
+
}): Promise<WriteBase | null>;
|
|
68
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { ToolError } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
|
+
import { EventLog } from "../conversations/event-log.js";
|
|
13
|
+
import { DeviceAccess } from "../devices/access.js";
|
|
14
|
+
import { ApiError } from "../errors.js";
|
|
15
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
16
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
17
|
+
import { KernelReadInstanceNotRunning, KernelReadNotAdmitted, KernelReadUnsupported, } from "../sandbox/kernel-read.js";
|
|
18
|
+
import { RetirementPendingError, SandboxService } from "../sandbox/sandbox.service.js";
|
|
19
|
+
import { checkFilePathShape, checkToolPath, looksBinary, } from "../tools/builtins/sandbox/common.js";
|
|
20
|
+
import { fileStateOf, lastFileState, normalizeSandboxPath, } from "../tools/builtins/sandbox/file-state.js";
|
|
21
|
+
import { TOOL_VIEW_DIFF_MAX_BYTES, TOOL_VIEW_DIFF_MAX_TEXT_BYTES } from "../tools/view.js";
|
|
22
|
+
import { currentExecutionClaim } from "./run-execution.js";
|
|
23
|
+
/**
|
|
24
|
+
* Reads the base of a streaming `Write` of `rawPath` in `conversationId`, or null (§4.1):
|
|
25
|
+
* 1. The path as `Write` takes it (`checkFilePathShape`, `checkToolPath`, normalized). A relative
|
|
26
|
+
* path gets none here: it resolves against the working root only inside a tool's use.
|
|
27
|
+
* 2. The step's current execution claim, for this conversation. The log's latest recorded state
|
|
28
|
+
* of the path (`lastFileState`): none, or one above `TOOL_VIEW_DIFF_MAX_TEXT_BYTES`, gives none.
|
|
29
|
+
* 3. A `write_base` kernel read (`withKernelRead`: the run `running`, `stat` / `readFile` of exactly
|
|
30
|
+
* the path, never making, waking or resuming an instance, no path lease), at most
|
|
31
|
+
* `TOOL_VIEW_DIFF_MAX_TEXT_BYTES` read (below `TOOL_VIEW_DIFF_MAX_BYTES`). A path in the skills
|
|
32
|
+
* directory (read-only to `Write`), a directory, a missing file, a cut read, a NUL byte, a size
|
|
33
|
+
* or sha256 other than the recorded state's: none. The state check is the guard that the base
|
|
34
|
+
* shows nothing the conversation had not already read unchanged (symlink targets included).
|
|
35
|
+
* Every failure (a refused admission, `KernelReadInstanceNotRunning`, a read error, an abort) gives
|
|
36
|
+
* none; an expected one ({@link expectedNoBase}) is logged at debug, any other as a warning.
|
|
37
|
+
*/
|
|
38
|
+
export async function readWriteBase(deps, input) {
|
|
39
|
+
const { conversationId, signal } = input;
|
|
40
|
+
try {
|
|
41
|
+
if (!input.path.startsWith("/"))
|
|
42
|
+
return null;
|
|
43
|
+
checkFilePathShape(input.path);
|
|
44
|
+
const path = normalizeSandboxPath(checkToolPath(input.path, "file_path"));
|
|
45
|
+
if (path === "/")
|
|
46
|
+
return null;
|
|
47
|
+
const claim = deps.claim();
|
|
48
|
+
if (!claim || claim.conversationId !== conversationId)
|
|
49
|
+
return null;
|
|
50
|
+
const seen = await lastFileState(deps.eventLog, conversationId, path);
|
|
51
|
+
if (seen === null || seen.size > TOOL_VIEW_DIFF_MAX_TEXT_BYTES)
|
|
52
|
+
return null;
|
|
53
|
+
signal.throwIfAborted();
|
|
54
|
+
const facts = await deps.runFacts(claim);
|
|
55
|
+
if (facts === null)
|
|
56
|
+
return null;
|
|
57
|
+
// checked last before the read: an attempt that ended starts no admission
|
|
58
|
+
signal.throwIfAborted();
|
|
59
|
+
const data = await deps.sandbox.withKernelRead({
|
|
60
|
+
orgId: claim.orgId,
|
|
61
|
+
deviceId: facts.deviceId,
|
|
62
|
+
holderConversationId: conversationId,
|
|
63
|
+
// a display-only read tells the model nothing
|
|
64
|
+
silent: true,
|
|
65
|
+
actor: { accountId: facts.accountId, conversationId, runId: claim.runId },
|
|
66
|
+
}, { claim, purpose: "write_base", path }, async (h, p, info, sig) => {
|
|
67
|
+
const skills = info.roots.skills;
|
|
68
|
+
if (path === skills || path.startsWith(`${skills}/`))
|
|
69
|
+
return null;
|
|
70
|
+
const st = await p.stat(h, path, sig);
|
|
71
|
+
if (st === null || st.isDir || st.size !== seen.size)
|
|
72
|
+
return null;
|
|
73
|
+
const got = await p.readFile(h, path, {
|
|
74
|
+
maxBytes: Math.min(TOOL_VIEW_DIFF_MAX_TEXT_BYTES, TOOL_VIEW_DIFF_MAX_BYTES),
|
|
75
|
+
signal: sig,
|
|
76
|
+
});
|
|
77
|
+
if (got === null || got.truncated)
|
|
78
|
+
return null;
|
|
79
|
+
return got.data;
|
|
80
|
+
}, signal);
|
|
81
|
+
if (data === null || signal.aborted)
|
|
82
|
+
return null;
|
|
83
|
+
if (data.byteLength > TOOL_VIEW_DIFF_MAX_TEXT_BYTES)
|
|
84
|
+
return null;
|
|
85
|
+
const now = fileStateOf(data, data.byteLength);
|
|
86
|
+
if (now.size !== seen.size || now.sha256 !== seen.sha256)
|
|
87
|
+
return null;
|
|
88
|
+
if (looksBinary(data) || data.includes(0))
|
|
89
|
+
return null;
|
|
90
|
+
const text = utf8(data);
|
|
91
|
+
// bytes that are not UTF-8 are binary here: no base
|
|
92
|
+
return text === null ? null : { text, sha256: now.sha256 };
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
if (signal.aborted)
|
|
96
|
+
return null;
|
|
97
|
+
// an outcome the person simply gets no base for: debug; anything else: warn
|
|
98
|
+
const level = expectedNoBase(err) ? "debug" : "warn";
|
|
99
|
+
deps.log[level]("write base not read; the row streams without it", { conversationId, err });
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** `data` as UTF-8 text, or null when it is not valid UTF-8. */
|
|
104
|
+
function utf8(data) {
|
|
105
|
+
try {
|
|
106
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(data);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The failures that only mean "no base now": the device's instance is not running, the read was
|
|
114
|
+
* not admitted (the run moved on, the authority refused it) or its runtime cannot enforce a
|
|
115
|
+
* read-only read, the sandbox is busy, the device is gone, its provider off or an earlier instance
|
|
116
|
+
* still awaits retirement, or the model's path is malformed (`Write` refuses it with the same
|
|
117
|
+
* `ToolError`).
|
|
118
|
+
*/
|
|
119
|
+
export function expectedNoBase(err) {
|
|
120
|
+
if (err instanceof KernelReadInstanceNotRunning ||
|
|
121
|
+
err instanceof KernelReadNotAdmitted ||
|
|
122
|
+
err instanceof KernelReadUnsupported ||
|
|
123
|
+
err instanceof RetirementPendingError ||
|
|
124
|
+
err instanceof ToolError)
|
|
125
|
+
return true;
|
|
126
|
+
return (err instanceof ApiError &&
|
|
127
|
+
(err.code === "device.unavailable" ||
|
|
128
|
+
err.code === "device.not_found" ||
|
|
129
|
+
err.code === "sandbox.busy"));
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The run worker's {@link WriteBaseReader} (streaming tool input spec §4.1): {@link readWriteBase}
|
|
133
|
+
* over the event log, the sandbox's kernel read and the run's facts read from PG. The device is
|
|
134
|
+
* the one the conversation tree is already bound to (never bound here), used only when the run's
|
|
135
|
+
* trigger account owns the conversation, its root and the device, and the device's provider is
|
|
136
|
+
* on in the org (`DeviceAccess.usable`), as a `Write` call would require.
|
|
137
|
+
*/
|
|
138
|
+
let WriteBaseService = class WriteBaseService {
|
|
139
|
+
deps;
|
|
140
|
+
constructor(db, eventLog, sandbox, access, log) {
|
|
141
|
+
this.deps = {
|
|
142
|
+
claim: currentExecutionClaim,
|
|
143
|
+
eventLog,
|
|
144
|
+
sandbox,
|
|
145
|
+
log,
|
|
146
|
+
runFacts: async (claim) => {
|
|
147
|
+
const run = await db.db
|
|
148
|
+
.selectFrom("runs")
|
|
149
|
+
.select("trigger_account_id")
|
|
150
|
+
.where("id", "=", claim.runId)
|
|
151
|
+
.where("conversation_id", "=", claim.conversationId)
|
|
152
|
+
.executeTakeFirst();
|
|
153
|
+
const convs = await db.db
|
|
154
|
+
.selectFrom("conversations")
|
|
155
|
+
.select(["id", "account_id", "device_id"])
|
|
156
|
+
.where("org_id", "=", claim.orgId)
|
|
157
|
+
.where("id", "in", [claim.conversationId, claim.rootId])
|
|
158
|
+
.execute();
|
|
159
|
+
const own = convs.find((c) => c.id === claim.conversationId);
|
|
160
|
+
const root = convs.find((c) => c.id === claim.rootId);
|
|
161
|
+
if (!run || !own || !root || root.device_id === null)
|
|
162
|
+
return null;
|
|
163
|
+
const accountId = run.trigger_account_id;
|
|
164
|
+
// a run another account triggered never uses the owner's device
|
|
165
|
+
if (own.account_id !== accountId || root.account_id !== accountId)
|
|
166
|
+
return null;
|
|
167
|
+
const device = await access.usable(claim.orgId, accountId, root.device_id);
|
|
168
|
+
return { deviceId: device.id, accountId };
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
read(input) {
|
|
173
|
+
return readWriteBase(this.deps, input);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
WriteBaseService = __decorate([
|
|
177
|
+
Injectable(),
|
|
178
|
+
__param(0, Inject(KernelDb)),
|
|
179
|
+
__param(1, Inject(EventLog)),
|
|
180
|
+
__param(2, Inject(SandboxService)),
|
|
181
|
+
__param(3, Inject(DeviceAccess)),
|
|
182
|
+
__param(4, Inject(KERNEL_LOGGER))
|
|
183
|
+
], WriteBaseService);
|
|
184
|
+
export { WriteBaseService };
|