@nylorun/harness 0.25.1-beta → 0.27.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 (42) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/HOST_CONTRACT.md +21 -18
  3. package/README.md +12 -13
  4. package/dist/api/executors.d.ts +18 -4
  5. package/dist/api/harness.d.ts +1 -1
  6. package/dist/api/harness.js +4 -4
  7. package/dist/api/host.d.ts +4 -0
  8. package/dist/api/host.js +62 -24
  9. package/dist/api/index.d.ts +1 -1
  10. package/dist/api/run.js +9 -0
  11. package/dist/definition/agent-definition.d.ts +2 -2
  12. package/dist/definition/agent-definition.js +2 -2
  13. package/dist/definition/registry.d.ts +3 -3
  14. package/dist/definition/registry.js +12 -15
  15. package/dist/loop/compaction/index.d.ts +4 -2
  16. package/dist/loop/compaction/index.js +78 -8
  17. package/dist/loop/dispatch.js +1 -1
  18. package/dist/loop/model/project.d.ts +6 -0
  19. package/dist/loop/model/project.js +59 -18
  20. package/dist/loop/run.js +2 -2
  21. package/dist/loop/state.js +0 -1
  22. package/dist/loop/step/canonicalize.d.ts +1 -3
  23. package/dist/loop/step/canonicalize.js +0 -15
  24. package/dist/loop/step/model-configuration.d.ts +4 -13
  25. package/dist/loop/step/model-configuration.js +12 -70
  26. package/dist/loop/step/resolve.js +0 -1
  27. package/dist/loop/step/run.js +33 -12
  28. package/dist/loop/step/runtime.d.ts +2 -2
  29. package/dist/loop/step/seal.js +0 -17
  30. package/dist/loop/step/slot-assembly.d.ts +5 -5
  31. package/dist/loop/step/slot-assembly.js +5 -5
  32. package/dist/loop/step/step-context.d.ts +5 -19
  33. package/dist/loop/step/step-context.js +9 -195
  34. package/dist/loop/transcript.js +7 -1
  35. package/dist/run/durable.d.ts +2 -6
  36. package/dist/run/durable.js +30 -40
  37. package/dist/types/execution.d.ts +0 -1
  38. package/package.json +6 -6
  39. package/dist/loop/step/compose.d.ts +0 -5
  40. package/dist/loop/step/compose.js +0 -109
  41. package/dist/loop/step/context-draft.d.ts +0 -8
  42. package/dist/loop/step/context-draft.js +0 -48
package/dist/api/host.js CHANGED
@@ -3,6 +3,10 @@
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
5
  * the call and reports its outcome.
6
+ *
7
+ * A tool call whose gate hop lost its answer (`executors.resends`) is sent again with the same
8
+ * key (R5.3): the harness waits a moment and asks core again with the same intent, and core
9
+ * counts the send, answering `execute` again or the call's outcome once it reached its cap.
6
10
  */
7
11
  import { HarnessApiError, effectRequestHash, } from "@nylorun/core/harness-api";
8
12
  import { runAbortKind } from "./abort.js";
@@ -20,30 +24,46 @@ export function apiHost(channel, executors, run) {
20
24
  throw error;
21
25
  }
22
26
  };
