@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
@@ -5,6 +5,7 @@ import type { ExecutionState, RunOptions } from "../types/execution.js";
5
5
  import type { ObserveEvent } from "@nylorun/core/define";
6
6
  import type { JsonValue } from "@nylorun/core/define";
7
7
  import { type ExecutionOutcomeEvent, type ObserveEmit } from "./observe.js";
8
+ import { type LoopConfig } from "./config.js";
8
9
  export interface Invocation {
9
10
  readonly agent: AgentDefinition;
10
11
  readonly options: RunOptions<any>;
@@ -14,6 +15,8 @@ export interface Invocation {
14
15
  readonly delegation?: DelegationHost;
15
16
  /** Set when this invocation is itself an agent used as a tool. */
16
17
  readonly delegated?: AgentRef;
18
+ /** The engine's loop settings, handed to the agents it uses as tools. */
19
+ readonly loop: LoopConfig;
17
20
  state: ExecutionState;
18
21
  /** Mutable durable session memory for this invocation. */
19
22
  sessionBag: Record<string, JsonValue>;
@@ -2,6 +2,7 @@ import { HarnessError } from "@nylorun/core/define";
2
2
  import { copyJson } from "@nylorun/core/define";
3
3
  import { createId } from "../utils/ids.js";
4
4
  import { createObservationSink } from "./observe.js";
5
+ import { DEFAULT_LOOP_CONFIG } from "./config.js";
5
6
  export function createInvocation(input) {
6
7
  const invocation = {
7
8
  agent: input.agent,
@@ -10,6 +11,7 @@ export function createInvocation(input) {
10
11
  definitions: input.definitions,
11
12
  ...(input.internals?.delegation ? { delegation: input.internals.delegation } : {}),
12
13
  ...(input.internals?.delegated ? { delegated: input.internals.delegated } : {}),
14
+ loop: input.internals?.loop ?? DEFAULT_LOOP_CONFIG,
13
15
  state: input.state,
14
16
  sessionBag: { ...(input.state.state ?? {}) },
15
17
  };
@@ -0,0 +1,77 @@
1
+ import { type JsonValue, type MediaReference, type PromptContentPart } from "@nylorun/core/define";
2
+ import { type ArtifactMeta, type ModelDescriptor, type RuntimeLimits } from "@nylorun/core/harness-api";
3
+ /**
4
+ * The first line of the user message that carries the turn's files, last in the prompt
5
+ * (`projectModelCall`). A model that reads the user's last words (the fixture model) skips it.
6
+ */
7
+ export declare const FILES_MESSAGE_HEADER = "Files for this turn:";
8
+ /** A media part: its declared type and the reference the Runtime made (`MediaReference`). */
9
+ export interface FilePart {
10
+ readonly mediaType: string;
11
+ readonly reference: JsonValue;
12
+ }
13
+ /** How one file reaches the model. */
14
+ export type FileView =
15
+ /** The part goes as it is: the Model Gate fetches the artifact and sends it natively. */
16
+ {
17
+ readonly kind: "media";
18
+ }
19
+ /** The harness reads it with `artifact.read` and inlines it as a `<file>` block. */
20
+ | {
21
+ readonly kind: "text";
22
+ }
23
+ /** The model is told why it does not see the file. */
24
+ | {
25
+ readonly kind: "note";
26
+ readonly why: string;
27
+ };
28
+ /** What `fileView` decides from: the turn's model and the Runtime limits. */
29
+ export interface FileViewContext {
30
+ /** `turn.start.model`; undefined when the Runtime sent none. */
31
+ readonly model?: ModelDescriptor;
32
+ readonly limits: Pick<RuntimeLimits, "modelFileBytes">;
33
+ }
34
+ /** One answer of the artifact seam, as `representFiles` reads it. */
35
+ export interface FileChunk {
36
+ readonly artifact: ArtifactMeta;
37
+ readonly bytes: Uint8Array;
38
+ readonly eof: boolean;
39
+ }
40
+ /** What `representFiles` needs: the decision's inputs, and the run's artifact reads. */
41
+ export interface FileContext extends FileViewContext {
42
+ readonly limits: Pick<RuntimeLimits, "modelFileBytes" | "modelCallBytes" | "chunkBytes">;
43
+ /**
44
+ * Reads `length` bytes of the artifact version from `offset` (`artifact.read`). A refusal of
45
+ * the seam (`HarnessApiError`) becomes a note; any other error is the run's.
46
+ */
47
+ read(reference: MediaReference, offset: number, length: number, signal?: AbortSignal): Promise<FileChunk>;
48
+ }
49
+ /** How the file `part` names reaches a model that reads `model.inputs`. */
50
+ export declare function fileView(part: FilePart, model: ModelDescriptor | undefined, limits: Pick<RuntimeLimits, "modelFileBytes">): FileView;
51
+ /** A text file as the model reads it. `type` is the media type without parameters. */
52
+ export declare function fileBlock(name: string, type: string, text: string): string;
53
+ /** Why the model does not see a file, in the prompt where the file would be. */
54
+ export declare function fileNote(name: string, type: string, why: string): string;
55
+ /**
56
+ * The line a file stands for in a prompt (protocol 12): its name, artifact id and version, and
57
+ * how the model reads it again. A file a tool returned names the tool. Every file is its line
58
+ * once its turn is over; in its own turn the line labels what follows it.
59
+ */
60
+ export declare function mediaReferenceLine(part: FilePart, origin: "uploaded" | {
61
+ readonly tool: string;
62
+ }): string;
63
+ /** A file of the turn in progress: its key (artifact and version), reference line and part. */
64
+ export interface LiveFile {
65
+ readonly key: string;
66
+ readonly line: string;
67
+ readonly part: FilePart;
68
+ }
69
+ /** The key a file goes by in one call: its artifact version, or its reference. */
70
+ export declare function fileKeyOf(part: FilePart): string;
71
+ /**
72
+ * What each live file becomes in the model call, by key: the media part, a `<file>` block, or
73
+ * a note. Text is read over the artifact seam, strictly as UTF-8, and inlined while the files
74
+ * inlined so far stay within `limits.modelCallBytes`; past it a file is a note. Without a
75
+ * context (a local run), every file goes as its media part and the adapter decides.
76
+ */
77
+ export declare function representFiles(files: readonly LiveFile[], context: FileContext | undefined, signal?: AbortSignal): Promise<ReadonlyMap<string, readonly PromptContentPart[]>>;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * How each file reaches the model (protocol 15): the harness decides, not the Model Gate. A file
3
+ * of the turn in progress (a message's media part, a file a tool returned, a `read_artifact`
4
+ * load) goes as one of three:
5
+ *
6
+ * - `media`: the media part itself, an artifact reference the Model Gate fetches and sends in
7
+ * the provider's own block (an image, a PDF, an Office document, audio, video the model reads);
8
+ * - `text`: the file's text, read here over the artifact seam (`artifact.read`) and inlined as a
9
+ * `<file>` block;
10
+ * - `note`: a line saying why the model does not see it, which we write.
11
+ *
12
+ * `fileView` decides from the model descriptor (`turn.start.model`) and the Runtime limits
13
+ * (`turn.start.limits`); without a descriptor the model is taken to read text and images. A
14
+ * harness of its own may use these as they are, or decide otherwise: the gate refuses only what
15
+ * the provider cannot take (`unsupported_input`).
16
+ */
17
+ import { essence, inputLabel, isModelImage, isText, modelInputOf, } from "@nylorun/core/contracts";
18
+ import { copyJson, mediaReferenceOf, } from "@nylorun/core/define";
19
+ import { HarnessApiError, } from "@nylorun/core/harness-api";
20
+ /**
21
+ * The first line of the user message that carries the turn's files, last in the prompt
22
+ * (`projectModelCall`). A model that reads the user's last words (the fixture model) skips it.
23
+ */
24
+ export const FILES_MESSAGE_HEADER = "Files for this turn:";
25
+ /** What a model reads when the Runtime sent no descriptor (a scripted provider, say). */
26
+ const FALLBACK_INPUTS = Object.freeze(["text", "image"]);
27
+ /** How the file `part` names reaches a model that reads `model.inputs`. */
28
+ export function fileView(part, model, limits) {
29
+ const size = mediaReferenceOf(part.reference)?.size;
30
+ if (size !== undefined && size > limits.modelFileBytes)
31
+ return note(`it is larger than the ${limits.modelFileBytes} bytes a model call carries`);
32
+ if (isText(part.mediaType))
33
+ return { kind: "text" };
34
+ const inputs = model?.inputs ?? FALLBACK_INPUTS;
35
+ const kind = modelInputOf(part.mediaType);
36
+ if (kind === undefined)
37
+ return note(`no model reads ${essence(part.mediaType)} files`);
38
+ if (!inputs.includes(kind))
39
+ return note(`this model does not read ${inputLabel(kind)}`);
40
+ if (kind === "image" && !isModelImage(part.mediaType))
41
+ return note("the model reads PNG, JPEG, GIF and WebP images only");
42
+ return { kind: "media" };
43
+ }
44
+ const note = (why) => ({ kind: "note", why });
45
+ /** A text file as the model reads it. `type` is the media type without parameters. */
46
+ export function fileBlock(name, type, text) {
47
+ return `<file name=${JSON.stringify(name)} type=${JSON.stringify(type)}>\n${text}\n</file>`;
48
+ }
49
+ /** Why the model does not see a file, in the prompt where the file would be. */
50
+ export function fileNote(name, type, why) {
51
+ return `(File ${JSON.stringify(name)}, ${type}, is not shown: ${why}.)`;
52
+ }
53
+ /**
54
+ * The line a file stands for in a prompt (protocol 12): its name, artifact id and version, and
55
+ * how the model reads it again. A file a tool returned names the tool. Every file is its line
56
+ * once its turn is over; in its own turn the line labels what follows it.
57
+ */
58
+ export function mediaReferenceLine(part, origin) {
59
+ const reference = mediaReferenceOf(part.reference);
60
+ const what = origin === "uploaded" ? "Uploaded artifact" : `Tool ${origin.tool} returned artifact`;
61
+ if (!reference)
62
+ return `[${what} (${part.mediaType})]`;
63
+ const name = JSON.stringify(reference.name ?? reference.artifactId);
64
+ return `[${what} ${name} · ${reference.artifactId} v${reference.version} · read_artifact to view]`;
65
+ }
66
+ /** The key a file goes by in one call: its artifact version, or its reference. */
67
+ export function fileKeyOf(part) {
68
+ const reference = mediaReferenceOf(part.reference);
69
+ return reference
70
+ ? `${reference.artifactId}@${reference.version}`
71
+ : JSON.stringify(part.reference);
72
+ }
73
+ /**
74
+ * What each live file becomes in the model call, by key: the media part, a `<file>` block, or
75
+ * a note. Text is read over the artifact seam, strictly as UTF-8, and inlined while the files
76
+ * inlined so far stay within `limits.modelCallBytes`; past it a file is a note. Without a
77
+ * context (a local run), every file goes as its media part and the adapter decides.
78
+ */
79
+ export async function representFiles(files, context, signal) {
80
+ const out = new Map();
81
+ let inlined = 0;
82
+ for (const file of files) {
83
+ if (out.has(file.key))
84
+ continue;
85
+ const view = context
86
+ ? fileView(file.part, context.model, context.limits)
87
+ : { kind: "media" };
88
+ if (view.kind === "media") {
89
+ out.set(file.key, [mediaPart(file.part)]);
90
+ continue;
91
+ }
92
+ if (view.kind === "note") {
93
+ out.set(file.key, [textPart(noteFor(file.part, view.why))]);
94
+ continue;
95
+ }
96
+ const read = await readText(file.part, context, context.limits.modelCallBytes - inlined, signal);
97
+ if (read.kind === "note") {
98
+ out.set(file.key, [textPart(fileNote(read.name, read.type, read.why))]);
99
+ continue;
100
+ }
101
+ inlined += read.bytes;
102
+ out.set(file.key, [textPart(fileBlock(read.name, read.type, read.text))]);
103
+ }
104
+ return out;
105
+ }
106
+ /** A text file's bytes, a chunk at a time, decoded strictly; or why it cannot be inlined. */
107
+ async function readText(part, context, room, signal) {
108
+ const reference = mediaReferenceOf(part.reference);
109
+ let name = reference?.name ?? reference?.artifactId ?? "file";
110
+ let type = essence(part.mediaType);
111
+ const refused = (why) => ({ kind: "note", name, type, why });
112
+ if (!reference)
113
+ return refused("it is not an artifact this harness can read");
114
+ const { modelFileBytes, chunkBytes } = context.limits;
115
+ const chunks = [];
116
+ let offset = 0;
117
+ try {
118
+ for (;;) {
119
+ const chunk = await context.read(reference, offset, chunkBytes, signal);
120
+ name = chunk.artifact.name;
121
+ type = essence(chunk.artifact.contentType);
122
+ if (chunk.artifact.kind !== "file")
123
+ return refused("it is a folder");
124
+ if (chunk.artifact.size > modelFileBytes)
125
+ return refused(`it is larger than the ${modelFileBytes} bytes a model call carries`);
126
+ if (chunk.artifact.size > room)
127
+ return refused(`inlined with this turn's other files, it would pass the ${context.limits.modelCallBytes} bytes a model call carries`);
128
+ if (chunk.bytes.byteLength > 0)
129
+ chunks.push(chunk.bytes);
130
+ offset += chunk.bytes.byteLength;
131
+ if (chunk.eof || chunk.bytes.byteLength === 0)
132
+ break;
133
+ }
134
+ }
135
+ catch (error) {
136
+ if (!(error instanceof HarnessApiError))
137
+ throw error;
138
+ return refused(error.message.replace(/\.$/u, ""));
139
+ }
140
+ const bytes = new Uint8Array(offset);
141
+ let at = 0;
142
+ for (const chunk of chunks) {
143
+ bytes.set(chunk, at);
144
+ at += chunk.byteLength;
145
+ }
146
+ try {
147
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
148
+ return { kind: "text", name, type, text, bytes: offset };
149
+ }
150
+ catch {
151
+ return refused("it is not UTF-8 text");
152
+ }
153
+ }
154
+ /** A note for a file decided before it was read: named by its reference. */
155
+ function noteFor(part, why) {
156
+ const reference = mediaReferenceOf(part.reference);
157
+ return fileNote(reference?.name ?? reference?.artifactId ?? "file", essence(part.mediaType), why);
158
+ }
159
+ function mediaPart(part) {
160
+ return Object.freeze({
161
+ type: "media",
162
+ mediaType: part.mediaType,
163
+ reference: copyJson(part.reference),
164
+ });
165
+ }
166
+ function textPart(text) {
167
+ return Object.freeze({ type: "text", text });
168
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The structured answer (protocol 15): with an output schema, the engine reads the model's
3
+ * final text as JSON. The Model Gate passes the model's text through; the instruction to answer
4
+ * in JSON (`schemaInstruction`) and the parse are ours.
5
+ *
6
+ * `repairJson` and `parseJsonWithRepair` are adapted from `utils/json-parse` in pi's `pi-ai`
7
+ * (MIT, Copyright (c) Earendil Works).
8
+ */
9
+ import { type ModelCandidate } from "@nylorun/core/define";
10
+ /**
11
+ * The candidate as the turn's structured answer. With `schema`, an answer that calls no tool and
12
+ * has no `json` block is its text blocks, joined, without one Markdown code fence, parsed as
13
+ * JSON (raw control characters and bad escapes in strings repaired): one `json` block, after
14
+ * the reasoning blocks. Text that is not JSON throws `model.invalid_output`. Without `schema`,
15
+ * or for a candidate that already holds a `json` block or a tool call, it is unchanged.
16
+ */
17
+ export declare function structuredAnswer(candidate: ModelCandidate, schema: unknown | undefined): ModelCandidate;
18
+ /** Open-weight models often wrap a JSON answer in a Markdown code fence. */
19
+ export declare function withoutCodeFence(text: string): string;
20
+ /**
21
+ * Repairs malformed JSON string literals: escapes raw control characters inside strings, and
22
+ * doubles a backslash before a character JSON does not escape.
23
+ */
24
+ export declare function repairJson(json: string): string;
25
+ /** `JSON.parse`, and on failure once more after `repairJson`; the first error if nothing changed. */
26
+ export declare function parseJsonWithRepair(json: string): unknown;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The structured answer (protocol 15): with an output schema, the engine reads the model's
3
+ * final text as JSON. The Model Gate passes the model's text through; the instruction to answer
4
+ * in JSON (`schemaInstruction`) and the parse are ours.
5
+ *
6
+ * `repairJson` and `parseJsonWithRepair` are adapted from `utils/json-parse` in pi's `pi-ai`
7
+ * (MIT, Copyright (c) Earendil Works).
8
+ */
9
+ import { HarnessError, } from "@nylorun/core/define";
10
+ /**
11
+ * The candidate as the turn's structured answer. With `schema`, an answer that calls no tool and
12
+ * has no `json` block is its text blocks, joined, without one Markdown code fence, parsed as
13
+ * JSON (raw control characters and bad escapes in strings repaired): one `json` block, after
14
+ * the reasoning blocks. Text that is not JSON throws `model.invalid_output`. Without `schema`,
15
+ * or for a candidate that already holds a `json` block or a tool call, it is unchanged.
16
+ */
17
+ export function structuredAnswer(candidate, schema) {
18
+ if (schema === undefined)
19
+ return candidate;
20
+ const { output } = candidate;
21
+ if (output.some((block) => block.type === "tool-call" || block.type === "json"))
22
+ return candidate;
23
+ const text = output
24
+ .filter((block) => block.type === "text")
25
+ .map((block) => block.text)
26
+ .join("");
27
+ let value;
28
+ try {
29
+ value = parseJsonWithRepair(withoutCodeFence(text));
30
+ }
31
+ catch (error) {
32
+ throw new HarnessError("model.invalid_output", `The model's final answer is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
33
+ }
34
+ return Object.freeze({
35
+ ...candidate,
36
+ output: Object.freeze([
37
+ ...output.filter((block) => block.type === "reasoning"),
38
+ Object.freeze({ type: "json", value }),
39
+ ]),
40
+ });
41
+ }
42
+ /** Open-weight models often wrap a JSON answer in a Markdown code fence. */
43
+ export function withoutCodeFence(text) {
44
+ const fenced = /^\s*```[a-zA-Z]*\s*\n([\s\S]*?)\n?```\s*$/.exec(text);
45
+ return fenced ? fenced[1] : text;
46
+ }
47
+ const VALID_JSON_ESCAPES = new Set(['"', "\\", "/", "b", "f", "n", "r", "t", "u"]);
48
+ function isControlCharacter(char) {
49
+ const codePoint = char.codePointAt(0);
50
+ return codePoint !== undefined && codePoint >= 0x00 && codePoint <= 0x1f;
51
+ }
52
+ function escapeControlCharacter(char) {
53
+ switch (char) {
54
+ case "\b":
55
+ return "\\b";
56
+ case "\f":
57
+ return "\\f";
58
+ case "\n":
59
+ return "\\n";
60
+ case "\r":
61
+ return "\\r";
62
+ case "\t":
63
+ return "\\t";
64
+ default:
65
+ return `\\u${char.codePointAt(0)?.toString(16).padStart(4, "0") ?? "0000"}`;
66
+ }
67
+ }
68
+ /**
69
+ * Repairs malformed JSON string literals: escapes raw control characters inside strings, and
70
+ * doubles a backslash before a character JSON does not escape.
71
+ */
72
+ export function repairJson(json) {
73
+ let repaired = "";
74
+ let inString = false;
75
+ for (let index = 0; index < json.length; index++) {
76
+ const char = json[index];
77
+ if (!inString) {
78
+ repaired += char;
79
+ if (char === '"')
80
+ inString = true;
81
+ continue;
82
+ }
83
+ if (char === '"') {
84
+ repaired += char;
85
+ inString = false;
86
+ continue;
87
+ }
88
+ if (char === "\\") {
89
+ const nextChar = json[index + 1];
90
+ if (nextChar === undefined) {
91
+ repaired += "\\\\";
92
+ continue;
93
+ }
94
+ if (nextChar === "u") {
95
+ const unicodeDigits = json.slice(index + 2, index + 6);
96
+ if (/^[0-9a-fA-F]{4}$/.test(unicodeDigits)) {
97
+ repaired += `\\u${unicodeDigits}`;
98
+ index += 5;
99
+ continue;
100
+ }
101
+ }
102
+ if (VALID_JSON_ESCAPES.has(nextChar)) {
103
+ repaired += `\\${nextChar}`;
104
+ index += 1;
105
+ continue;
106
+ }
107
+ repaired += "\\\\";
108
+ continue;
109
+ }
110
+ repaired += isControlCharacter(char) ? escapeControlCharacter(char) : char;
111
+ }
112
+ return repaired;
113
+ }
114
+ /** `JSON.parse`, and on failure once more after `repairJson`; the first error if nothing changed. */
115
+ export function parseJsonWithRepair(json) {
116
+ try {
117
+ return JSON.parse(json);
118
+ }
119
+ catch (error) {
120
+ const repaired = repairJson(json);
121
+ if (repaired !== json)
122
+ return JSON.parse(repaired);
123
+ throw error;
124
+ }
125
+ }
@@ -1,8 +1,18 @@
1
- import type { ModelCall, ModelRequest } from "@nylorun/core/define";
1
+ import type { ModelCall, PromptContentPart, ModelRequest } from "@nylorun/core/define";
2
+ import { type LiveFile } from "./files.js";
2
3
  /**
3
4
  * The model call for `request`. Every file in the transcript is its reference line (protocol 12),
4
5
  * 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.
6
+ * messages, tool results and `read_artifact` loads) also go once, after the conversation and
7
+ * the context, in one user message: each file's line, then what `files` (`representFiles`)
8
+ * made of it, a media part, a `<file>` block or a note. Without `files`, each goes as its media
9
+ * part. Their content reaches the model only in their own turn.
7
10
  */
8
- export declare function projectModelCall(request: ModelRequest): ModelCall;
11
+ export declare function projectModelCall(request: ModelRequest, files?: ReadonlyMap<string, readonly PromptContentPart[]>): ModelCall;
12
+ /**
13
+ * The files of the turn in progress, in the order the prompt names them, once each: a user
14
+ * message's media parts and the files its tool results returned.
15
+ */
16
+ export declare function liveFilesOf(request: ModelRequest): LiveFile[];
17
+ /** What a turn with an output schema asks of the model's final answer. */
18
+ export declare function schemaInstruction(schema: NonNullable<ModelRequest["outputSchema"]>): string;
@@ -1,29 +1,21 @@
1
- import { copyJson, freezeGraph, mediaReferenceLine, mediaReferenceOf } from "@nylorun/core/define";
1
+ import { copyJson, freezeGraph } from "@nylorun/core/define";
2
2
  import { summaryPrompt } from "../compaction/index.js";
3
+ import { FILES_MESSAGE_HEADER, fileKeyOf, mediaReferenceLine, } from "./files.js";
3
4
  /**
4
5
  * The model call for `request`. Every file in the transcript is its reference line (protocol 12),
5
6
  * 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.
7
+ * messages, tool results and `read_artifact` loads) also go once, after the conversation and
8
+ * the context, in one user message: each file's line, then what `files` (`representFiles`)
9
+ * made of it, a media part, a `<file>` block or a note. Without `files`, each goes as its media
10
+ * part. Their content reaches the model only in their own turn.
8
11
  */
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
- };
12
+ export function projectModelCall(request, files) {
21
13
  return freezeGraph({
22
14
  prompt: Object.freeze([
23
- ...projectInstructions(request.instructions),
24
- ...request.transcript.flatMap((entry) => projectEntry(entry, request.turnId, collect)),
15
+ ...projectInstructions(request.instructions, request.outputSchema),
16
+ ...request.transcript.flatMap((entry) => projectEntry(entry, request.turnId)),
25
17
  ...projectContext(request.context),
26
- ...projectFiles([...live.values()]),
18
+ ...projectFiles(liveFilesOf(request), files),
27
19
  ]),
28
20
  tools: Object.freeze(request.configuration.tools.map((tool) => Object.freeze({
29
21
  name: tool.name,
@@ -31,16 +23,56 @@ export function projectModelCall(request) {
31
23
  inputSchema: copyJson(tool.inputSchema.jsonSchema),
32
24
  }))),
33
25
  ...(request.model === undefined ? {} : { model: copyJson(request.model) }),
34
- ...(request.outputSchema === undefined ? {} : { outputSchema: copyJson(request.outputSchema) }),
35
26
  executionId: request.executionId,
36
27
  });
37
28
  }
38
- function projectInstructions(instructions) {
39
- const text = instructions.join("\n\n");
29
+ /**
30
+ * The files of the turn in progress, in the order the prompt names them, once each: a user
31
+ * message's media parts and the files its tool results returned.
32
+ */
33
+ export function liveFilesOf(request) {
34
+ const live = new Map();
35
+ const add = (line, part) => {
36
+ const key = fileKeyOf(part);
37
+ if (!live.has(key))
38
+ live.set(key, { key, line, part });
39
+ };
40
+ for (const entry of request.transcript) {
41
+ if (entry.turnId !== request.turnId)
42
+ continue;
43
+ if (entry.kind === "input") {
44
+ const event = entry.event;
45
+ if ((event.kind !== "user-message" && event.kind !== "interrupt") || !("content" in event))
46
+ continue;
47
+ for (const part of event.content ?? [])
48
+ if (part.type === "media")
49
+ add(mediaReferenceLine(part, "uploaded"), part);
50
+ }
51
+ else if (entry.kind === "tool-results")
52
+ for (const result of entry.results)
53
+ if (result.kind === "completed")
54
+ for (const file of result.files ?? [])
55
+ add(mediaReferenceLine(file, { tool: result.toolName }), file);
56
+ }
57
+ return [...live.values()];
58
+ }
59
+ /**
60
+ * The instructions, as one system text. With an output schema, our instruction to answer in
61
+ * JSON goes last, on its own line.
62
+ */
63
+ function projectInstructions(instructions, outputSchema) {
64
+ const text = [
65
+ ...(instructions.length > 0 ? [instructions.join("\n\n")] : []),
66
+ ...(outputSchema === undefined ? [] : [schemaInstruction(outputSchema)]),
67
+ ].join("\n");
40
68
  if (text === "")
41
69
  return [];
42
70
  return [freezeItem({ kind: "instructions", role: "system", content: [textPart(text)] })];
43
71
  }
72
+ /** What a turn with an output schema asks of the model's final answer. */
73
+ export function schemaInstruction(schema) {
74
+ return `Return the final answer as JSON matching this schema: ${JSON.stringify(schema)}. Use tools when needed before returning the final JSON.`;
75
+ }
44
76
  function projectContext(context) {
45
77
  if (context.items.length === 0)
46
78
  return [];
@@ -61,8 +93,8 @@ function renderContext(items) {
61
93
  "</runtime-context>",
62
94
  ].join("\n");
63
95
  }
64
- /** The files of the turn in progress, each labelled with its reference line. */
65
- function projectFiles(files) {
96
+ /** The files of the turn in progress, each its reference line and then what it became. */
97
+ function projectFiles(files, represented) {
66
98
  if (files.length === 0)
67
99
  return [];
68
100
  return [
@@ -70,20 +102,22 @@ function projectFiles(files) {
70
102
  kind: "message",
71
103
  role: "user",
72
104
  content: [
73
- textPart("Files for this turn:"),
74
- ...files.flatMap(({ line, part }) => [
105
+ textPart(FILES_MESSAGE_HEADER),
106
+ ...files.flatMap(({ key, line, part }) => [
75
107
  textPart(line),
76
- Object.freeze({
77
- type: "media",
78
- mediaType: part.mediaType,
79
- reference: copyJson(part.reference),
80
- }),
108
+ ...(represented?.get(key) ?? [
109
+ Object.freeze({
110
+ type: "media",
111
+ mediaType: part.mediaType,
112
+ reference: copyJson(part.reference),
113
+ }),
114
+ ]),
81
115
  ]),
82
116
  ],
83
117
  }),
84
118
  ];
85
119
  }
86
- function projectEntry(entry, turnId, collect) {
120
+ function projectEntry(entry, turnId) {
87
121
  if (entry.kind === "input") {
88
122
  if (entry.event.kind !== "user-message" && entry.event.kind !== "interrupt")
89
123
  return [];
@@ -95,9 +129,7 @@ function projectEntry(entry, turnId, collect) {
95
129
  ? entry.event.content.map((part) => {
96
130
  if (part.type === "text")
97
131
  return textPart(part.text);
98
- const line = mediaReferenceLine(part, "uploaded");
99
- collect(entry, line, part);
100
- return textPart(line);
132
+ return textPart(mediaReferenceLine(part, "uploaded"));
101
133
  })
102
134
  : [textPart(entry.event.text)],
103
135
  }),
@@ -141,14 +173,14 @@ function projectEntry(entry, turnId, collect) {
141
173
  ];
142
174
  }
143
175
  if (entry.kind === "tool-results")
144
- return entry.results.map((result) => projectToolResult(result, (line, part) => collect(entry, line, part)));
176
+ return entry.results.map(projectToolResult);
145
177
  if (entry.kind === "compaction")
146
178
  return [
147
179
  freezeItem({ kind: "message", role: "user", content: [textPart(summaryPrompt(entry))] }),
148
180
  ];
149
181
  return [];
150
182
  }
151
- function projectToolResult(result, collect) {
183
+ function projectToolResult(result) {
152
184
  return freezeItem({
153
185
  kind: "tool-result",
154
186
  toolCallId: result.callId,
@@ -159,11 +191,7 @@ function projectToolResult(result, collect) {
159
191
  // Files the tool returned, stored by the host (R2b C11): each is its reference line, and
160
192
  // goes to the model in its own turn with the turn's files.
161
193
  ...(result.kind === "completed" && result.files
162
- ? result.files.map((file) => {
163
- const line = mediaReferenceLine(file, { tool: result.toolName });
164
- collect(line, file);
165
- return textPart(line);
166
- })
194
+ ? result.files.map((file) => textPart(mediaReferenceLine(file, { tool: result.toolName })))
167
195
  : []),
168
196
  ],
169
197
  });
@@ -11,6 +11,8 @@ const acceptedOptions = new Set([
11
11
  "signal",
12
12
  "onEvent",
13
13
  "record",
14
+ "model",
15
+ "files",
14
16
  ]);
15
17
  export function validateRunOptions(options) {
16
18
  if (!options || typeof options.onModelCall !== "function")