@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.
Files changed (75) hide show
  1. package/CHANGELOG.md +131 -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 +21 -6
  10. package/dist/api/index.js +19 -4
  11. package/dist/api/run.d.ts +3 -0
  12. package/dist/api/run.js +91 -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 +9 -0
  20. package/dist/index.js +9 -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 +70 -41
  37. package/dist/loop/options.js +11 -3
  38. package/dist/loop/run.js +15 -5
  39. package/dist/loop/state.d.ts +6 -1
  40. package/dist/loop/state.js +19 -0
  41. package/dist/loop/step/canonicalize.d.ts +11 -2
  42. package/dist/loop/step/canonicalize.js +21 -5
  43. package/dist/loop/step/resolve.js +1 -0
  44. package/dist/loop/step/run.js +20 -3
  45. package/dist/loop/step/runtime.d.ts +6 -0
  46. package/dist/loop/step/seal.js +8 -2
  47. package/dist/loop/step/step-context.js +1 -1
  48. package/dist/run/durable.d.ts +58 -3
  49. package/dist/run/durable.js +104 -33
  50. package/dist/tools/artifacts.d.ts +33 -0
  51. package/dist/tools/artifacts.js +323 -0
  52. package/dist/tools/engine-tools.d.ts +50 -0
  53. package/dist/tools/engine-tools.js +42 -0
  54. package/dist/tools/mcp.d.ts +92 -0
  55. package/dist/tools/mcp.js +240 -0
  56. package/dist/tools/memory.d.ts +16 -0
  57. package/dist/tools/memory.js +140 -0
  58. package/dist/tools/outputs.d.ts +23 -0
  59. package/dist/tools/outputs.js +193 -0
  60. package/dist/tools/results.d.ts +108 -0
  61. package/dist/tools/results.js +329 -0
  62. package/dist/tools/sandbox.d.ts +35 -0
  63. package/dist/tools/sandbox.js +129 -0
  64. package/dist/tools/skills.d.ts +94 -0
  65. package/dist/tools/skills.js +243 -0
  66. package/dist/tools/text-page.d.ts +20 -0
  67. package/dist/tools/text-page.js +64 -0
  68. package/dist/tools/tool-search.d.ts +56 -0
  69. package/dist/tools/tool-search.js +174 -0
  70. package/dist/tools/trace.d.ts +13 -0
  71. package/dist/tools/trace.js +34 -0
  72. package/dist/tools/wake.d.ts +13 -0
  73. package/dist/tools/wake.js +33 -0
  74. package/dist/types/execution.d.ts +35 -1
  75. package/package.json +7 -7