23
- const execute = async (effect) => {
27
+ const execute = async (effect, requestHash, traceparent) => {
24
28
  const model = effect.kind === "model";
25
- try {
26
- const value = model
27
- ? await executors.model(effect, signal, run)
28
- : await executors.tool(effect, signal, run);
29
- return await ask("effect.outcome", { runId, effectId: effect.effectId, value });
30
- }
31
- catch (error) {
32
- // Another owner decides what the effect became.
33
- if (error instanceof HarnessApiError && error.code === "ownership_lost")
34
- throw error;
35
- const recoverable = model ? executors.recovers.model : executors.recovers.tool(effect, run);
36
- const kind = runAbortKind(signal);
37
- // The call goes on at its gate: the next run re-sends it and collects its outcome.
38
- if (recoverable && kind === "shutdown")
39
- throw error;
40
- if (recoverable && !model && kind === "cancel")
41
- await executors.cancelAtGate?.(effect, run);
42
- return ask("effect.outcome", {
43
- runId,
44
- effectId: effect.effectId,
45
- error: error instanceof Error ? error.message : String(error),
46
- });
29
+ for (let resent = 0;; resent += 1) {
30
+ try {
31
+ const value = model
32
+ ? 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 });
35
+ }
36
+ catch (error) {
37
+ // Another owner decides what the effect became.
38
+ if (error instanceof HarnessApiError && error.code === "ownership_lost")
39
+ throw error;
40
+ const recoverable = model ? executors.recovers.model : executors.recovers.tool(effect, run);
41
+ const kind = runAbortKind(signal);
42
+ // The call goes on at its gate: the next run re-sends it and collects its outcome.
43
+ if (recoverable && kind === "shutdown")
44
+ throw error;
45
+ // The hop lost the answer: core counts one more send, and the call goes again (R5.3).
46
+ if (!model && kind === undefined && executors.resends?.(effect, error, run)) {
47
+ await pause(RESEND_DELAYS_MS[Math.min(resent, RESEND_DELAYS_MS.length - 1)], signal);
48
+ const again = await ask("effect.intent", {
49
+ runId,
50
+ effect: intentOf(effect),
51
+ requestHash,
52
+ });
53
+ if (again.status === "execute") {
54
+ traceparent = again.traceparent ?? traceparent;
55
+ continue;
56
+ }
57
+ return again;
58
+ }
59
+ if (recoverable && !model && kind === "cancel")
60
+ await executors.cancelAtGate?.(effect, run);
61
+ return ask("effect.outcome", {
62
+ runId,
63
+ effectId: effect.effectId,
64
+ error: error instanceof Error ? error.message : String(error),
65
+ });
66
+ }
47
67
  }
48
68
  };
49
69
  return {
@@ -59,11 +79,29 @@ export function apiHost(channel, executors, run) {
59
79
  }
60
80
  const answer = await ask("effect.intent", { runId, effect: intentOf(effect), requestHash });
61
81
  if (answer.status === "execute")
62
- return execute(effect);
82
+ return execute(effect, requestHash, answer.traceparent);
63
83
  return answer;
64
84
  },
65
85
  };
66
86
  }
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];
89
+ /** Waits `ms`, or throws the reason as soon as `signal` aborts. */
90
+ function pause(ms, signal) {
91
+ return new Promise((resolve, reject) => {
92
+ if (signal.aborted)
93
+ return reject(signal.reason);
94
+ const onAbort = () => {
95
+ clearTimeout(timer);
96
+ reject(signal.reason);
97
+ };
98
+ const timer = setTimeout(() => {
99
+ signal.removeEventListener("abort", onAbort);
100
+ resolve();
101
+ }, ms);
102
+ signal.addEventListener("abort", onAbort, { once: true });
103
+ });
104
+ }
67
105
  /** What crosses for an effect: a model call's prompt stays here. */
68
106
  function intentOf(effect) {
69
107
  if (effect.kind !== "model")
@@ -5,7 +5,7 @@
5
5
  */
6
6
  export { createHarness, type Harness, type HarnessLogger, type HarnessOptions } from "./harness.js";
7
7
  export { ABORT_MESSAGES, RunAbort, runAbortKind } from "./abort.js";
8
- export type { HarnessExecutors, HarnessRun, McpRecorder, PreparedRun } from "./executors.js";
8
+ export type { HarnessExecutors, HarnessRun, McpRecorder, PreparedRun, ToolCallContext, } from "./executors.js";
9
9
  export { apiHost } from "./host.js";
10
10
  export { runTurn, type RunContext } from "./run.js";
11
11
  export { TranscriptCache } from "./transcript-cache.js";
package/dist/api/run.js CHANGED
@@ -45,6 +45,15 @@ export async function runTurn(ctx, run) {
45
45
  }
46
46
  }
47
47
  let checkpoint = start.checkpoint;
