@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.
Files changed (65) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/HOST_CONTRACT.md +15 -13
  3. package/README.md +3 -1
  4. package/dist/api/executors.d.ts +79 -11
  5. package/dist/api/harness.d.ts +83 -2
  6. package/dist/api/harness.js +43 -4
  7. package/dist/api/host.d.ts +30 -2
  8. package/dist/api/host.js +156 -8
  9. package/dist/api/index.d.ts +20 -6
  10. package/dist/api/index.js +18 -4
  11. package/dist/api/run.d.ts +3 -0
  12. package/dist/api/run.js +81 -16
  13. package/dist/flow/context.d.ts +3 -0
  14. package/dist/flow/context.js +2 -1
  15. package/dist/flow/engine.d.ts +2 -0
  16. package/dist/flow/engine.js +10 -7
  17. package/dist/flow/limits.d.ts +8 -5
  18. package/dist/flow/limits.js +11 -7
  19. package/dist/index.d.ts +8 -0
  20. package/dist/index.js +8 -0
  21. package/dist/loop/compaction/config.d.ts +39 -0
  22. package/dist/loop/compaction/config.js +29 -0
  23. package/dist/loop/compaction/index.d.ts +18 -8
  24. package/dist/loop/compaction/index.js +57 -66
  25. package/dist/loop/config.d.ts +20 -0
  26. package/dist/loop/config.js +17 -0
  27. package/dist/loop/delegation.d.ts +3 -0
  28. package/dist/loop/delegation.js +14 -10
  29. package/dist/loop/invocation.d.ts +3 -0
  30. package/dist/loop/invocation.js +2 -0
  31. package/dist/loop/model/files.d.ts +77 -0
  32. package/dist/loop/model/files.js +168 -0
  33. package/dist/loop/model/json-answer.d.ts +26 -0
  34. package/dist/loop/model/json-answer.js +125 -0
  35. package/dist/loop/model/project.d.ts +14 -4
  36. package/dist/loop/model/project.js +69 -41
  37. package/dist/loop/options.js +2 -0
  38. package/dist/loop/run.js +8 -3
  39. package/dist/loop/state.js +4 -0
  40. package/dist/loop/step/run.js +19 -3
  41. package/dist/loop/step/runtime.d.ts +3 -0
  42. package/dist/run/durable.d.ts +51 -3
  43. package/dist/run/durable.js +71 -31
  44. package/dist/tools/artifacts.d.ts +33 -0
  45. package/dist/tools/artifacts.js +323 -0
  46. package/dist/tools/engine-tools.d.ts +42 -0
  47. package/dist/tools/engine-tools.js +26 -0
  48. package/dist/tools/mcp.d.ts +92 -0
  49. package/dist/tools/mcp.js +240 -0
  50. package/dist/tools/outputs.d.ts +23 -0
  51. package/dist/tools/outputs.js +193 -0
  52. package/dist/tools/results.d.ts +108 -0
  53. package/dist/tools/results.js +329 -0
  54. package/dist/tools/sandbox.d.ts +35 -0
  55. package/dist/tools/sandbox.js +129 -0
  56. package/dist/tools/skills.d.ts +94 -0
  57. package/dist/tools/skills.js +243 -0
  58. package/dist/tools/text-page.d.ts +20 -0
  59. package/dist/tools/text-page.js +64 -0
  60. package/dist/tools/tool-search.d.ts +56 -0
  61. package/dist/tools/tool-search.js +174 -0
  62. package/dist/tools/trace.d.ts +13 -0
  63. package/dist/tools/trace.js +34 -0
  64. package/dist/types/execution.d.ts +20 -0
  65. package/package.json +2 -2
