@nylorun/harness 0.27.0-beta → 0.28.0-beta
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/CHANGELOG.md +109 -0
- package/HOST_CONTRACT.md +15 -13
- package/README.md +3 -1
- package/dist/api/executors.d.ts +79 -11
- package/dist/api/harness.d.ts +83 -2
- package/dist/api/harness.js +43 -4
- package/dist/api/host.d.ts +30 -2
- package/dist/api/host.js +156 -8
- package/dist/api/index.d.ts +20 -6
- package/dist/api/index.js +18 -4
- package/dist/api/run.d.ts +3 -0
- package/dist/api/run.js +81 -16
- package/dist/flow/context.d.ts +3 -0
- package/dist/flow/context.js +2 -1
- package/dist/flow/engine.d.ts +2 -0
- package/dist/flow/engine.js +10 -7
- package/dist/flow/limits.d.ts +8 -5
- package/dist/flow/limits.js +11 -7
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/loop/compaction/config.d.ts +39 -0
- package/dist/loop/compaction/config.js +29 -0
- package/dist/loop/compaction/index.d.ts +18 -8
- package/dist/loop/compaction/index.js +57 -66
- package/dist/loop/config.d.ts +20 -0
- package/dist/loop/config.js +17 -0
- package/dist/loop/delegation.d.ts +3 -0
- package/dist/loop/delegation.js +14 -10
- package/dist/loop/invocation.d.ts +3 -0
- package/dist/loop/invocation.js +2 -0
- package/dist/loop/model/files.d.ts +77 -0
- package/dist/loop/model/files.js +168 -0
- package/dist/loop/model/json-answer.d.ts +26 -0
- package/dist/loop/model/json-answer.js +125 -0
- package/dist/loop/model/project.d.ts +14 -4
- package/dist/loop/model/project.js +69 -41
- package/dist/loop/options.js +2 -0
- package/dist/loop/run.js +8 -3
- package/dist/loop/state.js +4 -0
- package/dist/loop/step/run.js +19 -3
- package/dist/loop/step/runtime.d.ts +3 -0
- package/dist/run/durable.d.ts +51 -3
- package/dist/run/durable.js +71 -31
- package/dist/tools/artifacts.d.ts +33 -0
- package/dist/tools/artifacts.js +323 -0
- package/dist/tools/engine-tools.d.ts +42 -0
- package/dist/tools/engine-tools.js +26 -0
- package/dist/tools/mcp.d.ts +92 -0
- package/dist/tools/mcp.js +240 -0
- package/dist/tools/outputs.d.ts +23 -0
- package/dist/tools/outputs.js +193 -0
- package/dist/tools/results.d.ts +108 -0
- package/dist/tools/results.js +329 -0
- package/dist/tools/sandbox.d.ts +35 -0
- package/dist/tools/sandbox.js +129 -0
- package/dist/tools/skills.d.ts +94 -0
- package/dist/tools/skills.js +243 -0
- package/dist/tools/text-page.d.ts +20 -0
- package/dist/tools/text-page.js +64 -0
- package/dist/tools/tool-search.d.ts +56 -0
- package/dist/tools/tool-search.js +174 -0
- package/dist/tools/trace.d.ts +13 -0
- package/dist/tools/trace.js +34 -0
- package/dist/types/execution.d.ts +20 -0
- package/package.json +2 -2
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool results that fit (R2b C11, Q22–Q24; protocol 15): our engine shapes what a tool returned
|
|
3
|
+
* before it reports the outcome (`effect.outcome`), since the record refuses an entry past the
|
|
4
|
+
* Runtime limit `recordEntryBytes` and a step's results are one transcript entry. The Tool Gate
|
|
5
|
+
* already refused an answer past `toolAnswerBytes` (`mcp.too-large`, `http.too-large`) and
|
|
6
|
+
* scrubbed the credential values it echoed. A harness of your own may use these as they are.
|
|
7
|
+
*
|
|
8
|
+
* - An `image`, `audio` or blob `resource` part of an MCP result becomes a file artifact of the
|
|
9
|
+
* session (`artifact.write`, keyed by the call), and the part says `{artifactId, version,
|
|
10
|
+
* contentType, size}`. An image also goes to the model as a file (`ToolOutcome.files`) when the
|
|
11
|
+
* turn's model reads it (`fileView`); a text-only model gets the part's stub alone.
|
|
12
|
+
* - Text or JSON past the call's cap becomes a file artifact, and the model gets `{truncated: true,
|
|
13
|
+
* artifactId, size, preview}`: the first `previewHeadBytes` and the last `previewTailBytes`. In
|
|
14
|
+
* a result of several parts each part is shaped alone, the largest text first, until the whole
|
|
15
|
+
* fits; one that still does not is stored whole.
|
|
16
|
+
* - A `resource_link` stays a link, never fetched, and a text resource that fits stays inline.
|
|
17
|
+
* - A failed outcome's message is cut to its start and end.
|
|
18
|
+
* - When an artifact cannot be stored (the Tenant's artifact limits, say), the preview stays and
|
|
19
|
+
* `dropped` says why the rest is gone: a result never passes its cap. Only an abort throws.
|
|
20
|
+
* - **One step's results share a budget** (`StepBudget`): `stepBudgetBytes`, or the record entry
|
|
21
|
+
* limit less `entryEnvelopeBytes` when that is less. Each result's cap is what the step's other
|
|
22
|
+
* results left of it, at most `resultInlineBytes` for an MCP or HTTP tool; once it is spent, a
|
|
23
|
+
* result becomes a stub naming its artifact, its preview cut to fit `stubBytes`.
|
|
24
|
+
*
|
|
25
|
+
* Each stored result's key (`spillKey`) is the call's effect id with the bytes' hash: a call run
|
|
26
|
+
* again after a crash, which the gate answers with the same bytes, writes nothing new, and other
|
|
27
|
+
* bytes never take the key of a preview already recorded. The model reads a stored result with
|
|
28
|
+
* `read_artifact`.
|
|
29
|
+
*/
|
|
30
|
+
import { createHash } from "node:crypto";
|
|
31
|
+
import { ARTIFACT_NAME_MAX, DEFAULT_CONTENT_TYPE, extensionFor, isText, normalizeContentType, } from "@nylorun/core/contracts";
|
|
32
|
+
import { fromBase64 } from "@nylorun/core/harness-api";
|
|
33
|
+
import { fileView } from "../loop/model/files.js";
|
|
34
|
+
import { jsonBytes, utf8Boundary } from "./text-page.js";
|
|
35
|
+
export { jsonBytes, utf8Boundary } from "./text-page.js";
|
|
36
|
+
export const DEFAULT_TOOL_RESULT_CONFIG = Object.freeze({
|
|
37
|
+
resultInlineBytes: 32 * 1024,
|
|
38
|
+
previewHeadBytes: 4 * 1024,
|
|
39
|
+
previewTailBytes: 1024,
|
|
40
|
+
stepBudgetBytes: 256 * 1024,
|
|
41
|
+
stubBytes: 512,
|
|
42
|
+
smallBytes: 1024,
|
|
43
|
+
minPreviewBytes: 64,
|
|
44
|
+
entryEnvelopeBytes: 4 * 1024,
|
|
45
|
+
});
|
|
46
|
+
/** `set` over the defaults. */
|
|
47
|
+
export function toolResultConfigOf(set) {
|
|
48
|
+
return Object.freeze({
|
|
49
|
+
...DEFAULT_TOOL_RESULT_CONFIG,
|
|
50
|
+
...Object.fromEntries(Object.entries(set ?? {}).filter(([, value]) => value !== undefined)),
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
const encoder = new TextEncoder();
|
|
54
|
+
const decoder = new TextDecoder();
|
|
55
|
+
/**
|
|
56
|
+
* The key a stored result of effect `effectId` is written under (`artifact.write`): the part's
|
|
57
|
+
* index (or `whole`) and the bytes' SHA-256, so the same bytes of the same call are one artifact,
|
|
58
|
+
* whichever run stores them, and other bytes another.
|
|
59
|
+
*/
|
|
60
|
+
export function spillKey(effectId, index, bytes) {
|
|
61
|
+
const content = createHash("sha256").update(bytes).digest("hex");
|
|
62
|
+
return `tr:${createHash("sha256").update(`${effectId}\n${index}\n${content}`).digest("hex")}`;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* What a tool outcome's result weighs in its step's transcript entry: a completed one's output,
|
|
66
|
+
* a failed one's message; 0 for anything else.
|
|
67
|
+
*/
|
|
68
|
+
export function resultBytes(value) {
|
|
69
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
70
|
+
return 0;
|
|
71
|
+
const outcome = value;
|
|
72
|
+
if (outcome.kind === "failed")
|
|
73
|
+
return typeof outcome.message === "string" ? encoder.encode(outcome.message).byteLength : 0;
|
|
74
|
+
if (outcome.kind !== "completed" || outcome.output === undefined)
|
|
75
|
+
return 0;
|
|
76
|
+
return jsonBytes(outcome.output);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* False for an outcome `shapeToolOutcome` returns as it is: a small tool result with no parts.
|
|
80
|
+
* Spares the shaping of most outcomes.
|
|
81
|
+
*/
|
|
82
|
+
export function mayNeedShaping(value, config) {
|
|
83
|
+
const output = value?.output;
|
|
84
|
+
if (value?.kind === "completed" && Array.isArray(output))
|
|
85
|
+
return true;
|
|
86
|
+
return resultBytes(value) > config.smallBytes;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* One run's tool results per model step (an agent's step: `[agent, stepId]`), which share one
|
|
90
|
+
* transcript entry. A result reserves its cap from what the step's other results took, and is
|
|
91
|
+
* counted once it is shaped; a replayed or recorded outcome is counted when it resolves. Shaping
|
|
92
|
+
* is serialized per step (`serialize`), so parallel calls never spend the same room.
|
|
93
|
+
*/
|
|
94
|
+
export class StepBudget {
|
|
95
|
+
config;
|
|
96
|
+
/** The step budget: `stepBudgetBytes`, held under the record entry limit. */
|
|
97
|
+
budget;
|
|
98
|
+
/** The most an MCP or HTTP tool result keeps inline: `resultInlineBytes`, held to the budget. */
|
|
99
|
+
inline;
|
|
100
|
+
used = new Map();
|
|
101
|
+
chains = new Map();
|
|
102
|
+
constructor(config, limits) {
|
|
103
|
+
this.config = config;
|
|
104
|
+
this.budget = Math.max(config.stubBytes, Math.min(config.stepBudgetBytes, limits.recordEntryBytes - config.entryEnvelopeBytes));
|
|
105
|
+
this.inline = Math.min(config.resultInlineBytes, this.budget);
|
|
106
|
+
}
|
|
107
|
+
/** Counts `value`, the outcome of `effect`, toward its step (once per effect). */
|
|
108
|
+
count(effect, value) {
|
|
109
|
+
const step = stepOf(effect);
|
|
110
|
+
if (step === undefined)
|
|
111
|
+
return;
|
|
112
|
+
const effects = this.used.get(step) ?? new Map();
|
|
113
|
+
effects.set(effect.effectId, resultBytes(value));
|
|
114
|
+
this.used.set(step, effects);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The cap of `effect`'s result: what its step's other results left of the budget, at most
|
|
118
|
+
* `inline` when `capped` (an MCP or HTTP tool), and never under a stub.
|
|
119
|
+
*/
|
|
120
|
+
reserve(effect, capped) {
|
|
121
|
+
const step = stepOf(effect);
|
|
122
|
+
let used = 0;
|
|
123
|
+
for (const [id, bytes] of (step === undefined ? undefined : this.used.get(step)) ?? [])
|
|
124
|
+
if (id !== effect.effectId)
|
|
125
|
+
used += bytes;
|
|
126
|
+
const room = this.budget - used;
|
|
127
|
+
return Math.max(this.config.stubBytes, capped ? Math.min(this.inline, room) : room);
|
|
128
|
+
}
|
|
129
|
+
/** Runs `shape` after the shaping of `effect`'s step that came before it. */
|
|
130
|
+
serialize(effect, shape) {
|
|
131
|
+
const step = stepOf(effect) ?? effect.effectId;
|
|
132
|
+
const previous = this.chains.get(step) ?? Promise.resolve();
|
|
133
|
+
const next = previous.then(shape, shape);
|
|
134
|
+
const settled = next.catch(() => undefined);
|
|
135
|
+
this.chains.set(step, settled);
|
|
136
|
+
void settled.then(() => {
|
|
137
|
+
if (this.chains.get(step) === settled)
|
|
138
|
+
this.chains.delete(step);
|
|
139
|
+
});
|
|
140
|
+
return next;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** The model step a tool call answers, and whose agent: its results share one transcript entry. */
|
|
144
|
+
function stepOf(effect) {
|
|
145
|
+
if (effect.kind !== "tool")
|
|
146
|
+
return undefined;
|
|
147
|
+
const stepId = effect.context?.stepId;
|
|
148
|
+
return typeof stepId === "string"
|
|
149
|
+
? JSON.stringify([effect.agent?.id ?? null, stepId])
|
|
150
|
+
: undefined;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The outcome `value` of `ctx.effect`, shaped to fit `ctx.limit` (see the module comment). An
|
|
154
|
+
* outcome that fits and has no binary part comes back as it is. MCP content parts are read only
|
|
155
|
+
* for an `mcp` call.
|
|
156
|
+
*/
|
|
157
|
+
export async function shapeToolOutcome(value, ctx) {
|
|
158
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
159
|
+
return value;
|
|
160
|
+
const outcome = value;
|
|
161
|
+
const { limit } = ctx;
|
|
162
|
+
if (outcome.kind === "failed" && typeof outcome.message === "string")
|
|
163
|
+
return encoder.encode(outcome.message).byteLength > limit
|
|
164
|
+
? { ...outcome, message: cutMessage(outcome.message, limit, ctx.config) }
|
|
165
|
+
: value;
|
|
166
|
+
if (outcome.kind !== "completed" || outcome.output === undefined)
|
|
167
|
+
return value;
|
|
168
|
+
const files = [];
|
|
169
|
+
let output = outcome.output;
|
|
170
|
+
if (ctx.effect.target?.kind === "mcp" && isContentParts(output))
|
|
171
|
+
output = await shapeParts(ctx, output, files);
|
|
172
|
+
let truncated = false;
|
|
173
|
+
if (jsonBytes(output) > limit) {
|
|
174
|
+
output = await storedWhole(ctx, output);
|
|
175
|
+
truncated = true;
|
|
176
|
+
}
|
|
177
|
+
if (output === outcome.output)
|
|
178
|
+
return value;
|
|
179
|
+
return {
|
|
180
|
+
...outcome,
|
|
181
|
+
output,
|
|
182
|
+
...(files.length > 0 ? { files } : {}),
|
|
183
|
+
...(truncated ? { truncated: true } : {}),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/** True for an MCP `content` array: objects with a `type` each. */
|
|
187
|
+
function isContentParts(value) {
|
|
188
|
+
return (Array.isArray(value) &&
|
|
189
|
+
value.length > 0 &&
|
|
190
|
+
value.every((part) => !!part &&
|
|
191
|
+
typeof part === "object" &&
|
|
192
|
+
!Array.isArray(part) &&
|
|
193
|
+
typeof part.type === "string"));
|
|
194
|
+
}
|
|
195
|
+
/** An MCP result's parts: binary ones stored, then the largest text ones until the whole fits. */
|
|
196
|
+
async function shapeParts(ctx, parts, files) {
|
|
197
|
+
const shaped = [];
|
|
198
|
+
for (const [index, part] of parts.entries())
|
|
199
|
+
shaped.push(await shapeBinary(ctx, part, index, files));
|
|
200
|
+
const texts = shaped
|
|
201
|
+
.map((part, index) => ({ index, bytes: textOf(part) === undefined ? 0 : jsonBytes(part) }))
|
|
202
|
+
.filter((item) => item.bytes > 0)
|
|
203
|
+
.sort((a, b) => b.bytes - a.bytes);
|
|
204
|
+
for (const { index } of texts) {
|
|
205
|
+
if (jsonBytes(shaped) <= ctx.limit)
|
|
206
|
+
break;
|
|
207
|
+
const part = shaped[index];
|
|
208
|
+
const text = textOf(part);
|
|
209
|
+
const resource = part.type === "resource" ? part.resource : undefined;
|
|
210
|
+
const contentType = resource ? textType(resource.mimeType) : "text/plain; charset=utf-8";
|
|
211
|
+
const kept = await ctx.store(encoder.encode(text), {
|
|
212
|
+
name: nameOf(ctx, contentType, index),
|
|
213
|
+
contentType,
|
|
214
|
+
index,
|
|
215
|
+
});
|
|
216
|
+
shaped[index] = withPreview({
|
|
217
|
+
type: part.type,
|
|
218
|
+
...(resource && typeof resource.uri === "string" ? { uri: resource.uri } : {}),
|
|
219
|
+
truncated: true,
|
|
220
|
+
...kept,
|
|
221
|
+
}, text, ctx.limit, ctx.config);
|
|
222
|
+
}
|
|
223
|
+
return shaped;
|
|
224
|
+
}
|
|
225
|
+
/** An `image`, `audio` or blob `resource` part, stored; any other part as it is. */
|
|
226
|
+
async function shapeBinary(ctx, part, index, files) {
|
|
227
|
+
const resource = part.type === "resource" && part.resource && typeof part.resource === "object"
|
|
228
|
+
? part.resource
|
|
229
|
+
: undefined;
|
|
230
|
+
const data = part.type === "image" || part.type === "audio"
|
|
231
|
+
? part.data
|
|
232
|
+
: resource !== undefined
|
|
233
|
+
? resource.blob
|
|
234
|
+
: undefined;
|
|
235
|
+
if (typeof data !== "string")
|
|
236
|
+
return part;
|
|
237
|
+
const declared = resource ? resource.mimeType : part.mimeType;
|
|
238
|
+
const contentType = (typeof declared === "string" ? normalizeContentType(declared) : undefined) ??
|
|
239
|
+
DEFAULT_CONTENT_TYPE;
|
|
240
|
+
const name = nameOf(ctx, contentType, index);
|
|
241
|
+
const kept = await ctx.store(fromBase64(data), { name, contentType, index });
|
|
242
|
+
// An image the turn's model reads goes to it as a file, beside the part (Q23).
|
|
243
|
+
if (part.type === "image" && "artifactId" in kept) {
|
|
244
|
+
const file = {
|
|
245
|
+
mediaType: contentType,
|
|
246
|
+
reference: { artifactId: kept.artifactId, version: kept.version, name, size: kept.size },
|
|
247
|
+
};
|
|
248
|
+
if (fileView(file, ctx.model, ctx.limits).kind === "media")
|
|
249
|
+
files.push(file);
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
type: part.type,
|
|
253
|
+
...(resource && typeof resource.uri === "string" ? { uri: resource.uri } : {}),
|
|
254
|
+
...("artifactId" in kept ? kept : { contentType, ...kept }),
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
/** The text a part carries inline: a text part's, or a text resource's. */
|
|
258
|
+
function textOf(part) {
|
|
259
|
+
if (part.type === "text" && typeof part.text === "string")
|
|
260
|
+
return part.text;
|
|
261
|
+
if (part.type === "resource" && part.resource && typeof part.resource === "object") {
|
|
262
|
+
const text = part.resource.text;
|
|
263
|
+
if (typeof text === "string")
|
|
264
|
+
return text;
|
|
265
|
+
}
|
|
266
|
+
return undefined;
|
|
267
|
+
}
|
|
268
|
+
function textType(declared) {
|
|
269
|
+
const type = typeof declared === "string" ? normalizeContentType(declared) : undefined;
|
|
270
|
+
return type !== undefined && isText(type) ? type : "text/plain; charset=utf-8";
|
|
271
|
+
}
|
|
272
|
+
/** `value` stored whole, as text or JSON, and the preview the model gets. */
|
|
273
|
+
async function storedWhole(ctx, value) {
|
|
274
|
+
const text = typeof value === "string" ? value : JSON.stringify(value);
|
|
275
|
+
const contentType = typeof value === "string" ? "text/plain; charset=utf-8" : "application/json";
|
|
276
|
+
const kept = await ctx.store(encoder.encode(text), {
|
|
277
|
+
name: nameOf(ctx, contentType),
|
|
278
|
+
contentType,
|
|
279
|
+
});
|
|
280
|
+
return withPreview({ truncated: true, ...kept }, text, ctx.limit, ctx.config);
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* `stub` with the preview of `text`: its start and end, or less, so that the whole fits `limit`
|
|
284
|
+
* (a step's budget spent); none when even a little does not.
|
|
285
|
+
*/
|
|
286
|
+
function withPreview(stub, text, limit, config) {
|
|
287
|
+
let budget = Math.min(config.previewHeadBytes + config.previewTailBytes, limit);
|
|
288
|
+
for (;;) {
|
|
289
|
+
const shaped = { ...stub, preview: previewOf(text, budget, config) };
|
|
290
|
+
const over = jsonBytes(shaped) - limit;
|
|
291
|
+
if (over <= 0 || budget === 0)
|
|
292
|
+
return shaped;
|
|
293
|
+
budget = budget - over < config.minPreviewBytes ? 0 : budget - over;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/** A name for a stored result: the tool's, with the part's number and the type's extension. */
|
|
297
|
+
function nameOf(ctx, contentType, index) {
|
|
298
|
+
const tool = (ctx.effect.toolName ?? "tool").replace(/[^A-Za-z0-9_.-]/gu, "_");
|
|
299
|
+
const extension = extensionFor(contentType) ?? "bin";
|
|
300
|
+
const suffix = `-result${index === undefined ? "" : `-${index + 1}`}.${extension}`;
|
|
301
|
+
// The name is a file name when the artifact is copied into a workspace (`ARTIFACT_NAME_MAX`).
|
|
302
|
+
return `${tool.slice(0, ARTIFACT_NAME_MAX - suffix.length)}${suffix}`;
|
|
303
|
+
}
|
|
304
|
+
/** What `previewOf` puts between a text's start and its end. */
|
|
305
|
+
const PREVIEW_SEPARATOR = "\n…\n";
|
|
306
|
+
/**
|
|
307
|
+
* The start and end of `text` in whole characters, `budget` bytes split as `previewHeadBytes` is
|
|
308
|
+
* to `previewTailBytes`: by default the first 4 KiB and the last 1 KiB.
|
|
309
|
+
*/
|
|
310
|
+
export function previewOf(text, budget, config) {
|
|
311
|
+
const bytes = encoder.encode(text);
|
|
312
|
+
if (bytes.byteLength <= budget)
|
|
313
|
+
return text;
|
|
314
|
+
if (budget <= 0)
|
|
315
|
+
return "";
|
|
316
|
+
const share = config.previewTailBytes / (config.previewHeadBytes + config.previewTailBytes || 1);
|
|
317
|
+
const tailBytes = Math.floor(budget * share);
|
|
318
|
+
const head = utf8Boundary(bytes, budget - tailBytes, "down");
|
|
319
|
+
const tail = utf8Boundary(bytes, bytes.byteLength - tailBytes, "up");
|
|
320
|
+
return `${decoder.decode(bytes.subarray(0, head))}${PREVIEW_SEPARATOR}${decoder.decode(bytes.subarray(tail))}`;
|
|
321
|
+
}
|
|
322
|
+
/** A message past `limit`: its start and end, and how long it was. */
|
|
323
|
+
export function cutMessage(message, limit, config) {
|
|
324
|
+
const note = `\n(The message was ${encoder.encode(message).byteLength} bytes; its middle is not shown.)`;
|
|
325
|
+
// Room for the note and the separator `previewOf` puts between the start and the end, as
|
|
326
|
+
// JSON: their bytes, escapes and the quotes.
|
|
327
|
+
const budget = Math.min(config.previewHeadBytes + config.previewTailBytes, limit - jsonBytes(`${note}${PREVIEW_SEPARATOR}`));
|
|
328
|
+
return `${previewOf(message, Math.max(0, budget), config)}${note}`;
|
|
329
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { DurableSessionTool } from "../run/durable.js";
|
|
2
|
+
/** What the sandbox tools hold a call to: the harness's configuration of them. */
|
|
3
|
+
export interface SandboxToolLimits {
|
|
4
|
+
/** The characters of `bash` stdout and stderr each keeps, its middle cut past it. */
|
|
5
|
+
readonly outputChars: number;
|
|
6
|
+
/** Seconds a `bash` command runs when it names no `timeout`. */
|
|
7
|
+
readonly defaultTimeoutS: number;
|
|
8
|
+
/** The longest `timeout` a `bash` command may name, in seconds. */
|
|
9
|
+
readonly maxTimeoutS: number;
|
|
10
|
+
/** Lines `read` returns when it names no `limit`. */
|
|
11
|
+
readonly readLines: number;
|
|
12
|
+
/** The most lines one `read` may ask for. */
|
|
13
|
+
readonly maxReadLines: number;
|
|
14
|
+
/** The characters of one line `read` and `grep` show, the rest cut. */
|
|
15
|
+
readonly lineChars: number;
|
|
16
|
+
/** Matches `grep` returns when it names no `max_results`. */
|
|
17
|
+
readonly grepResults: number;
|
|
18
|
+
/** The most matches one `grep` may ask for. */
|
|
19
|
+
readonly maxGrepResults: number;
|
|
20
|
+
/** The most paths `glob` returns. */
|
|
21
|
+
readonly globResults: number;
|
|
22
|
+
/** The most files `glob` looks through. */
|
|
23
|
+
readonly globScan: number;
|
|
24
|
+
}
|
|
25
|
+
/** The sandbox tools' limits when the harness sets none. */
|
|
26
|
+
export declare const DEFAULT_SANDBOX_TOOL_LIMITS: SandboxToolLimits;
|
|
27
|
+
/** The limits in force: `set`, with the default for each it leaves out. */
|
|
28
|
+
export declare function sandboxToolLimitsOf(set?: Partial<SandboxToolLimits>): SandboxToolLimits;
|
|
29
|
+
/** The note on the sandbox the model reads with the sandbox tools. */
|
|
30
|
+
export declare function sandboxInstructions(workspace: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* The six sandbox tools, in the order the model reads them, with `workspace` named in their text
|
|
33
|
+
* and `limits` in their schemas. Each is a `sandbox` effect named by its operation.
|
|
34
|
+
*/
|
|
35
|
+
export declare function sandboxTools(limits: SandboxToolLimits, workspace: string): DurableSessionTool[];
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/** The sandbox tools' limits when the harness sets none. */
|
|
2
|
+
export const DEFAULT_SANDBOX_TOOL_LIMITS = Object.freeze({
|
|
3
|
+
outputChars: 30_000,
|
|
4
|
+
defaultTimeoutS: 120,
|
|
5
|
+
maxTimeoutS: 600,
|
|
6
|
+
readLines: 2000,
|
|
7
|
+
maxReadLines: 5000,
|
|
8
|
+
lineChars: 2000,
|
|
9
|
+
grepResults: 200,
|
|
10
|
+
maxGrepResults: 1000,
|
|
11
|
+
globResults: 500,
|
|
12
|
+
globScan: 20_000,
|
|
13
|
+
});
|
|
14
|
+
/** The limits in force: `set`, with the default for each it leaves out. */
|
|
15
|
+
export function sandboxToolLimitsOf(set) {
|
|
16
|
+
return Object.freeze({ ...DEFAULT_SANDBOX_TOOL_LIMITS, ...definedOf(set ?? {}) });
|
|
17
|
+
}
|
|
18
|
+
function definedOf(value) {
|
|
19
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
|
|
20
|
+
}
|
|
21
|
+
const SANDBOX = Object.freeze({ kind: "sandbox" });
|
|
22
|
+
const SCHEMA = "http://json-schema.org/draft-07/schema#";
|
|
23
|
+
/** The note on the sandbox the model reads with the sandbox tools. */
|
|
24
|
+
export function sandboxInstructions(workspace) {
|
|
25
|
+
return (`You have an isolated Linux sandbox with a persistent working directory at ${workspace}. ` +
|
|
26
|
+
"Use bash to run commands, read/write/edit to work with files, and grep/glob to search. " +
|
|
27
|
+
"Network egress is limited by policy; a failed download usually means the host is not allowed.");
|
|
28
|
+
}
|
|
29
|
+
const object = (properties, required) => ({
|
|
30
|
+
$schema: SCHEMA,
|
|
31
|
+
type: "object",
|
|
32
|
+
properties,
|
|
33
|
+
required: [...required],
|
|
34
|
+
additionalProperties: false,
|
|
35
|
+
});
|
|
36
|
+
const path = { type: "string", minLength: 1 };
|
|
37
|
+
/**
|
|
38
|
+
* The six sandbox tools, in the order the model reads them, with `workspace` named in their text
|
|
39
|
+
* and `limits` in their schemas. Each is a `sandbox` effect named by its operation.
|
|
40
|
+
*/
|
|
41
|
+
export function sandboxTools(limits, workspace) {
|
|
42
|
+
const relative = `Relative paths resolve under ${workspace}.`;
|
|
43
|
+
const tools = [
|
|
44
|
+
{
|
|
45
|
+
name: "bash",
|
|
46
|
+
description: `Run a bash command in the sandbox. The working directory is ${workspace}. ` +
|
|
47
|
+
"Returns exitCode, stdout and stderr; a non-zero exit code is a normal result, not an error. " +
|
|
48
|
+
"Long output is truncated in the middle.",
|
|
49
|
+
inputSchema: object({
|
|
50
|
+
command: {
|
|
51
|
+
type: "string",
|
|
52
|
+
minLength: 1,
|
|
53
|
+
description: "The command line to run with bash.",
|
|
54
|
+
},
|
|
55
|
+
timeout: {
|
|
56
|
+
description: `Seconds before the command is killed. Default ${limits.defaultTimeoutS}, maximum ${limits.maxTimeoutS}.`,
|
|
57
|
+
type: "integer",
|
|
58
|
+
minimum: 1,
|
|
59
|
+
maximum: limits.maxTimeoutS,
|
|
60
|
+
},
|
|
61
|
+
}, ["command"]),
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: "read",
|
|
65
|
+
description: `Read a text file from the sandbox. ${relative} Returns numbered lines. ` +
|
|
66
|
+
"Use offset and limit to page through large files.",
|
|
67
|
+
inputSchema: object({
|
|
68
|
+
path,
|
|
69
|
+
offset: {
|
|
70
|
+
description: "First line to return, 1-based.",
|
|
71
|
+
type: "integer",
|
|
72
|
+
minimum: 1,
|
|
73
|
+
maximum: Number.MAX_SAFE_INTEGER,
|
|
74
|
+
},
|
|
75
|
+
limit: {
|
|
76
|
+
description: `Maximum number of lines. Default ${limits.readLines}.`,
|
|
77
|
+
type: "integer",
|
|
78
|
+
minimum: 1,
|
|
79
|
+
maximum: limits.maxReadLines,
|
|
80
|
+
},
|
|
81
|
+
}, ["path"]),
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
name: "write",
|
|
85
|
+
description: `Create or overwrite a text file in the sandbox. ${relative} Parent directories are created.`,
|
|
86
|
+
inputSchema: object({ path, content: { type: "string" } }, ["path", "content"]),
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
name: "edit",
|
|
90
|
+
description: `Replace text in a sandbox file. ${relative} old_string must match exactly and be unique ` +
|
|
91
|
+
"unless replace_all is true.",
|
|
92
|
+
inputSchema: object({
|
|
93
|
+
path,
|
|
94
|
+
old_string: { type: "string", minLength: 1 },
|
|
95
|
+
new_string: { type: "string" },
|
|
96
|
+
replace_all: { type: "boolean" },
|
|
97
|
+
}, ["path", "old_string", "new_string"]),
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
name: "grep",
|
|
101
|
+
description: `Search file contents in the sandbox with an extended regular expression. ${relative} ` +
|
|
102
|
+
"Returns matching lines as path:line:text.",
|
|
103
|
+
inputSchema: object({
|
|
104
|
+
pattern: { type: "string", minLength: 1 },
|
|
105
|
+
path: { description: `Directory or file to search. Default ${workspace}.`, ...path },
|
|
106
|
+
glob: {
|
|
107
|
+
description: 'Only search files whose name matches, e.g. "*.py".',
|
|
108
|
+
...path,
|
|
109
|
+
},
|
|
110
|
+
ignore_case: { type: "boolean" },
|
|
111
|
+
max_results: {
|
|
112
|
+
description: `Default ${limits.grepResults}.`,
|
|
113
|
+
type: "integer",
|
|
114
|
+
minimum: 1,
|
|
115
|
+
maximum: limits.maxGrepResults,
|
|
116
|
+
},
|
|
117
|
+
}, ["pattern"]),
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
name: "glob",
|
|
121
|
+
description: `Find files in the sandbox by glob pattern, e.g. "**/*.csv". ${relative} Returns matching paths.`,
|
|
122
|
+
inputSchema: object({
|
|
123
|
+
pattern: { type: "string", minLength: 1 },
|
|
124
|
+
path: { description: `Directory to search. Default ${workspace}.`, ...path },
|
|
125
|
+
}, ["pattern"]),
|
|
126
|
+
},
|
|
127
|
+
];
|
|
128
|
+
return tools.map((tool) => ({ ...tool, target: SANDBOX }));
|
|
129
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Our engine's skill tools (protocol 15), which run here, in the harness: `load_skill` for an
|
|
3
|
+
* agent with skills, and `read_skill_resource` when a skill has files besides `SKILL.md`. With
|
|
4
|
+
* them come the skill catalog the model reads (`skillCatalogText`) and, with a sandbox, the note
|
|
5
|
+
* on where each skill's files are (`skillFolderNote`).
|
|
6
|
+
*
|
|
7
|
+
* - `load_skill`: the skill's instructions (its `SKILL.md` after the frontmatter), the paths of
|
|
8
|
+
* its other files, and, when the session has a sandbox, where they are in it
|
|
9
|
+
* (`/skills/<name>@<hash>/`, read-only).
|
|
10
|
+
* - `read_skill_resource`: one text file of the skill. A binary file, or one larger than the
|
|
11
|
+
* harness reads into the model's context (`readBytes`, at most what one record entry holds), is
|
|
12
|
+
* refused: the model uses it in the sandbox, when there is one.
|
|
13
|
+
*
|
|
14
|
+
* A skill's bytes come over the Harness API's `definition.file` seam, a range of at most
|
|
15
|
+
* `turn.start.limits.chunkBytes` at a time. Expected problems are failed outcomes the model sees;
|
|
16
|
+
* only the run's own failures throw.
|
|
17
|
+
*
|
|
18
|
+
* With a sandbox, our engine also decides where and when the skills' files are in it (protocol
|
|
19
|
+
* 15): before each `sandbox` call it mounts each skill version of the turn's tree (the agent and
|
|
20
|
+
* the agents it uses as tools, which share its sandbox) at its folder (`skillFolderOf`) with
|
|
21
|
+
* `executors.files.mount` (`mountSkills`). The host only writes the files, and answers `present`
|
|
22
|
+
* for a folder the sandbox already holds since it last started.
|
|
23
|
+
*/
|
|
24
|
+
import { type AgentManifest, type SkillManifest } from "@nylorun/core/define";
|
|
25
|
+
import { type HarnessChannel } from "@nylorun/core/harness-api";
|
|
26
|
+
import type { DurableSessionTool, HostEffect } from "../run/durable.js";
|
|
27
|
+
import type { FailedFileOutcome, HarnessFiles, HarnessRun } from "../api/executors.js";
|
|
28
|
+
/** Loads a skill's `SKILL.md`. */
|
|
29
|
+
export declare const LOAD_SKILL_TOOL = "load_skill";
|
|
30
|
+
/** Reads one resource file of a skill. */
|
|
31
|
+
export declare const READ_SKILL_RESOURCE_TOOL = "read_skill_resource";
|
|
32
|
+
/** The most bytes of one skill file the skill tools read into the model's context by default. */
|
|
33
|
+
export declare const DEFAULT_SKILL_READ_BYTES: number;
|
|
34
|
+
/** True when `name` is one of our engine's skill tools. */
|
|
35
|
+
export declare function isSkillTool(name: string | undefined): boolean;
|
|
36
|
+
/** The text before the skill catalog: when to load a skill. */
|
|
37
|
+
export declare const SKILLS_USAGE = "The following skills provide specialized instructions. When a task matches a skill description, call load_skill with that name before proceeding.";
|
|
38
|
+
/** The skills the model may load, by name and description. */
|
|
39
|
+
export declare function formatSkillCatalog(skills: readonly {
|
|
40
|
+
readonly name: string;
|
|
41
|
+
readonly description: string;
|
|
42
|
+
}[]): string;
|
|
43
|
+
/** What the model reads of an agent's skills: when to load one, and the catalog. */
|
|
44
|
+
export declare function skillCatalogText(skills: readonly {
|
|
45
|
+
readonly name: string;
|
|
46
|
+
readonly description: string;
|
|
47
|
+
}[]): string[];
|
|
48
|
+
/** Where each skill's files are in the sandbox, for an agent with skills and a sandbox. */
|
|
49
|
+
export declare function skillFolderNote(skills: readonly SkillManifest[]): string;
|
|
50
|
+
/**
|
|
51
|
+
* `load_skill` for the agent's skills, and `read_skill_resource` when a skill has files besides
|
|
52
|
+
* `SKILL.md`. Empty for an agent without skills. Each runs here (`harness`).
|
|
53
|
+
*/
|
|
54
|
+
export declare function skillTools(skills: readonly SkillManifest[]): DurableSessionTool[];
|
|
55
|
+
/** What a skill tool runs with. */
|
|
56
|
+
export interface SkillToolContext {
|
|
57
|
+
readonly channel: Pick<HarnessChannel, "request">;
|
|
58
|
+
readonly run: HarnessRun;
|
|
59
|
+
/** The agent whose skill the call reads: the turn's agent, or the agent used as a tool. */
|
|
60
|
+
readonly agent: Pick<AgentManifest, "skills">;
|
|
61
|
+
/**
|
|
62
|
+
* The most bytes of one file read into the model's context: the harness's `skillReadBytes`.
|
|
63
|
+
* The answer is also held to the run's `limits.recordEntryBytes`, since it is one record entry.
|
|
64
|
+
*/
|
|
65
|
+
readonly readBytes: number;
|
|
66
|
+
/** The session has a sandbox: the skill's files are in it. */
|
|
67
|
+
readonly sandboxed: boolean;
|
|
68
|
+
readonly signal: AbortSignal;
|
|
69
|
+
}
|
|
70
|
+
type Outcome = {
|
|
71
|
+
readonly kind: "completed";
|
|
72
|
+
readonly output: Record<string, unknown>;
|
|
73
|
+
} | FailedFileOutcome;
|
|
74
|
+
/** Runs a call of one of our engine's skill tools, as its outcome. */
|
|
75
|
+
export declare function runSkillTool(effect: HostEffect, context: SkillToolContext): Promise<Outcome>;
|
|
76
|
+
/** A skill's files, by path in its folder, as `sha256:<hex>`. */
|
|
77
|
+
export type SkillFiles = Readonly<Record<string, string>>;
|
|
78
|
+
/**
|
|
79
|
+
* The skill versions of `manifest` and of the agents it uses as tools (they share its sandbox),
|
|
80
|
+
* by folder (`/skills/<name>@<hash>`): each distinct version once.
|
|
81
|
+
*/
|
|
82
|
+
export declare function sandboxSkillsOf(manifest: AgentManifest | undefined, into?: Map<string, Readonly<Record<string, string>>>): Map<string, SkillFiles>;
|
|
83
|
+
/**
|
|
84
|
+
* A definition file's bytes over `definition.file`, a range of at most the run's
|
|
85
|
+
* `limits.chunkBytes` at a time, as they come: a file may be larger than one frame holds.
|
|
86
|
+
*/
|
|
87
|
+
export declare function definitionFileChunks(channel: Pick<HarnessChannel, "request">, run: HarnessRun, sha256: string, signal: AbortSignal): AsyncGenerator<Uint8Array>;
|
|
88
|
+
/**
|
|
89
|
+
* Mounts the skill folders of the run's tree in its sandbox, before a `sandbox` call: each one
|
|
90
|
+
* the sandbox does not hold yet is written, read-only. A failed outcome (the call's, then) when
|
|
91
|
+
* one cannot be; nothing when the tree has no skills.
|
|
92
|
+
*/
|
|
93
|
+
export declare function mountSkills(files: HarnessFiles, channel: Pick<HarnessChannel, "request">, run: HarnessRun, signal: AbortSignal): Promise<FailedFileOutcome | undefined>;
|
|
94
|
+
export {};
|