48
+ // The state is ours alone (R4.2): core never reads it. The turn's manifest is core's choice
49
+ // (the pin, or a variant a message named), and the state follows it.
50
+ if (start.engine === "agent" &&
51
+ checkpoint.state &&
52
+ checkpoint.state.manifestHash !== checkpoint.manifestHash)
53
+ checkpoint = {
54
+ ...checkpoint,
55
+ state: { ...checkpoint.state, manifestHash: checkpoint.manifestHash },
56
+ };
48
57
  if (start.engine === "agent" && checkpoint.state) {
49
58
  transcript = ctx.cache.get(sessionId, cursor) ?? (await read(ctx, run));
50
59
  checkpoint = { ...checkpoint, state: withTranscript(checkpoint.state, transcript) };
@@ -1,11 +1,11 @@
1
- import type { BoundMiddleware } from "@nylorun/core/define";
1
+ import type { DefinitionPart } from "@nylorun/core/define";
2
2
  import type { ToolRegistry } from "./registry.js";
3
3
  import type { TurnOutputContract } from "@nylorun/core/define";
4
4
  import type { AgentManifest } from "@nylorun/core/define";
5
5
  import type { Implementations } from "@nylorun/core/define";
6
6
  export interface AgentDefinition {
7
7
  readonly id: string;
8
- readonly middleware: readonly BoundMiddleware[];
8
+ readonly parts: readonly DefinitionPart[];
9
9
  readonly registry: ToolRegistry;
10
10
  readonly output?: TurnOutputContract;
11
11
  readonly manifest: AgentManifest;
@@ -9,9 +9,9 @@ export function definitionFromBinding(binding) {
9
9
  id: binding.manifest.id,
10
10
  manifest: binding.manifest,
11
11
  hash: hashManifest(binding.manifest),
12
- middleware: binding.declarations,
12
+ parts: binding.parts,
13
13
  implementations: binding.implementations,
14
- registry: new Registry(binding.declarations, binding.tools),
14
+ registry: new Registry(binding.parts, binding.tools),
15
15
  ...(binding.outputSchema ? { output: bindOutputContract(binding.outputSchema) } : {}),
16
16
  });
17
17
  }
@@ -1,10 +1,10 @@
1
- import type { BoundMiddleware, BoundToolDefinition } from "@nylorun/core/define";
1
+ import type { DefinitionPart, BoundToolDefinition } from "@nylorun/core/define";
2
2
  import type { ToolReference } from "../types/execution.js";
3
3
  /** Definition-only lookup; no per-run selections or progress live here. */
4
4
  export declare class ToolRegistry {
5
5
  private readonly tools;
6
- private readonly owners;
7
- constructor(middleware: readonly BoundMiddleware[], snapshots?: readonly BoundToolDefinition[]);
6
+ private readonly registered;
7
+ constructor(parts: readonly DefinitionPart[], snapshots?: readonly BoundToolDefinition[]);
8
8
  reference(tool: BoundToolDefinition): ToolReference;
9
9
  restore(reference: ToolReference): BoundToolDefinition;
10
10
  }
@@ -5,25 +5,22 @@ import { copyJson } from "@nylorun/core/define";
5
5
  /** Definition-only lookup; no per-run selections or progress live here. */
