@nylorun/harness 0.27.1-beta → 0.29.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 +131 -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 +21 -6
- package/dist/api/index.js +19 -4
- package/dist/api/run.d.ts +3 -0
- package/dist/api/run.js +91 -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 +9 -0
- package/dist/index.js +9 -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 +70 -41
- package/dist/loop/options.js +11 -3
- package/dist/loop/run.js +15 -5
- package/dist/loop/state.d.ts +6 -1
- package/dist/loop/state.js +19 -0
- package/dist/loop/step/canonicalize.d.ts +11 -2
- package/dist/loop/step/canonicalize.js +21 -5
- package/dist/loop/step/resolve.js +1 -0
- package/dist/loop/step/run.js +20 -3
- package/dist/loop/step/runtime.d.ts +6 -0
- package/dist/loop/step/seal.js +8 -2
- package/dist/loop/step/step-context.js +1 -1
- package/dist/run/durable.d.ts +58 -3
- package/dist/run/durable.js +104 -33
- package/dist/tools/artifacts.d.ts +33 -0
- package/dist/tools/artifacts.js +323 -0
- package/dist/tools/engine-tools.d.ts +50 -0
- package/dist/tools/engine-tools.js +42 -0
- package/dist/tools/mcp.d.ts +92 -0
- package/dist/tools/mcp.js +240 -0
- package/dist/tools/memory.d.ts +16 -0
- package/dist/tools/memory.js +140 -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/tools/wake.d.ts +13 -0
- package/dist/tools/wake.js +33 -0
- package/dist/types/execution.d.ts +35 -1
- package/package.json +7 -7
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Our engine's outputs folder (protocol 15, Q5): a convention of our engine, not of the Runtime.
|
|
3
|
+
* When an agent's segment ends its turn `completed` in a session with a sandbox, our engine saves
|
|
4
|
+
* the files under its outputs directory (`/workspace/outputs` by default) as a version of the
|
|
5
|
+
* session's folder artifact `outputs`, over the artifact seam (`artifact.write` with
|
|
6
|
+
* `kind: "folder"`): the first save makes the folder, later turns add versions, and a turn whose
|
|
7
|
+
* outputs did not change adds none (the seam answers `unchanged`).
|
|
8
|
+
*
|
|
9
|
+
* - **Before the turn ends.** It runs before `turn.completed`, while the run is held, so the next
|
|
10
|
+
* turn cannot change the workspace under it. A slow save delays the turn's end, bounded by
|
|
11
|
+
* `OutputsConfig.maxBytes`.
|
|
12
|
+
* - **Never fails the turn.** A limit met is claimed as `artifact.export.skipped` (why, and the
|
|
13
|
+
* limit), any other failure as `artifact.export.failed`; the turn completes either way.
|
|
14
|
+
* - **Bounded.** At most `limits.folderEntries` files (the Runtime limit), each within the
|
|
15
|
+
* seam's per-file limit, all within `maxBytes` and the seam's total.
|
|
16
|
+
* - **Idempotent.** The write's key is the turn's (`outputs:<turnId>`): a run that saves again
|
|
17
|
+
* after a takeover stores nothing new.
|
|
18
|
+
*
|
|
19
|
+
* Nothing in the directory, no directory, or a sandbox never created saves nothing and claims
|
|
20
|
+
* nothing. A harness of your own saves no outputs folder unless it writes one.
|
|
21
|
+
*/
|
|
22
|
+
import { createHash } from "node:crypto";
|
|
23
|
+
import { posix } from "node:path";
|
|
24
|
+
import { OUTPUTS_ARTIFACT_NAME, contentTypeFor, } from "@nylorun/core/contracts";
|
|
25
|
+
import { SANDBOX_WORKSPACE } from "@nylorun/core/define";
|
|
26
|
+
import { toBase64 } from "@nylorun/core/harness-api";
|
|
27
|
+
/** The outputs folder by default: `/workspace/outputs`, at most 1 GiB a turn. */
|
|
28
|
+
export const DEFAULT_OUTPUTS_CONFIG = Object.freeze({
|
|
29
|
+
dir: `${SANDBOX_WORKSPACE}/outputs`,
|
|
30
|
+
maxBytes: 1024 * 1024 * 1024,
|
|
31
|
+
});
|
|
32
|
+
/** The outputs configuration: `set`, with the default for each field it leaves out. */
|
|
33
|
+
export function outputsConfigOf(set) {
|
|
34
|
+
return { ...DEFAULT_OUTPUTS_CONFIG, ...set };
|
|
35
|
+
}
|
|
36
|
+
/** Stops the save with `artifact.export.failed`: the sandbox or the seam failed, with its code. */
|
|
37
|
+
class SaveFailed extends Error {
|
|
38
|
+
code;
|
|
39
|
+
constructor(code, message) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.code = code;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Stops the save with `artifact.export.skipped`. */
|
|
45
|
+
class Skip extends Error {
|
|
46
|
+
reason;
|
|
47
|
+
limit;
|
|
48
|
+
path;
|
|
49
|
+
constructor(reason, message, limit, path) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.reason = reason;
|
|
52
|
+
this.limit = limit;
|
|
53
|
+
this.path = path;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Saves the run's outputs folder, claiming why when it stores nothing. Never throws. */
|
|
57
|
+
export async function saveOutputs(context) {
|
|
58
|
+
try {
|
|
59
|
+
await save(context);
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (context.signal.aborted)
|
|
63
|
+
return;
|
|
64
|
+
const payload = error instanceof Skip
|
|
65
|
+
? {
|
|
66
|
+
name: OUTPUTS_ARTIFACT_NAME,
|
|
67
|
+
reason: error.reason,
|
|
68
|
+
message: error.message,
|
|
69
|
+
...(error.limit === undefined ? {} : { limit: error.limit }),
|
|
70
|
+
...(error.path === undefined ? {} : { path: error.path }),
|
|
71
|
+
}
|
|
72
|
+
: {
|
|
73
|
+
name: OUTPUTS_ARTIFACT_NAME,
|
|
74
|
+
message: error instanceof Error ? error.message : String(error),
|
|
75
|
+
};
|
|
76
|
+
const { run } = context;
|
|
77
|
+
await context.channel
|
|
78
|
+
.request("event", {
|
|
79
|
+
runId: run.runId,
|
|
80
|
+
sessionId: run.grant.sessionId,
|
|
81
|
+
turnId: run.grant.turnId,
|
|
82
|
+
type: error instanceof Skip ? "artifact.export.skipped" : "artifact.export.failed",
|
|
83
|
+
payload,
|
|
84
|
+
})
|
|
85
|
+
.catch(() => undefined);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function save(context) {
|
|
89
|
+
const { channel, run, files, config, signal } = context;
|
|
90
|
+
const { limits } = run.start;
|
|
91
|
+
const { dir } = config;
|
|
92
|
+
const listing = await files.list(run, dir, limits.folderEntries, signal);
|
|
93
|
+
if (listing.kind === "missing")
|
|
94
|
+
return;
|
|
95
|
+
if (listing.kind === "failed")
|
|
96
|
+
throw new SaveFailed(listing.code, listing.message);
|
|
97
|
+
if (listing.entries.length === 0)
|
|
98
|
+
return;
|
|
99
|
+
if (listing.truncated)
|
|
100
|
+
throw new Skip("too_many_files", `${dir} holds more than ${limits.folderEntries} files`, limits.folderEntries);
|
|
101
|
+
const runId = run.runId;
|
|
102
|
+
const begun = await channel.request("artifact.write", {
|
|
103
|
+
runId,
|
|
104
|
+
op: "begin",
|
|
105
|
+
kind: "folder",
|
|
106
|
+
key: `outputs:${run.grant.turnId}`,
|
|
107
|
+
name: OUTPUTS_ARTIFACT_NAME,
|
|
108
|
+
sameName: true,
|
|
109
|
+
}, signal);
|
|
110
|
+
// This turn's outputs were saved already (a run that took over): nothing more to store.
|
|
111
|
+
if (begun.status === "written")
|
|
112
|
+
return;
|
|
113
|
+
if (begun.status !== "open")
|
|
114
|
+
throw new SaveFailed("artifact.unexpected", `artifact.write answered ${begun.status} to a begin`);
|
|
115
|
+
const { uploadId } = begun;
|
|
116
|
+
const fileBytes = begun.maxFileBytes ?? begun.maxBytes;
|
|
117
|
+
const maxBytes = Math.min(config.maxBytes, begun.maxBytes);
|
|
118
|
+
try {
|
|
119
|
+
const large = listing.entries.find((entry) => entry.size > fileBytes);
|
|
120
|
+
if (large)
|
|
121
|
+
throw tooLargeFile(dir, large.path, large.size, fileBytes);
|
|
122
|
+
const listed = listing.entries.reduce((sum, entry) => sum + entry.size, 0);
|
|
123
|
+
if (listed > maxBytes)
|
|
124
|
+
throw tooLarge(dir, listed, maxBytes);
|
|
125
|
+
let read = 0;
|
|
126
|
+
let sent = 0;
|
|
127
|
+
for (const entry of listing.entries) {
|
|
128
|
+
const got = await files.read(run, posix.join(dir, entry.path), fileBytes, signal);
|
|
129
|
+
// Gone since the listing: the folder is what is there now.
|
|
130
|
+
if (got.kind === "missing")
|
|
131
|
+
continue;
|
|
132
|
+
if (got.kind === "failed") {
|
|
133
|
+
if (got.code === "artifact.too_large")
|
|
134
|
+
throw tooLargeFile(dir, entry.path, entry.size, fileBytes);
|
|
135
|
+
throw new SaveFailed(got.code, got.message);
|
|
136
|
+
}
|
|
137
|
+
read += got.bytes.byteLength;
|
|
138
|
+
if (read > maxBytes)
|
|
139
|
+
throw tooLarge(dir, read, maxBytes);
|
|
140
|
+
await sendFile(channel, run, uploadId, entry.path, got.bytes, signal);
|
|
141
|
+
sent += 1;
|
|
142
|
+
}
|
|
143
|
+
// Every file vanished: no version.
|
|
144
|
+
if (sent === 0) {
|
|
145
|
+
await abort(channel, runId, uploadId);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const done = await channel.request("artifact.write", { runId, op: "commit", uploadId }, signal);
|
|
149
|
+
if (done.status === "refused")
|
|
150
|
+
throw new Skip(done.reason, done.message, done.limit);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
await abort(channel, runId, uploadId);
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/** One file of the folder: whole in its `file` request when it fits one chunk, else in chunks. */
|
|
158
|
+
async function sendFile(channel, run, uploadId, path, bytes, signal) {
|
|
159
|
+
const runId = run.runId;
|
|
160
|
+
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
|
161
|
+
const chunkBytes = run.start.limits.chunkBytes;
|
|
162
|
+
const whole = bytes.byteLength <= chunkBytes;
|
|
163
|
+
await channel.request("artifact.write", {
|
|
164
|
+
runId,
|
|
165
|
+
op: "file",
|
|
166
|
+
uploadId,
|
|
167
|
+
path,
|
|
168
|
+
size: bytes.byteLength,
|
|
169
|
+
sha256,
|
|
170
|
+
contentType: contentTypeFor(posix.basename(path)),
|
|
171
|
+
...(whole && bytes.byteLength > 0 ? { base64: toBase64(bytes) } : {}),
|
|
172
|
+
}, signal);
|
|
173
|
+
if (whole)
|
|
174
|
+
return;
|
|
175
|
+
for (let offset = 0; offset < bytes.byteLength; offset += chunkBytes)
|
|
176
|
+
await channel.request("artifact.write", {
|
|
177
|
+
runId,
|
|
178
|
+
op: "chunk",
|
|
179
|
+
uploadId,
|
|
180
|
+
sha256,
|
|
181
|
+
offset,
|
|
182
|
+
base64: toBase64(bytes.subarray(offset, offset + chunkBytes)),
|
|
183
|
+
}, signal);
|
|
184
|
+
}
|
|
185
|
+
async function abort(channel, runId, uploadId) {
|
|
186
|
+
await channel.request("artifact.write", { runId, op: "abort", uploadId }).catch(() => undefined);
|
|
187
|
+
}
|
|
188
|
+
function tooLargeFile(dir, path, size, limit) {
|
|
189
|
+
return new Skip("file_too_large", `${dir}/${path} is ${size} bytes; a file may hold at most ${limit}`, limit, path);
|
|
190
|
+
}
|
|
191
|
+
function tooLarge(dir, bytes, limit) {
|
|
192
|
+
return new Skip("too_large", `${dir} holds ${bytes} bytes; a save stores at most ${limit}`, limit);
|
|
193
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { type ModelDescriptor, type RuntimeLimits } from "@nylorun/core/harness-api";
|
|
2
|
+
import type { HostEffect } from "../run/durable.js";
|
|
3
|
+
export { jsonBytes, utf8Boundary } from "./text-page.js";
|
|
4
|
+
/** The harness's configuration of how our engine shapes tool results. */
|
|
5
|
+
export interface ToolResultConfig {
|
|
6
|
+
/** The most of one MCP or HTTP tool result kept inline, as JSON. Default 32 KiB. */
|
|
7
|
+
readonly resultInlineBytes: number;
|
|
8
|
+
/** How much of a stored result's start the preview keeps. Default 4 KiB. */
|
|
9
|
+
readonly previewHeadBytes: number;
|
|
10
|
+
/** How much of a stored result's end the preview keeps. Default 1 KiB. */
|
|
11
|
+
readonly previewTailBytes: number;
|
|
12
|
+
/** The most one step's results hold together. Default 256 KiB. */
|
|
13
|
+
readonly stepBudgetBytes: number;
|
|
14
|
+
/** A result's cap once its step's budget is spent: a stub naming its artifact. Default 512. */
|
|
15
|
+
readonly stubBytes: number;
|
|
16
|
+
/** A result this small is never shaped. Default 1 KiB. */
|
|
17
|
+
readonly smallBytes: number;
|
|
18
|
+
/** The smallest preview a stub keeps when its step's budget is nearly spent; less is none. Default 64. */
|
|
19
|
+
readonly minPreviewBytes: number;
|
|
20
|
+
/**
|
|
21
|
+
* What a step's transcript entry holds beside its results (ids, calls, stubs), kept out of the
|
|
22
|
+
* step's budget under the record entry limit. Default 4 KiB.
|
|
23
|
+
*/
|
|
24
|
+
readonly entryEnvelopeBytes: number;
|
|
25
|
+
}
|
|
26
|
+
export declare const DEFAULT_TOOL_RESULT_CONFIG: ToolResultConfig;
|
|
27
|
+
/** `set` over the defaults. */
|
|
28
|
+
export declare function toolResultConfigOf(set?: Partial<ToolResultConfig>): ToolResultConfig;
|
|
29
|
+
/** A stored artifact, as a shaped part names it; or why it could not be stored. */
|
|
30
|
+
export type Stored = {
|
|
31
|
+
readonly artifactId: string;
|
|
32
|
+
readonly version: number;
|
|
33
|
+
readonly contentType: string;
|
|
34
|
+
readonly size: number;
|
|
35
|
+
} | {
|
|
36
|
+
readonly dropped: string;
|
|
37
|
+
readonly size: number;
|
|
38
|
+
};
|
|
39
|
+
/** What shaping one outcome needs. */
|
|
40
|
+
export interface ShapeContext {
|
|
41
|
+
readonly effect: HostEffect;
|
|
42
|
+
/** This result's cap (`StepBudget.reserve`). */
|
|
43
|
+
readonly limit: number;
|
|
44
|
+
/** The turn's model (`turn.start.model`): whether an image goes to it as a file. */
|
|
45
|
+
readonly model?: ModelDescriptor;
|
|
46
|
+
readonly limits: Pick<RuntimeLimits, "modelFileBytes">;
|
|
47
|
+
readonly config: ToolResultConfig;
|
|
48
|
+
/** Stores `bytes` as an artifact of the call's session (`artifact.write`), or says why not. */
|
|
49
|
+
store(bytes: Uint8Array, artifact: {
|
|
50
|
+
readonly name: string;
|
|
51
|
+
readonly contentType: string;
|
|
52
|
+
readonly index?: number;
|
|
53
|
+
}): Promise<Stored>;
|
|
54
|
+
}
|
|
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 declare function spillKey(effectId: string, index: number | "whole", bytes: Uint8Array): string;
|
|
61
|
+
/**
|
|
62
|
+
* What a tool outcome's result weighs in its step's transcript entry: a completed one's output,
|
|
63
|
+
* a failed one's message; 0 for anything else.
|
|
64
|
+
*/
|
|
65
|
+
export declare function resultBytes(value: unknown): number;
|
|
66
|
+
/**
|
|
67
|
+
* False for an outcome `shapeToolOutcome` returns as it is: a small tool result with no parts.
|
|
68
|
+
* Spares the shaping of most outcomes.
|
|
69
|
+
*/
|
|
70
|
+
export declare function mayNeedShaping(value: unknown, config: Pick<ToolResultConfig, "smallBytes">): boolean;
|
|
71
|
+
/**
|
|
72
|
+
* One run's tool results per model step (an agent's step: `[agent, stepId]`), which share one
|
|
73
|
+
* transcript entry. A result reserves its cap from what the step's other results took, and is
|
|
74
|
+
* counted once it is shaped; a replayed or recorded outcome is counted when it resolves. Shaping
|
|
75
|
+
* is serialized per step (`serialize`), so parallel calls never spend the same room.
|
|
76
|
+
*/
|
|
77
|
+
export declare class StepBudget {
|
|
78
|
+
private readonly config;
|
|
79
|
+
/** The step budget: `stepBudgetBytes`, held under the record entry limit. */
|
|
80
|
+
readonly budget: number;
|
|
81
|
+
/** The most an MCP or HTTP tool result keeps inline: `resultInlineBytes`, held to the budget. */
|
|
82
|
+
readonly inline: number;
|
|
83
|
+
private readonly used;
|
|
84
|
+
private readonly chains;
|
|
85
|
+
constructor(config: ToolResultConfig, limits: Pick<RuntimeLimits, "recordEntryBytes">);
|
|
86
|
+
/** Counts `value`, the outcome of `effect`, toward its step (once per effect). */
|
|
87
|
+
count(effect: HostEffect, value: unknown): void;
|
|
88
|
+
/**
|
|
89
|
+
* The cap of `effect`'s result: what its step's other results left of the budget, at most
|
|
90
|
+
* `inline` when `capped` (an MCP or HTTP tool), and never under a stub.
|
|
91
|
+
*/
|
|
92
|
+
reserve(effect: HostEffect, capped: boolean): number;
|
|
93
|
+
/** Runs `shape` after the shaping of `effect`'s step that came before it. */
|
|
94
|
+
serialize<T>(effect: HostEffect, shape: () => Promise<T>): Promise<T>;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The outcome `value` of `ctx.effect`, shaped to fit `ctx.limit` (see the module comment). An
|
|
98
|
+
* outcome that fits and has no binary part comes back as it is. MCP content parts are read only
|
|
99
|
+
* for an `mcp` call.
|
|
100
|
+
*/
|
|
101
|
+
export declare function shapeToolOutcome(value: unknown, ctx: ShapeContext): Promise<unknown>;
|
|
102
|
+
/**
|
|
103
|
+
* The start and end of `text` in whole characters, `budget` bytes split as `previewHeadBytes` is
|
|
104
|
+
* to `previewTailBytes`: by default the first 4 KiB and the last 1 KiB.
|
|
105
|
+
*/
|
|
106
|
+
export declare function previewOf(text: string, budget: number, config: Pick<ToolResultConfig, "previewHeadBytes" | "previewTailBytes">): string;
|
|
107
|
+
/** A message past `limit`: its start and end, and how long it was. */
|
|
108
|
+
export declare function cutMessage(message: string, limit: number, config: ToolResultConfig): string;
|
|
@@ -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[];
|