@nylorun/core 0.22.0-beta → 0.24.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 (82) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +1 -1
  3. package/dist/compatibility.d.ts +120 -47
  4. package/dist/compatibility.js +122 -49
  5. package/dist/contracts.d.ts +2824 -907
  6. package/dist/contracts.js +1286 -585
  7. package/dist/define.d.ts +9 -12
  8. package/dist/define.js +8 -11
  9. package/dist/definition/assemble.d.ts +1 -3
  10. package/dist/definition/assemble.js +4 -8
  11. package/dist/definition/bound.d.ts +1 -1
  12. package/dist/definition/delegate.d.ts +5 -0
  13. package/dist/definition/delegate.js +6 -1
  14. package/dist/definition/from.d.ts +4 -2
  15. package/dist/definition/from.js +11 -29
  16. package/dist/definition/http-tool.d.ts +5 -3
  17. package/dist/definition/http-tool.js +8 -5
  18. package/dist/definition/manifest.d.ts +7 -6
  19. package/dist/definition/manifest.js +7 -6
  20. package/dist/definition/mcp.d.ts +1 -1
  21. package/dist/definition/media-reference.d.ts +2 -11
  22. package/dist/definition/media-reference.js +0 -12
  23. package/dist/definition/model-failure.js +1 -0
  24. package/dist/definition/removed.d.ts +7 -0
  25. package/dist/definition/removed.js +21 -0
  26. package/dist/definition/sections.d.ts +63 -0
  27. package/dist/definition/sections.js +204 -0
  28. package/dist/definition/trace.d.ts +0 -7
  29. package/dist/definition/trace.js +0 -34
  30. package/dist/definition/variant.d.ts +1 -1
  31. package/dist/definition/variant.js +1 -3
  32. package/dist/harness-api/artifacts.d.ts +84 -0
  33. package/dist/harness-api/artifacts.js +128 -0
  34. package/dist/harness-api/gates.d.ts +0 -4
  35. package/dist/harness-api/gates.js +0 -4
  36. package/dist/harness-api/harness-api.schema.json +2798 -1124
  37. package/dist/harness-api/index.d.ts +9 -6
  38. package/dist/harness-api/index.js +9 -6
  39. package/dist/harness-api/json-schema.js +5 -2
  40. package/dist/harness-api/mcp.d.ts +77 -30
  41. package/dist/harness-api/mcp.js +42 -25
  42. package/dist/harness-api/messages.d.ts +47 -17
  43. package/dist/harness-api/messages.js +20 -5
  44. package/dist/harness-api/schema.d.ts +609 -200
  45. package/dist/harness-api/schema.js +345 -62
  46. package/dist/harness-api/transcript.d.ts +8 -10
  47. package/dist/harness-api/transcript.js +27 -11
  48. package/dist/harness-api/transport.d.ts +7 -1
  49. package/dist/harness-api/transport.js +10 -7
  50. package/dist/manifest-schemas.d.ts +9 -5
  51. package/dist/manifest-schemas.js +23 -27
  52. package/dist/schemas/agent-manifest.schema.json +1508 -365
  53. package/dist/schemas/harness-manifest.schema.json +1273 -0
  54. package/dist/schemas/{environment-manifest.schema.json → runtime-manifest.schema.json} +165 -84
  55. package/dist/types/manifest.d.ts +72 -14
  56. package/dist/types/manifest.js +4 -0
  57. package/dist/types/model.d.ts +15 -5
  58. package/dist/utils/definition-files.d.ts +20 -6
  59. package/dist/utils/definition-files.js +31 -17
  60. package/dist/utils/file-systems.d.ts +20 -0
  61. package/dist/utils/file-systems.js +20 -0
  62. package/dist/utils/harness-id.d.ts +4 -1
  63. package/dist/utils/harness-id.js +4 -1
  64. package/dist/utils/media-types.d.ts +30 -0
  65. package/dist/utils/media-types.js +128 -0
  66. package/dist/utils/memory.d.ts +64 -0
  67. package/dist/utils/memory.js +139 -0
  68. package/dist/utils/runtime-limits.d.ts +280 -0
  69. package/dist/utils/runtime-limits.js +585 -0
  70. package/dist/utils/runtime-tools.d.ts +8 -16
  71. package/dist/utils/runtime-tools.js +8 -27
  72. package/dist/utils/sandbox.d.ts +4 -1
  73. package/dist/utils/sandbox.js +4 -1
  74. package/package.json +6 -5
  75. package/dist/definition/deferred-tools.d.ts +0 -27
  76. package/dist/definition/deferred-tools.js +0 -82
  77. package/dist/definition/runtime-manifest.d.ts +0 -30
  78. package/dist/definition/runtime-manifest.js +0 -132
  79. package/dist/definition/sandbox-tools.d.ts +0 -5
  80. package/dist/definition/sandbox-tools.js +0 -109
  81. package/dist/definition/skill-tools.d.ts +0 -23
  82. package/dist/definition/skill-tools.js +0 -76