6
6
  export class ToolRegistry {
7
7
  tools = new Map();
8
- owners = new WeakMap();
9
- constructor(middleware, snapshots) {
10
- for (const capability of middleware) {
11
- for (const tool of [...(capability.tools ?? []), ...(capability.sessionTools ?? [])]) {
12
- const key = JSON.stringify([capability.id, tool.name]);
13
- if (this.tools.has(key) || this.owners.has(tool))
14
- throw new HarnessError("tool.invalid", `Duplicate registered tool '${tool.name}' in '${capability.id}'`);
15
- this.tools.set(key, snapshots?.find((snapshot) => snapshot.source === tool) ??
16
- bindTool(tool, { middlewareId: capability.id, slot: capability.id }));
17
- this.owners.set(tool, capability.id);
8
+ registered = new WeakSet();
9
+ constructor(parts, snapshots) {
10
+ for (const part of parts) {
11
+ for (const tool of [...(part.tools ?? []), ...(part.sessionTools ?? [])]) {
12
+ if (this.tools.has(tool.name) || this.registered.has(tool))
13
+ throw new HarnessError("tool.invalid", `Duplicate registered tool '${tool.name}'`);
14
+ this.tools.set(tool.name, snapshots?.find((snapshot) => snapshot.source === tool) ??
15
+ bindTool(tool, { partId: part.id, slot: part.id }));
16
+ this.registered.add(tool);
18
17
  }
19
18
  }
20
19
  }
21
20
  reference(tool) {
22
- const capabilityId = this.owners.get(tool.source);
23
- if (!capabilityId)
24
- throw new HarnessError("tool.unregistered", `Tool '${tool.name}' is not registered. Declare it in capability.tools.`);
21
+ if (!this.registered.has(tool.source))
22
+ throw new HarnessError("tool.unregistered", `Tool '${tool.name}' is not registered. Declare it with .tools().`);
25
23
  const reference = copyJson({
26
- capabilityId,
27
24
  toolName: tool.source.name,
28
25
  descriptor: descriptor(tool),
29
26
  });
@@ -33,7 +30,7 @@ export class ToolRegistry {
33
30
  restore(reference) {
34
31
  if ("familyId" in reference || "binding" in reference || "version" in reference)
35
32
  throw new HarnessError("execution.incompatible", "Saved state uses a removed tool-family reference. Register an ordinary tool and start a new execution.");
36
- const registered = this.tools.get(JSON.stringify([reference.capabilityId, reference.toolName]));
33
+ const registered = this.tools.get(reference.toolName);
37
34
  if (!registered || canonical(descriptor(registered)) !== canonical(reference.descriptor))
38
35
  throw new HarnessError("execution.incompatible", `Missing or changed registered tool '${reference.toolName}'`);
39
36
  return registered;
@@ -18,9 +18,11 @@ export declare function contextBudget(transcript: readonly TranscriptEntry[]): C
18
18
  /**
19
19
  * Tokens the next prompt needs: the last reported usage, which already counts the
20
20
  * instructions, tools and everything before it, plus an estimate of what came after.
21
- * Without usage, everything is estimated.
21
+ * Without usage, everything is estimated. The files of turn `turnId` go to the model as media
22
+ * (protocol 12) and count by their size; those of an earlier turn the reported call carried are
23
+ * reference lines now, and come off it.
22
24
  */
23
- export declare function estimateTokens(transcript: readonly TranscriptEntry[]): number;
25
+ export declare function estimateTokens(transcript: readonly TranscriptEntry[], turnId?: string): number;
24
26
  /** A rough token count of what one entry contributes to a prompt. */
25
27
  export declare function entryTokens(entry: TranscriptEntry): number;
26
28
  /**
@@ -1,4 +1,4 @@
1
- import { HarnessError, isModelFailureOutcome } from "@nylorun/core/define";
1
+ import { HarnessError, isModelFailureOutcome, mediaReferenceLine, mediaReferenceOf, } from "@nylorun/core/define";
2
2
  /** Characters per token for the heuristic estimate; the reserve absorbs its error. */
3
3
  const CHARS_PER_TOKEN = 4;
4
4
  /** The kept tail is at most this many tokens, and at most this share of the window. */
@@ -33,9 +33,12 @@ export function contextBudget(transcript) {
33
33
  /**
34
34
  * Tokens the next prompt needs: the last reported usage, which already counts the
35
35
  * instructions, tools and everything before it, plus an estimate of what came after.
36
- * Without usage, everything is estimated.
36
+ * Without usage, everything is estimated. The files of turn `turnId` go to the model as media
37
+ * (protocol 12) and count by their size; those of an earlier turn the reported call carried are
38
+ * reference lines now, and come off it.
37
39
  */
38
- export function estimateTokens(transcript) {
40
+ export function estimateTokens(transcript, turnId) {
41
+ const live = (item) => (item.turnId === turnId ? fileTokens(item) : 0);
39
42
  for (let index = transcript.length - 1; index >= 0; index--) {
40
43
  const entry = transcript[index];
41
44
  if (entry.kind !== "candidate" || !entry.candidate.usage)
@@ -48,9 +51,62 @@ export function estimateTokens(transcript) {
48
51
  (usage.outputTokens ?? 0);
49
52
  if (reported <= 0)
50
53
  continue;
51
- return reported + transcript.slice(index + 1).reduce((sum, item) => sum + entryTokens(item), 0);
54
+ const dropped = entry.turnId === turnId
55
+ ? 0
56
+ : transcript
57
+ .slice(0, index)
58
+ .reduce((sum, item) => sum + (item.turnId === entry.turnId ? fileTokens(item) : 0), 0);
59
+ return Math.max(0, reported -
60
+ dropped +
61
+ transcript.slice(index + 1).reduce((sum, item) => sum + entryTokens(item) + live(item), 0));
52
62
  }
53
- return transcript.reduce((sum, item) => sum + entryTokens(item), 0);
63
+ return transcript.reduce((sum, item) => sum + entryTokens(item) + live(item), 0);
64
+ }
65
+ /** Tokens per image, and the most one other file counts for, in the estimate. */
66
+ const IMAGE_TOKENS = 1_600;
67
+ const FILE_TOKENS_MAX = 100_000;
68
+ /** A rough token count of the files an entry names, as media: by type and size. */
69
+ function fileTokens(entry) {
70
+ return filesOf(entry).reduce((sum, { part }) => {
71
+ const size = mediaReferenceOf(part.reference)?.size ?? 0;
72
+ const type = part.mediaType.split(";")[0].trim().toLowerCase();
73
+ if (type.startsWith("image/"))
74
+ return sum + IMAGE_TOKENS;
75
+ if (isTextType(type))
76
+ return sum + Math.ceil(size / CHARS_PER_TOKEN);
77
+ return sum + Math.min(Math.ceil(size / 8), FILE_TOKENS_MAX);
78
+ }, 0);
79
+ }
80
+ function isTextType(type) {
81
+ return (type.startsWith("text/") ||
82
+ type.endsWith("+json") ||
83
+ type.endsWith("+xml") ||
84
+ [
85
+ "application/json",
86
+ "application/xml",
87
+ "application/yaml",
88
+ "application/x-yaml",
89
+ "application/javascript",
90
+ ].includes(type));
91
+ }
92
+ /** The files an entry names (protocol 12): a message's media parts, and a tool result's files. */
93
+ function filesOf(entry) {
94
+ if (entry.kind === "input") {
95
+ const event = entry.event;
96
+ if ((event.kind !== "user-message" && event.kind !== "interrupt") ||
97
+ !("content" in event) ||
98
+ !event.content)
99
+ return [];
100
+ return event.content.flatMap((part) => part.type === "media" ? [{ line: mediaReferenceLine(part, "uploaded"), part }] : []);
101
+ }
102
+ if (entry.kind === "tool-results")
103
+ return entry.results.flatMap((result) => result.kind === "completed" && result.files
104
+ ? result.files.map((part) => ({
105
+ line: mediaReferenceLine(part, { tool: result.toolName }),
106
+ part,
107
+ }))
108
+ : []);
109
+ return [];
54
110
  }
55
111
  /** A rough token count of what one entry contributes to a prompt. */
56
112
  export function entryTokens(entry) {
@@ -84,7 +140,7 @@ export function findCut(transcript, keepTokens) {
84
140
  */
85
141
  export async function compact(input) {
86
142
  const { transcript } = input;
87
- const tokensBefore = estimateTokens(transcript);
143
+ const tokensBefore = estimateTokens(transcript, input.turnId);
88
144
  const window = input.budget?.contextWindow ?? tokensBefore;
89
145
  const keepTokens = Math.max(1, Math.min(KEEP_TOKENS, Math.floor(window * KEEP_SHARE)));
90
146
  const cut = findCut(transcript, keepTokens);
@@ -98,6 +154,15 @@ export async function compact(input) {
98
154
  entry.turnId === input.turnId &&
99
155
  (entry.event.kind === "user-message" || entry.event.kind === "interrupt"));
100
156
  const tail = [...request, ...transcript.slice(cut)];
157
+ // The files the summarized part named stay readable by their reference lines (protocol 12).
158
+ const files = [
159
+ ...new Set([
160
+ ...(previous?.files ?? []),
161
+ ...older
162
+ .filter((entry) => !request.includes(entry))
163
+ .flatMap((entry) => filesOf(entry).map(({ line }) => line)),
164
+ ]),
165
+ ];
101
166
  const keptTokens = tail.reduce((sum, entry) => sum + entryTokens(entry), 0);
102
167
  const reserve = input.budget?.reserve ?? DEFAULT_RESERVE;
103
168
  const maxOutputTokens = Math.max(256, Math.floor(reserve * 0.8));
@@ -141,6 +206,7 @@ export async function compact(input) {
141
206
  trigger: input.trigger,
142
207
  tokensBefore,
143
208
  tokensAfter: keptTokens + Math.ceil(summary.length / CHARS_PER_TOKEN),
209
+ ...(files.length > 0 ? { files } : {}),
144
210
  };
145
211
  return Object.freeze([Object.freeze(entry), ...tail]);
146
212
  }
@@ -151,6 +217,7 @@ export function summaryPrompt(entry) {
151
217
  "<summary>",
152
218
  entry.summary,
153
219
  "</summary>",
220
+ ...(entry.files?.length ? ["Files in this session:", ...entry.files] : []),
154
221
  ].join("\n");
155
222
  }
156
223
  const SYSTEM = [
@@ -245,7 +312,7 @@ function entryText(entry, clip) {
245
312
  if (event.kind === "user-message" || event.kind === "interrupt")
246
313
  return `[User]: ${"content" in event && event.content
247
314
  ? event.content
248
- .map((part) => (part.type === "text" ? part.text : `[${part.mediaType}]`))
315
+ .map((part) => part.type === "text" ? part.text : mediaReferenceLine(part, "uploaded"))
249
316
  .join(" ")
250
317
  : (event.text ?? "")}`;
251
318
  if (event.kind === "approve")
@@ -269,7 +336,10 @@ function entryText(entry, clip) {
269
336
  case "tool-results":
270
337
  return entry.results
271
338
  .map((result) => result.kind === "completed"
272
- ? `[Tool ${result.toolName} result]: ${clipped(result.output, clip)}`
339
+ ? [
340
+ `[Tool ${result.toolName} result]: ${clipped(result.output, clip)}`,
341
+ ...(result.files ?? []).map((file) => mediaReferenceLine(file, { tool: result.toolName })),
342
+ ].join("\n")
273
343
  : result.kind === "denied"
274
344
  ? `[Tool ${result.toolName} denied]: ${result.reason ?? ""}`
275
345
  : `[Tool ${result.toolName} failed]: ${result.message}`)
@@ -70,7 +70,7 @@ export async function dispatchPlan(invocation) {
70
70
  callId: call.callId,
71
71
  invocationId: call.invocationId,
72
72
  toolName: call.toolName,
73
- middlewareId: call.reference.capabilityId,
73
+ partId: definition.owner.partId,
74
74
  slot: definition.owner.slot,
75
75
  };
76
76
  observe({ type: "tool.started", ...eventIds, attributes: { args: call.args } });
@@ -1,2 +1,8 @@
1
1
  import type { ModelCall, ModelRequest } from "@nylorun/core/define";
2
+ /**
3
+ * The model call for `request`. Every file in the transcript is its reference line (protocol 12),
4
+ * so a message projects the same in every later call. The files of the turn in progress (its
5
+ * messages, tool results and `read_artifact` loads) also go once, as media, in one user message
6
+ * after the conversation and the context: their bytes reach the model only in their own turn.
7
+ */
2
8
  export declare function projectModelCall(request: ModelRequest): ModelCall;
@@ -1,11 +1,29 @@
1
- import { copyJson, freezeGraph } from "@nylorun/core/define";
1
+ import { copyJson, freezeGraph, mediaReferenceLine, mediaReferenceOf } from "@nylorun/core/define";
2
2
  import { summaryPrompt } from "../compaction/index.js";
3
+ /**
4
+ * The model call for `request`. Every file in the transcript is its reference line (protocol 12),
5
+ * so a message projects the same in every later call. The files of the turn in progress (its
6
+ * messages, tool results and `read_artifact` loads) also go once, as media, in one user message
7
+ * after the conversation and the context: their bytes reach the model only in their own turn.
8
+ */
3
9
  export function projectModelCall(request) {
10
+ const live = new Map();
11
+ const collect = (entry, line, part) => {
12
+ if (entry.turnId !== request.turnId)
13
+ return;
14
+ const reference = mediaReferenceOf(part.reference);
15
+ const key = reference
16
+ ? `${reference.artifactId}@${reference.version}`
17
+ : JSON.stringify(part.reference);
18
+ if (!live.has(key))
19
+ live.set(key, { line, part });
20
+ };
4
21
  return freezeGraph({
5
22
  prompt: Object.freeze([
6
23
  ...projectInstructions(request.instructions),
7
- ...request.transcript.flatMap((entry) => projectEntry(entry, request.turnId)),
24
+ ...request.transcript.flatMap((entry) => projectEntry(entry, request.turnId, collect)),
8
25
  ...projectContext(request.context),
26
+ ...projectFiles([...live.values()]),
9
27
  ]),
10
28
  tools: Object.freeze(request.configuration.tools.map((tool) => Object.freeze({
11
29
  name: tool.name,
@@ -43,7 +61,29 @@ function renderContext(items) {
43
61
  "</runtime-context>",
44
62
  ].join("\n");
45
63
  }
46
- function projectEntry(entry, turnId) {
64
+ /** The files of the turn in progress, each labelled with its reference line. */
65
+ function projectFiles(files) {
66
+ if (files.length === 0)
67
+ return [];
68
+ return [
69
+ freezeItem({
70
+ kind: "message",
71
+ role: "user",
72
+ content: [
73
+ textPart("Files for this turn:"),
74
+ ...files.flatMap(({ line, part }) => [
75
+ textPart(line),
76
+ Object.freeze({
77
+ type: "media",
78
+ mediaType: part.mediaType,
79
+ reference: copyJson(part.reference),
80
+ }),
81
+ ]),
82
+ ],
83
+ }),
84
+ ];
85
+ }
86
+ function projectEntry(entry, turnId, collect) {
47
87
  if (entry.kind === "input") {
48
88
  if (entry.event.kind !== "user-message" && entry.event.kind !== "interrupt")
49
89
  return [];
@@ -52,13 +92,13 @@ function projectEntry(entry, turnId) {
52
92
  kind: "message",
53
93
  role: "user",
54
94
  content: "content" in entry.event
55
- ? entry.event.content.map((part) => part.type === "text"
56
- ? textPart(part.text)
57
- : Object.freeze({
58
- type: "media",
59
- mediaType: part.mediaType,
60
- reference: copyJson(part.reference),
61
- }))
95
+ ? entry.event.content.map((part) => {
96
+ if (part.type === "text")
97
+ return textPart(part.text);
98
+ const line = mediaReferenceLine(part, "uploaded");
99
+ collect(entry, line, part);
100
+ return textPart(line);
101
+ })
62
102
  : [textPart(entry.event.text)],
63
103
  }),
64
104
  ];
@@ -101,14 +141,14 @@ function projectEntry(entry, turnId) {
101
141
  ];
102
142
  }
103
143
  if (entry.kind === "tool-results")
104
- return entry.results.map(projectToolResult);
144
+ return entry.results.map((result) => projectToolResult(result, (line, part) => collect(entry, line, part)));
105
145
  if (entry.kind === "compaction")
106
146
  return [
107
147
  freezeItem({ kind: "message", role: "user", content: [textPart(summaryPrompt(entry))] }),
108
148
  ];
109
149
  return [];
110
150
  }
111
- function projectToolResult(result) {
151
+ function projectToolResult(result, collect) {
112
152
  return freezeItem({
113
153
  kind: "tool-result",
114
154
  toolCallId: result.callId,
@@ -116,13 +156,14 @@ function projectToolResult(result) {
116
156
  status: result.kind,
117
157
  content: [
118
158
  textPart(JSON.stringify(toolResultPayload(result))),
119
- // Images the tool returned, stored by the host (R2b C11): the model call resolves them.
159
+ // Files the tool returned, stored by the host (R2b C11): each is its reference line, and
160
+ // goes to the model in its own turn with the turn's files.
120
161
  ...(result.kind === "completed" && result.files
121
- ? result.files.map((file) => Object.freeze({
122
- type: "media",
123
- mediaType: file.mediaType,
124
- reference: copyJson(file.reference),
125
- }))
162
+ ? result.files.map((file) => {
163
+ const line = mediaReferenceLine(file, { tool: result.toolName });
164
+ collect(line, file);
165
+ return textPart(line);
166
+ })
126
167
  : []),
127
168
  ],
128
169
  });
package/dist/loop/run.js CHANGED
@@ -112,7 +112,7 @@ export async function execute(agent, options, internals = {}) {
112
112
  // Keep the next prompt inside the model's window, before it is sent.
113
113
  const budget = contextBudget(invocation.state.transcript);
114
114
  if (budget &&
115
- estimateTokens(invocation.state.transcript) > budget.contextWindow - budget.reserve)
115
+ estimateTokens(invocation.state.transcript, turnId) > budget.contextWindow - budget.reserve)
116
116
  await compactHistory("threshold", stepId);
117
117
  const snapshot = {
118
118
  id: invocation.state.executionId,
@@ -123,7 +123,7 @@ export async function execute(agent, options, internals = {}) {
123
123
  };
124
124
  const result = await runStep({
125
125
  agent: {
126
- middleware: agent.middleware,
126
+ parts: agent.parts,
127
127
  invoke: options.onModelCall,
128
128
  registry: agent.registry,
129
129
  sessionState: invocation.sessionBag,
@@ -36,7 +36,6 @@ const outcome = z.discriminatedUnion("kind", [
36
36
  ]);
37
37
  const reference = z
38
38
  .object({
39
- capabilityId: id,
40
39
  toolName: id,
41
40
  descriptor: z
42
41
  .object({
@@ -1,4 +1,4 @@
1
- import type { ModelCandidate, ModelOutputBlock, ModelToolCall } from "@nylorun/core/define";
1
+ import type { ModelCandidate, ModelOutputBlock } from "@nylorun/core/define";
2
2
  import type { JsonObject } from "@nylorun/core/define";
3
3
  export interface CanonicalCall {
4
4
  readonly id: string;
@@ -12,10 +12,8 @@ export declare function canonicalizeCalls(calls: readonly {
12
12
  readonly name?: string;
13
13
  readonly args: JsonObject;
14
14
  }[]): readonly CanonicalCall[];
15
- export declare function callsFromCanonical(calls: readonly CanonicalCall[]): readonly ModelToolCall[];
16
15
  export declare function canonicalizeOutput(output: readonly ModelOutputBlock[]): {
17
16
  readonly output: readonly ModelOutputBlock[];
18
17
  readonly calls: readonly CanonicalCall[];
19
18
  };
20
19
  export declare function candidateFromCanonical(candidate: ModelCandidate, output: readonly ModelOutputBlock[]): ModelCandidate;
21
- export declare function identityKey(name: string, args: unknown): string;
@@ -18,13 +18,6 @@ export function canonicalizeCalls(calls) {
18
18
  });
19
19
  }));
20
20
  }
21
- export function callsFromCanonical(calls) {
22
- return Object.freeze(calls.map((call) => Object.freeze({
23
- id: call.id,
24
- name: call.name,
25
- args: call.args,
26
- })));
27
- }
28
21
  export function canonicalizeOutput(output) {
29
22
  const calls = canonicalizeCalls(output.flatMap((block) => (block.type === "tool-call" ? [block] : [])));
30
23
  let index = 0;
@@ -55,11 +48,3 @@ export function candidateFromCanonical(candidate, output) {
55
48
  ...(candidate.evidence === undefined ? {} : { evidence: candidate.evidence }),
56
49
  });
57
50
  }
58
- export function identityKey(name, args) {
59
- try {
60
- return `${name}:${JSON.stringify(copyJson(args))}`;
61
- }
62
- catch {
63
- return `${name}:${String(args)}`;
64
- }
65
- }
@@ -1,19 +1,10 @@
1
1
  import type { InternalModelConfigurationSnapshot } from "./describe.js";
2
- import type { ModelConfigurationMutationOptions, ModelDirective } from "@nylorun/core/define";
2
+ import type { ModelConfigurationMutationOptions } from "@nylorun/core/define";
3
3
  import type { ToolDefinition } from "@nylorun/core/define";
4
- /** Per-step, middleware-owned model configuration draft. It never persists past the call. */
4
+ /** Per-step model configuration draft, set from the definition's parts. It never persists past the call. */
5
5
  export declare class ModelConfigurationDraft {
6
6
  #private;
7
- constructor(directive?: ModelDirective);
8
- setInstructions(middlewareId: string, middlewareOrder: number, slot: string, items: readonly string[], options?: ModelConfigurationMutationOptions): void;
9
- setTools(middlewareId: string, middlewareOrder: number, slot: string, tools: readonly ToolDefinition[], options?: ModelConfigurationMutationOptions): void;
10
- select(middlewareId: string, middlewareOrder: number, directive: ModelDirective, options?: Omit<ModelConfigurationMutationOptions, "order">): void;
11
- replace(middlewareId: string, middlewareOrder: number, directive: ModelDirective, options?: Omit<ModelConfigurationMutationOptions, "order">): void;
12
- /** Hide tools from this model call: every tool a capability contributed, or tools by name. */
13
- exclude(input: {
14
- readonly capabilities?: readonly string[];
15
- readonly tools?: readonly string[];
16
- }): void;
17
- clear(options?: Omit<ModelConfigurationMutationOptions, "order">): void;
7
+ setInstructions(partId: string, partOrder: number, slot: string, items: readonly string[], options?: ModelConfigurationMutationOptions): void;
8
+ setTools(partId: string, partOrder: number, slot: string, tools: readonly ToolDefinition[], options?: ModelConfigurationMutationOptions): void;
18
9
  snapshot(): InternalModelConfigurationSnapshot;
19
10
  }