@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.
Files changed (65) hide show
  1. package/CHANGELOG.md +100 -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
@@ -6,17 +6,55 @@
6
6
  * every `renewEveryMs`; renewing stops once the run is aborted.
7
7
  */
8
8
  import { DEFAULT_HARNESS, HARNESS_API_VERSION, } from "@nylorun/core/harness-api";
9
+ import { sandboxToolLimitsOf } from "../tools/sandbox.js";
10
+ import { DEFAULT_SKILL_READ_BYTES } from "../tools/skills.js";
11
+ import { mcpToolConfigOf } from "../tools/mcp.js";
12
+ import { toolResultConfigOf } from "../tools/results.js";
13
+ import { outputsConfigOf } from "../tools/outputs.js";
9
14
  import { ABORT_MESSAGES, RunAbort } from "./abort.js";
10
15
  import { runTurn } from "./run.js";
11
16
  import { TranscriptCache } from "./transcript-cache.js";
17
+ import { loopConfigOf } from "../loop/config.js";
18
+ import { DEFAULT_FLOW_VALUE_CHARS } from "../flow/limits.js";
19
+ /** The transcript cache's budget when the harness sets none, in MiB. */
20
+ export const DEFAULT_TRANSCRIPT_CACHE_MB = 256;
21
+ /** How soon a `lease` request that failed is sent again, by default. */
22
+ export const DEFAULT_LEASE_RETRY_MS = 100;
23
+ /**
24
+ * The waits before each resend of a tool call whose gate hop lost its answer (R5.3), by default;
25
+ * the last repeats.
26
+ */
27
+ export const DEFAULT_RESEND_DELAYS_MS = Object.freeze([1_000, 2_000, 4_000]);
28
+ /** The default of the harness's `artifactPageBytes` setting: one `read_artifact` page. */
29
+ export const DEFAULT_ARTIFACT_PAGE_BYTES = 32 * 1024;
12
30
  export function createHarness(options) {
13
31
  const { channel, executors } = options;
14
32
  const maxRuns = options.maxRuns ?? Infinity;
15
- const cache = new TranscriptCache((options.transcriptCacheMb ?? 256) * 1024 * 1024);
33
+ const cache = new TranscriptCache((options.transcriptCacheMb ?? DEFAULT_TRANSCRIPT_CACHE_MB) * 1024 * 1024);
34
+ const leaseRetryMs = options.leaseRetryMs ?? DEFAULT_LEASE_RETRY_MS;
35
+ const engine = {
36
+ artifactPageBytes: options.artifactPageBytes ?? DEFAULT_ARTIFACT_PAGE_BYTES,
37
+ sandboxTools: sandboxToolLimitsOf(options.sandboxTools),
38
+ skillReadBytes: options.skillReadBytes ?? DEFAULT_SKILL_READ_BYTES,
39
+ mcpTools: mcpToolConfigOf(options.mcpTools),
40
+ toolResults: toolResultConfigOf(options.toolResults),
41
+ outputs: outputsConfigOf(options.outputs),
42
+ loop: loopConfigOf({
43
+ ...(options.compaction ? { compaction: options.compaction } : {}),
44
+ ...(options.partialOutputChars === undefined
45
+ ? {}
46
+ : { partialOutputChars: options.partialOutputChars }),
47
+ }),
48
+ flowValueChars: options.flowValueChars ?? DEFAULT_FLOW_VALUE_CHARS,
49
+ resendDelaysMs: options.resendDelaysMs?.length
50
+ ? options.resendDelaysMs
51
+ : DEFAULT_RESEND_DELAYS_MS,
52
+ };
16
53
  const live = new Map();
17
54
  const finished = new Set();
18
55
  const leasing = new AbortController();
19
- let renewEveryMs = 10_000;
56
+ // Core says how often to renew in its answer to `hello`; no run is leased before it.
57
+ let renewEveryMs;
20
58
  let stopped = false;
21
59
  let waiting = false;
22
60
  const abort = (run, kind, message) => {
@@ -72,8 +110,9 @@ export function createHarness(options) {
72
110
  };
73
111
  live.set(run.runId, run);
74
112
  options.onGrant?.(grant);
113
+ options.onStart?.(grant, start);
75
114
  const stopRenewing = renew(run);
76
- const done = runTurn({ channel, executors, cache }, run)
115
+ const done = runTurn({ channel, executors, cache, engine }, run)
77
116
  .catch((error) => options.logger?.warn("harness run failed", {
78
117
  runId: run.runId,
79
118
  message: error instanceof Error ? error.message : String(error),
@@ -101,7 +140,7 @@ export function createHarness(options) {
101
140
  options.logger?.warn("harness lease failed", {
102
141
  message: error instanceof Error ? error.message : String(error),
103
142
  });
104
- setTimeout(lease, 100).unref?.();
143
+ setTimeout(lease, leaseRetryMs).unref?.();
105
144
  });
106
145
  };
107
146
  return {
@@ -2,7 +2,15 @@
2
2
  * The engine's `DurableHost` over the Harness API. An effect whose outcome came with the run
3
3
  * (same id, same request hash) resolves here; any other becomes an `effect.intent`. A model
4
4
  * intent carries no prompt: core stores its hash. When core answers `execute`, the harness runs
5
- * the call and reports its outcome.
5
+ * the call and reports its outcome: a `harness` tool (ours) here, over the Harness API's seams,
6
+ * and anything else through the executors. Before a `sandbox` call our engine mounts the skill
7
+ * folders of the turn's tree (`mountSkills`); the host only writes them.
8
+ *
9
+ * Every tool outcome is shaped before it is reported (`shapeToolOutcome`, protocol 15): the
10
+ * record refuses an entry past `limits.recordEntryBytes`, so a large or binary MCP or HTTP result,
11
+ * or a sandbox result past what its step has left, is stored with `artifact.write` (keyed by the
12
+ * effect) and the outcome carries a preview. One step's results share a budget (`StepBudget`),
13
+ * which replayed outcomes count toward. A cancel skips the shaping: its outcome is discarded.
6
14
  *
7
15
  * A tool call whose gate hop lost its answer (`executors.resends`) is sent again with the same
8
16
  * key (R5.3): the harness waits a moment and asks core again with the same intent, and core
@@ -10,5 +18,25 @@
10
18
  */
11
19
  import { type HarnessChannel } from "@nylorun/core/harness-api";
12
20
  import type { DurableHost } from "../run/durable.js";
21
+ import type { EngineToolOptions } from "../tools/engine-tools.js";
22
+ import type { McpToolSet } from "../tools/mcp.js";
13
23
  import type { HarnessExecutors, HarnessRun } from "./executors.js";
14
- export declare function apiHost(channel: HarnessChannel, executors: HarnessExecutors, run: HarnessRun): DurableHost;
24
+ import type { LoopConfig } from "../loop/config.js";
25
+ /**
26
+ * Our engine's configuration in a harness (`createHarness`): its own tools, its loop, and how it
27
+ * sends again a tool call whose gate hop lost its answer.
28
+ */
29
+ export interface EngineConfig extends EngineToolOptions {
30
+ readonly loop: LoopConfig;
31
+ /** How much of a value a flow's failure message quotes. */
32
+ readonly flowValueChars: number;
33
+ /** The waits before each resend; the last repeats for every resend after. */
34
+ readonly resendDelaysMs: readonly number[];
35
+ }
36
+ /**
37
+ * The host of one run. A `harness` tool call is one of our engine's own tools, run here: the skill
38
+ * tools over `definition.file`, the artifact tools over the artifact seam and `executors.files`,
39
+ * `tool_search` over the run's MCP tools (`mcp`). Every other tool call goes to `executors.tool`,
40
+ * which routes it by its target.
41
+ */
42
+ export declare function apiHost(channel: HarnessChannel, executors: HarnessExecutors, run: HarnessRun, engine: EngineConfig, mcp?: McpToolSet): DurableHost;
package/dist/api/host.js CHANGED
@@ -2,17 +2,38 @@
2
2
  * The engine's `DurableHost` over the Harness API. An effect whose outcome came with the run
3
3
  * (same id, same request hash) resolves here; any other becomes an `effect.intent`. A model
4
4
  * intent carries no prompt: core stores its hash. When core answers `execute`, the harness runs
5
- * the call and reports its outcome.
5
+ * the call and reports its outcome: a `harness` tool (ours) here, over the Harness API's seams,
6
+ * and anything else through the executors. Before a `sandbox` call our engine mounts the skill
7
+ * folders of the turn's tree (`mountSkills`); the host only writes them.
8
+ *
9
+ * Every tool outcome is shaped before it is reported (`shapeToolOutcome`, protocol 15): the
10
+ * record refuses an entry past `limits.recordEntryBytes`, so a large or binary MCP or HTTP result,
11
+ * or a sandbox result past what its step has left, is stored with `artifact.write` (keyed by the
12
+ * effect) and the outcome carries a preview. One step's results share a budget (`StepBudget`),
13
+ * which replayed outcomes count toward. A cancel skips the shaping: its outcome is discarded.
6
14
  *
7
15
  * A tool call whose gate hop lost its answer (`executors.resends`) is sent again with the same
8
16
  * key (R5.3): the harness waits a moment and asks core again with the same intent, and core
9
17
  * counts the send, answering `execute` again or the call's outcome once it reached its cap.
10
18
  */
11
- import { HarnessApiError, effectRequestHash, } from "@nylorun/core/harness-api";
19
+ import { HarnessApiError, effectRequestHash, writeArtifactBytes, } from "@nylorun/core/harness-api";
20
+ import { delegatesOf } from "@nylorun/core/define";
21
+ import { isArtifactTool, runArtifactTool } from "../tools/artifacts.js";
22
+ import { isSkillTool, mountSkills, runSkillTool } from "../tools/skills.js";
23
+ import { StepBudget, jsonBytes, mayNeedShaping, shapeToolOutcome, spillKey, } from "../tools/results.js";
24
+ import { isToolSearch, runToolSearch } from "../tools/tool-search.js";
12
25
  import { runAbortKind } from "./abort.js";
13
- export function apiHost(channel, executors, run) {
26
+ /**
27
+ * The host of one run. A `harness` tool call is one of our engine's own tools, run here: the skill
28
+ * tools over `definition.file`, the artifact tools over the artifact seam and `executors.files`,
29
+ * `tool_search` over the run's MCP tools (`mcp`). Every other tool call goes to `executors.tool`,
30
+ * which routes it by its target.
31
+ */
32
+ export function apiHost(channel, executors, run, engine, mcp) {
14
33
  const recorded = new Map(run.start.outcomes.map((outcome) => [outcome.effectId, outcome]));
15
34
  const { signal, runId } = run;
35
+ const { limits } = run.start;
36
+ const budget = new StepBudget(engine.toolResults, limits);
16
37
  const ask = async (method, params) => {
17
38
  try {
18
39
  return await channel.request(method, params);
@@ -30,8 +51,19 @@ export function apiHost(channel, executors, run) {
30
51
  try {
31
52
  const value = model
32
53
  ? await executors.model(effect, signal, run)
33
- : await executors.tool(effect, signal, run, traceparent ? { traceparent } : {});
34
- return await ask("effect.outcome", { runId, effectId: effect.effectId, value });
54
+ : effect.target?.kind === "harness"
55
+ ? await engineTool(effect)
56
+ : ((await mounted(effect)) ??
57
+ (await executors.tool(effect, signal, run, traceparent ? { traceparent } : {})));
58
+ const outcome = model ? value : await shape(effect, value);
59
+ const answer = await ask("effect.outcome", {
60
+ runId,
61
+ effectId: effect.effectId,
62
+ value: outcome,
63
+ });
64
+ if (answer.status === "completed")
65
+ budget.count(effect, answer.outcome.value);
66
+ return answer;
35
67
  }
36
68
  catch (error) {
37
69
  // Another owner decides what the effect became.
@@ -44,7 +76,8 @@ export function apiHost(channel, executors, run) {
44
76
  throw error;
45
77
  // The hop lost the answer: core counts one more send, and the call goes again (R5.3).
46
78
  if (!model && kind === undefined && executors.resends?.(effect, error, run)) {
47
- await pause(RESEND_DELAYS_MS[Math.min(resent, RESEND_DELAYS_MS.length - 1)], signal);
79
+ const delays = engine.resendDelaysMs;
80
+ await pause(delays[Math.min(resent, delays.length - 1)], signal);
48
81
  const again = await ask("effect.intent", {
49
82
  runId,
50
83
  effect: intentOf(effect),
@@ -66,6 +99,102 @@ export function apiHost(channel, executors, run) {
66
99
  }
67
100
  }
68
101
  };
102
+ /**
103
+ * A tool call's outcome as it is recorded: shaped to fit what its step has left (an MCP or
104
+ * HTTP tool also to the inline cap), its stored parts written as artifacts of the call. Our
105
+ * engine's own tools are sized by their own configuration and go as they are; after a cancel
106
+ * nothing is stored, since the outcome is discarded.
107
+ */
108
+ const shape = (effect, value) => {
109
+ const kind = effect.target?.kind;
110
+ if (effect.kind !== "tool" || kind === "harness" || effect.toolName === undefined)
111
+ return Promise.resolve(value);
112
+ if (runAbortKind(signal) === "cancel" || !mayNeedShaping(value, engine.toolResults)) {
113
+ budget.count(effect, value);
114
+ return Promise.resolve(value);
115
+ }
116
+ return budget.serialize(effect, async () => {
117
+ const result = await shapeToolOutcome(value, {
118
+ effect,
119
+ limit: budget.reserve(effect, kind === "mcp" || kind === "http"),
120
+ ...(run.start.model ? { model: run.start.model } : {}),
121
+ limits,
122
+ config: engine.toolResults,
123
+ store: (bytes, artifact) => store(effect, bytes, artifact),
124
+ });
125
+ // Shaping keeps a result under its cap; one that a store could not hold is refused here,
126
+ // never by the record.
127
+ const fitted = jsonBytes(result) > budget.budget ? tooLarge(result) : result;
128
+ budget.count(effect, fitted);
129
+ return fitted;
130
+ });
131
+ };
132
+ /** Stores a tool result's bytes as an artifact of the run's session, linked to its call. */
133
+ const store = async (effect, bytes, artifact) => {
134
+ try {
135
+ const { artifact: written } = await writeArtifactBytes(channel, {
136
+ runId,
137
+ key: spillKey(effect.effectId, artifact.index ?? "whole", bytes),
138
+ name: artifact.name,
139
+ contentType: artifact.contentType,
140
+ effectId: effect.effectId,
141
+ chunkBytes: limits.chunkBytes,
142
+ signal,
143
+ }, bytes);
144
+ return {
145
+ artifactId: written.artifactId,
146
+ version: written.version,
147
+ contentType: written.contentType,
148
+ size: written.size,
149
+ };
150
+ }
151
+ catch (error) {
152
+ if (signal.aborted)
153
+ throw error;
154
+ // A limit is the Tenant's to raise: the preview stays, and the model learns why the rest
155
+ // is gone. A run core no longer lets this harness hold is not ours to go on with.
156
+ if (!(error instanceof HarnessApiError) || LOST.has(error.code))
157
+ throw error;
158
+ return {
159
+ dropped: `The result could not be stored as an artifact: ${error.message}`,
160
+ size: bytes.byteLength,
161
+ };
162
+ }
163
+ };
164
+ /**
165
+ * Before a `sandbox` call, the skill folders of the turn's tree, which our engine decides about
166
+ * (protocol 15): a failed outcome, the call's own, when one cannot be put in the sandbox.
167
+ */
168
+ const mounted = async (effect) => effect.target?.kind === "sandbox" && executors.files
169
+ ? mountSkills(executors.files, channel, run, signal)
170
+ : undefined;
171
+ /** Runs a call of one of our engine's own tools. */
172
+ const engineTool = (effect) => {
173
+ if (isToolSearch(effect))
174
+ return Promise.resolve(runToolSearch(effect, mcp?.deferredOf(effect.agent?.id) ?? [], engine.mcpTools));
175
+ if (isArtifactTool(effect.toolName))
176
+ return runArtifactTool(effect, {
177
+ channel,
178
+ run,
179
+ ...(executors.files ? { files: executors.files } : {}),
180
+ pageBytes: engine.artifactPageBytes,
181
+ signal,
182
+ });
183
+ if (isSkillTool(effect.toolName))
184
+ return runSkillTool(effect, {
185
+ channel,
186
+ run,
187
+ agent: agentOf(run.start.manifest, effect),
188
+ readBytes: engine.skillReadBytes,
189
+ sandboxed: run.start.environment?.sandbox !== undefined,
190
+ signal,
191
+ });
192
+ return Promise.resolve({
193
+ kind: "failed",
194
+ code: "tool.unknown",
195
+ message: `This harness runs no tool named '${effect.toolName ?? ""}'.`,
196
+ });
197
+ };
69
198
  return {
70
199
  async resolveEffect(effect) {
71
200
  if (signal.aborted)
@@ -75,17 +204,29 @@ export function apiHost(channel, executors, run) {
75
204
  if (known) {
76
205
  if (known.requestHash !== requestHash)
77
206
  throw new HarnessApiError("effect_drift", "Effect identity request drift");
207
+ // A replayed result took its share of its step's budget.
208
+ budget.count(effect, known.outcome.value);
78
209
  return { status: "completed", outcome: known.outcome };
79
210
  }
80
211
  const answer = await ask("effect.intent", { runId, effect: intentOf(effect), requestHash });
81
212
  if (answer.status === "execute")
82
213
  return execute(effect, requestHash, answer.traceparent);
214
+ if (answer.status === "completed")
215
+ budget.count(effect, answer.outcome.value);
83
216
  return answer;
84
217
  },
85
218
  };
86
219
  }
87
- /** How long the harness waits before it sends a call whose gate hop was lost again. */
88
- const RESEND_DELAYS_MS = [1_000, 2_000, 4_000];
220
+ /** A tool result our engine could not make fit its step: the model sees why. */
221
+ function tooLarge(value) {
222
+ return {
223
+ kind: "failed",
224
+ code: "tool.result-too-large",
225
+ message: `The tool's result is ${jsonBytes(value)} bytes as shaped, more than one step's results may hold, and it could not be stored as an artifact.`,
226
+ };
227
+ }
228
+ /** Answers that say the run is no longer this harness's to go on with. */
229
+ const LOST = new Set(["ownership_lost", "run_not_held", "turn_cancelled"]);
89
230
  /** Waits `ms`, or throws the reason as soon as `signal` aborts. */
90
231
  function pause(ms, signal) {
91
232
  return new Promise((resolve, reject) => {
@@ -102,6 +243,13 @@ function pause(ms, signal) {
102
243
  signal.addEventListener("abort", onAbort, { once: true });
103
244
  });
104
245
  }
246
+ /** The agent of the turn's manifest an effect is for: the root, or an agent it uses as a tool. */
247
+ function agentOf(manifest, effect) {
248
+ if (effect.agent === undefined)
249
+ return manifest;
250
+ return (delegatesOf(manifest).find((delegate) => delegate.manifest.id === effect.agent.id)?.manifest ??
251
+ {});
252
+ }
105
253
  /** What crosses for an effect: a model call's prompt stays here. */
106
254
  function intentOf(effect) {
107
255
  if (effect.kind !== "model")
@@ -1,11 +1,25 @@
1
1
  /**
2
- * `@nylorun/harness/api`: a harness over the Harness API v1. It leases runs from core, resumes
3
- * the engine with a DurableHost over the record, and runs model, MCP and sandbox calls through
4
- * the executors it is given.
2
+ * `@nylorun/harness/api`: a harness over the Harness API (v4). It leases runs from core, resumes
3
+ * the engine with a DurableHost over the record, and runs model, MCP, HTTP and sandbox calls
4
+ * through the executors it is given, and our engine's own tools (skills, artifacts) over the
5
+ * Harness API's seams. Our engine writes the model's instructions and defines its tools from the
6
+ * turn's facts (`engineToolsFor`); a harness of your own may use the same helpers.
5
7
  */
6
- export { createHarness, type Harness, type HarnessLogger, type HarnessOptions } from "./harness.js";
8
+ export { DEFAULT_LEASE_RETRY_MS, DEFAULT_RESEND_DELAYS_MS, DEFAULT_TRANSCRIPT_CACHE_MB, createHarness, type Harness, type HarnessLogger, type HarnessOptions, } from "./harness.js";
9
+ export { DEFAULT_COMPACTION_CONFIG, compactionConfigOf, type CompactionConfig, } from "../loop/compaction/config.js";
10
+ export { DEFAULT_LOOP_CONFIG, DEFAULT_PARTIAL_OUTPUT_CHARS, loopConfigOf, type LoopConfig, } from "../loop/config.js";
11
+ export { DEFAULT_FLOW_VALUE_CHARS } from "../flow/limits.js";
7
12
  export { ABORT_MESSAGES, RunAbort, runAbortKind } from "./abort.js";
8
- export type { HarnessExecutors, HarnessRun, McpRecorder, PreparedRun, ToolCallContext, } from "./executors.js";
9
- export { apiHost } from "./host.js";
13
+ export type { FailedFileOutcome, HarnessExecutors, HarnessFileEntry, HarnessFiles, HarnessRun, McpRecorder, PreparedRun, ToolCallContext, } from "./executors.js";
14
+ export { apiHost, type EngineConfig } from "./host.js";
15
+ export { artifactInstructions, artifactToolsFor, isArtifactTool, runArtifactTool, type ArtifactToolContext, type ArtifactToolOptions, } from "../tools/artifacts.js";
16
+ export { engineToolsFor, type EngineToolOptions, type EngineTools } from "../tools/engine-tools.js";
17
+ export { DEFAULT_SANDBOX_TOOL_LIMITS, sandboxInstructions, sandboxToolLimitsOf, sandboxTools, type SandboxToolLimits, } from "../tools/sandbox.js";
18
+ export { DEFAULT_SKILL_READ_BYTES, LOAD_SKILL_TOOL, READ_SKILL_RESOURCE_TOOL, SKILLS_USAGE, definitionFileChunks, formatSkillCatalog, isSkillTool, runSkillTool, skillCatalogText, skillFolderNote, mountSkills, sandboxSkillsOf, skillTools, type SkillFiles, type SkillToolContext, } from "../tools/skills.js";
19
+ export { skillOfToolCall } from "../tools/trace.js";
10
20
  export { runTurn, type RunContext } from "./run.js";
11
21
  export { TranscriptCache } from "./transcript-cache.js";
22
+ export { DEFAULT_MCP_TOOL_CONFIG, MODEL_TOOL_NAME_MAX, mcpToolConfigOf, mcpToolKey, mcpToolName, mcpToolNames, mcpToolSet, type McpLayout, type McpRenamedTool, type McpToolConfig, type McpToolSet, } from "../tools/mcp.js";
23
+ export { TOOL_CALL_TOOL, TOOL_SEARCH_TOOL, deferredToolsNote, deferredToolsTools, isToolSearch, rank, runToolSearch, tokens, type DeferredServerNote, } from "../tools/tool-search.js";
24
+ export { DEFAULT_TOOL_RESULT_CONFIG, StepBudget, cutMessage, jsonBytes, mayNeedShaping, previewOf, resultBytes, shapeToolOutcome, spillKey, toolResultConfigOf, utf8Boundary, type ShapeContext, type Stored, type ToolResultConfig, } from "../tools/results.js";
25
+ export { DEFAULT_OUTPUTS_CONFIG, outputsConfigOf, saveOutputs, type OutputsConfig, type OutputsContext, } from "../tools/outputs.js";
package/dist/api/index.js CHANGED
@@ -1,10 +1,24 @@
1
1
  /**
2
- * `@nylorun/harness/api`: a harness over the Harness API v1. It leases runs from core, resumes
3
- * the engine with a DurableHost over the record, and runs model, MCP and sandbox calls through
4
- * the executors it is given.
2
+ * `@nylorun/harness/api`: a harness over the Harness API (v4). It leases runs from core, resumes
3
+ * the engine with a DurableHost over the record, and runs model, MCP, HTTP and sandbox calls
4
+ * through the executors it is given, and our engine's own tools (skills, artifacts) over the
5
+ * Harness API's seams. Our engine writes the model's instructions and defines its tools from the
6
+ * turn's facts (`engineToolsFor`); a harness of your own may use the same helpers.
5
7
  */
6
- export { createHarness } from "./harness.js";
8
+ export { DEFAULT_LEASE_RETRY_MS, DEFAULT_RESEND_DELAYS_MS, DEFAULT_TRANSCRIPT_CACHE_MB, createHarness, } from "./harness.js";
9
+ export { DEFAULT_COMPACTION_CONFIG, compactionConfigOf, } from "../loop/compaction/config.js";
10
+ export { DEFAULT_LOOP_CONFIG, DEFAULT_PARTIAL_OUTPUT_CHARS, loopConfigOf, } from "../loop/config.js";
11
+ export { DEFAULT_FLOW_VALUE_CHARS } from "../flow/limits.js";
7
12
  export { ABORT_MESSAGES, RunAbort, runAbortKind } from "./abort.js";
8
13
  export { apiHost } from "./host.js";
14
+ export { artifactInstructions, artifactToolsFor, isArtifactTool, runArtifactTool, } from "../tools/artifacts.js";
15
+ export { engineToolsFor } from "../tools/engine-tools.js";
16
+ export { DEFAULT_SANDBOX_TOOL_LIMITS, sandboxInstructions, sandboxToolLimitsOf, sandboxTools, } from "../tools/sandbox.js";
17
+ export { DEFAULT_SKILL_READ_BYTES, LOAD_SKILL_TOOL, READ_SKILL_RESOURCE_TOOL, SKILLS_USAGE, definitionFileChunks, formatSkillCatalog, isSkillTool, runSkillTool, skillCatalogText, skillFolderNote, mountSkills, sandboxSkillsOf, skillTools, } from "../tools/skills.js";
18
+ export { skillOfToolCall } from "../tools/trace.js";
9
19
  export { runTurn } from "./run.js";
10
20
  export { TranscriptCache } from "./transcript-cache.js";
21
+ export { DEFAULT_MCP_TOOL_CONFIG, MODEL_TOOL_NAME_MAX, mcpToolConfigOf, mcpToolKey, mcpToolName, mcpToolNames, mcpToolSet, } from "../tools/mcp.js";
22
+ export { TOOL_CALL_TOOL, TOOL_SEARCH_TOOL, deferredToolsNote, deferredToolsTools, isToolSearch, rank, runToolSearch, tokens, } from "../tools/tool-search.js";
23
+ export { DEFAULT_TOOL_RESULT_CONFIG, StepBudget, cutMessage, jsonBytes, mayNeedShaping, previewOf, resultBytes, shapeToolOutcome, spillKey, toolResultConfigOf, utf8Boundary, } from "../tools/results.js";
24
+ export { DEFAULT_OUTPUTS_CONFIG, outputsConfigOf, saveOutputs, } from "../tools/outputs.js";
package/dist/api/run.d.ts CHANGED
@@ -8,10 +8,13 @@
8
8
  */
9
9
  import { type HarnessChannel } from "@nylorun/core/harness-api";
10
10
  import type { HarnessExecutors, HarnessRun } from "./executors.js";
11
+ import { type EngineConfig } from "./host.js";
11
12
  import type { TranscriptCache } from "./transcript-cache.js";
12
13
  export interface RunContext {
13
14
  readonly channel: HarnessChannel;
14
15
  readonly executors: HarnessExecutors;
15
16
  readonly cache: TranscriptCache;
17
+ /** The harness's configuration of our engine's own tools. */
18
+ readonly engine: EngineConfig;
16
19
  }
17
20
  export declare function runTurn(ctx: RunContext, run: HarnessRun): Promise<void>;
package/dist/api/run.js CHANGED
@@ -6,11 +6,14 @@
6
6
  * A run core stopped for a shutdown or a lost lease is given back (`lease.release`); core
7
7
  * settles nothing for it, as it never did for an advance it stopped.
8
8
  */
9
- import { transcriptOf, transcriptUpdates, withTranscript, } from "@nylorun/core/harness-api";
9
+ import { fromBase64, transcriptOf, transcriptUpdates, withTranscript, } from "@nylorun/core/harness-api";
10
10
  import { runDurable } from "../run/durable.js";
11
11
  import { runFlowDurable } from "../flow/engine.js";
12
12
  import { runAbortKind } from "./abort.js";
13
13
  import { apiHost } from "./host.js";
14
+ import { engineToolsFor } from "../tools/engine-tools.js";
15
+ import { mcpToolSet } from "../tools/mcp.js";
16
+ import { saveOutputs } from "../tools/outputs.js";
14
17
  const METHODS = {
15
18
  completed: "turn.completed",
16
19
  paused: "turn.paused",
@@ -31,16 +34,9 @@ export async function runTurn(ctx, run) {
31
34
  try {
32
35
  if (start.engine === "agent" && ctx.executors.prepare) {
33
36
  const prepared = await ctx.executors.prepare(run, (params) => ctx.channel.request("session.mcp", { runId, ...params }));
34
- if (prepared) {
35
- start = {
36
- ...start,
37
- sessionTools: prepared.sessionTools,
38
- routing: {
39
- ...start.routing,
40
- ...(prepared.mcpSnapshot === undefined ? {} : { mcpSnapshot: prepared.mcpSnapshot }),
41
- },
42
- };
43
- // The executors route this run's MCP calls by the snapshot it now has.
37
+ if (prepared?.mcp) {
38
+ start = { ...start, mcp: prepared.mcp };
39
+ // The executors and our engine's tools read the run's facts as they now are.
44
40
  run.start = start;
45
41
  }
46
42
  }
@@ -58,7 +54,18 @@ export async function runTurn(ctx, run) {
58
54
  transcript = ctx.cache.get(sessionId, cursor) ?? (await read(ctx, run));
59
55
  checkpoint = { ...checkpoint, state: withTranscript(checkpoint.state, transcript) };
60
56
  }
61
- const host = apiHost(ctx.channel, ctx.executors, run);
57
+ // The session's MCP tools as our engine offers them (protocol 15): named, and laid out as our
58
+ // state pinned them while the facts stay the same.
59
+ const engineTools = (agent) => engineToolsFor(agent, start.environment, ctx.engine);
60
+ const mcp = start.engine === "agent" && start.mcp
61
+ ? mcpToolSet(start.mcp, start.manifest, {
62
+ config: ctx.engine.mcpTools,
63
+ ...(start.model ? { model: start.model } : {}),
64
+ ...(checkpoint.state?.mcpLayout ? { layout: checkpoint.state.mcpLayout } : {}),
65
+ taken: (agent) => engineTools(agent).tools.map((tool) => tool.name),
66
+ })
67
+ : undefined;
68
+ const host = apiHost(ctx.channel, ctx.executors, run, ctx.engine, mcp);
62
69
  const result = start.engine === "flow"
63
70
  ? await runFlowDurable({
64
71
  manifest: start.manifest,
@@ -66,16 +73,34 @@ export async function runTurn(ctx, run) {
66
73
  signal,
67
74
  host,
68
75
  limits: start.options.flowLimits,
76
+ valueChars: ctx.engine.flowValueChars,
69
77
  })
70
78
  : await runDurable({
71
79
  manifest: start.manifest,
72
80
  checkpoint,
73
81
  signal,
74
82
  host,
75
- sessionTools: start.sessionTools,
83
+ ...(mcp ? { mcp } : {}),
84
+ // Our engine's own tools and text, from the turn's facts (protocol 15).
85
+ engineTools,
76
86
  ...(start.options.yieldAfter ? { yieldAfter: start.options.yieldAfter } : {}),
87
+ ...(start.model ? { model: start.model } : {}),
88
+ files: filesOf(ctx, run, start),
89
+ loop: ctx.engine.loop,
77
90
  });
78
- ({ output, after } = outputOf(runId, result, transcript));
91
+ // Our engine's outputs folder (Q5): saved before the turn ends, while the run is held.
92
+ if (start.engine === "agent" &&
93
+ result.status === "completed" &&
94
+ start.environment?.sandbox !== undefined &&
95
+ ctx.executors.files)
96
+ await saveOutputs({
97
+ channel: ctx.channel,
98
+ run,
99
+ files: ctx.executors.files,
100
+ config: ctx.engine.outputs,
101
+ signal,
102
+ });
103
+ ({ output, after } = outputOf(runId, result, transcript, start.limits.recordEntryBytes));
79
104
  }
80
105
  catch (error) {
81
106
  output = {
@@ -108,6 +133,26 @@ export async function runTurn(ctx, run) {
108
133
  else
109
134
  ctx.cache.delete(sessionId);
110
135
  }
136
+ /**
137
+ * How the run's engine reads the turn's files (protocol 15): it decides from the model
138
+ * descriptor and the Runtime limits, and reads text over the artifact seam.
139
+ */
140
+ function filesOf(ctx, run, start) {
141
+ return {
142
+ ...(start.model ? { model: start.model } : {}),
143
+ limits: start.limits,
144
+ async read(reference, offset, length, signal) {
145
+ const answer = await ctx.channel.request("artifact.read", {
146
+ runId: run.runId,
147
+ artifactId: reference.artifactId,
148
+ version: reference.version,
149
+ offset,
150
+ length,
151
+ }, signal ?? run.signal);
152
+ return { artifact: answer.artifact, bytes: fromBase64(answer.base64), eof: answer.eof };
153
+ },
154
+ };
155
+ }
111
156
  /** The edited transcript's size from the cached one's and the edits, without serializing it. */
112
157
  function estimate(cache, sessionId, start, output) {
113
158
  const base = cache.bytesOf(sessionId);
@@ -132,7 +177,7 @@ async function read(ctx, run) {
132
177
  }
133
178
  }
134
179
  /** The engine's result as an output. An agent's state goes without its transcript. */
135
- function outputOf(runId, result, start) {
180
+ function outputOf(runId, result, start, recordEntryBytes) {
136
181
  if (result.status === "waiting" || result.status === "uncertain")
137
182
  return { output: { runId, status: result.status, effectIds: [...result.effectIds] } };
138
183
  const outcome = ("result" in result ? result.result : {});
@@ -147,14 +192,34 @@ function outputOf(runId, result, start) {
147
192
  if (outcome.state === undefined)
148
193
  return { output: { runId, status: result.status, ...fields } };
149
194
  const after = transcriptOf(outcome.state);
195
+ const compaction = compactionOf(start, after, result);
150
196
  return {
151
197
  output: {
152
198
  runId,
153
199
  status: result.status,
154
200
  state: withTranscript(outcome.state, []),
155
- transcript: transcriptUpdates(start, after),
201
+ transcript: transcriptUpdates(start, after, recordEntryBytes, compaction),
156
202
  ...fields,
157
203
  },
158
204
  after,
159
205
  };
160
206
  }
207
+ /**
208
+ * What the segment says of a compaction it made (Q4): its transcript starts with a summary it did
209
+ * not start with, written by the root's summary calls. Our engine keeps one summary, first; a
210
+ * segment that compacted twice names every summary call, and the facts of the last.
211
+ */
212
+ function compactionOf(start, after, result) {
213
+ const ids = "summaryEffectIds" in result ? result.summaryEffectIds : undefined;
214
+ const entry = after[0];
215
+ if (!ids?.length || entry?.kind !== "compaction")
216
+ return undefined;
217
+ if (JSON.stringify(start[0]) === JSON.stringify(entry))
218
+ return undefined;
219
+ return {
220
+ trigger: entry.trigger === "overflow" ? "overflow" : "threshold",
221
+ tokensBefore: Math.max(0, Math.round(Number(entry.tokensBefore) || 0)),
222
+ tokensAfter: Math.max(0, Math.round(Number(entry.tokensAfter) || 0)),
223
+ summaryEffectIds: [...ids],
224
+ };
225
+ }
@@ -11,6 +11,8 @@ export type FlowContext = {
11
11
  readonly signal?: AbortSignal;
12
12
  /** Operator ceilings (Map items / Loop iterations). */
13
13
  readonly limits: FlowOperatorLimits;
14
+ /** How much of a value a failure message quotes. */
15
+ readonly valueChars: number;
14
16
  readonly pending: Map<string, "pending" | "uncertain">;
15
17
  /** Interactions tool nodes wait on, by interaction id. */
16
18
  readonly interactions: Map<string, FlowInteraction>;
@@ -38,6 +40,7 @@ export declare function createFlowContext(options: {
38
40
  readonly host: DurableHost;
39
41
  readonly signal?: AbortSignal;
40
42
  readonly limits?: Partial<FlowOperatorLimits> | null;
43
+ readonly valueChars?: number;
41
44
  }): FlowContext;
42
45
  /**
43
46
  * The result of a flow that unwound on a suspension: waiting (or uncertain) while any effect is
@@ -1,5 +1,5 @@
1
1
  import { HostSuspension } from "../loop/host-suspension.js";
2
- import { resolveOperatorLimits } from "./limits.js";
2
+ import { DEFAULT_FLOW_VALUE_CHARS, resolveOperatorLimits, } from "./limits.js";
3
3
  import { flowEffectId, nodeKeyOf } from "./paths.js";
4
4
  import { failedValueOf, FlowNodeError, FlowPause, } from "./types.js";
5
5
  export function createFlowContext(options) {
@@ -13,6 +13,7 @@ export function createFlowContext(options) {
13
13
  host: options.host,
14
14
  signal: options.signal,
15
15
  limits: resolveOperatorLimits(options.limits),
16
+ valueChars: options.valueChars ?? DEFAULT_FLOW_VALUE_CHARS,
16
17
  pending,
17
18
  interactions,
18
19
  inFlight,
@@ -33,4 +33,6 @@ export declare function runFlowDurable(options: {
33
33
  signal?: AbortSignal;
34
34
  /** Operator ceilings (`maxMapItems`, `maxLoopIterations`). Host/Runtime supplies these. */
35
35
  limits?: Partial<FlowOperatorLimits> | null;
36
+ /** How much of a value a failure message quotes. Default `DEFAULT_FLOW_VALUE_CHARS`. */
37
+ valueChars?: number;
36
38
  }): Promise<FlowDurableResult>;