@@ -0,0 +1,243 @@
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 { SKILL_ENTRY, SKILLS_MOUNT, skillFolderOf, skillInstructions, } from "@nylorun/core/define";
25
+ import { fromBase64 } from "@nylorun/core/harness-api";
26
+ /** Loads a skill's `SKILL.md`. */
27
+ export const LOAD_SKILL_TOOL = "load_skill";
28
+ /** Reads one resource file of a skill. */
29
+ export const READ_SKILL_RESOURCE_TOOL = "read_skill_resource";
30
+ /** The most bytes of one skill file the skill tools read into the model's context by default. */
31
+ export const DEFAULT_SKILL_READ_BYTES = 10 * 1024 * 1024;
32
+ /** True when `name` is one of our engine's skill tools. */
33
+ export function isSkillTool(name) {
34
+ return name === LOAD_SKILL_TOOL || name === READ_SKILL_RESOURCE_TOOL;
35
+ }
36
+ /** The text before the skill catalog: when to load a skill. */
37
+ export 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 function formatSkillCatalog(skills) {
40
+ const entries = skills
41
+ .map((skill) => ` <skill>\n <name>${escapeXml(skill.name)}</name>\n <description>${escapeXml(skill.description)}</description>\n </skill>`)
42
+ .join("\n");
43
+ return `<available_skills>\n${entries}\n</available_skills>`;
44
+ }
45
+ function escapeXml(value) {
46
+ return value
47
+ .replaceAll("&", "&amp;")
48
+ .replaceAll("<", "&lt;")
49
+ .replaceAll(">", "&gt;")
50
+ .replaceAll('"', "&quot;");
51
+ }
52
+ /** What the model reads of an agent's skills: when to load one, and the catalog. */
53
+ export function skillCatalogText(skills) {
54
+ return [
55
+ SKILLS_USAGE,
56
+ formatSkillCatalog(skills.map(({ name, description }) => ({ name, description }))),
57
+ ];
58
+ }
59
+ /** Where each skill's files are in the sandbox, for an agent with skills and a sandbox. */
60
+ export function skillFolderNote(skills) {
61
+ return `Each skill's files are in the sandbox, read-only, in its own folder under ${SKILLS_MOUNT}/ (${skills
62
+ .map((skill) => `${skill.name}: ${skillFolderOf(skill)}/`)
63
+ .join(", ")}): read them there and run their scripts with bash.`;
64
+ }
65
+ const HARNESS = Object.freeze({ kind: "harness" });
66
+ const SCHEMA = "http://json-schema.org/draft-07/schema#";
67
+ /**
68
+ * `load_skill` for the agent's skills, and `read_skill_resource` when a skill has files besides
69
+ * `SKILL.md`. Empty for an agent without skills. Each runs here (`harness`).
70
+ */
71
+ export function skillTools(skills) {
72
+ if (skills.length === 0)
73
+ return [];
74
+ const names = skills.map((skill) => skill.name).sort();
75
+ const name = names.length === 1 ? { type: "string", const: names[0] } : { type: "string", enum: names };
76
+ const tools = [
77
+ {
78
+ name: LOAD_SKILL_TOOL,
79
+ description: "Load the full instructions for a named skill. Call this before following a skill.",
80
+ inputSchema: {
81
+ $schema: SCHEMA,
82
+ type: "object",
83
+ properties: { name },
84
+ required: ["name"],
85
+ additionalProperties: false,
86
+ },
87
+ target: HARNESS,
88
+ },
89
+ ];
90
+ if (skills.some((skill) => Object.keys(skill.files).some((path) => path !== SKILL_ENTRY)))
91
+ tools.push({
92
+ name: READ_SKILL_RESOURCE_TOOL,
93
+ description: "Read one text resource from a skill after load_skill.",
94
+ inputSchema: {
95
+ $schema: SCHEMA,
96
+ type: "object",
97
+ properties: { name, path: { type: "string", minLength: 1 } },
98
+ required: ["name", "path"],
99
+ additionalProperties: false,
100
+ },
101
+ target: HARNESS,
102
+ });
103
+ return tools;
104
+ }
105
+ const failed = (code, message) => ({
106
+ kind: "failed",
107
+ code,
108
+ message,
109
+ });
110
+ /** UTF-8 text, or undefined for bytes that are not (a NUL byte, or invalid UTF-8). */
111
+ function textOf(bytes) {
112
+ if (bytes.includes(0))
113
+ return undefined;
114
+ try {
115
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
116
+ }
117
+ catch {
118
+ return undefined;
119
+ }
120
+ }
121
+ /** The bytes of definition file `sha256`, or undefined once it passes `maxBytes`. */
122
+ async function readDefinitionFile(context, sha256, maxBytes) {
123
+ const { channel, run, signal } = context;
124
+ // No range asks for more than one byte past what the file may hold.
125
+ const length = Math.min(run.start.limits.chunkBytes, maxBytes + 1);
126
+ const chunks = [];
127
+ let total = 0;
128
+ for (let offset = 0;; offset += length) {
129
+ const { base64 } = await channel.request("definition.file", { runId: run.runId, sha256, offset, length }, signal);
130
+ const chunk = fromBase64(base64);
131
+ total += chunk.byteLength;
132
+ if (total > maxBytes)
133
+ return undefined;
134
+ if (chunk.byteLength > 0)
135
+ chunks.push(chunk);
136
+ if (chunk.byteLength < length)
137
+ break;
138
+ }
139
+ const bytes = new Uint8Array(total);
140
+ let at = 0;
141
+ for (const chunk of chunks) {
142
+ bytes.set(chunk, at);
143
+ at += chunk.byteLength;
144
+ }
145
+ return bytes;
146
+ }
147
+ /** The size of `value` as JSON, in UTF-8 bytes. */
148
+ const jsonBytes = (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength;
149
+ /** Runs a call of one of our engine's skill tools, as its outcome. */
150
+ export async function runSkillTool(effect, context) {
151
+ const input = (effect.input ?? {});
152
+ const skills = new Map(Object.values(context.agent.skills ?? {}).map((skill) => [skill.name, skill]));
153
+ const name = typeof input.name === "string" ? input.name : "";
154
+ const skill = skills.get(name);
155
+ if (!skill)
156
+ return effect.toolName === LOAD_SKILL_TOOL
157
+ ? { kind: "completed", output: { unknown: name, available: [...skills.keys()].sort() } }
158
+ : failed("skill.unknown", `There is no skill '${name}'.`);
159
+ const { sandboxed } = context;
160
+ const recordBytes = context.run.start.limits.recordEntryBytes;
161
+ const maxBytes = Math.min(context.readBytes, recordBytes);
162
+ const directory = `${skillFolderOf(skill)}/`;
163
+ const tooLarge = (path) => failed("skill.resource_too_large", sandboxed
164
+ ? `${path} is larger than ${maxBytes} bytes, too large to read here. It is in the sandbox at ${directory}${path}; use it there.`
165
+ : `${path} is larger than ${maxBytes} bytes; only smaller files can be read without a sandbox.`);
166
+ /** The answer, unless it is larger than one record entry holds. */
167
+ const answer = (path, output) => {
168
+ const outcome = { kind: "completed", output };
169
+ return jsonBytes(outcome) > recordBytes ? tooLarge(path) : outcome;
170
+ };
171
+ if (effect.toolName === LOAD_SKILL_TOOL) {
172
+ const entry = await readDefinitionFile(context, skill.files[SKILL_ENTRY], maxBytes);
173
+ if (!entry)
174
+ return tooLarge(SKILL_ENTRY);
175
+ const text = textOf(entry);
176
+ if (text === undefined)
177
+ return failed("skill.binary_resource", `${SKILL_ENTRY} of '${skill.name}' is not text.`);
178
+ const resources = Object.keys(skill.files)
179
+ .filter((path) => path !== SKILL_ENTRY)
180
+ .sort();
181
+ return answer(SKILL_ENTRY, {
182
+ name: skill.name,
183
+ content: skillInstructions(text),
184
+ ...(resources.length === 0 ? {} : { resources }),
185
+ ...(sandboxed ? { sandboxPath: directory } : {}),
186
+ });
187
+ }
188
+ const path = typeof input.path === "string" ? input.path : "";
189
+ if (skill.files[path] === undefined)
190
+ return failed("skill.unknown_resource", `Skill '${skill.name}' has no resource '${path}'.`);
191
+ const bytes = await readDefinitionFile(context, skill.files[path], maxBytes);
192
+ if (!bytes)
193
+ return tooLarge(path);
194
+ const content = textOf(bytes);
195
+ if (content === undefined)
196
+ return failed("skill.binary_resource", sandboxed
197
+ ? `${path} is not a text file. It is in the sandbox at ${directory}${path}; use it there.`
198
+ : `${path} is not a text file; only text files can be read without a sandbox.`);
199
+ return answer(path, { name: skill.name, path, content });
200
+ }
201
+ /**
202
+ * The skill versions of `manifest` and of the agents it uses as tools (they share its sandbox),
203
+ * by folder (`/skills/<name>@<hash>`): each distinct version once.
204
+ */
205
+ export function sandboxSkillsOf(manifest, into = new Map()) {
206
+ for (const skill of Object.values(manifest?.skills ?? {})) {
207
+ const folder = skillFolderOf(skill);
208
+ if (!into.has(folder))
209
+ into.set(folder, skill.files);
210
+ }
211
+ for (const tool of manifest?.tools ?? [])
212
+ if (tool.agent !== undefined && !("kind" in tool.agent))
213
+ sandboxSkillsOf(tool.agent, into);
214
+ return into;
215
+ }
216
+ /**
217
+ * A definition file's bytes over `definition.file`, a range of at most the run's
218
+ * `limits.chunkBytes` at a time, as they come: a file may be larger than one frame holds.
219
+ */
220
+ export async function* definitionFileChunks(channel, run, sha256, signal) {
221
+ const length = run.start.limits.chunkBytes;
222
+ for (let offset = 0;; offset += length) {
223
+ const { base64 } = await channel.request("definition.file", { runId: run.runId, sha256, offset, length }, signal);
224
+ const chunk = fromBase64(base64);
225
+ if (chunk.byteLength > 0)
226
+ yield chunk;
227
+ if (chunk.byteLength < length)
228
+ return;
229
+ }
230
+ }
231
+ /**
232
+ * Mounts the skill folders of the run's tree in its sandbox, before a `sandbox` call: each one
233
+ * the sandbox does not hold yet is written, read-only. A failed outcome (the call's, then) when
234
+ * one cannot be; nothing when the tree has no skills.
235
+ */
236
+ export async function mountSkills(files, channel, run, signal) {
237
+ for (const [folder, skill] of sandboxSkillsOf(run.start.manifest)) {
238
+ const mounted = await files.mount(run, folder, skill, (sha256) => definitionFileChunks(channel, run, sha256, signal), signal);
239
+ if (mounted.kind === "failed")
240
+ return mounted;
241
+ }
242
+ return undefined;
243
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Pages of UTF-8 text for `read_artifact`: a page is whole characters, and at most a set number
3
+ * of bytes once escaped as JSON, since the model reads it inside a JSON tool result.
4
+ */
5
+ /** The bytes of `value` as JSON. */
6
+ export declare function jsonBytes(value: unknown): number;
7
+ /**
8
+ * The nearest position at or around `at` that is not inside a UTF-8 character: moving `down`
9
+ * (towards the start) or `up` (towards the end).
10
+ */
11
+ export declare function utf8Boundary(bytes: Uint8Array, at: number, direction: "down" | "up"): number;
12
+ /**
13
+ * The text of a page of UTF-8 `bytes` in whole characters, at most `maxBytes` once escaped as
14
+ * JSON, and how many bytes it used: the next page starts there. A page that starts inside a
15
+ * character skips its rest, and one that ends inside one (not `last`) stops before it.
16
+ */
17
+ export declare function textPage(bytes: Uint8Array, last: boolean, maxBytes: number): {
18
+ text: string;
19
+ bytes: number;
20
+ };
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Pages of UTF-8 text for `read_artifact`: a page is whole characters, and at most a set number
3
+ * of bytes once escaped as JSON, since the model reads it inside a JSON tool result.
4
+ */
5
+ const encoder = new TextEncoder();
6
+ const decoder = new TextDecoder();
7
+ /** The bytes of `value` as JSON. */
8
+ export function jsonBytes(value) {
9
+ return encoder.encode(JSON.stringify(value) ?? "null").byteLength;
10
+ }
11
+ /**
12
+ * The nearest position at or around `at` that is not inside a UTF-8 character: moving `down`
13
+ * (towards the start) or `up` (towards the end).
14
+ */
15
+ export function utf8Boundary(bytes, at, direction) {
16
+ let position = Math.max(0, Math.min(at, bytes.byteLength));
17
+ const inside = (index) => index < bytes.byteLength && (bytes[index] & 0xc0) === 0x80;
18
+ if (direction === "down")
19
+ while (position > 0 && inside(position))
20
+ position -= 1;
21
+ else
22
+ while (inside(position))
23
+ position += 1;
24
+ return position;
25
+ }
26
+ /** Where the last whole character of `bytes` ends: before a character its end cuts off. */
27
+ function wholeEnd(bytes) {
28
+ if (bytes.byteLength === 0)
29
+ return 0;
30
+ const lead = utf8Boundary(bytes, bytes.byteLength - 1, "down");
31
+ const first = bytes[lead];
32
+ const length = first < 0x80 ? 1 : first >= 0xf0 ? 4 : first >= 0xe0 ? 3 : first >= 0xc0 ? 2 : 1;
33
+ return lead + length > bytes.byteLength ? lead : bytes.byteLength;
34
+ }
35
+ /**
36
+ * The text of a page of UTF-8 `bytes` in whole characters, at most `maxBytes` once escaped as
37
+ * JSON, and how many bytes it used: the next page starts there. A page that starts inside a
38
+ * character skips its rest, and one that ends inside one (not `last`) stops before it.
39
+ */
40
+ export function textPage(bytes, last, maxBytes) {
41
+ const from = utf8Boundary(bytes, 0, "up");
42
+ let to = last ? bytes.byteLength : wholeEnd(bytes);
43
+ // A page shorter than one character: take what there is.
44
+ if (to <= from)
45
+ to = bytes.byteLength;
46
+ const decode = (end) => decoder.decode(bytes.subarray(from, end));
47
+ const text = decode(to);
48
+ if (jsonBytes(text) <= maxBytes)
49
+ return { text, bytes: to };
50
+ // Escaped (quotes, newlines, control characters), text takes more room than its bytes: the page
51
+ // ends at the last character boundary whose text still fits, found by halving.
52
+ const fits = (end) => jsonBytes(decode(end)) <= maxBytes;
53
+ let low = from;
54
+ let high = to;
55
+ while (high - low > 1) {
56
+ const middle = Math.floor((low + high) / 2);
57
+ if (fits(utf8Boundary(bytes, middle, "down")))
58
+ low = middle;
59
+ else
60
+ high = middle;
61
+ }
62
+ const end = Math.max(from, utf8Boundary(bytes, low, "down"));
63
+ return { text: decode(end), bytes: end };
64
+ }
@@ -0,0 +1,56 @@
1
+ import type { DurableSessionTool, HostEffect } from "../run/durable.js";
2
+ import type { McpToolConfig } from "./mcp.js";
3
+ /** Finds deferred tools by a query (BM25 over their names and descriptions). */
4
+ export declare const TOOL_SEARCH_TOOL = "tool_search";
5
+ /** Runs a deferred tool by name, as a call of that tool. */
6
+ export declare const TOOL_CALL_TOOL = "tool_call";
7
+ /** A server some of whose tools are deferred, as the model's note names it. */
8
+ export interface DeferredServerNote {
9
+ readonly serverName: string;
10
+ /** How many of its tools are deferred. */
11
+ readonly tools: number;
12
+ /** The server's own instructions (MCP `initialize`), if it gave any. */
13
+ readonly instructions?: string;
14
+ }
15
+ /**
16
+ * `tool_search` (ours, `harness`) and `tool_call`, as our engine gives them to an agent with
17
+ * deferred tools. Their schemas reach the model; change them deliberately.
18
+ */
19
+ export declare function deferredToolsTools(config: Pick<McpToolConfig, "toolSearchDefaultLimit" | "toolSearchMaxLimit">): readonly DurableSessionTool[];
20
+ /**
21
+ * The note the model reads beside `tool_search`: each server with deferred tools, how many, and
22
+ * its own instructions cut to `config.serverInstructionsMaxChars`.
23
+ */
24
+ export declare function deferredToolsNote(servers: readonly DeferredServerNote[], config: Pick<McpToolConfig, "serverInstructionsMaxChars">): string;
25
+ /** True when `effect` calls our engine's `tool_search`. */
26
+ export declare function isToolSearch(effect: Pick<HostEffect, "toolName" | "target">): boolean;
27
+ /** Runs `tool_search` over `deferred`, the deferred tools of the call's agent. */
28
+ export declare function runToolSearch(effect: Pick<HostEffect, "input">, deferred: readonly DurableSessionTool[], config: Pick<McpToolConfig, "toolSearchDefaultLimit" | "toolSearchMaxLimit">): {
29
+ kind: string;
30
+ code: string;
31
+ message: string;
32
+ output?: undefined;
33
+ } | {
34
+ code?: undefined;
35
+ message?: undefined;
36
+ kind: string;
37
+ output: {
38
+ tools: {
39
+ name: string;
40
+ description?: string | undefined;
41
+ inputSchema: import("@nylorun/core/define").JsonObject;
42
+ }[];
43
+ message?: string | undefined;
44
+ };
45
+ };
46
+ /**
47
+ * Lower-case words of `text`: `camelCase`, `snake_case` and `kebab-case` split into words, and a
48
+ * plural `s` dropped (`issues` finds `issue`).
49
+ */
50
+ export declare function tokens(text: string): string[];
51
+ /**
52
+ * The tools that match `query`, best first, by BM25 over each tool's name (counted twice, with
53
+ * the server's own name for it) and description. A tool no word of the query is in is left out;
54
+ * ties keep the given order.
55
+ */
56
+ export declare function rank(tools: readonly DurableSessionTool[], query: string): DurableSessionTool[];
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Deferred MCP tools (R2b C10, Q20), run by our engine: `tool_search` finds an agent's deferred
3
+ * tools, ranked with BM25 over their names and descriptions, and returns each match's name,
4
+ * description and `inputSchema`; `tool_call` runs one by name, as that tool's own call
5
+ * (`deferredToolCall` in `run/durable.ts`). `tool_search` is our engine's tool (`harness`): it
6
+ * reads only the run's MCP tools (`McpToolSet`), so the same query finds the same tools while the
7
+ * session's layout stands; a tool the turn disables is never there.
8
+ */
9
+ import { z } from "zod";
10
+ import { normalizedSchemasFor, tool, ToolError } from "@nylorun/core/define";
11
+ /** Finds deferred tools by a query (BM25 over their names and descriptions). */
12
+ export const TOOL_SEARCH_TOOL = "tool_search";
13
+ /** Runs a deferred tool by name, as a call of that tool. */
14
+ export const TOOL_CALL_TOOL = "tool_call";
15
+ /** BM25's term saturation and length normalization, the usual values. */
16
+ const K1 = 1.2;
17
+ const B = 0.75;
18
+ const HARNESS = Object.freeze({ kind: "harness" });
19
+ async function runsInHarness() {
20
+ throw new ToolError("tools.runtime-only", "tool_search and tool_call run in Nylorun's harness. Connect the agent to a Runtime to use them.");
21
+ }
22
+ /**
23
+ * `tool_search` (ours, `harness`) and `tool_call`, as our engine gives them to an agent with
24
+ * deferred tools. Their schemas reach the model; change them deliberately.
25
+ */
26
+ export function deferredToolsTools(config) {
27
+ return [searchTool(config), callTool()].map((item, index) => {
28
+ const schemas = normalizedSchemasFor(item);
29
+ const manifest = {
30
+ name: item.name,
31
+ ...(item.description === undefined ? {} : { description: item.description }),
32
+ inputSchema: schemas.inputSchema.jsonSchema,
33
+ };
34
+ // `tool_call` makes the effect of the tool it names; it is never one itself.
35
+ return index === 0 ? { ...manifest, target: HARNESS } : manifest;
36
+ });
37
+ }
38
+ /**
39
+ * The note the model reads beside `tool_search`: each server with deferred tools, how many, and
40
+ * its own instructions cut to `config.serverInstructionsMaxChars`.
41
+ */
42
+ export function deferredToolsNote(servers, config) {
43
+ const max = config.serverInstructionsMaxChars;
44
+ const lines = servers.map((server) => {
45
+ const head = `- ${server.serverName}: ${server.tools} tool${server.tools === 1 ? "" : "s"}`;
46
+ const text = server.instructions?.trim();
47
+ if (!text)
48
+ return head;
49
+ const cut = text.length > max ? `${text.slice(0, max)}…` : text;
50
+ return `${head}. The server says: ${cut}`;
51
+ });
52
+ return [
53
+ "Some tools of these MCP servers are not in your tool list. Find them with tool_search (a few words of what you need), then run one with tool_call, passing its name and arguments that match its inputSchema.",
54
+ ...lines,
55
+ ].join("\n");
56
+ }
57
+ function searchTool(config) {
58
+ return tool({
59
+ name: TOOL_SEARCH_TOOL,
60
+ description: "Search the tools not in your tool list by name and description. Returns the best matches, each with its name, description and inputSchema. Run one with tool_call.",
61
+ inputSchema: z.object({
62
+ query: z.string().min(1).describe("Words of what the tool does, or of its name."),
63
+ limit: z
64
+ .number()
65
+ .int()
66
+ .min(1)
67
+ .max(config.toolSearchMaxLimit)
68
+ .optional()
69
+ .describe(`How many tools to return. Default ${config.toolSearchDefaultLimit}.`),
70
+ }),
71
+ effects: "read",
72
+ execute: runsInHarness,
73
+ });
74
+ }
75
+ function callTool() {
76
+ return tool({
77
+ name: TOOL_CALL_TOOL,
78
+ description: "Run a tool tool_search found, by its name. arguments must match that tool's inputSchema; the result is the tool's own.",
79
+ inputSchema: z.object({
80
+ name: z.string().min(1).describe("The tool's name, as tool_search returned it."),
81
+ arguments: z
82
+ .record(z.string(), z.unknown())
83
+ .optional()
84
+ .describe("The tool's arguments, matching its inputSchema. Default {}."),
85
+ }),
86
+ effects: "write",
87
+ execute: runsInHarness,
88
+ });
89
+ }
90
+ /** True when `effect` calls our engine's `tool_search`. */
91
+ export function isToolSearch(effect) {
92
+ return effect.target?.kind === "harness" && effect.toolName === TOOL_SEARCH_TOOL;
93
+ }
94
+ /** Runs `tool_search` over `deferred`, the deferred tools of the call's agent. */
95
+ export function runToolSearch(effect, deferred, config) {
96
+ const input = (effect.input ?? {});
97
+ const query = typeof input.query === "string" ? input.query : "";
98
+ const limit = typeof input.limit === "number" && Number.isSafeInteger(input.limit)
99
+ ? Math.min(Math.max(input.limit, 1), config.toolSearchMaxLimit)
100
+ : config.toolSearchDefaultLimit;
101
+ if (query.trim() === "")
102
+ return {
103
+ kind: "failed",
104
+ code: "tools.invalid_input",
105
+ message: "Give a query: words of what the tool does.",
106
+ };
107
+ const found = rank(deferred, query).slice(0, limit);
108
+ return {
109
+ kind: "completed",
110
+ output: {
111
+ tools: found.map((tool) => ({
112
+ name: tool.name,
113
+ ...(tool.description === undefined ? {} : { description: tool.description }),
114
+ inputSchema: tool.inputSchema,
115
+ })),
116
+ ...(found.length === 0
117
+ ? {
118
+ message: `No tool matches '${query}'. Try other words; ${deferred.length} tools are searchable.`,
119
+ }
120
+ : {}),
121
+ },
122
+ };
123
+ }
124
+ /**
125
+ * Lower-case words of `text`: `camelCase`, `snake_case` and `kebab-case` split into words, and a
126
+ * plural `s` dropped (`issues` finds `issue`).
127
+ */
128
+ export function tokens(text) {
129
+ return text
130
+ .replace(/([a-z0-9])([A-Z])/gu, "$1 $2")
131
+ .toLowerCase()
132
+ .split(/[^\p{L}\p{N}]+/u)
133
+ .filter((word) => word.length > 0)
134
+ .map((word) => word.length > 3 && word.endsWith("s") && !word.endsWith("ss") ? word.slice(0, -1) : word);
135
+ }
136
+ /**
137
+ * The tools that match `query`, best first, by BM25 over each tool's name (counted twice, with
138
+ * the server's own name for it) and description. A tool no word of the query is in is left out;
139
+ * ties keep the given order.
140
+ */
141
+ export function rank(tools, query) {
142
+ const words = [...new Set(tokens(query))];
143
+ if (words.length === 0 || tools.length === 0)
144
+ return [];
145
+ const docs = tools.map((tool) => {
146
+ const own = tool.target?.kind === "mcp" ? tool.target.tool : "";
147
+ const name = [...tokens(tool.name), ...tokens(own)];
148
+ const terms = [...name, ...name, ...tokens(tool.description ?? "")];
149
+ const counts = new Map();
150
+ for (const term of terms)
151
+ counts.set(term, (counts.get(term) ?? 0) + 1);
152
+ return { tool, counts, length: terms.length };
153
+ });
154
+ const average = docs.reduce((sum, doc) => sum + doc.length, 0) / docs.length || 1;
155
+ const idf = new Map(words.map((word) => {
156
+ const df = docs.filter((doc) => doc.counts.has(word)).length;
157
+ return [word, Math.log(1 + (docs.length - df + 0.5) / (df + 0.5))];
158
+ }));
159
+ return docs
160
+ .map((doc, order) => {
161
+ let score = 0;
162
+ for (const word of words) {
163
+ const tf = doc.counts.get(word) ?? 0;
164
+ if (tf === 0)
165
+ continue;
166
+ score +=
167
+ idf.get(word) * ((tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * doc.length) / average)));
168
+ }
169
+ return { tool: doc.tool, score, order };
170
+ })
171
+ .filter((item) => item.score > 0)
172
+ .sort((a, b) => b.score - a.score || a.order - b.order)
173
+ .map((item) => item.tool);
174
+ }
@@ -0,0 +1,13 @@
1
+ import { type AgentManifest } from "@nylorun/core/define";
2
+ import type { EffectTarget } from "@nylorun/core/harness-api";
3
+ /**
4
+ * The skill of `manifest` a call of our engine's tool ran, which the effect names (`skill`):
5
+ * `load_skill` and `read_skill_resource` name it in their input. A sandbox call (`bash`, `read`,
6
+ * `grep`, `glob`, …) is matched on the skills' folder, `/skills/<name>@<hash>/` (or
7
+ * `/skills/<name>/`), in its input's text: exact for a path argument, and for `bash` only when the
8
+ * command names the folder. The first skill of the agent the input names wins.
9
+ */
10
+ export declare function skillOfToolCall(manifest: Pick<AgentManifest, "skills"> | undefined, tool: {
11
+ readonly name: string;
12
+ readonly target?: EffectTarget;
13
+ }, input: unknown): string | undefined;
@@ -0,0 +1,34 @@
1
+ import { SKILLS_MOUNT } from "@nylorun/core/define";
2
+ import { isSkillTool } from "./skills.js";
3
+ const MOUNT = new RegExp(`${SKILLS_MOUNT}/([^/@\\s"'\`]+)(?:@[0-9a-f]{12})?/`, "g");
4
+ /**
5
+ * The skill of `manifest` a call of our engine's tool ran, which the effect names (`skill`):
6
+ * `load_skill` and `read_skill_resource` name it in their input. A sandbox call (`bash`, `read`,
7
+ * `grep`, `glob`, …) is matched on the skills' folder, `/skills/<name>@<hash>/` (or
8
+ * `/skills/<name>/`), in its input's text: exact for a path argument, and for `bash` only when the
9
+ * command names the folder. The first skill of the agent the input names wins.
10
+ */
11
+ export function skillOfToolCall(manifest, tool, input) {
12
+ const skills = manifest?.skills;
13
+ if (!skills)
14
+ return undefined;
15
+ if (tool.target?.kind === "harness" && isSkillTool(tool.name)) {
16
+ const name = input?.name;
17
+ return typeof name === "string" && skills[name] !== undefined ? name : undefined;
18
+ }
19
+ if (tool.target?.kind !== "sandbox")
20
+ return undefined;
21
+ for (const text of strings(input))
22
+ for (const match of text.matchAll(MOUNT))
23
+ if (skills[match[1]] !== undefined)
24
+ return match[1];
25
+ return undefined;
26
+ }
27
+ /** The string values of a tool's input, one level deep: its path, pattern or command. */
28
+ function strings(input) {
29
+ if (typeof input === "string")
30
+ return [input];
31
+ if (!input || typeof input !== "object")
32
+ return [];
33
+ return Object.values(input).filter((value) => typeof value === "string");
34
+ }
@@ -1,4 +1,6 @@
1
1
  import type { ModelAdapter } from "@nylorun/core/define";