@@ -0,0 +1,129 @@
1
+ /** The sandbox tools' limits when the harness sets none. */
2
+ export const DEFAULT_SANDBOX_TOOL_LIMITS = Object.freeze({
3
+ outputChars: 30_000,
4
+ defaultTimeoutS: 120,
5
+ maxTimeoutS: 600,
6
+ readLines: 2000,
7
+ maxReadLines: 5000,
8
+ lineChars: 2000,
9
+ grepResults: 200,
10
+ maxGrepResults: 1000,
11
+ globResults: 500,
12
+ globScan: 20_000,
13
+ });
14
+ /** The limits in force: `set`, with the default for each it leaves out. */
15
+ export function sandboxToolLimitsOf(set) {
16
+ return Object.freeze({ ...DEFAULT_SANDBOX_TOOL_LIMITS, ...definedOf(set ?? {}) });
17
+ }
18
+ function definedOf(value) {
19
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
20
+ }
21
+ const SANDBOX = Object.freeze({ kind: "sandbox" });
22
+ const SCHEMA = "http://json-schema.org/draft-07/schema#";
23
+ /** The note on the sandbox the model reads with the sandbox tools. */
24
+ export function sandboxInstructions(workspace) {
25
+ return (`You have an isolated Linux sandbox with a persistent working directory at ${workspace}. ` +
26
+ "Use bash to run commands, read/write/edit to work with files, and grep/glob to search. " +
27
+ "Network egress is limited by policy; a failed download usually means the host is not allowed.");
28
+ }
29
+ const object = (properties, required) => ({
30
+ $schema: SCHEMA,
31
+ type: "object",
32
+ properties,
33
+ required: [...required],
34
+ additionalProperties: false,
35
+ });
36
+ const path = { type: "string", minLength: 1 };
37
+ /**
38
+ * The six sandbox tools, in the order the model reads them, with `workspace` named in their text
39
+ * and `limits` in their schemas. Each is a `sandbox` effect named by its operation.
40
+ */
41
+ export function sandboxTools(limits, workspace) {
42
+ const relative = `Relative paths resolve under ${workspace}.`;
43
+ const tools = [
44
+ {
45
+ name: "bash",
46
+ description: `Run a bash command in the sandbox. The working directory is ${workspace}. ` +
47
+ "Returns exitCode, stdout and stderr; a non-zero exit code is a normal result, not an error. " +
48
+ "Long output is truncated in the middle.",
49
+ inputSchema: object({
50
+ command: {
51
+ type: "string",
52
+ minLength: 1,
53
+ description: "The command line to run with bash.",
54
+ },
55
+ timeout: {
56
+ description: `Seconds before the command is killed. Default ${limits.defaultTimeoutS}, maximum ${limits.maxTimeoutS}.`,
57
+ type: "integer",
58
+ minimum: 1,
59
+ maximum: limits.maxTimeoutS,
60
+ },
61
+ }, ["command"]),
62
+ },
63
+ {
64
+ name: "read",
65
+ description: `Read a text file from the sandbox. ${relative} Returns numbered lines. ` +
66
+ "Use offset and limit to page through large files.",
67
+ inputSchema: object({
68
+ path,
69
+ offset: {
70
+ description: "First line to return, 1-based.",
71
+ type: "integer",
72
+ minimum: 1,
73
+ maximum: Number.MAX_SAFE_INTEGER,
74
+ },
75
+ limit: {
76
+ description: `Maximum number of lines. Default ${limits.readLines}.`,
77
+ type: "integer",
78
+ minimum: 1,
79
+ maximum: limits.maxReadLines,
80
+ },
81
+ }, ["path"]),
82
+ },
83
+ {
84
+ name: "write",
85
+ description: `Create or overwrite a text file in the sandbox. ${relative} Parent directories are created.`,
86
+ inputSchema: object({ path, content: { type: "string" } }, ["path", "content"]),
87
+ },
88
+ {
89
+ name: "edit",
90
+ description: `Replace text in a sandbox file. ${relative} old_string must match exactly and be unique ` +
91
+ "unless replace_all is true.",
92
+ inputSchema: object({
93
+ path,
94
+ old_string: { type: "string", minLength: 1 },
95
+ new_string: { type: "string" },
96
+ replace_all: { type: "boolean" },
97
+ }, ["path", "old_string", "new_string"]),
98
+ },
99
+ {
100
+ name: "grep",
101
+ description: `Search file contents in the sandbox with an extended regular expression. ${relative} ` +
102
+ "Returns matching lines as path:line:text.",
103
+ inputSchema: object({
104
+ pattern: { type: "string", minLength: 1 },
105
+ path: { description: `Directory or file to search. Default ${workspace}.`, ...path },
106
+ glob: {
107
+ description: 'Only search files whose name matches, e.g. "*.py".',
108
+ ...path,
109
+ },
110
+ ignore_case: { type: "boolean" },
111
+ max_results: {
112
+ description: `Default ${limits.grepResults}.`,
113
+ type: "integer",
114
+ minimum: 1,
115
+ maximum: limits.maxGrepResults,
116
+ },
117
+ }, ["pattern"]),
118
+ },
119
+ {
120
+ name: "glob",
121
+ description: `Find files in the sandbox by glob pattern, e.g. "**/*.csv". ${relative} Returns matching paths.`,
122
+ inputSchema: object({
123
+ pattern: { type: "string", minLength: 1 },
124
+ path: { description: `Directory to search. Default ${workspace}.`, ...path },
125
+ }, ["pattern"]),
126
+ },
127
+ ];
128
+ return tools.map((tool) => ({ ...tool, target: SANDBOX }));
129
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Our engine's skill tools (protocol 15), which run here, in the harness: `load_skill` for an
3
+ * agent with skills, and `read_skill_resource` when a skill has files besides `SKILL.md`. With
4
+ * them come the skill catalog the model reads (`skillCatalogText`) and, with a sandbox, the note
5
+ * on where each skill's files are (`skillFolderNote`).
6
+ *
7
+ * - `load_skill`: the skill's instructions (its `SKILL.md` after the frontmatter), the paths of
8
+ * its other files, and, when the session has a sandbox, where they are in it
9
+ * (`/skills/<name>@<hash>/`, read-only).
10
+ * - `read_skill_resource`: one text file of the skill. A binary file, or one larger than the
11
+ * harness reads into the model's context (`readBytes`, at most what one record entry holds), is
12
+ * refused: the model uses it in the sandbox, when there is one.
13
+ *
14
+ * A skill's bytes come over the Harness API's `definition.file` seam, a range of at most
15
+ * `turn.start.limits.chunkBytes` at a time. Expected problems are failed outcomes the model sees;
16
+ * only the run's own failures throw.
17
+ *
18
+ * With a sandbox, our engine also decides where and when the skills' files are in it (protocol
19
+ * 15): before each `sandbox` call it mounts each skill version of the turn's tree (the agent and
20
+ * the agents it uses as tools, which share its sandbox) at its folder (`skillFolderOf`) with
21
+ * `executors.files.mount` (`mountSkills`). The host only writes the files, and answers `present`
22
+ * for a folder the sandbox already holds since it last started.
23
+ */
24
+ import { type AgentManifest, type SkillManifest } from "@nylorun/core/define";
25
+ import { type HarnessChannel } from "@nylorun/core/harness-api";
26
+ import type { DurableSessionTool, HostEffect } from "../run/durable.js";
27
+ import type { FailedFileOutcome, HarnessFiles, HarnessRun } from "../api/executors.js";
28
+ /** Loads a skill's `SKILL.md`. */
29
+ export declare const LOAD_SKILL_TOOL = "load_skill";
30
+ /** Reads one resource file of a skill. */
31
+ export declare const READ_SKILL_RESOURCE_TOOL = "read_skill_resource";
32
+ /** The most bytes of one skill file the skill tools read into the model's context by default. */
33
+ export declare const DEFAULT_SKILL_READ_BYTES: number;
34
+ /** True when `name` is one of our engine's skill tools. */
35
+ export declare function isSkillTool(name: string | undefined): boolean;
36
+ /** The text before the skill catalog: when to load a skill. */
37
+ export declare const SKILLS_USAGE = "The following skills provide specialized instructions. When a task matches a skill description, call load_skill with that name before proceeding.";
38
+ /** The skills the model may load, by name and description. */
39
+ export declare function formatSkillCatalog(skills: readonly {
40
+ readonly name: string;
41
+ readonly description: string;
42
+ }[]): string;
43
+ /** What the model reads of an agent's skills: when to load one, and the catalog. */
44
+ export declare function skillCatalogText(skills: readonly {
45
+ readonly name: string;
46
+ readonly description: string;
47
+ }[]): string[];
48
+ /** Where each skill's files are in the sandbox, for an agent with skills and a sandbox. */
49
+ export declare function skillFolderNote(skills: readonly SkillManifest[]): string;
50
+ /**
51
+ * `load_skill` for the agent's skills, and `read_skill_resource` when a skill has files besides
52
+ * `SKILL.md`. Empty for an agent without skills. Each runs here (`harness`).
53
+ */
54
+ export declare function skillTools(skills: readonly SkillManifest[]): DurableSessionTool[];
55
+ /** What a skill tool runs with. */
56
+ export interface SkillToolContext {
57
+ readonly channel: Pick<HarnessChannel, "request">;
58
+ readonly run: HarnessRun;
59
+ /** The agent whose skill the call reads: the turn's agent, or the agent used as a tool. */
60
+ readonly agent: Pick<AgentManifest, "skills">;
61
+ /**
62
+ * The most bytes of one file read into the model's context: the harness's `skillReadBytes`.
63
+ * The answer is also held to the run's `limits.recordEntryBytes`, since it is one record entry.
64
+ */
65
+ readonly readBytes: number;
66
+ /** The session has a sandbox: the skill's files are in it. */
67
+ readonly sandboxed: boolean;
68
+ readonly signal: AbortSignal;
69
+ }
70
+ type Outcome = {
71
+ readonly kind: "completed";
72
+ readonly output: Record<string, unknown>;
73
+ } | FailedFileOutcome;
74
+ /** Runs a call of one of our engine's skill tools, as its outcome. */
75
+ export declare function runSkillTool(effect: HostEffect, context: SkillToolContext): Promise<Outcome>;
76
+ /** A skill's files, by path in its folder, as `sha256:<hex>`. */
77
+ export type SkillFiles = Readonly<Record<string, string>>;
78
+ /**
79
+ * The skill versions of `manifest` and of the agents it uses as tools (they share its sandbox),
80
+ * by folder (`/skills/<name>@<hash>`): each distinct version once.
81
+ */
82
+ export declare function sandboxSkillsOf(manifest: AgentManifest | undefined, into?: Map<string, Readonly<Record<string, string>>>): Map<string, SkillFiles>;
83
+ /**
84
+ * A definition file's bytes over `definition.file`, a range of at most the run's
85
+ * `limits.chunkBytes` at a time, as they come: a file may be larger than one frame holds.
86
+ */
87
+ export declare function definitionFileChunks(channel: Pick<HarnessChannel, "request">, run: HarnessRun, sha256: string, signal: AbortSignal): AsyncGenerator<Uint8Array>;
88
+ /**
89
+ * Mounts the skill folders of the run's tree in its sandbox, before a `sandbox` call: each one
90
+ * the sandbox does not hold yet is written, read-only. A failed outcome (the call's, then) when
91
+ * one cannot be; nothing when the tree has no skills.
92
+ */
93
+ export declare function mountSkills(files: HarnessFiles, channel: Pick<HarnessChannel, "request">, run: HarnessRun, signal: AbortSignal): Promise<FailedFileOutcome | undefined>;
94
+ export {};
@@ -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[];