@nylorun/harness 0.27.1-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 +100 -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,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session's MCP tools as our engine offers them (protocol 15). The Runtime states what the
|
|
3
|
+
* session's MCP servers listed (`turn.start.mcp`: raw names and schemas, and whether the turn
|
|
4
|
+
* leaves each tool `enabled`); our engine names each tool for the model, decides which to defer,
|
|
5
|
+
* and makes each call an effect of the tool's identity (`target: {kind: "mcp", server, tool}`).
|
|
6
|
+
*
|
|
7
|
+
* - **Names** (R2b C6): `server__tool`, each character outside `[A-Za-z0-9_-]` replaced by `_`,
|
|
8
|
+
* since MCP allows `.` and 128 characters and OpenAI, Bedrock and Gemini on Vertex do not. A
|
|
9
|
+
* name over `MODEL_TOOL_NAME_MAX` (64), or a renamed one that collides, keeps 55 characters and
|
|
10
|
+
* adds `_` and 8 hex characters of the SHA-256 of the raw `server/tool`. A name the agent's own
|
|
11
|
+
* tools or an earlier tool already took leaves the tool out.
|
|
12
|
+
* - **Deferral** (R2b C10): a tool the manifest defers, or, when the manifest says nothing, every
|
|
13
|
+
* tool of an agent whose listed MCP tools would pass a share of the model's context window
|
|
14
|
+
* (`McpToolConfig`), leaves the model's list; the model finds it with `tool_search` and runs it
|
|
15
|
+
* with `tool_call`.
|
|
16
|
+
* - **The layout is pinned** (`McpLayout`, in our engine's state): decided the first time the
|
|
17
|
+
* session's facts are seen and kept while they stay the same, so every model call of the
|
|
18
|
+
* session lists the same tools (a stable prompt prefix, no drift on a replayed model call when
|
|
19
|
+
* the Tenant's model changes).
|
|
20
|
+
*
|
|
21
|
+
* A tool the turn disables, or whose input schema our engine cannot use, is left out.
|
|
22
|
+
*/
|
|
23
|
+
import { createHash } from "node:crypto";
|
|
24
|
+
import { schemaFromJSON } from "@nylorun/core/define";
|
|
25
|
+
import { delegatesOf, MODEL_TOOL_NAME_MAX } from "@nylorun/core/define";
|
|
26
|
+
import { TOOL_CALL_TOOL, TOOL_SEARCH_TOOL, deferredToolsNote, deferredToolsTools, } from "./tool-search.js";
|
|
27
|
+
export { MODEL_TOOL_NAME_MAX };
|
|
28
|
+
/** The hex characters of the hash a shortened or colliding tool name ends with. */
|
|
29
|
+
const NAME_HASH_CHARS = 8;
|
|
30
|
+
export const DEFAULT_MCP_TOOL_CONFIG = Object.freeze({
|
|
31
|
+
deferShare: 0.1,
|
|
32
|
+
charsPerToken: 4,
|
|
33
|
+
fallbackContextWindow: 32_768,
|
|
34
|
+
serverInstructionsMaxChars: 2_000,
|
|
35
|
+
toolSearchDefaultLimit: 8,
|
|
36
|
+
toolSearchMaxLimit: 20,
|
|
37
|
+
});
|
|
38
|
+
/** `set` over the defaults. */
|
|
39
|
+
export function mcpToolConfigOf(set) {
|
|
40
|
+
return Object.freeze({ ...DEFAULT_MCP_TOOL_CONFIG, ...definedOf(set ?? {}) });
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The name the model knows an MCP tool by (R2b C6, Q13): `server__tool` with each character
|
|
44
|
+
* outside `[A-Za-z0-9_-]` replaced by `_`. A name over 64 characters, or one that collides
|
|
45
|
+
* (`suffixed`), keeps 55 and adds `_` and 8 hex characters of the SHA-256 of the raw
|
|
46
|
+
* `server/tool`.
|
|
47
|
+
*/
|
|
48
|
+
export function mcpToolName(server, tool, options = {}) {
|
|
49
|
+
const name = `${server}__${tool}`.replace(/[^A-Za-z0-9_-]/gu, "_");
|
|
50
|
+
if (name.length <= MODEL_TOOL_NAME_MAX && !options.suffixed)
|
|
51
|
+
return name;
|
|
52
|
+
// Part of the names pinned sessions' tools already have (protocol 15's naming), so a constant:
|
|
53
|
+
// 8 hex characters of the hash and the `_` before them.
|
|
54
|
+
const hash = createHash("sha256")
|
|
55
|
+
.update(`${server}/${tool}`)
|
|
56
|
+
.digest("hex")
|
|
57
|
+
.slice(0, NAME_HASH_CHARS);
|
|
58
|
+
return `${name.slice(0, MODEL_TOOL_NAME_MAX - NAME_HASH_CHARS - 1)}_${hash}`;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The model-facing names of a server's tools (`tools`, raw names, in the server's order), and
|
|
62
|
+
* those it renamed or left out. Names that need no change go first, so a renamed tool never takes
|
|
63
|
+
* the name of another of the server's tools; a renamed one that collides gets the hash suffix;
|
|
64
|
+
* a name `taken` holds (the agent's own tools, an earlier server's tools) leaves the tool out.
|
|
65
|
+
* Adds the names it gives to `taken`.
|
|
66
|
+
*/
|
|
67
|
+
export function mcpToolNames(server, tools, taken) {
|
|
68
|
+
const names = new Map();
|
|
69
|
+
const renamed = [];
|
|
70
|
+
const omitted = [];
|
|
71
|
+
for (const tool of tools) {
|
|
72
|
+
const name = mcpToolName(server, tool);
|
|
73
|
+
if (name !== `${server}__${tool}`)
|
|
74
|
+
continue;
|
|
75
|
+
if (taken.has(name))
|
|
76
|
+
omitted.push(name);
|
|
77
|
+
else {
|
|
78
|
+
taken.add(name);
|
|
79
|
+
names.set(tool, name);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
for (const tool of tools) {
|
|
83
|
+
let name = mcpToolName(server, tool);
|
|
84
|
+
if (name === `${server}__${tool}`)
|
|
85
|
+
continue;
|
|
86
|
+
if (taken.has(name))
|
|
87
|
+
name = mcpToolName(server, tool, { suffixed: true });
|
|
88
|
+
if (taken.has(name)) {
|
|
89
|
+
omitted.push(name);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
taken.add(name);
|
|
93
|
+
names.set(tool, name);
|
|
94
|
+
renamed.push({ serverToolName: tool, name });
|
|
95
|
+
}
|
|
96
|
+
return { names, renamed, omitted };
|
|
97
|
+
}
|
|
98
|
+
/** The key of an MCP tool's identity in a layout: its agent, server and own name. */
|
|
99
|
+
export function mcpToolKey(agentId, server, tool) {
|
|
100
|
+
return JSON.stringify([agentId ?? null, server, tool]);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The session's MCP tools from the turn's facts (`turn.start.mcp`) for the agent tree `manifest`.
|
|
104
|
+
* `layout` is the one our engine's state keeps: followed while its `factsHash` matches, else the
|
|
105
|
+
* deferral is decided again from the model's window (`model.contextWindow`, or
|
|
106
|
+
* `config.fallbackContextWindow`). `taken(agent)` names an agent's other tools (our engine's
|
|
107
|
+
* own), which an MCP tool's name may not take besides the agent's declared tools.
|
|
108
|
+
*/
|
|
109
|
+
export function mcpToolSet(facts, manifest, options) {
|
|
110
|
+
const { config } = options;
|
|
111
|
+
const factsHash = hashOf(facts ?? { servers: [] });
|
|
112
|
+
const agents = new Map([
|
|
113
|
+
[undefined, manifest],
|
|
114
|
+
...delegatesOf(manifest).map(({ manifest: child }) => [child.id, child]),
|
|
115
|
+
]);
|
|
116
|
+
const named = [];
|
|
117
|
+
const takenOf = new Map();
|
|
118
|
+
for (const server of facts?.servers ?? []) {
|
|
119
|
+
const agent = agents.get(server.agentId);
|
|
120
|
+
if (!agent)
|
|
121
|
+
continue;
|
|
122
|
+
let taken = takenOf.get(server.agentId);
|
|
123
|
+
if (!taken) {
|
|
124
|
+
taken = new Set([
|
|
125
|
+
...(agent.tools ?? []).map((tool) => tool.name),
|
|
126
|
+
...(options.taken?.(agent) ?? []),
|
|
127
|
+
TOOL_SEARCH_TOOL,
|
|
128
|
+
TOOL_CALL_TOOL,
|
|
129
|
+
]);
|
|
130
|
+
takenOf.set(server.agentId, taken);
|
|
131
|
+
}
|
|
132
|
+
const usable = server.tools.flatMap((tool) => {
|
|
133
|
+
if (!tool.enabled)
|
|
134
|
+
return [];
|
|
135
|
+
const inputSchema = usableSchema(tool.inputSchema);
|
|
136
|
+
return inputSchema ? [{ fact: tool, inputSchema }] : [];
|
|
137
|
+
});
|
|
138
|
+
const { names } = mcpToolNames(server.name, usable.map((item) => item.fact.name), taken);
|
|
139
|
+
for (const { fact, inputSchema } of usable) {
|
|
140
|
+
const name = names.get(fact.name);
|
|
141
|
+
if (name === undefined)
|
|
142
|
+
continue;
|
|
143
|
+
const outputSchema = fact.outputSchema ? usableSchema(fact.outputSchema) : undefined;
|
|
144
|
+
named.push({
|
|
145
|
+
agentId: server.agentId,
|
|
146
|
+
server: server.name,
|
|
147
|
+
key: mcpToolKey(server.agentId, server.name, fact.name),
|
|
148
|
+
setting: fact.deferred,
|
|
149
|
+
tool: {
|
|
150
|
+
...(server.agentId === undefined ? {} : { agentId: server.agentId }),
|
|
151
|
+
name,
|
|
152
|
+
...(fact.description === undefined || fact.description.length === 0
|
|
153
|
+
? {}
|
|
154
|
+
: { description: fact.description }),
|
|
155
|
+
inputSchema,
|
|
156
|
+
...(outputSchema === undefined ? {} : { outputSchema }),
|
|
157
|
+
target: { kind: "mcp", server: server.name, tool: fact.name },
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const layout = options.layout !== undefined && options.layout.factsHash === factsHash
|
|
163
|
+
? options.layout
|
|
164
|
+
: { factsHash, deferred: decideDeferral(named, options.model, config) };
|
|
165
|
+
const deferredKeys = new Set(layout.deferred);
|
|
166
|
+
const inline = [];
|
|
167
|
+
const deferred = new Map();
|
|
168
|
+
const notes = new Map();
|
|
169
|
+
for (const item of named) {
|
|
170
|
+
if (!deferredKeys.has(item.key)) {
|
|
171
|
+
inline.push(item.tool);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
deferred.set(item.agentId, [
|
|
175
|
+
...(deferred.get(item.agentId) ?? []),
|
|
176
|
+
{ ...item.tool, deferred: true },
|
|
177
|
+
]);
|
|
178
|
+
const servers = notes.get(item.agentId) ?? new Map();
|
|
179
|
+
servers.set(item.server, (servers.get(item.server) ?? 0) + 1);
|
|
180
|
+
notes.set(item.agentId, servers);
|
|
181
|
+
}
|
|
182
|
+
const session = [];
|
|
183
|
+
for (const [agentId, tools] of deferred) {
|
|
184
|
+
const servers = [...notes.get(agentId)].map(([serverName, count]) => {
|
|
185
|
+
const instructions = facts?.servers.find((item) => item.agentId === agentId && item.name === serverName)?.instructions;
|
|
186
|
+
return { serverName, tools: count, ...(instructions ? { instructions } : {}) };
|
|
187
|
+
});
|
|
188
|
+
const [search, call] = deferredToolsTools(config);
|
|
189
|
+
for (const tool of [{ ...search, instructions: [deferredToolsNote(servers, config)] }, call])
|
|
190
|
+
session.push({ ...(agentId === undefined ? {} : { agentId }), ...tool });
|
|
191
|
+
session.push(...tools);
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
tools: [...inline, ...session],
|
|
195
|
+
layout,
|
|
196
|
+
deferredOf: (agentId) => deferred.get(agentId) ?? [],
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* The identities of the tools to defer: a tool's own setting, else whether the JSON of its
|
|
201
|
+
* agent's MCP tools that would be listed (`name`, `description`, `inputSchema`) passes
|
|
202
|
+
* `deferShare` of the model's context window, at `charsPerToken` characters a token.
|
|
203
|
+
*/
|
|
204
|
+
function decideDeferral(named, model, config) {
|
|
205
|
+
const window = model?.contextWindow ?? config.fallbackContextWindow;
|
|
206
|
+
const limit = window * config.charsPerToken * config.deferShare;
|
|
207
|
+
const listed = new Map();
|
|
208
|
+
for (const item of named) {
|
|
209
|
+
if (item.setting === true)
|
|
210
|
+
continue;
|
|
211
|
+
const size = JSON.stringify({
|
|
212
|
+
name: item.tool.name,
|
|
213
|
+
description: item.tool.description ?? "",
|
|
214
|
+
inputSchema: item.tool.inputSchema,
|
|
215
|
+
}).length;
|
|
216
|
+
listed.set(item.agentId, (listed.get(item.agentId) ?? 0) + size);
|
|
217
|
+
}
|
|
218
|
+
return named
|
|
219
|
+
.filter((item) => item.setting ?? (listed.get(item.agentId) ?? 0) > limit)
|
|
220
|
+
.map((item) => item.key);
|
|
221
|
+
}
|
|
222
|
+
/** An input or output schema our engine can check calls against; undefined when it cannot. */
|
|
223
|
+
function usableSchema(value) {
|
|
224
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
225
|
+
return undefined;
|
|
226
|
+
const schema = JSON.parse(JSON.stringify(value));
|
|
227
|
+
try {
|
|
228
|
+
schemaFromJSON(schema);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
return schema;
|
|
234
|
+
}
|
|
235
|
+
function hashOf(value) {
|
|
236
|
+
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
237
|
+
}
|
|
238
|
+
function definedOf(value) {
|
|
239
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
|
|
240
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type HarnessChannel } from "@nylorun/core/harness-api";
|
|
2
|
+
import type { HarnessFiles, HarnessRun } from "../api/executors.js";
|
|
3
|
+
/** Where our engine finds a turn's outputs, and the most bytes one save stores. */
|
|
4
|
+
export interface OutputsConfig {
|
|
5
|
+
/** The directory saved, absolute in the sandbox. */
|
|
6
|
+
readonly dir: string;
|
|
7
|
+
/** The most bytes of files one save reads and sends (before the seam's dedupe). */
|
|
8
|
+
readonly maxBytes: number;
|
|
9
|
+
}
|
|
10
|
+
/** The outputs folder by default: `/workspace/outputs`, at most 1 GiB a turn. */
|
|
11
|
+
export declare const DEFAULT_OUTPUTS_CONFIG: OutputsConfig;
|
|
12
|
+
/** The outputs configuration: `set`, with the default for each field it leaves out. */
|
|
13
|
+
export declare function outputsConfigOf(set: Partial<OutputsConfig> | undefined): OutputsConfig;
|
|
14
|
+
/** What a save runs with. */
|
|
15
|
+
export interface OutputsContext {
|
|
16
|
+
readonly channel: Pick<HarnessChannel, "request">;
|
|
17
|
+
readonly run: HarnessRun;
|
|
18
|
+
readonly files: HarnessFiles;
|
|
19
|
+
readonly config: OutputsConfig;
|
|
20
|
+
readonly signal: AbortSignal;
|
|
21
|
+
}
|
|
22
|
+
/** Saves the run's outputs folder, claiming why when it stores nothing. Never throws. */
|
|
23
|
+
export declare function saveOutputs(context: OutputsContext): Promise<void>;
|
|
@@ -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;
|