2
+ import type { ModelDescriptor } from "@nylorun/core/harness-api";
3
+ import type { FileContext } from "../loop/model/files.js";
2
4
  import type { InputEvent, MessageInput, TranscriptEntry } from "@nylorun/core/define";
3
5
  import type { ObserveEvent } from "@nylorun/core/define";
4
6
  import type { JsonObject, JsonValue, Tripwire } from "@nylorun/core/define";
@@ -83,6 +85,14 @@ export interface ExecutionState {
83
85
  * Runtime persists this with the checkpoint.
84
86
  */
85
87
  readonly state?: JsonObject;
88
+ /**
89
+ * Which of the session's MCP tools our engine defers (R2b C10, `McpLayout`), decided once for
90
+ * the facts whose hash it names and kept while they stay the same.
91
+ */
92
+ readonly mcpLayout?: {
93
+ readonly factsHash: string;
94
+ readonly deferred: readonly string[];
95
+ };
86
96
  }
87
97
  export type ExecutionEvent = (ObserveEvent | {
88
98
  readonly type: "execution.completed" | "execution.paused" | "execution.cancelled" | "execution.failed" | "observation.failed";
@@ -102,6 +112,16 @@ export interface RunOptions<Info = unknown> {
102
112
  readonly signal?: AbortSignal;
103
113
  readonly onEvent?: (event: ExecutionEvent) => void | Promise<void>;
104
114
  readonly record?: (state: ExecutionState) => void | Promise<void>;
115
+ /**
116
+ * The model the calls use (`turn.start.model`, protocol 15): its window budgets the prompt
117
+ * before any answer reports one.
118
+ */
119
+ readonly model?: ModelDescriptor;
120
+ /**
121
+ * How the turn's files reach the model (`representFiles`): the model, the Runtime limits and
122
+ * the run's artifact reads. Without it every file goes as its media part.
123
+ */
124
+ readonly files?: FileContext;
105
125
  }
106
126
  export type RunResult<Output = string> = {
107
127
  readonly status: "completed";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nylorun/harness",
3
- "version": "0.27.0-beta",
3
+ "version": "0.28.0-beta",
4
4
  "description": "Nylorun's TypeScript agent execution engine. See github.com/nylorun/agents.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -77,7 +77,7 @@
77
77
  "zod": "^4.6.5"
78
78
  },
79
79
  "dependencies": {
80
- "@nylorun/core": "0.21.0-beta"
80
+ "@nylorun/core": "0.23.0-beta"
81
81
  },
82
82
  "peerDependencies": {
83
83
  "zod": "^4.6.5"