@@ -0,0 +1,204 @@
1
+ import { DEFAULT_HARNESS } from "../utils/harness-id.js";
2
+ export function isWorkflowHarness(harness) {
3
+ return harness.kind === "workflow";
4
+ }
5
+ /** The harness that runs the loop: `harness.id`, else ours. */
6
+ export function harnessIdOf(harness) {
7
+ return harness.id ?? DEFAULT_HARNESS;
8
+ }
9
+ /** Whether a loop manifest, or any agent it embeds or delegates to, carries skills. */
10
+ function hasSkills(manifest) {
11
+ if ("kind" in manifest)
12
+ return Object.values(manifest.agents).some(hasSkills);
13
+ if (Object.keys(manifest.skills ?? {}).length > 0)
14
+ return true;
15
+ return (manifest.tools ?? []).some((tool) => tool.agent !== undefined && hasSkills(tool.agent));
16
+ }
17
+ /**
18
+ * What the harness section needs of the runtime, derived rather than declared: a custom harness
19
+ * needs a pod (it runs from the pod's image); skills need a sandbox to be mounted in; otherwise
20
+ * nothing.
21
+ */
22
+ export function sandboxNeedOf(harness) {
23
+ if (harnessIdOf(harness) !== DEFAULT_HARNESS)
24
+ return "pod";
25
+ if (isWorkflowHarness(harness))
26
+ return Object.values(harness.agents).some(hasSkills) ? "sandbox" : "none";
27
+ if (Object.keys(harness.skills ?? {}).length > 0)
28
+ return "sandbox";
29
+ return (harness.tools ?? []).some((tool) => tool.agent !== undefined && hasSkills(tool.agent)) ? "sandbox" : "none";
30
+ }
31
+ /** Whether a runtime of `kind` gives the loop what it needs. */
32
+ export function kindMeets(kind, need) {
33
+ if (need === "pod")
34
+ return kind === "pod";
35
+ if (need === "sandbox")
36
+ return kind === "virtual" || kind === "pod";
37
+ return true;
38
+ }
39
+ /**
40
+ * A credential URL as the vault compares it: origin, path and query, with the default port and
41
+ * no fragment. Undefined for a URL the vault would refuse. The vault binds a `bearer` or
42
+ * `headers` credential to one URL and sends it to a server or HTTP tool declared at exactly that
43
+ * URL, so a slot covers a server when the two normalize the same.
44
+ */
45
+ export function normalizeCredentialUrl(input) {
46
+ let url;
47
+ try {
48
+ url = new URL(input);
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ if (url.username !== "" || url.password !== "" || url.hash !== "")
54
+ return undefined;
55
+ if (url.protocol !== "https:" && url.protocol !== "http:")
56
+ return undefined;
57
+ if ((url.protocol === "https:" && url.port === "443") || (url.protocol === "http:" && url.port === "80"))
58
+ url.port = "";
59
+ return `${url.origin}${url.pathname}${url.search}`;
60
+ }
61
+ const quoted = (value) => JSON.stringify(value);
62
+ /** The runtime section an Agent made from `manifest` has: `kind: "none"` when it is absent. */
63
+ export function runtimeOf(manifest) {
64
+ return manifest.runtime ?? { kind: "none" };
65
+ }
66
+ /**
67
+ * Every gap between the harness and runtime sections, worded for a person, in the manifest's
68
+ * order. Empty when they fit:
69
+ *
70
+ * 1. A custom harness (`harness.id` not `nylorun`) needs `runtime.kind` `pod` with an `image`.
71
+ * 2. Every credential the harness names is a declared slot of the right type: an MCP server's or
72
+ * HTTP tool's `credential` a `bearer` or `headers` slot bound to its URL, a skill's `secrets`
73
+ * `environment_secret` or `environment_variable` slots.
74
+ * 3. The runtime's kind gives the harness the sandbox it needs (`sandboxNeedOf`).
75
+ */
76
+ export function sectionGaps(manifest) {
77
+ const { harness } = manifest;
78
+ const runtime = runtimeOf(manifest);
79
+ const gaps = [];
80
+ const kindText = manifest.runtime === undefined ? "the manifest has no runtime section" : `the runtime is ${quoted(runtime.kind)}`;
81
+ // 1. A custom harness runs from its pod's image.
82
+ const harnessId = harnessIdOf(harness);
83
+ if (harnessId !== DEFAULT_HARNESS) {
84
+ if (runtime.kind !== "pod")
85
+ gaps.push(`harness.id ${quoted(harnessId)} needs runtime.kind "pod"; ${kindText}`);
86
+ else if (runtime.image === undefined)
87
+ gaps.push(`harness.id ${quoted(harnessId)} needs runtime.image: a custom harness runs from its pod's image`);
88
+ }
89
+ // 2. Credentials name declared slots of the right type.
90
+ const slots = runtime.secrets ?? {};
91
+ const urlSlot = (where, name, url, what) => {
92
+ const slot = slots[name];
93
+ if (slot === undefined) {
94
+ gaps.push(`${where} ${quoted(name)} is not a secret slot in runtime.secrets`);
95
+ return;
96
+ }
97
+ if (slot.type !== "bearer" && slot.type !== "headers") {
98
+ gaps.push(`${where} ${quoted(name)} is a slot of type ${slot.type}; ${what} needs a bearer or headers slot`);
99
+ return;
100
+ }
101
+ const want = normalizeCredentialUrl(url);
102
+ if (want === undefined || normalizeCredentialUrl(slot.url) !== want)
103
+ gaps.push(`${where} ${quoted(name)} is bound to ${slot.url}, not to ${what}'s URL ${url}`);
104
+ };
105
+ if (!isWorkflowHarness(harness)) {
106
+ for (const [key, server] of Object.entries(harness.mcpServers ?? {}))
107
+ if (server.credential !== undefined)
108
+ urlSlot(`harness.mcpServers.${key}.credential`, server.credential, server.url, "an MCP server");
109
+ for (const tool of harness.tools ?? [])
110
+ if (tool.http?.credential !== undefined)
111
+ urlSlot(`harness.tools.${tool.name}.http.credential`, tool.http.credential, tool.http.url, "an HTTP tool");
112
+ for (const [key, skill] of Object.entries(harness.skills ?? {}))
113
+ for (const name of skill.secrets ?? []) {
114
+ const slot = slots[name];
115
+ if (slot === undefined)
116
+ gaps.push(`harness.skills.${key}.secrets ${quoted(name)} is not a secret slot in runtime.secrets`);
117
+ else if (slot.type !== "environment_secret" && slot.type !== "environment_variable")
118
+ gaps.push(`harness.skills.${key}.secrets ${quoted(name)} is a slot of type ${slot.type}; a skill reads environment_secret or environment_variable slots`);
119
+ }
120
+ }
121
+ // 3. The sandbox the loop needs. A custom harness's pod is gap 1.
122
+ const need = sandboxNeedOf(harness);
123
+ if (need === "sandbox" && !kindMeets(runtime.kind, need)) {
124
+ const what = isWorkflowHarness(harness) ? "harness.agents carry skills, which need" : "harness.skills needs";
125
+ gaps.push(manifest.runtime === undefined
126
+ ? `${what} a sandbox; the manifest has no runtime section, so an Agent made from it has none`
127
+ : `${what} a sandbox; runtime.kind ${quoted(runtime.kind)} has none`);
128
+ }
129
+ return gaps;
130
+ }
131
+ /**
132
+ * The loop manifest the harness runs for a version of an agent manifest: the harness section
133
+ * with the manifest's name as its id, in the shape the engine reads (agent manifest v7, workflow
134
+ * manifest v3). The fields only the Runtime reads (`credential`, a skill's `secrets`, `plugins`,
135
+ * `loop`, the harness id) stay out.
136
+ */
137
+ export function loopManifestOf(manifest) {
138
+ const { harness } = manifest;
139
+ const identity = {
140
+ id: manifest.name,
141
+ ...(manifest.description === undefined ? {} : { description: manifest.description }),
142
+ ...(manifest.metadata === undefined ? {} : { metadata: manifest.metadata }),
143
+ };
144
+ if (isWorkflowHarness(harness))
145
+ return {
146
+ kind: "workflow",
147
+ workflowSchemaVersion: 3,
148
+ ...identity,
149
+ ...(harness.inputSchema === undefined ? {} : { inputSchema: harness.inputSchema }),
150
+ ...(harness.outputSchema === undefined ? {} : { outputSchema: harness.outputSchema }),
151
+ root: harness.root,
152
+ agents: harness.agents,
153
+ };
154
+ const skills = Object.entries(harness.skills ?? {}).map(([key, { secrets: _, ...skill }]) => [key, skill]);
155
+ const servers = Object.entries(harness.mcpServers ?? {}).map(([key, { credential: _, ...server }]) => [key, server]);
156
+ return {
157
+ manifestSchemaVersion: 7,
158
+ ...identity,
159
+ ...(harness.outputSchema === undefined ? {} : { outputSchema: harness.outputSchema }),
160
+ ...(harness.instructions === undefined ? {} : { instructions: harness.instructions }),
161
+ ...(harness.tools === undefined ? {} : { tools: harness.tools }),
162
+ ...(skills.length === 0 ? {} : { skills: Object.fromEntries(skills) }),
163
+ ...(servers.length === 0 ? {} : { mcpServers: Object.fromEntries(servers) }),
164
+ };
165
+ }
166
+ /**
167
+ * The harness section a loop manifest makes (an SDK-built agent or flow, or a v7 manifest being
168
+ * migrated): its loop fields, without its identity, which the agent manifest holds. A v7
169
+ * manifest's `requires.secrets` become no skill's: the composer asks for them by name.
170
+ */
171
+ export function harnessSectionOf(loop, options = {}) {
172
+ const plugins = options.plugins ?? pluginsOf(loop);
173
+ const extra = {
174
+ ...(options.harness === undefined || options.harness === DEFAULT_HARNESS ? {} : { id: options.harness }),
175
+ ...(plugins.length === 0 ? {} : { plugins }),
176
+ };
177
+ if ("kind" in loop)
178
+ return {
179
+ kind: "workflow",
180
+ ...extra,
181
+ ...(loop.inputSchema === undefined ? {} : { inputSchema: loop.inputSchema }),
182
+ ...(loop.outputSchema === undefined ? {} : { outputSchema: loop.outputSchema }),
183
+ root: loop.root,
184
+ agents: loop.agents,
185
+ };
186
+ return {
187
+ ...extra,
188
+ ...(loop.instructions === undefined ? {} : { instructions: loop.instructions }),
189
+ ...(loop.tools === undefined ? {} : { tools: loop.tools }),
190
+ ...(loop.skills === undefined ? {} : { skills: loop.skills }),
191
+ ...(loop.mcpServers === undefined ? {} : { mcpServers: loop.mcpServers }),
192
+ ...(loop.outputSchema === undefined ? {} : { outputSchema: loop.outputSchema }),
193
+ };
194
+ }
195
+ /** The Agent Plugins whose labels a loop manifest's skills and servers carry, each once, by name. */
196
+ export function pluginsOf(loop) {
197
+ if ("kind" in loop)
198
+ return [];
199
+ const byName = new Map();
200
+ for (const item of [...Object.values(loop.skills ?? {}), ...Object.values(loop.mcpServers ?? {})])
201
+ if (item.plugin !== undefined && !byName.has(item.plugin.name))
202
+ byName.set(item.plugin.name, { ...item.plugin });
203
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
204
+ }
@@ -4,13 +4,6 @@ export interface ToolCallTrace {
4
4
  readonly skill?: string;
5
5
  readonly plugin?: PluginLabel;
6
6
  }
7
- /**
8
- * The skill of `manifest` a tool call ran. `load_skill` and `read_skill_resource` name it in their
9
- * input. A sandbox tool (`bash`, `read`, `grep`, `glob`, …) is matched on the skills' mount path,
10
- * `/skills/<name>@<hash>/` (or `/skills/<name>/`, before D66), in its input's text: exact for a path argument, and for `bash` only when the
11
- * command names the path. The first skill of the agent the input names wins.
12
- */
13
- export declare function skillOfToolCall(manifest: Pick<AgentManifest, "skills"> | undefined, toolName: string | undefined, input: unknown): string | undefined;
14
7
  /** The plugin that brought the skill or MCP server `name` to `manifest`, if one did. */
15
8
  export declare function pluginOf(manifest: Pick<AgentManifest, "skills" | "mcpServers"> | undefined, what: {
16
9
  readonly skill?: string;
@@ -1,29 +1,3 @@
1
- import { SKILLS_MOUNT } from "../utils/definition-files.js";
2
- import { isSandboxToolName } from "../utils/sandbox.js";
3
- import { SKILL_TOOL_NAMES } from "./skill-tools.js";
4
- const MOUNT = new RegExp(`${SKILLS_MOUNT}/([^/@\\s"'\`]+)(?:@[0-9a-f]{12})?/`, "g");
5
- /**
6
- * The skill of `manifest` a tool call ran. `load_skill` and `read_skill_resource` name it in their
7
- * input. A sandbox tool (`bash`, `read`, `grep`, `glob`, …) is matched on the skills' mount path,
8
- * `/skills/<name>@<hash>/` (or `/skills/<name>/`, before D66), in its input's text: exact for a path argument, and for `bash` only when the
9
- * command names the path. The first skill of the agent the input names wins.
10
- */
11
- export function skillOfToolCall(manifest, toolName, input) {
12
- const skills = manifest?.skills;
13
- if (!skills || toolName === undefined)
14
- return undefined;
15
- if (SKILL_TOOL_NAMES.has(toolName)) {
16
- const name = input?.name;
17
- return typeof name === "string" && skills[name] !== undefined ? name : undefined;
18
- }
19
- if (!isSandboxToolName(toolName))
20
- return undefined;
21
- for (const text of strings(input))
22
- for (const match of text.matchAll(MOUNT))
23
- if (skills[match[1]] !== undefined)
24
- return match[1];
25
- return undefined;
26
- }
27
1
  /** The plugin that brought the skill or MCP server `name` to `manifest`, if one did. */
28
2
  export function pluginOf(manifest, what) {
29
3
  if (what.skill !== undefined)
@@ -32,11 +6,3 @@ export function pluginOf(manifest, what) {
32
6
  return manifest?.mcpServers?.[what.server]?.plugin;
33
7
  return undefined;
34
8
  }
35
- /** The string values of a tool's input, one level deep: its path, pattern or command. */
36
- function strings(input) {
37
- if (typeof input === "string")
38
- return [input];
39
- if (!input || typeof input !== "object")
40
- return [];
41
- return Object.values(input).filter((value) => typeof value === "string");
42
- }
@@ -4,6 +4,6 @@ import type { AgentManifest } from "../types/manifest.js";
4
4
  * (`loops.md` §3.4). A variant may remove tools (agents used as tools and HTTP tools included),
5
5
  * tighten its MCP servers' tool settings (R2b C9, Q18), and change its instructions, name,
6
6
  * description and metadata. Its skills and servers are setup: the sandbox holds the skills from
7
- * the session's start. It never sets `runtime`; the turn runs with the pin's.
7
+ * the session's start.
8
8
  */
9
9
  export declare function isVariantOf(candidate: AgentManifest, pinned: AgentManifest): boolean;
@@ -58,15 +58,13 @@ function tightensServers(pinned, candidate) {
58
58
  * (`loops.md` §3.4). A variant may remove tools (agents used as tools and HTTP tools included),
59
59
  * tighten its MCP servers' tool settings (R2b C9, Q18), and change its instructions, name,
60
60
  * description and metadata. Its skills and servers are setup: the sandbox holds the skills from
61
- * the session's start. It never sets `runtime`; the turn runs with the pin's.
61
+ * the session's start.
62
62
  */
63
63
  export function isVariantOf(candidate, pinned) {
64
64
  if (candidate.id !== pinned.id)
65
65
  return false;
66
66
  if (candidate.manifestSchemaVersion !== pinned.manifestSchemaVersion)
67
67
  return false;
68
- if (candidate.runtime !== undefined)
69
- return false;
70
68
  if (!same(candidate.outputSchema, pinned.outputSchema))
71
69
  return false;
72
70
  // What the agent needs of its Environment was checked when the session opened (D65).
@@ -0,0 +1,84 @@
1
+ /**
2
+ * A harness's side of the artifact seam (protocol 15): reading an artifact the run's session may
3
+ * read in chunks (`artifact.read`), and writing one (`artifact.write`: `begin`, `chunk`,
4
+ * `commit`, `abort`). Chunks are at most `chunkBytes`: pass the run's
5
+ * `turn.start.limits.chunkBytes`, which core holds them to. Our engine's `read_artifact` and
6
+ * `save_artifact` use these, and any harness may.
7
+ */
8
+ import type { HarnessChannel } from "./rpc.js";
9
+ import type { ArtifactMeta } from "./messages.js";
10
+ /** What the helpers need of a channel: its requests to core. */
11
+ export type ArtifactRequester = Pick<HarnessChannel, "request">;
12
+ export interface ReadArtifactOptions {
13
+ readonly runId: string;
14
+ readonly artifactId: string;
15
+ /** Default: the latest, which the first answer pins for the chunks after it. */
16
+ readonly version?: number;
17
+ /** The first byte to read. Default 0. */
18
+ readonly offset?: number;
19
+ /** The most bytes each request asks for: the run's `turn.start.limits.chunkBytes`. */
20
+ readonly chunkBytes: number;
21
+ readonly signal?: AbortSignal;
22
+ }
23
+ export interface ReadArtifact {
24
+ readonly artifact: ArtifactMeta;
25
+ /**
26
+ * The bytes from `offset` to the end, a chunk at a time: the first came with `artifact`, the
27
+ * rest are asked for as they are read. Read it once.
28
+ */
29
+ chunks(): AsyncIterable<Uint8Array>;
30
+ }
31
+ /** Opens an artifact to read: its metadata, and its bytes as chunks. */
32
+ export declare function readArtifact(channel: ArtifactRequester, options: ReadArtifactOptions): Promise<ReadArtifact>;
33
+ export interface ArtifactWriteOptions {
34
+ readonly runId: string;
35
+ /** Makes the write idempotent within the session: a key written before answers its version. */
36
+ readonly key: string;
37
+ /** A new artifact's name. */
38
+ readonly name?: string;
39
+ /** Write a new version of this artifact of the session instead. */
40
+ readonly artifactId?: string;
41
+ /** Default: what the name's extension implies. */
42
+ readonly contentType?: string;
43
+ /** The tool call the artifact comes from: an effect of the run's turn. */
44
+ readonly effectId?: string;
45
+ /** The body's size when known: core refuses one past its limits before a byte is sent. */
46
+ readonly size?: number;
47
+ /** The most bytes one chunk carries: the run's `turn.start.limits.chunkBytes`. */
48
+ readonly chunkBytes: number;
49
+ readonly signal?: AbortSignal;
50
+ }
51
+ /** A version `artifact.write` stored, and whether this write stored it (not an earlier one). */
52
+ export interface WrittenArtifact {
53
+ readonly artifact: ArtifactMeta;
54
+ readonly created: boolean;
55
+ }
56
+ /** An upload in progress. */
57
+ export interface OpenArtifactWrite {
58
+ readonly kind: "open";
59
+ readonly uploadId: string;
60
+ /** The most bytes the upload may hold, when it opened. */
61
+ readonly maxBytes: number;
62
+ /** Sends `bytes` next, in chunks of at most `chunkBytes`. */
63
+ write(bytes: Uint8Array): Promise<void>;
64
+ /** Stores what was sent as the version. */
65
+ commit(): Promise<WrittenArtifact>;
66
+ /** Drops the upload; nothing is stored. */
67
+ abort(): Promise<void>;
68
+ }
69
+ /**
70
+ * Begins a write. Answers `written` when the key was written before (nothing more to send), else
71
+ * the open upload.
72
+ */
73
+ export declare function openArtifactWrite(channel: ArtifactRequester, options: ArtifactWriteOptions): Promise<({
74
+ readonly kind: "written";
75
+ } & WrittenArtifact) | OpenArtifactWrite>;
76
+ /**
77
+ * Writes `bytes` as the artifact: in the `begin` when they fit one chunk, else as an upload,
78
+ * which an error aborts.
79
+ */
80
+ export declare function writeArtifactBytes(channel: ArtifactRequester, options: ArtifactWriteOptions, bytes: Uint8Array): Promise<WrittenArtifact>;
81
+ /** `bytes` as base64. */
82
+ export declare function toBase64(bytes: Uint8Array): string;
83
+ /** The bytes base64 `text` encodes. */
84
+ export declare function fromBase64(text: string): Uint8Array;
@@ -0,0 +1,128 @@
1
+ /** Opens an artifact to read: its metadata, and its bytes as chunks. */
2
+ export async function readArtifact(channel, options) {
3
+ const { runId, artifactId, chunkBytes, signal } = options;
4
+ const start = options.offset ?? 0;
5
+ const first = await channel.request("artifact.read", {
6
+ runId,
7
+ artifactId,
8
+ ...(options.version === undefined ? {} : { version: options.version }),
9
+ offset: start,
10
+ length: chunkBytes,
11
+ }, signal);
12
+ // The chunks after the first read the version the first did, even if a newer one lands.
13
+ const version = first.artifact.version;
14
+ return {
15
+ artifact: first.artifact,
16
+ async *chunks() {
17
+ let answer = first;
18
+ let offset = start;
19
+ for (;;) {
20
+ const bytes = fromBase64(answer.base64);
21
+ if (bytes.byteLength > 0)
22
+ yield bytes;
23
+ offset += bytes.byteLength;
24
+ if (answer.eof || bytes.byteLength === 0)
25
+ return;
26
+ answer = await channel.request("artifact.read", { runId, artifactId, version, offset, length: chunkBytes }, signal);
27
+ }
28
+ },
29
+ };
30
+ }
31
+ /**
32
+ * Begins a write. Answers `written` when the key was written before (nothing more to send), else
33
+ * the open upload.
34
+ */
35
+ export async function openArtifactWrite(channel, options) {
36
+ const answer = await channel.request("artifact.write", beginOf(options), options.signal);
37
+ return opened(channel, options, answer);
38
+ }
39
+ /**
40
+ * Writes `bytes` as the artifact: in the `begin` when they fit one chunk, else as an upload,
41
+ * which an error aborts.
42
+ */
43
+ export async function writeArtifactBytes(channel, options, bytes) {
44
+ if (bytes.byteLength <= options.chunkBytes) {
45
+ const answer = await channel.request("artifact.write", { ...beginOf({ ...options, size: bytes.byteLength }), base64: toBase64(bytes) }, options.signal);
46
+ if (answer.status !== "written")
47
+ throw new Error(`artifact.write answered ${answer.status} to a whole body`);
48
+ return { artifact: answer.artifact, created: answer.created };
49
+ }
50
+ const upload = await openArtifactWrite(channel, { ...options, size: bytes.byteLength });
51
+ if (upload.kind === "written")
52
+ return { artifact: upload.artifact, created: upload.created };
53
+ try {
54
+ await upload.write(bytes);
55
+ return await upload.commit();
56
+ }
57
+ catch (error) {
58
+ await upload.abort().catch(() => undefined);
59
+ throw error;
60
+ }
61
+ }
62
+ function beginOf(options) {
63
+ return {
64
+ runId: options.runId,
65
+ op: "begin",
66
+ key: options.key,
67
+ ...(options.name === undefined ? {} : { name: options.name }),
68
+ ...(options.artifactId === undefined ? {} : { artifactId: options.artifactId }),
69
+ ...(options.contentType === undefined ? {} : { contentType: options.contentType }),
70
+ ...(options.effectId === undefined ? {} : { effectId: options.effectId }),
71
+ ...(options.size === undefined ? {} : { size: options.size }),
72
+ };
73
+ }
74
+ function opened(channel, options, begun) {
75
+ if (begun.status === "written")
76
+ return { kind: "written", artifact: begun.artifact, created: begun.created };
77
+ if (begun.status !== "open")
78
+ throw new Error(`artifact.write answered ${begun.status} to a begin`);
79
+ const { runId, chunkBytes, signal } = options;
80
+ const { uploadId, maxBytes } = begun;
81
+ let received = begun.received;
82
+ return {
83
+ kind: "open",
84
+ uploadId,
85
+ maxBytes,
86
+ async write(bytes) {
87
+ for (let at = 0; at < bytes.byteLength; at += chunkBytes) {
88
+ const chunk = bytes.subarray(at, Math.min(at + chunkBytes, bytes.byteLength));
89
+ const sent = await channel.request("artifact.write", { runId, op: "chunk", uploadId, offset: received, base64: toBase64(chunk) }, signal);
90
+ if (sent.status !== "open")
91
+ throw new Error(`artifact.write answered ${sent.status} to a chunk`);
92
+ received = sent.received;
93
+ }
94
+ },
95
+ async commit() {
96
+ const done = await channel.request("artifact.write", { runId, op: "commit", uploadId }, signal);
97
+ if (done.status !== "written")
98
+ throw new Error(`artifact.write answered ${done.status} to a commit`);
99
+ return { artifact: done.artifact, created: done.created };
100
+ },
101
+ async abort() {
102
+ await channel.request("artifact.write", { runId, op: "abort", uploadId });
103
+ },
104
+ };
105
+ }
106
+ const NodeBuffer = globalThis.Buffer;
107
+ /** `bytes` as base64. */
108
+ export function toBase64(bytes) {
109
+ if (NodeBuffer)
110
+ return NodeBuffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
111
+ let binary = "";
112
+ // `fromCharCode` takes its bytes as arguments: a slice at a time keeps under the engine's cap.
113
+ for (let at = 0; at < bytes.byteLength; at += 0x8000)
114
+ binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000));
115
+ return btoa(binary);
116
+ }
117
+ /** The bytes base64 `text` encodes. */
118
+ export function fromBase64(text) {
119
+ if (NodeBuffer) {
120
+ const decoded = NodeBuffer.from(text, "base64");
121
+ return new Uint8Array(decoded.buffer, decoded.byteOffset, decoded.byteLength);
122
+ }
123
+ const binary = atob(text);
124
+ const bytes = new Uint8Array(binary.length);
125
+ for (let at = 0; at < binary.length; at += 1)
126
+ bytes[at] = binary.charCodeAt(at);
127
+ return bytes;
128
+ }
@@ -30,10 +30,6 @@ export declare const MCP_LIST_PATH = "/nylorun/v1/mcp/list";
30
30
  export declare const MCP_CLOSE_PATH = "/nylorun/v1/mcp/close";
31
31
  export declare const TOOL_CALLS_PATH = "/nylorun/v1/tool-calls";
32
32
  export declare const HTTP_CALLS_PATH = "/nylorun/v1/http-calls";
33
- /** Largest model call body the gate reads: one `ModelCall` with its whole projected history. */
34
- export declare const MAX_MODEL_CALL_BYTES: number;
35
- /** Largest tool call body the gate reads. */
36
- export declare const MAX_TOOL_BODY_BYTES: number;
37
33
  /**
38
34
  * One model call. It names no session, turn or agent: the gate takes them from the run token,
39
35
  * and refuses a body that names them. `call` is the engine's `ModelCall`.
@@ -29,10 +29,6 @@ export const MCP_LIST_PATH = "/nylorun/v1/mcp/list";
29
29
  export const MCP_CLOSE_PATH = "/nylorun/v1/mcp/close";
30
30
  export const TOOL_CALLS_PATH = "/nylorun/v1/tool-calls";
31
31
  export const HTTP_CALLS_PATH = "/nylorun/v1/http-calls";
32
- /** Largest model call body the gate reads: one `ModelCall` with its whole projected history. */
33
- export const MAX_MODEL_CALL_BYTES = 32 * 1024 * 1024;
34
- /** Largest tool call body the gate reads. */
35
- export const MAX_TOOL_BODY_BYTES = 8 * 1024 * 1024;
36
32
  /**
37
33
  * One model call. It names no session, turn or agent: the gate takes them from the run token,
38
34
  * and refuses a body that names them. `call` is the engine's `ModelCall`.