@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
package/dist/contracts.js CHANGED
@@ -1,19 +1,26 @@
1
1
  /** Public wire contracts only. Never import checkpoint or engine modules here. */
2
2
  import { z } from "zod";
3
- import { SANDBOX_NETWORK_PRESETS, SANDBOX_TOOL_NAMES, isSandboxHostPattern, parseSandboxDuration, parseSandboxSize, } from "./utils/sandbox.js";
4
- import { REMOVED_MANIFEST_FIELDS, manifestVersionIssue, workflowVersionIssue, } from "./definition/removed.js";
5
- import { RUNTIME_TOOL_NAMES } from "./utils/runtime-tools.js";
3
+ import { SANDBOX_NETWORK_PRESETS, isSandboxHostPattern, parseSandboxDuration, parseSandboxSize, } from "./utils/sandbox.js";
4
+ import { REMOVED_MANIFEST_FIELDS, REMOVED_RUNTIME_SECTION_FIELDS, agentManifestVersionIssue, manifestVersionIssue, workflowVersionIssue, } from "./definition/removed.js";
6
5
  import { DELEGATE_INPUT_SCHEMA, DELEGATE_NAME_PATTERN } from "./definition/delegate.js";
7
6
  import { stdioMcpRefusal } from "./definition/mcp.js";
8
- import { APPROVAL_MODES, HTTP_TOOL_MAX_TIMEOUT_MS, HTTP_TOOL_METHODS, httpInputIssue, httpUrlIssue, httpUrlTemplateIssue, httpVerifierIssue, } from "./definition/http-tool.js";
7
+ import { APPROVAL_MODES, HTTP_TOOL_METHODS, httpInputIssue, httpUrlIssue, httpUrlTemplateIssue, httpVerifierIssue, } from "./definition/http-tool.js";
9
8
  import { canonical } from "./utils/canonical.js";
9
+ import { FILE_NAME_MAX, FILE_PATH_MAX, LINK_TARGET_MAX } from "./utils/file-systems.js";
10
+ export { FILE_NAME_MAX, FILE_PATH_MAX } from "./utils/file-systems.js";
10
11
  import { DEFAULT_HARNESS, HARNESS_ID_PATTERN, isHarnessId } from "./utils/harness-id.js";
11
12
  export { DEFAULT_HARNESS, HARNESS_ID_PATTERN, isHarnessId };
12
- import { DEFINITION_FILE_MAX_BYTES, isDefinitionFileHash, skillFilesIssue } from "./utils/definition-files.js";
13
+ import { isDefinitionFileHash, skillFilesIssue } from "./utils/definition-files.js";
14
+ import { MEMORY_ACCESS, MEMORY_INSTRUCTIONS_MAX, MEMORY_OPERATIONS } from "./utils/memory.js";
15
+ export { MEMORY_ACCESS, MEMORY_COMMANDS, MEMORY_DESCRIPTION_MAX, MEMORY_INSTRUCTIONS_MAX, MEMORY_OPERATIONS, MEMORY_PATH_MAX, MEMORY_ROOT, checkMemoryCall, memoryAliasOf, memoryDescriptionOf, memoryPathOf, memoryPathWithin, } from "./utils/memory.js";
13
16
  export { PROTOCOL_VERSION, ERROR_CODES } from "./compatibility.js";
14
- export { DEFINITION_FILE_MAX_BYTES, SKILL_FILES_MAX, definitionFilesOf, isDefinitionFileHash, } from "./utils/definition-files.js";
17
+ export { SKILL_TOTAL_BYTES_DEFAULT, definitionFilesOf, isDefinitionFileHash, skillsOf, } from "./utils/definition-files.js";
18
+ export { HARNESS_LIMIT_DEFAULTS, HarnessLimitsSchema, JS_STRING_MAX_LENGTH, RECORD_ENVELOPE_RESERVE_BYTES, RUNTIME_LIMIT_CEILINGS, RUNTIME_LIMIT_DEFAULTS, RuntimeLimitsSchema, S2_RECORD_MAX_BYTES, TIMER_MAX_MS, harnessLimitsOf, inlineBodyBytes, limitExceededMessage, runtimeLimitIssues, runtimeLimitsOf, } from "./utils/runtime-limits.js";
19
+ import { RuntimeLimitsSchema, TIMER_MAX_MS } from "./utils/runtime-limits.js";
20
+ export { DEFAULT_CONTENT_TYPE, MODEL_IMAGE_TYPES, contentTypeFor, essence, extensionFor, inputLabel, isModelImage, isOffice, isText, modelInputOf, normalizeContentType, } from "./utils/media-types.js";
15
21
  import { ERROR_CODES, isArtifactId } from "./compatibility.js";
16
22
  export const RequestIdSchema = z.string().min(1);
23
+ /** At most 256 characters: an identifier's grammar is the protocol's (it crosses the Runtime API, the Harness API and tokens, and means the same in every installation), so its length is a constant of protocol 15, not a setting. */
17
24
  export const IdempotencyKeySchema = z.string().min(1).max(256);
18
25
  const jsonObject = z.record(z.string(), z.unknown());
19
26
  /**
@@ -122,7 +129,8 @@ const sandboxManifestSchema = z
122
129
  .optional(),
123
130
  resources: z
124
131
  .object({
125
- cpus: z.number().int().min(1).max(64).optional(),
132
+ /** At most the Tenant's `limits.resources.cpus` (`environments.config`). */
133
+ cpus: z.number().int().min(1).optional(),
126
134
  memory: z
127
135
  .string()
128
136
  .refine((value) => parseSandboxSize(value) !== undefined, {
@@ -149,7 +157,7 @@ const httpToolTargetSchema = z
149
157
  }),
150
158
  method: z.enum(HTTP_TOOL_METHODS).optional(),
151
159
  credential: z.string().min(1).optional(),
152
- timeoutMs: z.number().int().positive().max(HTTP_TOOL_MAX_TIMEOUT_MS).optional(),
160
+ timeoutMs: z.number().int().positive().max(TIMER_MAX_MS).optional(),
153
161
  })
154
162
  .strict();
155
163
  /** A name kept for a later kind of `what` (tool, verifier), refused for now. */
@@ -199,14 +207,12 @@ const removedFieldError = (removedFields) => (issue) => {
199
207
  const removed = issue.keys?.find((key) => removedFields[key] !== undefined);
200
208
  return removed === undefined ? undefined : removedFields[removed];
201
209
  };
202
- /** What the Runtime adds to a session's agent; only the Runtime writes it. */
203
- const runtimeManifestSchema = z
204
- .object({
205
- sandbox: sandboxManifestSchema.optional(),
206
- tools: z.array(toolManifestSchema).optional(),
207
- instructions: z.array(z.string()).optional(),
208
- })
209
- .strict();
210
+ /**
211
+ * An environment variable name a shell secret or plain variable may take (R2c, D50): a POSIX
212
+ * name, of any length (POSIX and Linux set none; a request's body bounds it). Names the sandbox
213
+ * needs for itself (the proxy, the trust store, `PATH`, `HOME`) and `NYLORUN_*` are reserved.
214
+ */
215
+ export const ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
210
216
  /**
211
217
  * What an agent needs of the Environment its session opens on (protocol 14, D65), checked when a
212
218
  * session opens (`409 environment_unsuitable`). `sandbox`: `any` needs kind `virtual` or `pod`,
@@ -216,7 +222,8 @@ const runtimeManifestSchema = z
216
222
  const agentRequirementsSchema = z
217
223
  .object({
218
224
  sandbox: z.enum(["none", "any", "pod"]).optional(),
219
- secrets: z.array(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/, "A secret name in requires is an environment variable name")).max(64).optional(),
225
+ /** At most the Tenant's Runtime limit `environmentSecretSlots`, checked when the agent is deployed. */
226
+ secrets: z.array(z.string().regex(ENVIRONMENT_NAME_PATTERN, "A secret name in requires is an environment variable name")).optional(),
220
227
  })
221
228
  .strict();
222
229
  const agentManifestSchema = z
@@ -234,7 +241,6 @@ const agentManifestSchema = z
234
241
  skills: z.record(z.string(), skillManifestSchema).optional(),
235
242
  mcpServers: z.record(z.string(), mcpServerSchema).optional(),
236
243
  requires: agentRequirementsSchema.optional(),
237
- runtime: runtimeManifestSchema.optional(),
238
244
  // Reserved for Functions, which are deferred: developer code the Runtime will run from
239
245
  // uploaded definition files (a `functions/` folder). Any value is refused below.
240
246
  functions: z.unknown().optional().meta({ description: "Reserved: Functions are not available yet" }),
@@ -245,37 +251,17 @@ const agentManifestSchema = z
245
251
  delegationIssues(manifest, (message) => ctx.addIssue({ code: "custom", message }));
246
252
  const names = new Set();
247
253
  for (const tool of manifest.tools ?? []) {
248
- if (RUNTIME_TOOL_NAMES.has(tool.name))
249
- ctx.addIssue({
250
- code: "custom",
251
- message: `Tool '${tool.name}' takes the name of a tool the Runtime serves; rename it`,
252
- });
253
254
  if (tool.name.includes("__"))
254
255
  ctx.addIssue({
255
256
  code: "custom",
256
257
  message: `Tool '${tool.name}' must not contain '__', which names an MCP server's tools`,
257
258
  });
258
259
  }
259
- for (const tool of [...(manifest.tools ?? []), ...(manifest.runtime?.tools ?? [])]) {
260
+ for (const tool of manifest.tools ?? []) {
260
261
  if (names.has(tool.name))
261
262
  ctx.addIssue({ code: "custom", message: "Tool names must be unique" });
262
263
  names.add(tool.name);
263
264
  }
264
- for (const tool of manifest.runtime?.tools ?? [])
265
- if (!RUNTIME_TOOL_NAMES.has(tool.name))
266
- ctx.addIssue({
267
- code: "custom",
268
- message: `runtime.tools holds only the tools the Runtime serves, not '${tool.name}'`,
269
- });
270
- if (manifest.runtime?.sandbox !== undefined) {
271
- const pinned = new Set((manifest.runtime.tools ?? []).map((tool) => tool.name));
272
- for (const name of SANDBOX_TOOL_NAMES)
273
- if (!pinned.has(name))
274
- ctx.addIssue({
275
- code: "custom",
276
- message: `runtime.sandbox comes with the sandbox tools; runtime.tools has no '${name}'`,
277
- });
278
- }
279
265
  if (manifest.skills && Object.keys(manifest.skills).length === 0)
280
266
  ctx.addIssue({ code: "custom", message: "skills must be omitted when the agent has no skills" });
281
267
  for (const [key, skill] of Object.entries(manifest.skills ?? {}))
@@ -292,14 +278,8 @@ const agentManifestSchema = z
292
278
  * (`ManifestDrift`): the hand-written type keeps its read-only fields and its docs.
293
279
  */
294
280
  export const AgentManifestSchema = agentManifestSchema;
295
- /** Agents used as tools: one level deep, `{ task }` input, one shared sandbox spec. */
281
+ /** Agents used as tools: one level deep, `{ task }` input. */
296
282
  function delegationIssues(manifest, issue) {
297
- const sandboxes = new Set();
298
- const addSandbox = (agent) => {
299
- if (agent.runtime?.sandbox)
300
- sandboxes.add(canonical(agent.runtime.sandbox));
301
- };
302
- addSandbox(manifest);
303
283
  for (const tool of manifest.tools ?? []) {
304
284
  const child = tool.agent;
305
285
  if (!child)
@@ -312,18 +292,12 @@ function delegationIssues(manifest, issue) {
312
292
  issue(`Agent tool '${tool.name}' must take the standard { task } input`);
313
293
  if (tool.outputSchema !== undefined)
314
294
  issue(`Agent tool '${tool.name}' must not declare outputSchema; the agent's outputSchema applies`);
315
- if ("kind" in child) {
316
- // A flow agent runs in its own linked session; its leaves may delegate in turn.
317
- if (child.sandbox !== undefined && Object.keys(child.sandbox).length > 0)
318
- sandboxes.add(canonical(child.sandbox));
295
+ // A flow agent runs in its own linked session; its leaves may delegate in turn.
296
+ if ("kind" in child)
319
297
  continue;
320
- }
321
298
  if (child.tools?.some((item) => item.agent !== undefined))
322
299
  issue(`'${child.id}' delegates to another agent; nested delegation is not supported yet`);
323
- addSandbox(child);
324
300
  }
325
- if (sandboxes.size > 1)
326
- issue("An agent and the agents it uses as tools must declare identical sandboxes");
327
301
  }
328
302
  // Workflow manifest v3 (flow agents): `id` on any node, embedded agents, no functions.
329
303
  const workflowNodeOptions = { id: z.string().min(1).optional() };
@@ -485,19 +459,15 @@ function referencedAgents(node) {
485
459
  }
486
460
  /** Workflow definition document. `kind: "workflow"`; a missing `kind` is never a workflow. */
487
461
  export const WorkflowManifestSchema = workflowManifestSchema;
488
- /** Registry document: agent (no `kind`, or legacy) or workflow (`kind: "workflow"`). */
462
+ /**
463
+ * A loop manifest: what the engine runs (agent manifest v7's shape, or workflow manifest v3's),
464
+ * as the Runtime makes it from an agent manifest v8's harness section (`loopManifestOf`) and a
465
+ * session pins it.
466
+ */
489
467
  export const DefinitionDocumentSchema = z.union([
490
468
  AgentManifestSchema,
491
469
  WorkflowManifestSchema,
492
470
  ]);
493
- export const PutAgentRequestSchema = z
494
- .object({
495
- requestId: RequestIdSchema,
496
- /** Agent or workflow document. Registry `kind` is carried on the document. */
497
- manifest: DefinitionDocumentSchema,
498
- implementationVersion: z.string().min(1),
499
- })
500
- .strict();
501
471
  const hostPatternSchema = z.string().refine(isSandboxHostPattern, {
502
472
  message: "network.allowedHosts entries must be host names such as api.github.com or *.example.com",
503
473
  });
@@ -506,7 +476,8 @@ const durationSchema = (name) => z.string().refine((value) => parseSandboxDurati
506
476
  });
507
477
  const resourcesSchema = z
508
478
  .object({
509
- cpus: z.number().int().min(1).max(64).optional(),
479
+ /** At most the Tenant's `limits.resources.cpus` (`environments.config`), which it sets. */
480
+ cpus: z.number().int().min(1).optional(),
510
481
  memory: z
511
482
  .string()
512
483
  .refine((value) => parseSandboxSize(value) !== undefined, {
@@ -517,29 +488,35 @@ const resourcesSchema = z
517
488
  .strict();
518
489
  // --- Environments (protocol 11, R2d, blueprint D55 and D56) --------------------------------
519
490
  /**
520
- * An Environment id: 1–200 characters, one or more `/`-separated segments of letters, digits,
521
- * `.`, `_` and `-`, each starting with a letter or digit (`user-42`, `users/alice/web`). Ids are
522
- * hierarchical so a grant can name a family of them (`users/alice/*`).
491
+ * An Agent id (protocol 16; an Environment id before): 1–200 characters, one or more
492
+ * `/`-separated segments of letters, digits, `.`, `_` and `-`, each starting with a letter or
493
+ * digit (`triage`, `users/alice/triage`). Ids are hierarchical so a grant can name a family of
494
+ * them (`users/alice/*`).
523
495
  */
524
- const ENVIRONMENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
525
- export const ENVIRONMENT_ID_MAX_LENGTH = 200;
526
- export function isEnvironmentId(value) {
527
- return (typeof value === "string" &&
528
- value.length <= ENVIRONMENT_ID_MAX_LENGTH &&
529
- ENVIRONMENT_ID_PATTERN.test(value));
496
+ const AGENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
497
+ /**
498
+ * An identifier's grammar is the protocol's (B15): it crosses the Runtime API, tokens and grants
499
+ * and means the same in every installation, so its length is a constant of the protocol, not a
500
+ * setting.
501
+ */
502
+ export const AGENT_ID_MAX_LENGTH = 200;
503
+ export function isAgentId(value) {
504
+ return typeof value === "string" && value.length <= AGENT_ID_MAX_LENGTH && AGENT_ID_PATTERN.test(value);
530
505
  }
531
- /** An Environment grant: an exact Environment id, or a prefix ending in `/*` (`team-a/*`). */
532
- export function isEnvironmentGrant(value) {
506
+ /** An Agent grant: an exact Agent id, or a prefix ending in `/*` (`team-a/*`). */
507
+ export function isAgentGrant(value) {
533
508
  if (typeof value !== "string")
534
509
  return false;
535
- return value.endsWith("/*") ? isEnvironmentId(value.slice(0, -2)) : isEnvironmentId(value);
510
+ return value === "*" || (value.endsWith("/*") ? isAgentId(value.slice(0, -2)) : isAgentId(value));
536
511
  }
537
512
  /**
538
- * Whether `grants` (a token caller's Environment grants) reach Environment `id`: an exact entry,
539
- * or a prefix entry `p/*` for any id below `p/`. No grants reach no Environment.
513
+ * Whether `grants` (a token caller's Agent grants) reach Agent `id`: `*`, an exact entry, or a
514
+ * prefix entry `p/*` for any id below `p/`. No grants reach no Agent.
540
515
  */
541
- export function environmentGranted(grants, id) {
516
+ export function agentGranted(grants, id) {
542
517
  for (const grant of grants ?? []) {
518
+ if (grant === "*")
519
+ return true;
543
520
  if (grant.endsWith("/*")) {
544
521
  if (id.startsWith(grant.slice(0, -1)))
545
522
  return true;
@@ -549,14 +526,14 @@ export function environmentGranted(grants, id) {
549
526
  }
550
527
  return false;
551
528
  }
552
- export const EnvironmentIdSchema = z
529
+ export const AgentIdSchema = z
553
530
  .string()
554
- .refine(isEnvironmentId, {
555
- message: "An Environment id is up to 200 characters: /-separated segments of letters, digits, '.', '_' and '-'",
531
+ .refine(isAgentId, {
532
+ message: "An Agent id is up to 200 characters: /-separated segments of letters, digits, '.', '_' and '-'",
556
533
  })
557
- .meta({ description: "An Environment id, such as `user-42` or `users/alice/web`" });
558
- export const EnvironmentGrantSchema = z.string().refine(isEnvironmentGrant, {
559
- message: "An Environment grant is an Environment id, or a prefix ending in /* such as team-a/*",
534
+ .meta({ description: "An Agent id, such as `triage` or `users/alice/triage`" });
535
+ export const AgentGrantSchema = z.string().refine(isAgentGrant, {
536
+ message: "An Agent grant is *, an Agent id, or a prefix ending in /* such as team-a/*",
560
537
  });
561
538
  /**
562
539
  * `virtual`: a just-bash workspace in the harness container, no cluster (a local convenience).
@@ -564,19 +541,18 @@ export const EnvironmentGrantSchema = z.string().refine(isEnvironmentGrant, {
564
541
  * compute, only the vault, for agents whose tools are remote MCP servers and HTTP tools.
565
542
  */
566
543
  export const ENVIRONMENT_KINDS = ["virtual", "pod", "none"];
567
- const LABEL_KEY_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._/-]{0,61}[A-Za-z0-9])?$/;
568
- const LABEL_VALUE_PATTERN = /^[\x20-\x7e]{0,256}$/;
569
- export const ENVIRONMENT_LABELS_MAX = 32;
570
- /** The developer's own key-value pairs; the Runtime stores and filters them, never reads them. */
571
- export const EnvironmentLabelsSchema = z
572
- .record(z.string().regex(LABEL_KEY_PATTERN, {
573
- message: "Label keys are 1-63 letters, digits, '.', '_', '/' and '-'",
544
+ const LABEL_KEY_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._/-]*[A-Za-z0-9])?$/;
545
+ const LABEL_VALUE_PATTERN = /^[\x20-\x7e]*$/;
546
+ /**
547
+ * The developer's own key-value pairs; the Runtime stores and filters them, never reads them. How
548
+ * many, and how long a key and a value may be, are the Tenant's Runtime limits
549
+ * `environmentLabels`, `labelKeyChars` and `labelValueChars`, checked when they are set.
550
+ */
551
+ export const EnvironmentLabelsSchema = z.record(z.string().regex(LABEL_KEY_PATTERN, {
552
+ message: "Label keys are letters, digits, '.', '_', '/' and '-', and start and end with a letter or digit",
574
553
  }), z.string().regex(LABEL_VALUE_PATTERN, {
575
- message: "Label values are up to 256 printable ASCII characters",
576
- }))
577
- .refine((labels) => Object.keys(labels).length <= ENVIRONMENT_LABELS_MAX, {
578
- message: `At most ${ENVIRONMENT_LABELS_MAX} labels`,
579
- });
554
+ message: "Label values are printable ASCII characters",
555
+ }));
580
556
  /** A harness id (track R4): what a harness names itself in `hello`. */
581
557
  export const HarnessIdSchema = z.string().regex(HARNESS_ID_PATTERN, {
582
558
  message: "harness must be a harness id: lowercase letters, digits and dashes, starting with a letter",
@@ -593,14 +569,15 @@ export const EnvironmentLifecycleSchema = z
593
569
  deleteAfter: durationSchema("lifecycle.deleteAfter").optional(),
594
570
  })
595
571
  .strict();
596
- /** The most setup commands and input files an Environment's recipe holds (step 2). */
597
- export const ENVIRONMENT_SETUP_MAX = 16;
598
- /** A setup command's longest timeout (default 10m). */
599
- export const ENVIRONMENT_SETUP_TIMEOUT_MAX_MS = 30 * 60_000;
572
+ /**
573
+ * The default of a setup command's `timeout` setting. The longest one may ask for is the Tenant's
574
+ * Runtime limit `setupCommandMs`.
575
+ */
576
+ export const ENVIRONMENT_SETUP_TIMEOUT_DEFAULT = "10m";
600
577
  const absoluteWorkspacePath = (name) => z
601
578
  .string()
602
579
  .min(1)
603
- .max(1024)
580
+ .max(FILE_PATH_MAX)
604
581
  .refine((value) => (value === "/workspace" || value.startsWith("/workspace/")) &&
605
582
  !value.split("/").some((segment) => segment === ".." || segment === "."), { message: `${name} must be /workspace or a path under it, without . or .. segments` });
606
583
  /**
@@ -610,15 +587,12 @@ const absoluteWorkspacePath = (name) => z
610
587
  */
611
588
  export const EnvironmentSetupCommandSchema = z
612
589
  .object({
613
- command: z.string().min(1).max(4096),
590
+ /** At most the Tenant's Runtime limit `setupCommandChars`, checked when the manifest is put. */
591
+ command: z.string().min(1),
614
592
  /** Where it runs. Default `/workspace`. */
615
593
  cwd: absoluteWorkspacePath("cwd").optional(),
616
- /** Default 10m, at most 30m. */
617
- timeout: durationSchema("timeout")
618
- .refine((value) => (parseSandboxDuration(value) ?? 0) <= ENVIRONMENT_SETUP_TIMEOUT_MAX_MS, {
619
- message: "timeout is at most 30m",
620
- })
621
- .optional(),
594
+ /** Default 10m (`ENVIRONMENT_SETUP_TIMEOUT_DEFAULT`), at most the Tenant's `setupCommandMs`. */
595
+ timeout: durationSchema("timeout").optional(),
622
596
  })
623
597
  .strict();
624
598
  /**
@@ -626,18 +600,16 @@ export const EnvironmentSetupCommandSchema = z
626
600
  * is made or reset, before the setup commands. A file artifact is written at `path`; a folder
627
601
  * artifact is unpacked under it.
628
602
  */
629
- /** The most files one `files` entry by hash names (Q6). */
630
- export const ENVIRONMENT_FILES_MAX = 1000;
631
603
  /** A file's path inside a `files` entry by hash: relative, `/`-separated, without `.` or `..`. */
632
604
  const relativeFilePath = z
633
605
  .string()
634
606
  .min(1)
635
- .max(1024)
607
+ .max(FILE_PATH_MAX)
636
608
  .refine((value) => !value.startsWith("/") && !value.includes("\0") && value.split("/").every((segment) => segment !== "" && segment !== "." && segment !== ".."), { message: "a file's path is relative, without empty, . or .. segments" });
637
609
  /**
638
610
  * One input file entry (pods only): an artifact version copied to `path` (a file artifact, or a
639
611
  * folder's files under it), or (Q6) files by content hash, each `sha256:<hex>` of a definition
640
- * file the Tenant holds (`PUT /v1/files/sha256:<hex>`, at most 10 MiB each), copied under `path`
612
+ * file the Tenant holds (`PUT /v1/files/sha256:<hex>`, at most 2 GiB each), copied under `path`
641
613
  * at its relative path. A manifest by hash moves to another Tenant with its files.
642
614
  */
643
615
  export const EnvironmentFileSchema = z.union([
@@ -653,67 +625,89 @@ export const EnvironmentFileSchema = z.union([
653
625
  path: absoluteWorkspacePath("path"),
654
626
  files: z
655
627
  .record(relativeFilePath, z.string().refine(isDefinitionFileHash, { message: "each file is sha256:<64 lowercase hex>" }))
656
- .refine((files) => Object.keys(files).length >= 1 && Object.keys(files).length <= ENVIRONMENT_FILES_MAX, {
657
- message: `files names 1 to ${ENVIRONMENT_FILES_MAX} files`,
658
- }),
628
+ // At most the Tenant's Runtime limit `environmentFilesPerEntry`, checked when made (Q6).
629
+ .refine((files) => Object.keys(files).length >= 1, { message: "files names at least one file" }),
659
630
  })
660
631
  .strict(),
661
632
  ]);
662
633
  /**
663
- * An environment manifest's name (protocol 14, D63): 1–64 letters, digits, `.`, `_` and `-`,
664
- * starting with a letter or digit, such as `analyst-box`.
634
+ * An agent manifest's name (protocol 16): 1–64 letters, digits, `.`, `_` and `-`, starting with a
635
+ * letter or digit, such as `triage`; a version is at most 9 digits. Manifest names and Agent ids
636
+ * are separate namespaces.
665
637
  */
666
- const ENVIRONMENT_MANIFEST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
667
- export function isEnvironmentManifestName(value) {
668
- return typeof value === "string" && ENVIRONMENT_MANIFEST_NAME_PATTERN.test(value);
638
+ const AGENT_MANIFEST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
639
+ export function isAgentManifestName(value) {
640
+ return typeof value === "string" && AGENT_MANIFEST_NAME_PATTERN.test(value);
669
641
  }
670
- export const EnvironmentManifestNameSchema = z
642
+ export const AgentManifestNameSchema = z
671
643
  .string()
672
- .refine(isEnvironmentManifestName, {
673
- message: "An environment manifest's name is 1-64 letters, digits, '.', '_' and '-', starting with a letter or digit",
644
+ .refine(isAgentManifestName, {
645
+ message: "An agent manifest's name is 1-64 letters, digits, '.', '_' and '-', starting with a letter or digit",
674
646
  })
675
- .meta({ description: "An environment manifest's name, such as `analyst-box`" });
647
+ .meta({ description: "An agent manifest's name, such as `triage`" });
676
648
  /**
677
- * Which manifest an Environment is made from: `name` (its latest version when the Environment is
678
- * created) or `name@n` (version `n`). Either way the Environment keeps that version for life.
649
+ * Which agent manifest an Agent is made from: `name` (tracking: the latest version when the Agent
650
+ * is created; track T3 moves it on) or `name@n` (pinned to version `n`).
679
651
  */
680
- export function parseEnvironmentManifestRef(ref) {
652
+ export function parseAgentManifestRef(ref) {
681
653
  const at = ref.lastIndexOf("@");
682
654
  const name = at < 0 ? ref : ref.slice(0, at);
683
- if (!isEnvironmentManifestName(name))
655
+ if (!isAgentManifestName(name))
684
656
  return undefined;
685
657
  if (at < 0)
686
658
  return { name };
687
659
  const version = ref.slice(at + 1);
688
660
  return /^[1-9][0-9]{0,8}$/.test(version) ? { name, version: Number(version) } : undefined;
689
661
  }
690
- export const EnvironmentManifestRefSchema = z
662
+ export const AgentManifestRefSchema = z
691
663
  .string()
692
- .refine((value) => parseEnvironmentManifestRef(value) !== undefined, {
693
- message: "manifest is an environment manifest's name, or name@version such as analyst-box@3",
664
+ .refine((value) => parseAgentManifestRef(value) !== undefined, {
665
+ message: "manifest is an agent manifest's name, or name@version such as triage@3",
694
666
  })
695
- .meta({ description: "`name` (the latest version when the Environment is created) or `name@n`" });
667
+ .meta({ description: "`name` (tracking) or `name@n` (pinned)" });
696
668
  /**
697
- * `PUT /v1/environments/{environmentId}`: creates the Environment and its vault, or finds the
698
- * one with this id, so "get or create" is one call. An Environment is made from one version of an
699
- * environment manifest (`manifest`) or from the inline manifest these fields make, and never
700
- * changes what it runs after that (protocol 14, D63): on an existing one, `labels` replace its
701
- * labels and `ownerUserId` sets or clears its owner guard, a field that matches what it runs is
702
- * accepted, and anything else is `409 environment_immutable`, naming the fork that makes a new
703
- * Environment instead.
669
+ * What an Environment's artifacts, its sessions' skills and its disk versions may hold: part of
670
+ * its manifest, fixed for its life. Each limit left out is the Tenant's (`/v1/tenant/artifacts`,
671
+ * `/v1/tenant/skills`, `/v1/tenant/limits`) as it is when the limit is checked, and none may be
672
+ * above the Tenant's.
704
673
  */
705
- export const PutEnvironmentRequestSchema = z
674
+ export const EnvironmentLimitsSchema = z
706
675
  .object({
707
- requestId: RequestIdSchema.optional(),
708
- /**
709
- * The environment manifest to make the Environment from (Host feature
710
- * `environment-manifests`): `name` or `name@n`. With it, none of the inline fields below is
711
- * sent; `labels`, `ownerUserId` and `from` still are.
712
- */
713
- manifest: EnvironmentManifestRefSchema.optional(),
714
- /** Default `virtual`. `pod` needs sandbox pods (`nylorun local sandbox enable`). Fixed. */
715
- kind: z.enum(ENVIRONMENT_KINDS).optional(),
716
- labels: EnvironmentLabelsSchema.optional(),
676
+ artifacts: z
677
+ .object({
678
+ /** The largest file one artifact upload, save or export may store. */
679
+ fileBytes: z.number().int().positive().optional(),
680
+ /** The most bytes the artifacts of its sessions and its disk versions may hold together. */
681
+ totalBytes: z.number().int().positive().optional(),
682
+ })
683
+ .strict()
684
+ .optional(),
685
+ skills: z
686
+ .object({
687
+ /** The most bytes one skill's files may hold together, for a session to open in it. */
688
+ totalBytes: z.number().int().positive().optional(),
689
+ })
690
+ .strict()
691
+ .optional(),
692
+ /** Its disk versions, within the Tenant's Runtime limits `diskVersion*` (`/v1/tenant/limits`). */
693
+ disk: z
694
+ .object({
695
+ /** The most bytes of files one version of its disk holds. */
696
+ versionBytes: z.number().int().positive().optional(),
697
+ /** The most entries (files, links, empty directories) one version holds. */
698
+ versionEntries: z.number().int().positive().optional(),
699
+ })
700
+ .strict()
701
+ .optional(),
702
+ })
703
+ .strict();
704
+ /**
705
+ * The fields of a runtime section (agent manifest v8, protocol 16): what the Runtime provides
706
+ * around an Agent's loop. Environment manifest v1's fields, which they were until protocol 16.
707
+ */
708
+ const runtimeFields = {
709
+ /** `virtual`, `pod` (needs sandbox pods, `nylorun local sandbox enable`) or `none`. Fixed. */
710
+ kind: z.enum(ENVIRONMENT_KINDS),
717
711
  /** Pods only: the workload image (default the Tenant's, else `python:3.13-slim`). */
718
712
  image: z.string().min(1).optional(),
719
713
  resources: resourcesSchema.optional(),
@@ -729,42 +723,45 @@ export const PutEnvironmentRequestSchema = z
729
723
  .object({ allowedHosts: z.array(hostPatternSchema).optional() })
730
724
  .strict()
731
725
  .optional(),
732
- /**
733
- * The harness that runs the Environment's sessions (track R4): `nylorun` (ours, the default)
734
- * or the id of a custom harness. A pod Environment whose harness is not ours runs its
735
- * `image` as the harness: the image's own entrypoint, with nothing copied in. It is fixed
736
- * for the Environment's life (protocol 14): to run another harness, fork onto a manifest
737
- * version that names it. Each session pins the harness when it opens; a session whose
738
- * Environment id was deleted and made again with another harness fails its next turn with
739
- * `harness_mismatch`.
740
- */
741
- harness: HarnessIdSchema.optional(),
742
- /**
743
- * The owner guard: when set, only sessions of this owner may name the Environment (checked
744
- * when a session opens and at every turn start). `null` clears it.
745
- */
746
- ownerUserId: z.string().min(1).nullable().optional(),
747
726
  lifecycle: EnvironmentLifecycleSchema.optional(),
727
+ /** Pods only: commands run when the disk is made or reset, before any turn. */
728
+ setup: z.array(EnvironmentSetupCommandSchema).optional(),
729
+ /** Pods only: artifact versions or files by hash copied in when the disk is made or reset, before `setup`. */
730
+ files: z.array(EnvironmentFileSchema).optional(),
731
+ /** What its artifacts and its sessions' skills may hold, at most the Tenant's limits. Fixed. */
732
+ limits: EnvironmentLimitsSchema.optional(),
733
+ };
734
+ /**
735
+ * `PUT /v1/agents/{agentId}` (protocol 16): creates the Agent, its vault and its compute from a
736
+ * saved agent manifest, or finds the one with this id, so "get or create" is one call. An Agent is
737
+ * the live instance of one version of an agent manifest: `manifest: "name"` records that it
738
+ * tracks the manifest (its latest version, and every version saved later) and `"name@n"` that it
739
+ * is pinned to one; the version it runs is `resolvedVersion`. On an existing Agent, `labels`
740
+ * replace its labels, `owner` sets or clears its owner guard, and `manifest` moves it (track T3,
741
+ * D73): to another version of its manifest, tracking or pinned. A move changes no data: its id,
742
+ * disk, vault and sessions stay. A harness-only change applies at once; a runtime change of a pod
743
+ * waits for its next start; one that adds a required secret waits for its value. Its manifest's
744
+ * name, kind, harness and storage are fixed (`409 agent_fixed_field`); fork it to change them.
745
+ * `?dryRun=true` answers the move's plan (`AgentMovePlan`) and changes nothing.
746
+ */
747
+ export const PutAgentRequestSchema = z
748
+ .object({
749
+ requestId: RequestIdSchema.optional(),
750
+ /** The agent manifest it is made from: `name` (tracking) or `name@n` (pinned). */
751
+ manifest: AgentManifestRefSchema,
748
752
  /**
749
- * Pods only (Host feature `environment-setup`): commands run when the disk is made or reset,
750
- * before any turn. A change applies at the next reset.
751
- */
752
- setup: z.array(EnvironmentSetupCommandSchema).max(ENVIRONMENT_SETUP_MAX).optional(),
753
- /** Pods only: artifact versions copied in when the disk is made or reset, before `setup`. */
754
- files: z.array(EnvironmentFileSchema).max(ENVIRONMENT_SETUP_MAX).optional(),
755
- /**
756
- * The secrets an Environment of this kind needs, by name (D64): each slot's type, binding,
757
- * whether it is required and a description, never a value. With slots declared, a secret
758
- * write sends only the value and a name not declared is `409 secret_not_in_manifest`.
753
+ * The owner guard: when set, only sessions of this owner may run on the Agent (checked when
754
+ * a session opens and at every turn start). `null` clears it.
759
755
  */
760
- secrets: z.lazy(() => EnvironmentSecretSlotsSchema).optional(),
756
+ owner: z.string().min(1).nullable().optional(),
757
+ labels: EnvironmentLabelsSchema.optional(),
761
758
  /**
762
- * Only when the `PUT` creates the Environment (Host feature `environment-disk-versions`): its
763
- * disk starts from this version of another Environment's disk. Its vault starts empty.
759
+ * Only when the `PUT` creates the Agent (Host feature `environment-disk-versions`): its disk
760
+ * starts from this version of another Agent's disk. Its vault starts empty.
764
761
  */
765
762
  from: z
766
763
  .object({
767
- environment: EnvironmentIdSchema,
764
+ agent: AgentIdSchema,
768
765
  version: z.union([z.number().int().positive(), z.literal("latest")]),
769
766
  })
770
767
  .strict()
@@ -772,8 +769,9 @@ export const PutEnvironmentRequestSchema = z
772
769
  })
773
770
  .strict();
774
771
  /**
775
- * What an Environment runs (its inline manifest, called the recipe before protocol 14), resolved
776
- * against the Tenant's limits when it was made. It never changes after that.
772
+ * What an Agent's environment runs: its manifest version's runtime section resolved against the
773
+ * Tenant's limits when the Agent was made, with the harness that runs its loop. It never changes
774
+ * after that.
777
775
  */
778
776
  export const EnvironmentRecipeSchema = z
779
777
  .object({
@@ -785,12 +783,19 @@ export const EnvironmentRecipeSchema = z
785
783
  lifecycle: EnvironmentLifecycleSchema,
786
784
  setup: z.array(EnvironmentSetupCommandSchema).optional(),
787
785
  files: z.array(EnvironmentFileSchema).optional(),
786
+ /** As the manifest set them: a limit left out is the Tenant's when it is checked. */
787
+ limits: EnvironmentLimitsSchema.optional(),
788
788
  secrets: z.lazy(() => EnvironmentSecretSlotsSchema).optional(),
789
789
  })
790
790
  .strict();
791
- /** A session that names an Environment, as the Environment's view lists it. */
792
- export const EnvironmentSessionSchema = z
793
- .object({ id: z.string(), activeTurnId: z.string().nullable() })
791
+ /** A session on an Agent, as the Agent's view lists it: none is special (D71). */
792
+ export const AgentSessionSchema = z
793
+ .object({
794
+ id: z.string(),
795
+ ownerUserId: z.string(),
796
+ status: z.string(),
797
+ activeTurnId: z.string().nullable(),
798
+ })
794
799
  .strict();
795
800
  /** What the Runtime wants of a pod (`desired`) and what it last saw (`observed`). */
796
801
  export const POD_DESIRED = ["running", "suspended", "deleted"];
@@ -802,7 +807,7 @@ export const POD_OBSERVED = [
802
807
  "failed",
803
808
  "deleting",
804
809
  ];
805
- export const EnvironmentPodViewSchema = z
810
+ export const AgentPodViewSchema = z
806
811
  .object({
807
812
  desired: z.enum(POD_DESIRED),
808
813
  observed: z.enum(POD_OBSERVED),
@@ -820,58 +825,110 @@ export const EnvironmentPodViewSchema = z
820
825
  })
821
826
  .strict();
822
827
  /**
823
- * The compute states an Environment reports today: `ready` until a tool first runs in a virtual
824
- * one, then `creating`, `running` or `stopped`. An open set: clients must accept values they do
825
- * not know (a later release may add one, such as `cold`).
828
+ * The compute states an Agent's environment reports (`compute.state`): `ready` until a tool
829
+ * first runs in a virtual one, then `creating`, `running` or `stopped`. An open set: clients must
830
+ * accept values they do not know.
831
+ */
832
+ export const COMPUTE_STATES = ["ready", "creating", "running", "stopped"];
833
+ /**
834
+ * An Agent's state (protocol 16), derived when it is read, the first that holds:
835
+ *
836
+ * - `paused`: its desired state is `off` (nothing in protocol 16 sets it; track T6 adds the control).
837
+ * - `failing`: its compute failed or was lost, or a session's latest finished turn failed.
838
+ * - `input_required`: a session waits on a person (an approval or interaction, or an uncertain
839
+ * effect), even while another works.
840
+ * - `working`: a turn runs.
841
+ * - `sleeping`: nothing to do.
842
+ *
843
+ * An open set: clients must accept values they do not know.
826
844
  */
827
- export const ENVIRONMENT_STATES = ["ready", "creating", "running", "stopped"];
828
- /** `PUT` and `GET /v1/environments/{environmentId}`. */
829
- export const EnvironmentViewSchema = z
845
+ export const AGENT_STATES = ["paused", "failing", "input_required", "working", "sleeping"];
846
+ /** What made an Agent's state, or another state that also holds (`attention`). */
847
+ export const AgentAttentionSchema = z
848
+ .object({
849
+ state: z.enum(AGENT_STATES),
850
+ /** The session behind it; absent for the Agent's compute. */
851
+ sessionId: z.string().optional(),
852
+ /** Why, for a person: the session's status, or the compute's failure. */
853
+ reason: z.string(),
854
+ })
855
+ .strict();
856
+ /** `PUT` and `GET /v1/agents/{agentId}`. */
857
+ export const AgentViewSchema = z
830
858
  .object({
831
859
  id: z.string(),
832
- kind: z.enum(ENVIRONMENT_KINDS),
833
- labels: z.record(z.string(), z.string()),
860
+ /** How it names its manifest: `name` (tracking) or `name@n` (pinned). */
861
+ manifest: z.string(),
862
+ /** The version of the manifest it runs: each turn takes it when the turn starts. */
863
+ resolvedVersion: z.number().int().positive(),
864
+ /** The hash of that version. */
865
+ manifestHash: z.string(),
866
+ /** Whether `manifest` tracks the manifest's latest version or pins one. */
867
+ tracking: z.enum(["tracking", "pinned"]),
834
868
  /**
835
- * What it runs, fixed when it was made (protocol 14): its manifest's fields, or the inline
836
- * ones, resolved against the Tenant's limits.
869
+ * Track T3: the version it moves to while it is outdated, else `null`. It waits for a value of
870
+ * each required secret the version adds (`waitingFor: "secrets"`) or for its pod's next start
871
+ * (`"start"`); turns run `resolvedVersion` meanwhile.
837
872
  */
838
- manifest: EnvironmentRecipeSchema,
839
- /** The environment manifest it was made from and its version, when it was made from one. */
840
- manifestName: z.string().optional(),
841
- manifestVersion: z.number().int().positive().optional(),
842
- /** The hash of what it runs (`manifest`). */
843
- manifestHash: z.string().optional(),
873
+ targetVersion: z.number().int().positive().nullable(),
874
+ /** What the move to `targetVersion` waits for, else `null`. */
875
+ waitingFor: z.enum(["secrets", "start"]).nullable(),
844
876
  /**
845
- * The Environment it was forked from (`POST .../fork`, Q15), and the disk version it started
846
- * from (`null` for an empty disk).
877
+ * A version that failed to start: the Agent went back to the one it ran, and a tracking Agent
878
+ * does not move to it again on its own. `null` once a start on a new version succeeds.
847
879
  */
848
- forkedFrom: z
849
- .object({ environment: z.string(), disk: z.number().int().positive().nullable() })
880
+ failedVersion: z.number().int().positive().nullable(),
881
+ /**
882
+ * While its pod starts on a new version: the version it ran before, which a failed start
883
+ * goes back to, and since when it starts. `null` otherwise.
884
+ */
885
+ startCheck: z
886
+ .object({ from: z.number().int().positive(), startedAt: z.string() })
850
887
  .strict()
851
- .optional(),
888
+ .nullable(),
889
+ kind: z.enum(ENVIRONMENT_KINDS),
890
+ /** The harness that runs its loop: its manifest's `harness.id`, else `nylorun`. */
891
+ harness: z.string(),
892
+ /** The owner guard, or `null`. */
893
+ owner: z.string().nullable(),
894
+ labels: z.record(z.string(), z.string()),
895
+ /** See `AGENT_STATES`: an open set. */
896
+ state: z.string().meta({ description: "working, sleeping, input_required, failing or paused; an open set" }),
897
+ /** Every state that holds, with the session behind each: what made `state` first. */
898
+ attention: z.array(AgentAttentionSchema),
899
+ /** `on`, or `off` once paused (track T6). */
900
+ desired: z.enum(["on", "off"]),
901
+ /** When its next trigger fires: the earliest next run of its active triggers (D74), or `null`. */
902
+ nextWakeAt: z.string().nullable(),
903
+ compute: z
904
+ .object({
905
+ /** See `COMPUTE_STATES`: an open set. */
906
+ state: z.string().meta({ description: "ready, creating, running or stopped; an open set" }),
907
+ /** Kind `pod`: what the Runtime wants of the pod and what it last saw. */
908
+ pod: AgentPodViewSchema.optional(),
909
+ })
910
+ .strict(),
911
+ /** What its environment runs: the runtime section of `resolvedVersion`, resolved. */
912
+ runtime: EnvironmentRecipeSchema,
913
+ /** The limits in force now: its manifest's, else the Tenant's, never above the Tenant's. */
914
+ limits: z
915
+ .object({
916
+ artifacts: z.object({ fileBytes: z.number().int(), totalBytes: z.number().int() }).strict(),
917
+ skills: z.object({ totalBytes: z.number().int() }).strict(),
918
+ disk: z.object({ versionBytes: z.number().int(), versionEntries: z.number().int() }).strict(),
919
+ })
920
+ .strict(),
921
+ /** Its sessions (acting for a subject, only the subject's own). */
922
+ sessions: z.array(AgentSessionSchema),
852
923
  /** Each secret slot its manifest declares, and whether its vault holds a value for it. */
853
- slots: z
854
- .array(z
924
+ slots: z.array(z
855
925
  .object({
856
926
  name: z.string(),
857
927
  type: z.string(),
858
928
  required: z.boolean(),
859
929
  set: z.boolean(),
860
930
  })
861
- .strict())
862
- .optional(),
863
- /** Always 1 since protocol 14: an Environment never changes what it runs. */
864
- version: z.number().int().positive(),
865
- /** Always `version`. */
866
- appliedVersion: z.number().int().positive(),
867
- /** The owner guard, or `null`. */
868
- ownerUserId: z.string().nullable(),
869
- /** See `ENVIRONMENT_STATES`: an open set. */
870
- state: z.string().meta({ description: "ready, creating, running or stopped; an open set" }),
871
- /** Kind `pod`: what the Runtime wants of the pod and what it last saw. */
872
- pod: EnvironmentPodViewSchema.optional(),
873
- /** When it was last used: a turn, a recipe change, a secret write, a stop or a reset. */
874
- lastUsedAt: z.string(),
931
+ .strict()),
875
932
  /**
876
933
  * Its disk versions (Host feature `environment-disk-versions`): the latest, and the copy
877
934
  * that holds the disk now, if one does. Absent for kind `none`.
@@ -886,20 +943,25 @@ export const EnvironmentViewSchema = z
886
943
  startedAt: z.string(),
887
944
  })
888
945
  .strict()
889
- .optional(),
946
+ .nullable(),
890
947
  })
891
948
  .strict()
892
949
  .optional(),
893
- /** Sessions that name it (acting for a subject, only the subject's own). */
894
- sessions: z.array(EnvironmentSessionSchema),
950
+ /** The Agent it was forked from (`POST .../fork`), and the disk version it started from. */
951
+ forkedFrom: z
952
+ .object({ agent: z.string(), disk: z.number().int().positive().nullable() })
953
+ .strict()
954
+ .nullable(),
955
+ /** When it was last used: a turn, a secret write, a stop or a reset. */
956
+ lastUsedAt: z.string(),
895
957
  createdAt: z.string(),
896
958
  updatedAt: z.string(),
897
959
  })
898
960
  .strict();
899
- /** `POST /v1/environments/{id}/snapshot`: a new version of the Environment's disk. */
900
- export const EnvironmentSnapshotSchema = z
961
+ /** `POST /v1/agents/{id}/snapshot`: a new version of the Agent's disk. */
962
+ export const AgentSnapshotSchema = z
901
963
  .object({
902
- environmentId: z.string(),
964
+ agentId: z.string(),
903
965
  artifactId: z.string(),
904
966
  version: z.number().int().positive(),
905
967
  format: z.string(),
@@ -915,29 +977,29 @@ export const EnvironmentSnapshotSchema = z
915
977
  createdAt: z.string(),
916
978
  })
917
979
  .strict();
918
- /** `POST /v1/environments/{id}/restore`: which version of its disk to put back. */
919
- export const RestoreEnvironmentRequestSchema = z
980
+ /** `POST /v1/agents/{id}/restore`: which version of its disk to put back. */
981
+ export const RestoreAgentRequestSchema = z
920
982
  .object({
921
983
  requestId: RequestIdSchema.optional(),
922
984
  version: z.union([z.number().int().positive(), z.literal("latest")]),
923
985
  })
924
986
  .strict();
925
- export const EnvironmentRestoreSchema = z
987
+ export const AgentRestoreSchema = z
926
988
  .object({
927
- environmentId: z.string(),
989
+ agentId: z.string(),
928
990
  restored: z.number().int().positive(),
929
991
  /**
930
- * `done` once the version is back (a virtual Environment); `pending` while a pod's new volume
931
- * is seeded (`disk.operation` in the view until it ends; turns wait for it).
992
+ * `done` once the version is back (a virtual Agent); `pending` while a pod's new volume is
993
+ * seeded (`disk.operation` in the view until it ends; turns wait for it).
932
994
  */
933
995
  status: z.enum(["done", "pending"]),
934
996
  volumeGeneration: z.number().int().nonnegative().optional(),
935
997
  })
936
998
  .strict();
937
- /** `GET /v1/environments/{id}/versions`: its disk versions, newest first. */
938
- export const EnvironmentVersionsSchema = z
999
+ /** `GET /v1/agents/{id}/versions`: its disk versions, newest first. */
1000
+ export const AgentDiskVersionsSchema = z
939
1001
  .object({
940
- environmentId: z.string(),
1002
+ agentId: z.string(),
941
1003
  /** The folder artifact that holds them (read trees, files and diffs through `/v1/artifacts`). */
942
1004
  artifactId: z.string().nullable(),
943
1005
  latest: z.number().int().positive().nullable(),
@@ -950,22 +1012,19 @@ export const EnvironmentVersionsSchema = z
950
1012
  .strict()),
951
1013
  })
952
1014
  .strict();
953
- export const ListEnvironmentsResponseSchema = z
954
- .object({ environments: z.array(EnvironmentViewSchema) })
955
- .strict();
956
- export const DeleteEnvironmentResponseSchema = z
1015
+ export const DeleteAgentResponseSchema = z
957
1016
  .object({ id: z.string(), deleted: z.boolean() })
958
1017
  .strict();
959
- /** A turn that was running on an Environment when one of its connections opened (D67). */
1018
+ /** A turn that was running on an Agent when one of its connections opened (D67). */
960
1019
  export const EgressRunningTurnSchema = z
961
1020
  .object({ sessionId: z.string(), turnId: z.string() })
962
1021
  .strict();
963
1022
  /**
964
- * One connection a pod Environment opened through egress-gate (track R7, Q6): written when it
965
- * closes, or at once when the gate refused it, to the Environment's own stream as
966
- * `environment.egress` (D67). The connection is the Environment's: its egress token names the pod,
967
- * and the Environment's sessions run turns in parallel (D66). `runningTurns` lists the turns
968
- * active on it as the connection opened, at most 16, as context and never as the owner.
1023
+ * One connection a pod Agent opened through egress-gate (track R7, Q6): written when it closes,
1024
+ * or at once when the gate refused it, to the Agent's own stream as `agent.egress` (D67). The
1025
+ * connection is the Agent's: its egress token names the pod, and the Agent's sessions run turns
1026
+ * in parallel (D66). `runningTurns` lists the turns active on it as the connection opened, at
1027
+ * most 16, as context and never as the owner.
969
1028
  *
970
1029
  * `startedAt` is the gate's clock at CONNECT and `durationMs` runs from there to the close, so
971
1030
  * the span is the gate's own measurement. `bytesUp` is what the sandbox sent, `bytesDown` what it
@@ -975,7 +1034,7 @@ export const EgressRunningTurnSchema = z
975
1034
  */
976
1035
  export const EgressConnectionPayloadSchema = z
977
1036
  .object({
978
- environmentId: z.string(),
1037
+ agentId: z.string(),
979
1038
  host: z.string(),
980
1039
  port: z.number().int(),
981
1040
  outcome: z.enum(["allowed", "refused"]),
@@ -994,100 +1053,172 @@ export const EgressConnectionPayloadSchema = z
994
1053
  runningTurns: z.array(EgressRunningTurnSchema).max(16),
995
1054
  })
996
1055
  .passthrough();
997
- /** The schema id of an Environment's lifecycle events (its stream in the record). */
998
- export const ENVIRONMENT_EVENT_SCHEMA = "nylorun.environment-event/1";
999
- export const ENVIRONMENT_EVENT_TYPES = [
1000
- "environment.created",
1001
- "environment.attached",
1002
- "environment.detached",
1003
- "environment.deleted",
1056
+ /** The schema id of an Agent's lifecycle events (its stream in the record). */
1057
+ export const AGENT_EVENT_SCHEMA = "nylorun.agent-event/1";
1058
+ /**
1059
+ * `memory.updated` (track T5, D72): the session's agent changed the Agent's memory with its
1060
+ * `memory` tool: each memory the call changed, what changed it and its version after. The Agent's
1061
+ * stream carries the same as `agent.memory_updated`, with the session.
1062
+ */
1063
+ export const MemoryUpdatedPayloadSchema = z
1064
+ .object({
1065
+ effectId: z.string(),
1066
+ changes: z
1067
+ .array(z.object({ path: z.string(), operation: z.enum(MEMORY_OPERATIONS), version: z.number().int().positive() }).strict())
1068
+ .min(1),
1069
+ })
1070
+ .passthrough();
1071
+ export const AGENT_EVENT_TYPES = [
1072
+ "agent.created",
1073
+ "agent.attached",
1074
+ "agent.detached",
1075
+ "agent.deleted",
1004
1076
  // Kind `pod` (Host feature `sandbox-pods`).
1005
- "environment.running",
1006
- "environment.suspended",
1007
- "environment.relaunched",
1008
- "environment.lost",
1009
- "environment.reset",
1010
- "environment.failed",
1011
- // Forked into a new Environment (Q15).
1012
- "environment.forked",
1013
- // egress-gate: every connection the Environment opens (R7, D67).
1014
- "environment.egress",
1077
+ "agent.running",
1078
+ "agent.suspended",
1079
+ "agent.relaunched",
1080
+ "agent.lost",
1081
+ "agent.reset",
1082
+ "agent.failed",
1083
+ // Forked into a new Agent (Q15).
1084
+ "agent.forked",
1085
+ // Moved to another version of its manifest (track T3, D73).
1086
+ "agent.outdated",
1087
+ "agent.version_changed",
1088
+ "agent.start_failed",
1089
+ // egress-gate: every connection the Agent opens (R7, D67).
1090
+ "agent.egress",
1091
+ // Triggers (track T4, D74): each run, and a trigger paused or resumed.
1092
+ "agent.run",
1093
+ "agent.trigger_paused",
1094
+ "agent.trigger_resumed",
1095
+ "agent.trigger_secret_rotated",
1096
+ // Memory (track T5, D72): a turn changed the Agent's memories.
1097
+ "agent.memory_updated",
1015
1098
  ];
1016
- /** The payload of each Environment lifecycle event. */
1017
- export const ENVIRONMENT_EVENT_PAYLOADS = {
1018
- "environment.created": z
1099
+ /** The payload of each Agent lifecycle event. */
1100
+ export const AGENT_EVENT_PAYLOADS = {
1101
+ "agent.created": z
1019
1102
  .object({
1020
1103
  kind: z.enum(ENVIRONMENT_KINDS),
1021
1104
  labels: z.record(z.string(), z.string()),
1022
- /** The environment manifest and version it was made from (protocol 14, D63). */
1023
- manifest: z.object({ name: z.string(), version: z.number().int().positive() }).strict().optional(),
1024
- /** The Environment it was forked from, and the disk version it started from (Q15). */
1105
+ /** The agent manifest and version it was made from, and how it refers to it. */
1106
+ manifest: z
1107
+ .object({ name: z.string(), version: z.number().int().positive(), tracking: z.enum(["tracking", "pinned"]) })
1108
+ .strict(),
1109
+ /** The Agent it was forked from, and the disk version it started from (Q15). */
1025
1110
  forkedFrom: z
1026
- .object({ environment: z.string(), disk: z.number().int().positive().nullable() })
1111
+ .object({ agent: z.string(), disk: z.number().int().positive().nullable() })
1027
1112
  .strict()
1028
1113
  .optional(),
1029
1114
  })
1030
1115
  .passthrough(),
1031
- "environment.attached": z.object({ sessionId: z.string() }).passthrough(),
1032
- "environment.detached": z
1116
+ "agent.attached": z.object({ sessionId: z.string() }).passthrough(),
1117
+ "agent.detached": z
1033
1118
  .object({ sessionId: z.string(), reason: z.enum(["reset"]) })
1034
1119
  .passthrough(),
1035
1120
  /** Deleted by a `DELETE`, or by the sweep once `lifecycle.deleteAfter` passed (`reason`). */
1036
- "environment.deleted": z
1121
+ "agent.deleted": z
1037
1122
  .object({ reason: z.enum(["delete", "deleteAfter"]).optional() })
1038
1123
  .passthrough(),
1039
- /** A pod joined and serves the Environment. */
1040
- "environment.running": z.object({ hostEpoch: z.number().int() }).passthrough(),
1124
+ /** A pod joined and serves the Agent. */
1125
+ "agent.running": z.object({ hostEpoch: z.number().int() }).passthrough(),
1041
1126
  /** Stopped (`POST .../stop`, or idle): the volume is kept; the next turn starts it again. */
1042
- "environment.suspended": z.object({ reason: z.enum(["stop", "idle"]) }).passthrough(),
1127
+ "agent.suspended": z.object({ reason: z.enum(["stop", "idle", "restart"]) }).passthrough(),
1043
1128
  /** Its pod was replaced (same volume): the old pod's host token no longer works. */
1044
- "environment.relaunched": z.object({ hostEpoch: z.number().int() }).passthrough(),
1129
+ "agent.relaunched": z.object({ hostEpoch: z.number().int() }).passthrough(),
1045
1130
  /** Its volume or node is gone: turns are refused until a reset. */
1046
- "environment.lost": z.object({ reason: z.string() }).passthrough(),
1131
+ "agent.lost": z.object({ reason: z.string() }).passthrough(),
1047
1132
  /** Reset: a new pod on a new, empty volume. */
1048
- "environment.reset": z.object({ volumeGeneration: z.number().int() }).passthrough(),
1133
+ "agent.reset": z.object({ volumeGeneration: z.number().int() }).passthrough(),
1049
1134
  /** The pod did not become ready. */
1050
- "environment.failed": z.object({ reason: z.string() }).passthrough(),
1051
- /** Forked into Environment `to`: its disk started from version `disk`, `secrets` were copied. */
1052
- "environment.forked": z
1135
+ "agent.failed": z.object({ reason: z.string() }).passthrough(),
1136
+ /** Forked into Agent `to`: its disk started from version `disk`, `secrets` were copied. */
1137
+ "agent.forked": z
1053
1138
  .object({
1054
1139
  to: z.string(),
1055
1140
  disk: z.number().int().positive().nullable(),
1056
- manifest: z.object({ name: z.string(), version: z.number().int().positive() }).strict().optional(),
1141
+ manifest: z.object({ name: z.string(), version: z.number().int().positive() }).strict(),
1057
1142
  secrets: z.number().int().nonnegative(),
1058
1143
  })
1059
1144
  .passthrough(),
1145
+ /**
1146
+ * Asked to move to version `to` of its manifest, which waits (track T3): for a value of each
1147
+ * required secret it adds (`secrets`), or for its pod's next start (`start`).
1148
+ */
1149
+ "agent.outdated": z
1150
+ .object({
1151
+ from: z.number().int().positive(),
1152
+ to: z.number().int().positive(),
1153
+ waitingFor: z.enum(["secrets", "start"]),
1154
+ })
1155
+ .passthrough(),
1156
+ /** Runs version `to` of its manifest now: turns that start from here run it (track T3). */
1157
+ "agent.version_changed": z
1158
+ .object({ from: z.number().int().positive(), to: z.number().int().positive() })
1159
+ .passthrough(),
1160
+ /**
1161
+ * Its pod did not start on version `to` (its setup failed, the pod failed, or it took longer
1162
+ * than the Host allows): it went back to version `from`, with its disk as it was (track T3).
1163
+ */
1164
+ "agent.start_failed": z
1165
+ .object({
1166
+ from: z.number().int().positive(),
1167
+ to: z.number().int().positive(),
1168
+ reason: z.string(),
1169
+ reverted: z.boolean(),
1170
+ })
1171
+ .passthrough(),
1060
1172
  /** A connection through egress-gate, with the turns running as it opened (D67). */
1061
- "environment.egress": EgressConnectionPayloadSchema,
1173
+ "agent.egress": EgressConnectionPayloadSchema,
1174
+ /** A trigger fired, or was run by hand: the run and what came of it (`TriggerRunSchema`). */
1175
+ "agent.run": z
1176
+ .object({
1177
+ runId: z.string(),
1178
+ triggerId: z.string(),
1179
+ dueAt: z.string(),
1180
+ late: z.boolean(),
1181
+ status: z.string(),
1182
+ reason: z.string().optional(),
1183
+ sessionId: z.string().optional(),
1184
+ })
1185
+ .passthrough(),
1186
+ "agent.trigger_paused": z.object({ triggerId: z.string(), reason: z.string() }).passthrough(),
1187
+ "agent.trigger_resumed": z.object({ triggerId: z.string() }).passthrough(),
1188
+ /** A webhook trigger's signing secret was made or replaced; the one before stopped working. */
1189
+ "agent.trigger_secret_rotated": z.object({ triggerId: z.string() }).passthrough(),
1190
+ /** A turn changed the Agent's memories (`memory.updated` in its session): which, and how. */
1191
+ "agent.memory_updated": MemoryUpdatedPayloadSchema.extend({ sessionId: z.string(), turnId: z.string() }),
1062
1192
  };
1063
- /** One lifecycle event on an Environment's stream, numbered from 0. */
1064
- export const EnvironmentEventSchema = z
1193
+ /** One lifecycle event on an Agent's stream, numbered from 0. */
1194
+ export const AgentEventSchema = z
1065
1195
  .object({
1066
- schema: z.literal(ENVIRONMENT_EVENT_SCHEMA),
1196
+ schema: z.literal(AGENT_EVENT_SCHEMA),
1067
1197
  eventId: z.string(),
1068
1198
  tenantId: z.string(),
1069
- environmentId: z.string(),
1199
+ agentId: z.string(),
1070
1200
  seq: z.number().int().nonnegative(),
1071
1201
  time: z.string(),
1072
- type: z.enum(ENVIRONMENT_EVENT_TYPES),
1202
+ type: z.enum(AGENT_EVENT_TYPES),
1073
1203
  payload: z.record(z.string(), z.unknown()),
1074
1204
  })
1075
1205
  .strict();
1076
- export const ListEnvironmentEventsResponseSchema = z
1077
- .object({ events: z.array(EnvironmentEventSchema) })
1206
+ export const ListAgentEventsResponseSchema = z
1207
+ .object({ events: z.array(AgentEventSchema) })
1078
1208
  .strict();
1209
+ /**
1210
+ * `PUT /v1/sessions/{id}` (protocol 16): the session's Agent, owner and info. The session runs on
1211
+ * the Agent for its life (its sandbox, its vault's credentials) and pins the manifest version the
1212
+ * Agent runs when it opens. No session is special (D71): an app that keeps one conversation
1213
+ * going reuses its id.
1214
+ */
1079
1215
  export const PutSessionRequestSchema = z
1080
1216
  .object({
1081
1217
  requestId: RequestIdSchema,
1082
- agentId: z.string().min(1),
1218
+ /** The Agent the session runs on. Fixed once the session exists. */
1219
+ agent: AgentIdSchema,
1083
1220
  ownerUserId: z.string().min(1),
1084
1221
  info: jsonObject.optional(),
1085
- /**
1086
- * The Environment the session runs in: its sandbox, and its vault's credentials for the
1087
- * session's shell, MCP servers and HTTP tools. Omitted: no sandbox and no credentials.
1088
- * Fixed once the session exists.
1089
- */
1090
- environment: EnvironmentIdSchema.optional(),
1091
1222
  })
1092
1223
  .strict();
1093
1224
  /** The hosts a harness can run on (blueprint D38). */
@@ -1109,19 +1240,15 @@ export const TenantEnvironmentsConfigSchema = z
1109
1240
  /** Stop compute after this long without use; an Environment's `lifecycle.idle` is at most this. */
1110
1241
  idle: durationSchema("limits.idle").optional(),
1111
1242
  /** The most Environments the Tenant may hold. Default 100. */
1112
- environments: z.number().int().min(0).max(100_000).optional(),
1243
+ environments: z.number().int().min(0).optional(),
1113
1244
  })
1114
1245
  .strict()
1115
1246
  .optional(),
1116
1247
  /** Pods: how long a pod has to stop. Read at every timer. */
1117
1248
  lifecycle: z
1118
1249
  .object({
1119
- /** The pod's grace period to stop, at most 30s. Default 10s. */
1120
- stopGrace: durationSchema("lifecycle.stopGrace")
1121
- .refine((value) => (parseSandboxDuration(value) ?? 0) <= 30_000, {
1122
- message: "lifecycle.stopGrace is at most 30s",
1123
- })
1124
- .optional(),
1250
+ /** The pod's grace period to stop (its `terminationGracePeriodSeconds`). Default 10s. */
1251
+ stopGrace: durationSchema("lifecycle.stopGrace").optional(),
1125
1252
  })
1126
1253
  .strict()
1127
1254
  .optional(),
@@ -1202,12 +1329,6 @@ const credentialRoutingChange = {
1202
1329
  via: CredentialViaSchema.nullable().optional(),
1203
1330
  identity: CredentialIdentitySchema.nullable().optional(),
1204
1331
  };
1205
- /**
1206
- * An environment variable name a shell secret or plain variable may take (R2c, D50): a POSIX
1207
- * name. Names the sandbox needs for itself (the proxy, the trust store, `PATH`, `HOME`) and
1208
- * `NYLORUN_*` are reserved.
1209
- */
1210
- export const ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1211
1332
  export const RESERVED_ENVIRONMENT_NAMES = new Set([
1212
1333
  "PATH",
1213
1334
  "HOME",
@@ -1234,8 +1355,12 @@ const EnvironmentNameSchema = z
1234
1355
  .string()
1235
1356
  .regex(ENVIRONMENT_NAME_PATTERN, "An environment variable name is a letter or _ followed by letters, digits or _")
1236
1357
  .refine((name) => !isReservedEnvironmentName(name), "That environment variable name is reserved");
1237
- /** The value a sandbox sees for every `environment_secret` (R2c, D50): never the secret. */
1238
- export const ENVIRONMENT_SECRET_SENTINEL = "nylorun-managed";
1358
+ /**
1359
+ * The value a sandbox sees for every `environment_secret` (R2c, D50): never the secret. Word
1360
+ * characters only, so CLIs that check a token's format before sending it (the Vercel CLI
1361
+ * refuses anything matching `\W`) still send the request egress-gate sets the header on.
1362
+ */
1363
+ export const ENVIRONMENT_SECRET_SENTINEL = "nylorun_managed";
1239
1364
  /**
1240
1365
  * How egress-gate writes an `environment_secret` into a request (R2c, D50): one header, set on
1241
1366
  * every request to a bound host. `format` is text with `{value}` once, optionally inside a
@@ -1276,17 +1401,21 @@ const AllowedHostsSchema = z
1276
1401
  .toLowerCase()
1277
1402
  .refine((host) => /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(host) && !/^\d+(\.\d+){3}$/.test(host), "allowedHosts takes exact host names such as api.github.com: no wildcard, port or IP address"))
1278
1403
  .min(1)
1279
- .max(32)
1280
1404
  .refine((hosts) => new Set(hosts).size === hosts.length, "allowedHosts lists each host once");
1405
+ /** At most the Tenant's Runtime limit `secretValueChars`, checked when it is written. */
1281
1406
  const EnvironmentValueSchema = z
1282
1407
  .string()
1283
1408
  .min(1)
1284
- .max(8192)
1285
1409
  .refine((value) => !/[\r\n\0]/.test(value), "A value has no CR, LF or NUL");
1286
- /** The name of a credential for a tool (`bearer` or `headers`): a label of 1–64 characters. */
1410
+ /**
1411
+ * The name of a credential for a tool (`bearer` or `headers`): a label of 1–64 characters.
1412
+ * An identifier's grammar is the protocol's (B15): it crosses the Runtime API, tokens and grants
1413
+ * and means the same in every installation, so its length is a constant of protocol 15, not a
1414
+ * setting.
1415
+ */
1287
1416
  export const TOOL_SECRET_NAME_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
1288
1417
  /**
1289
- * `PUT /v1/environments/{environmentId}/secrets/{name}` (D56): creates or replaces one credential
1418
+ * `PUT /v1/agents/{agentId}/secrets/{name}` (D56): creates or replaces one credential
1290
1419
  * in the Environment's vault. For `environment_secret` and `environment_variable` the name is
1291
1420
  * the variable's name (a POSIX name, not reserved); for `bearer` and `headers` it is a label.
1292
1421
  * The same name and type keeps the credential and re-seals its value and binding; another type
@@ -1294,7 +1423,7 @@ export const TOOL_SECRET_NAME_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
1294
1423
  * credentials bound to one host, or two `bearer`/`headers` credentials for one URL, are
1295
1424
  * `409 credential_conflict`.
1296
1425
  */
1297
- export const PutEnvironmentSecretRequestSchema = z.discriminatedUnion("type", [
1426
+ export const PutAgentSecretRequestSchema = z.discriminatedUnion("type", [
1298
1427
  z
1299
1428
  .object({
1300
1429
  requestId: RequestIdSchema.optional(),
@@ -1334,10 +1463,10 @@ export const PutEnvironmentSecretRequestSchema = z.discriminatedUnion("type", [
1334
1463
  * A secret write on an Environment whose manifest declares the secret's slot (D64): only the
1335
1464
  * value, `value` (or `headers` for a `headers` slot). Its type and binding come from the slot.
1336
1465
  */
1337
- export const PutEnvironmentSecretValueRequestSchema = z
1466
+ export const PutAgentSecretValueRequestSchema = z
1338
1467
  .object({
1339
1468
  requestId: RequestIdSchema.optional(),
1340
- value: z.string().min(1).max(8192).optional(),
1469
+ value: z.string().min(1).optional(),
1341
1470
  headers: CredentialHeadersSchema.optional(),
1342
1471
  })
1343
1472
  .strict()
@@ -1361,11 +1490,12 @@ export function environmentSecretNameError(type, name) {
1361
1490
  const slotBase = {
1362
1491
  /** Whether a session whose agent needs it may open without it. Default false. */
1363
1492
  required: z.boolean().optional(),
1364
- description: z.string().max(500).optional(),
1493
+ /** At most the Tenant's Runtime limit `secretDescriptionChars`, checked when the manifest is put. */
1494
+ description: z.string().optional(),
1365
1495
  };
1366
1496
  /**
1367
1497
  * One secret an Environment of a kind needs (D64): its type and binding, never its value. The
1368
- * value is written into each Environment's vault (`PUT /v1/environments/{id}/secrets/{name}`
1498
+ * value is written into each Environment's vault (`PUT /v1/agents/{id}/secrets/{name}`
1369
1499
  * with `{ value }`, or `{ headers }` for `headers`), and the binding comes from here.
1370
1500
  */
1371
1501
  export const EnvironmentSecretSlotSchema = z.discriminatedUnion("type", [
@@ -1381,74 +1511,472 @@ export const EnvironmentSecretSlotSchema = z.discriminatedUnion("type", [
1381
1511
  z.object({ type: z.literal("bearer"), url: z.string().min(1), ...credentialRouting, ...slotBase }).strict(),
1382
1512
  z.object({ type: z.literal("headers"), url: z.string().min(1), ...credentialRouting, ...slotBase }).strict(),
1383
1513
  ]);
1384
- /** The most secret slots one manifest declares. */
1385
- export const ENVIRONMENT_SECRET_SLOTS_MAX = 64;
1514
+ /** A manifest's secret slots: at most the Tenant's Runtime limit `environmentSecretSlots`. */
1386
1515
  export const EnvironmentSecretSlotsSchema = z
1387
1516
  .record(z.string(), EnvironmentSecretSlotSchema)
1388
1517
  .superRefine((slots, ctx) => {
1389
- const names = Object.keys(slots);
1390
- if (names.length > ENVIRONMENT_SECRET_SLOTS_MAX)
1391
- ctx.addIssue({ code: "custom", message: `At most ${ENVIRONMENT_SECRET_SLOTS_MAX} secrets` });
1392
- for (const name of names) {
1518
+ for (const name of Object.keys(slots)) {
1393
1519
  const error = environmentSecretNameError(slots[name].type, name);
1394
1520
  if (error)
1395
1521
  ctx.addIssue({ code: "custom", path: [name], message: error });
1396
1522
  }
1397
1523
  });
1398
- /** The schema version of an environment manifest; the Runtime refuses one it does not know. */
1399
- export const ENVIRONMENT_MANIFEST_SCHEMA_VERSION = 1;
1400
- const environmentFields = PutEnvironmentRequestSchema.shape;
1524
+ // --- Agent manifest v8 (protocol 16, track T2) ----------------------------------------------
1525
+ /** The schema version of an agent manifest the Runtime saves at `/v1/agent-manifests/{name}`. */
1526
+ export const AGENT_MANIFEST_V8_SCHEMA_VERSION = 8;
1527
+ /** A skill of the harness section: v7's, and the secret slots its scripts read. */
1528
+ const harnessSkillSchema = z
1529
+ .object({
1530
+ name: z.string().min(1),
1531
+ description: z.string().min(1),
1532
+ files: z.record(z.string(), z.string()),
1533
+ plugin: pluginLabelSchema.optional(),
1534
+ secrets: z
1535
+ .array(z.string().regex(ENVIRONMENT_NAME_PATTERN, "A skill's secrets are environment variable names"))
1536
+ .optional(),
1537
+ })
1538
+ .strict()
1539
+ .superRefine((skill, ctx) => {
1540
+ const issue = skillFilesIssue(skill.files);
1541
+ if (issue)
1542
+ ctx.addIssue({ code: "custom", path: ["files"], message: `Skill '${skill.name}' ${issue}` });
1543
+ });
1544
+ const harnessMcpServerFields = {
1545
+ name: modelFacingName("MCP server"),
1546
+ url: z.string().min(1),
1547
+ headers: z.record(z.string(), z.string()).optional(),
1548
+ /** A `runtime.secrets` slot of type `bearer` or `headers` bound to `url`. */
1549
+ credential: z.string().min(1).optional(),
1550
+ ...mcpServerSettings,
1551
+ };
1552
+ const harnessMcpServerSchema = z.discriminatedUnion("type", [
1553
+ z.object({ type: z.literal("streamable-http"), ...harnessMcpServerFields }).strict(),
1554
+ z.object({ type: z.literal("sse"), ...harnessMcpServerFields }).strict(),
1555
+ ], { error: (issue) => stdioIssue(issue.input) });
1556
+ const harnessIdField = HarnessIdSchema.optional().meta({
1557
+ description: "The harness that runs the loop: `nylorun` (ours, the default) or a custom harness's id",
1558
+ });
1559
+ const harnessLoopField = definitionJson
1560
+ .optional()
1561
+ .meta({ description: "The harness's own settings, passed to it in turn.start; the Runtime never reads them" });
1401
1562
  /**
1402
- * An environment manifest (protocol 14, D63): a named, versioned definition of a kind of
1403
- * Environment, saved like an agent (`PUT /v1/environment-manifests/{name}`). It holds what every
1404
- * Environment made from it shares; an Environment's id, labels, owner guard, disk and secret
1405
- * values are its own. Written as a JSON file with `$schema`, which clients drop before saving.
1563
+ * `harness.memory` (track T5, D72): turns the Agent's memory on. Its `access` holds in every turn,
1564
+ * whoever starts it; `instructions` follow the engine's own memory rules.
1406
1565
  */
1407
- export const EnvironmentManifestSchema = z
1566
+ const harnessMemoryField = z
1567
+ .strictObject({
1568
+ access: z.enum(MEMORY_ACCESS).optional().meta({ description: "`read_write` (the default) or `read_only`" }),
1569
+ instructions: z
1570
+ .string()
1571
+ .max(MEMORY_INSTRUCTIONS_MAX)
1572
+ .optional()
1573
+ .meta({ description: "What this agent should remember, after the engine's own memory rules" }),
1574
+ })
1575
+ .optional()
1576
+ .meta({ description: "The Agent's memory: Markdown files under /memories it keeps across sessions (D72)" });
1577
+ /** Fields the harness section refuses with where they went. */
1578
+ const REMOVED_HARNESS_FIELDS = Object.freeze({
1579
+ requires: "harness.requires left the API in agent manifest v8: the Runtime checks the harness against the runtime section when the manifest is saved. Keep requires in harness.manifest.json, where the CLI checks it",
1580
+ manifestSchemaVersion: "manifestSchemaVersion belongs at the top of the agent manifest, not in harness",
1581
+ name: "name belongs at the top of the agent manifest, not in harness",
1582
+ description: "description belongs at the top of the agent manifest, not in harness",
1583
+ metadata: "metadata belongs at the top of the agent manifest, not in harness",
1584
+ approval: "Tool approvals are the Tenant's tool policy (PUT /v1/tenant/tool-policy)",
1585
+ });
1586
+ const agentHarnessObject = z
1587
+ .strictObject({
1588
+ id: harnessIdField,
1589
+ instructions: z.array(z.string()).optional(),
1590
+ tools: z.array(toolManifestSchema).optional(),
1591
+ skills: z.record(z.string(), harnessSkillSchema).optional(),
1592
+ mcpServers: z.record(z.string(), harnessMcpServerSchema).optional(),
1593
+ plugins: z.array(pluginLabelSchema).optional(),
1594
+ outputSchema: definitionJson.optional(),
1595
+ loop: harnessLoopField,
1596
+ memory: harnessMemoryField,
1597
+ functions: z.unknown().optional().meta({ description: "Reserved: Functions are not available yet" }),
1598
+ }, { error: removedFieldError(REMOVED_HARNESS_FIELDS) })
1599
+ .superRefine((harness, ctx) => {
1600
+ if (harness.functions !== undefined)
1601
+ ctx.addIssue({ code: "custom", path: ["functions"], message: "Functions are not available yet" });
1602
+ delegationIssues({ tools: harness.tools }, (message) => ctx.addIssue({ code: "custom", message }));
1603
+ const names = new Set();
1604
+ for (const tool of harness.tools ?? []) {
1605
+ if (tool.name.includes("__"))
1606
+ ctx.addIssue({
1607
+ code: "custom",
1608
+ message: `Tool '${tool.name}' must not contain '__', which names an MCP server's tools`,
1609
+ });
1610
+ if (names.has(tool.name))
1611
+ ctx.addIssue({ code: "custom", message: "Tool names must be unique" });
1612
+ names.add(tool.name);
1613
+ }
1614
+ if (harness.skills && Object.keys(harness.skills).length === 0)
1615
+ ctx.addIssue({ code: "custom", message: "harness.skills must be omitted when the agent has no skills" });
1616
+ for (const [key, skill] of Object.entries(harness.skills ?? {}))
1617
+ if (key !== skill.name)
1618
+ ctx.addIssue({ code: "custom", message: `harness.skills key '${key}' must equal the skill name` });
1619
+ if (harness.mcpServers && Object.keys(harness.mcpServers).length === 0)
1620
+ ctx.addIssue({ code: "custom", message: "harness.mcpServers must be omitted when the agent has no servers" });
1621
+ for (const [key, server] of Object.entries(harness.mcpServers ?? {}))
1622
+ if (key !== server.name)
1623
+ ctx.addIssue({ code: "custom", message: `harness.mcpServers key '${key}' must equal the server name` });
1624
+ });
1625
+ const workflowHarnessObject = z
1408
1626
  .object({
1409
- manifestSchemaVersion: z.literal(ENVIRONMENT_MANIFEST_SCHEMA_VERSION, {
1410
- error: (issue) => `manifestSchemaVersion ${JSON.stringify(issue.input)} is not one this Runtime reads: use ${ENVIRONMENT_MANIFEST_SCHEMA_VERSION}`,
1627
+ kind: z.literal("workflow"),
1628
+ id: harnessIdField,
1629
+ inputSchema: definitionJson.optional(),
1630
+ outputSchema: definitionJson.optional(),
1631
+ root: workflowNodeSchema,
1632
+ agents: z.record(z.string().min(1), z.union([workflowManifestSchema, AgentManifestSchema])),
1633
+ plugins: z.array(pluginLabelSchema).optional(),
1634
+ loop: harnessLoopField,
1635
+ })
1636
+ .strict()
1637
+ .superRefine((flow, ctx) => {
1638
+ if (flow.id !== undefined && flow.id !== DEFAULT_HARNESS)
1639
+ ctx.addIssue({ code: "custom", path: ["id"], message: `A flow runs in our harness: harness.id must be ${DEFAULT_HARNESS} or left out` });
1640
+ for (const agentId of referencedAgents(flow.root))
1641
+ if (!(agentId in flow.agents))
1642
+ ctx.addIssue({
1643
+ code: "custom",
1644
+ path: ["agents"],
1645
+ message: `Agent '${agentId}' is used in the flow but not embedded in agents`,
1646
+ });
1647
+ for (const [key, agent] of Object.entries(flow.agents))
1648
+ if (agent.id !== key)
1649
+ ctx.addIssue({ code: "custom", path: ["agents", key], message: `Embedded agent '${agent.id}' must be keyed by its id` });
1650
+ });
1651
+ /** What runs inside the loop of an agent: the `harness` section of agent manifest v8. */
1652
+ export const AgentHarnessSectionSchema = agentHarnessObject.meta({
1653
+ id: "AgentHarnessSection",
1654
+ });
1655
+ /** A flow's `harness` section (`kind: "workflow"`). */
1656
+ export const WorkflowHarnessSectionSchema = workflowHarnessObject.meta({
1657
+ id: "WorkflowHarnessSection",
1658
+ });
1659
+ /** The `harness` section: an agent's loop, or a flow (`kind: "workflow"`). */
1660
+ export const HarnessSectionSchema = z.union([WorkflowHarnessSectionSchema, AgentHarnessSectionSchema]);
1661
+ /**
1662
+ * A trigger's id in `runtime.triggers` (track T4, D74): 1–64 letters, digits, `.`, `_` and `-`,
1663
+ * starting with a letter or digit. The map key; it names the trigger in routes and runs.
1664
+ */
1665
+ export const TriggerIdSchema = z
1666
+ .string()
1667
+ .regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/, {
1668
+ message: "A trigger id is 1-64 letters, digits, '.', '_' and '-', starting with a letter or digit",
1669
+ })
1670
+ .meta({ description: "A trigger's id, such as `hourly-check`" });
1671
+ /** The signature schemes a webhook trigger verifies (D75): Standard Webhooks only in T4. */
1672
+ export const WEBHOOK_SCHEMES = ["standard-webhooks"];
1673
+ /**
1674
+ * One trigger of an agent manifest's `runtime.triggers` (track T4, D74): exactly one of
1675
+ * `schedule` (five-field cron, minute granularity, in `timezone`, an IANA name, default UTC), `at`
1676
+ * (one run at an RFC 3339 time with an offset) or `webhook` (a webhook endpoint verified with the
1677
+ * named scheme), plus the `session` each run goes to and the author's `prompt`.
1678
+ *
1679
+ * `session` is a session id of the Agent, opened on the trigger's first run if it does not
1680
+ * exist, or `"new"` for a new session per run (`run-<runId>`). The Runtime keeps no main session
1681
+ * (D71). The cron's smallest gap, the `at` time, the prompt's length and how many triggers a
1682
+ * manifest holds are checked against the Tenant's Runtime limits when it is saved.
1683
+ */
1684
+ export const TriggerSchema = z
1685
+ .strictObject({
1686
+ schedule: z
1687
+ .string()
1688
+ .regex(/^\S+(\s+\S+){4}$/, { message: "schedule is five cron fields: minute hour day-of-month month day-of-week" })
1689
+ .optional(),
1690
+ timezone: z.string().min(1).optional(),
1691
+ at: z.iso.datetime({ offset: true, message: "at is an RFC 3339 time with an offset, such as 2026-11-01T09:00:00+05:30" }).optional(),
1692
+ webhook: z.enum(WEBHOOK_SCHEMES).optional(),
1693
+ session: z.string().min(1).max(200),
1694
+ prompt: z.string().min(1),
1695
+ })
1696
+ .superRefine((trigger, ctx) => {
1697
+ const kinds = [trigger.schedule, trigger.at, trigger.webhook].filter((value) => value !== undefined);
1698
+ if (kinds.length !== 1)
1699
+ ctx.addIssue({ code: "custom", message: "A trigger has exactly one of schedule, at or webhook" });
1700
+ if (trigger.timezone !== undefined && trigger.schedule === undefined)
1701
+ ctx.addIssue({ code: "custom", path: ["timezone"], message: "timezone goes with schedule" });
1702
+ })
1703
+ .meta({ id: "Trigger" });
1704
+ /** What a trigger is: the field it has, or `wake` for a session's own booking (D77). */
1705
+ export const TRIGGER_KINDS = ["schedule", "at", "webhook", "wake"];
1706
+ /** A trigger's kind, from its manifest entry. */
1707
+ export function triggerKindOf(trigger) {
1708
+ return trigger.schedule !== undefined ? "schedule" : trigger.at !== undefined ? "at" : "webhook";
1709
+ }
1710
+ /**
1711
+ * A trigger's status on an Agent (D74): `active` fires, `paused` does not (`pausedReason`
1712
+ * `manual`, or `new` for one an upgrade added), `completed` is an `at` that ran.
1713
+ */
1714
+ export const TRIGGER_STATUSES = ["active", "paused", "completed"];
1715
+ /** `GET /v1/agents/{id}/triggers`: one trigger, from its manifest entry and the Agent's state. */
1716
+ export const TriggerViewSchema = z
1717
+ .object({
1718
+ id: z.string(),
1719
+ kind: z.enum(TRIGGER_KINDS),
1720
+ status: z.enum(TRIGGER_STATUSES),
1721
+ pausedReason: z.string().nullable(),
1722
+ schedule: z.string().optional(),
1723
+ timezone: z.string().optional(),
1724
+ at: z.string().optional(),
1725
+ /** The session each run goes to: a session id, or `new`. */
1726
+ session: z.string(),
1727
+ /** When it fires next, or `null` while paused or completed. */
1728
+ nextRunAt: z.string().nullable(),
1729
+ lastRunAt: z.string().nullable(),
1730
+ /**
1731
+ * A webhook trigger's endpoint (D75): `POST` Standard Webhooks deliveries to it. The origin is
1732
+ * the one this read reached.
1733
+ */
1734
+ webhookUrl: z.string().optional(),
1735
+ /** Whether a webhook trigger has a signing secret (`POST .../secret` makes one). */
1736
+ secretSet: z.boolean().optional(),
1737
+ })
1738
+ .strict();
1739
+ export const TriggerListSchema = z.object({ triggers: z.array(TriggerViewSchema) }).strict();
1740
+ /**
1741
+ * What a run came to (D74): `started` a turn, `queued` a message behind a running turn,
1742
+ * `skipped` (nothing started: `overlap`, `rate_limited`, `paused`) or `failed` (`queue_full`,
1743
+ * `session_conflict`, `agent_unavailable`).
1744
+ */
1745
+ export const TRIGGER_RUN_STATUSES = ["started", "queued", "skipped", "failed"];
1746
+ /** One run: a trigger fired, or was run by hand. */
1747
+ export const TriggerRunSchema = z
1748
+ .object({
1749
+ id: z.string(),
1750
+ triggerId: z.string(),
1751
+ kind: z.enum(TRIGGER_KINDS),
1752
+ /** When it was due; for a run by hand or a webhook, when it arrived. */
1753
+ dueAt: z.string(),
1754
+ firedAt: z.string(),
1755
+ /** Fired more than the Host's `triggers.lateGraceMs` after it was due (after downtime). */
1756
+ late: z.boolean(),
1757
+ status: z.enum(TRIGGER_RUN_STATUSES),
1758
+ reason: z.string().nullable(),
1759
+ sessionId: z.string().nullable(),
1760
+ turnId: z.string().nullable(),
1761
+ queuedMessageId: z.string().nullable(),
1762
+ })
1763
+ .strict();
1764
+ /** `GET /v1/agents/{id}/runs`: runs, newest first. */
1765
+ export const TriggerRunPageSchema = z
1766
+ .object({ runs: z.array(TriggerRunSchema), nextCursor: z.string().nullable() })
1767
+ .strict();
1768
+ /**
1769
+ * `POST /v1/agents/{id}/triggers/{triggerId}/secret` (D75): a webhook trigger's new signing secret,
1770
+ * in the Standard Webhooks format (`whsec_` and 32 random bytes in base64), shown this once. It
1771
+ * replaces the one before at once.
1772
+ */
1773
+ export const WebhookSecretResponseSchema = z
1774
+ .object({ triggerId: z.string(), webhookUrl: z.string(), secret: z.string() })
1775
+ .strict();
1776
+ /** `POST /v1/webhooks/{endpointId}`: the run a delivery made, or the run a repeated delivery made. */
1777
+ export const WebhookAcceptedResponseSchema = z
1778
+ .object({ runId: z.string(), status: z.enum(TRIGGER_RUN_STATUSES), reason: z.string().nullable() })
1779
+ .strict();
1780
+ /** `POST /v1/agents/{id}/triggers/{triggerId}/run`: the run it made. */
1781
+ export const RunTriggerResponseSchema = z.object({ run: TriggerRunSchema }).strict();
1782
+ /**
1783
+ * One of an Agent's memories (track T5, D72), as `GET /v1/agents/{id}/memories` lists it: its
1784
+ * path under `/memories`, size, content hash (the precondition a `PUT` may send), the
1785
+ * `description` of its frontmatter when it has one, and its version, which every change bumps.
1786
+ */
1787
+ export const MemorySummarySchema = z
1788
+ .object({
1789
+ path: z.string(),
1790
+ bytes: z.number().int().nonnegative(),
1791
+ contentSha256: z.string(),
1792
+ description: z.string().nullable(),
1793
+ version: z.number().int().positive(),
1794
+ updatedAt: z.string(),
1795
+ })
1796
+ .strict();
1797
+ /** `GET /v1/agents/{id}/memories`: memories by path. */
1798
+ export const MemoryListSchema = z
1799
+ .object({ memories: z.array(MemorySummarySchema), nextCursor: z.string().nullable() })
1800
+ .strict();
1801
+ /** `GET /v1/agents/{id}/memories/{path}`: one memory with its content. */
1802
+ export const MemorySchema = MemorySummarySchema.extend({ content: z.string() }).strict();
1803
+ /**
1804
+ * `PUT /v1/agents/{id}/memories/{path}`: the memory's whole content, creating it or replacing it.
1805
+ * With `contentSha256`, the write applies only while the memory's content still has that hash
1806
+ * (`409 memory_conflict` with the current text otherwise); an empty string requires that no
1807
+ * memory has the path.
1808
+ */
1809
+ export const PutMemoryRequestSchema = z
1810
+ .object({
1811
+ content: z.string(),
1812
+ contentSha256: z.string().optional(),
1813
+ })
1814
+ .strict();
1815
+ /**
1816
+ * One change to a memory: what changed it (`create`, `str_replace`, `insert`, `delete`,
1817
+ * `rename`), the content it left (`null` for a delete), and who made it: `agent:<manifest>@<n>`
1818
+ * for a turn, with its session, turn and trigger run, or the principal of an API call. A rename's
1819
+ * version is on the new path and names the old one in `fromPath`.
1820
+ */
1821
+ export const MemoryVersionSchema = z
1822
+ .object({
1823
+ id: z.string(),
1824
+ path: z.string(),
1825
+ fromPath: z.string().nullable(),
1826
+ operation: z.enum(MEMORY_OPERATIONS),
1827
+ bytes: z.number().int().nonnegative().nullable(),
1828
+ contentSha256: z.string().nullable(),
1829
+ actor: z.string(),
1830
+ sessionId: z.string().nullable(),
1831
+ turnId: z.string().nullable(),
1832
+ triggerRunId: z.string().nullable(),
1833
+ createdAt: z.string(),
1834
+ })
1835
+ .strict();
1836
+ /** `GET /v1/agents/{id}/memory_versions/{versionId}`: one version with the content it left. */
1837
+ export const MemoryVersionDetailSchema = MemoryVersionSchema.extend({ content: z.string().nullable() })
1838
+ .strict();
1839
+ /** `GET /v1/agents/{id}/memory_versions`: versions, newest first. */
1840
+ export const MemoryVersionPageSchema = z
1841
+ .object({ versions: z.array(MemoryVersionSchema), nextCursor: z.string().nullable() })
1842
+ .strict();
1843
+ /**
1844
+ * What the Runtime provides around the loop: the `runtime` section of agent manifest v8, with
1845
+ * environment manifest v1's fields but its identity and its `harness` (now `harness.id`).
1846
+ * `triggers` (track T4, D74) start the Agent's turns with no client connected; `selfWake` offers
1847
+ * the agent `schedule_wake`, which books its session's next turn (D77).
1848
+ */
1849
+ const runtimeSectionObject = z
1850
+ .strictObject({
1851
+ kind: z.enum(ENVIRONMENT_KINDS, {
1852
+ error: () => `runtime.kind is required: ${ENVIRONMENT_KINDS.join(", ")}`,
1411
1853
  }),
1412
- name: EnvironmentManifestNameSchema,
1413
- description: z.string().max(1024).optional(),
1414
- kind: environmentFields.kind,
1415
- image: environmentFields.image,
1416
- resources: environmentFields.resources,
1417
- storage: environmentFields.storage,
1418
- network: environmentFields.network,
1419
- harness: environmentFields.harness,
1420
- lifecycle: environmentFields.lifecycle,
1421
- setup: environmentFields.setup,
1422
- files: environmentFields.files,
1854
+ image: runtimeFields.image,
1855
+ resources: runtimeFields.resources,
1856
+ storage: runtimeFields.storage,
1857
+ network: runtimeFields.network,
1858
+ lifecycle: runtimeFields.lifecycle,
1859
+ setup: runtimeFields.setup,
1860
+ files: runtimeFields.files,
1861
+ limits: runtimeFields.limits,
1423
1862
  secrets: EnvironmentSecretSlotsSchema.optional(),
1863
+ triggers: z
1864
+ .record(TriggerIdSchema, TriggerSchema)
1865
+ .optional()
1866
+ .meta({ description: "What starts the Agent's turns with no client connected, by trigger id (D74)" }),
1867
+ selfWake: z
1868
+ .boolean()
1869
+ .optional()
1870
+ .meta({ description: "Offer the agent schedule_wake: it books its session's next turn itself (D77)" }),
1871
+ }, { error: removedFieldError(REMOVED_RUNTIME_SECTION_FIELDS) })
1872
+ .meta({ id: "RuntimeSection" });
1873
+ export const RuntimeSectionSchema = runtimeSectionObject;
1874
+ /**
1875
+ * Agent manifest v8 (protocol 16, track T2): one versioned document with what runs inside the
1876
+ * agent loop (`harness`) and what the Runtime provides around it (`runtime`), saved at
1877
+ * `PUT /v1/agent-manifests/{name}`. Without `runtime`, an Agent made from it is kind `none`.
1878
+ * The Runtime also checks the two sections against each other when it is saved (`sectionGaps`).
1879
+ */
1880
+ export const AgentManifestV8Schema = z
1881
+ .object({
1882
+ manifestSchemaVersion: z.literal(AGENT_MANIFEST_V8_SCHEMA_VERSION, {
1883
+ error: (issue) => agentManifestVersionIssue(issue.input),
1884
+ }),
1885
+ name: AgentManifestNameSchema,
1886
+ /** At most the Tenant's Runtime limit `manifestDescriptionChars`, checked when it is saved. */
1887
+ description: z.string().optional(),
1888
+ metadata: definitionJson.optional(),
1889
+ harness: HarnessSectionSchema,
1890
+ runtime: RuntimeSectionSchema.optional(),
1891
+ })
1892
+ .strict()
1893
+ .meta({ id: "AgentManifestV8" });
1894
+ /**
1895
+ * `harness.manifest.json`, an authoring file `nylorun apply` and the SDK's `composeManifest`
1896
+ * read: the harness section, whose `skills`, `mcpServers` and `plugins` may be paths relative to
1897
+ * the file, with a `credentials` map from MCP server or HTTP tool names to `runtime.secrets`
1898
+ * slots, and `requires`, a portable contract the composer checks against the runtime section.
1899
+ * The API never sees it.
1900
+ */
1901
+ export const HARNESS_MANIFEST_FILE_SCHEMA_VERSION = 1;
1902
+ const pathField = (what) => z.string().min(1).meta({ description: `A path to ${what}, relative to this file` });
1903
+ export const HarnessManifestFileSchema = z
1904
+ .object({
1905
+ $schema: z.string().optional(),
1906
+ id: harnessIdField,
1907
+ instructions: z.array(z.string()).optional(),
1908
+ tools: z.array(toolManifestSchema).optional(),
1909
+ skills: z
1910
+ .union([pathField("a folder of skill folders"), z.record(z.string(), harnessSkillSchema)])
1911
+ .optional(),
1912
+ mcpServers: z
1913
+ .union([pathField("an mcp.json file"), z.record(z.string(), harnessMcpServerSchema)])
1914
+ .optional(),
1915
+ plugins: z.array(z.union([pathField("an Agent Plugin folder"), pluginLabelSchema])).optional(),
1916
+ outputSchema: definitionJson.optional(),
1917
+ loop: harnessLoopField,
1918
+ memory: harnessMemoryField,
1919
+ /** MCP server or HTTP tool name → the `runtime.secrets` slot it authenticates with. */
1920
+ credentials: z.record(z.string().min(1), z.string().min(1)).optional(),
1921
+ /** What this harness needs of any runtime it is combined with; checked by the composer only. */
1922
+ requires: agentRequirementsSchema.optional(),
1923
+ })
1924
+ .strict();
1925
+ /** `runtime.manifest.json`: the runtime section as a file, often shared by many agents. */
1926
+ export const RUNTIME_MANIFEST_FILE_SCHEMA_VERSION = 1;
1927
+ export const RuntimeManifestFileSchema = runtimeSectionObject.extend({
1928
+ $schema: z.string().optional(),
1929
+ /** Also `{ path, from }`: a folder beside the file that the composer uploads by hash as `{ path, files }`. */
1930
+ files: z
1931
+ .array(z.union([
1932
+ EnvironmentFileSchema,
1933
+ z.object({ path: z.string().min(1), from: z.string().min(1) }).strict(),
1934
+ ]))
1935
+ .optional(),
1936
+ });
1937
+ /**
1938
+ * `agent.manifest.json`: an agent manifest v8 whose `harness` and `runtime` may each be a path to
1939
+ * an authoring file (or inline). The composer resolves both and sends one document.
1940
+ */
1941
+ export const AgentManifestFileSchema = z
1942
+ .object({
1943
+ $schema: z.string().optional(),
1944
+ manifestSchemaVersion: z.literal(AGENT_MANIFEST_V8_SCHEMA_VERSION, {
1945
+ error: (issue) => agentManifestVersionIssue(issue.input),
1946
+ }),
1947
+ name: AgentManifestNameSchema,
1948
+ description: z.string().optional(),
1949
+ metadata: definitionJson.optional(),
1950
+ harness: z.union([pathField("a harness.manifest.json file"), HarnessManifestFileSchema, WorkflowHarnessSectionSchema]),
1951
+ runtime: z.union([pathField("a runtime.manifest.json file"), RuntimeManifestFileSchema]).optional(),
1424
1952
  })
1425
1953
  .strict();
1426
- /** `PUT /v1/environment-manifests/{name}`: the manifest, whose `name` is the path's. */
1427
- export const PutEnvironmentManifestRequestSchema = EnvironmentManifestSchema.extend({
1954
+ /** `PUT /v1/agent-manifests/{name}`: the manifest, whose `name` is the path's. */
1955
+ export const PutAgentManifestRequestSchema = AgentManifestV8Schema.extend({
1428
1956
  requestId: RequestIdSchema.optional(),
1429
1957
  }).strict();
1430
1958
  /** Who saved a version: the subject a request acted for, else `application`. */
1431
- export const EnvironmentManifestSavedBySchema = z.object({ actor: z.string() }).strict();
1432
- /** One version of an environment manifest. */
1433
- export const EnvironmentManifestViewSchema = z
1959
+ export const AgentManifestSavedBySchema = z.object({ actor: z.string() }).strict();
1960
+ /** One version of an agent manifest. */
1961
+ export const AgentManifestViewSchema = z
1434
1962
  .object({
1435
1963
  name: z.string(),
1436
1964
  version: z.number().int().positive(),
1437
1965
  /** The hash of `manifest`: equal manifests have equal hashes. */
1438
1966
  hash: z.string(),
1439
- manifest: EnvironmentManifestSchema,
1440
- savedBy: EnvironmentManifestSavedBySchema,
1967
+ manifest: AgentManifestV8Schema,
1968
+ savedBy: AgentManifestSavedBySchema,
1441
1969
  createdAt: z.string(),
1442
- /** How many Environments were made from this version. */
1443
- environments: z.number().int().nonnegative(),
1970
+ /** How many Agents were made from this version. */
1971
+ agents: z.number().int().nonnegative(),
1444
1972
  })
1445
1973
  .strict();
1446
- /** `GET /v1/environment-manifests`: each manifest's latest version, by name. */
1447
- export const ListEnvironmentManifestsResponseSchema = z
1448
- .object({ manifests: z.array(EnvironmentManifestViewSchema) })
1974
+ /** `GET /v1/agent-manifests`: each manifest's latest version, by name. */
1975
+ export const ListAgentManifestsResponseSchema = z
1976
+ .object({ manifests: z.array(AgentManifestViewSchema) })
1449
1977
  .strict();
1450
- /** `GET /v1/environment-manifests/{name}/versions`: every version, newest first. */
1451
- export const EnvironmentManifestVersionsSchema = z
1978
+ /** `GET /v1/agent-manifests/{name}/versions`: every version, newest first. */
1979
+ export const AgentManifestVersionsSchema = z
1452
1980
  .object({
1453
1981
  name: z.string(),
1454
1982
  latest: z.number().int().positive(),
@@ -1456,24 +1984,36 @@ export const EnvironmentManifestVersionsSchema = z
1456
1984
  .object({
1457
1985
  version: z.number().int().positive(),
1458
1986
  hash: z.string(),
1459
- savedBy: EnvironmentManifestSavedBySchema,
1987
+ savedBy: AgentManifestSavedBySchema,
1460
1988
  createdAt: z.string(),
1461
- environments: z.number().int().nonnegative(),
1989
+ agents: z.number().int().nonnegative(),
1462
1990
  })
1463
1991
  .strict()),
1464
1992
  })
1465
1993
  .strict();
1466
1994
  /** Something a save would do that the saver should know: never a refusal. */
1467
- export const EnvironmentManifestWarningSchema = z
1995
+ export const AgentManifestWarningSchema = z
1468
1996
  .object({ code: z.string(), message: z.string() })
1469
1997
  .strict();
1998
+ /** One field a save changes, by its section and its path in it. */
1999
+ export const AgentManifestChangeSchema = z
2000
+ .object({
2001
+ /** `harness`, `runtime`, or `manifest` for the top-level fields. */
2002
+ section: z.enum(["manifest", "harness", "runtime"]),
2003
+ path: z.string(),
2004
+ op: z.enum(["add", "remove", "replace"]),
2005
+ from: z.unknown().optional(),
2006
+ to: z.unknown().optional(),
2007
+ })
2008
+ .strict();
1470
2009
  /**
1471
- * `PUT /v1/environment-manifests/{name}?dryRun=true`: what saving it would do, with nothing
1472
- * saved. `errors` lists every reason the Runtime would refuse it (the Tenant's limits, for one);
1473
- * a save with errors is `400`. `behind` counts the Environments made from an older version than
1474
- * the one it would save. No Environment changes when a version is saved (D63).
2010
+ * `PUT /v1/agent-manifests/{name}?dryRun=true`: what saving it would do, with nothing saved.
2011
+ * `errors` lists every reason the Runtime would refuse it: the gaps between its sections, the
2012
+ * Tenant's limits, its files; a save with errors is refused. A save moves every Agent that tracks
2013
+ * the manifest (track T3): `moves` counts them by when the new version applies. `behind` counts
2014
+ * the Agents that stay on an older version: pinned ones, and tracking ones it cannot move.
1475
2015
  */
1476
- export const EnvironmentManifestPlanSchema = z
2016
+ export const AgentManifestPlanSchema = z
1477
2017
  .object({
1478
2018
  name: z.string(),
1479
2019
  /** The latest version now, or `null` for a new manifest. */
@@ -1481,54 +2021,62 @@ export const EnvironmentManifestPlanSchema = z
1481
2021
  /** The version a save would answer: `from` when nothing changed. */
1482
2022
  to: z.number().int().positive(),
1483
2023
  unchanged: z.boolean(),
1484
- changes: z.array(z.object({ path: z.string(), from: z.unknown().optional(), to: z.unknown().optional() }).strict()),
1485
- warnings: z.array(EnvironmentManifestWarningSchema),
2024
+ changes: z.array(AgentManifestChangeSchema),
2025
+ warnings: z.array(AgentManifestWarningSchema),
1486
2026
  errors: z.array(z.string()),
1487
2027
  behind: z.number().int().nonnegative(),
2028
+ /** The tracking Agents a save moves: at once, at their pod's next start, once their secrets are set. */
2029
+ moves: z
2030
+ .object({
2031
+ now: z.number().int().nonnegative(),
2032
+ nextStart: z.number().int().nonnegative(),
2033
+ secrets: z.number().int().nonnegative(),
2034
+ })
2035
+ .strict(),
1488
2036
  })
1489
2037
  .strict();
1490
- /** `PUT /v1/environment-manifests/{name}`: the version saved (or the latest, unchanged). */
1491
- export const SaveEnvironmentManifestResponseSchema = z
2038
+ /** `PUT /v1/agent-manifests/{name}`: the version saved (or the latest, unchanged). */
2039
+ export const SaveAgentManifestResponseSchema = z
1492
2040
  .object({
1493
- manifest: EnvironmentManifestViewSchema,
2041
+ manifest: AgentManifestViewSchema,
1494
2042
  unchanged: z.boolean(),
1495
- warnings: z.array(EnvironmentManifestWarningSchema),
2043
+ warnings: z.array(AgentManifestWarningSchema),
1496
2044
  })
1497
2045
  .strict();
1498
- export const DeleteEnvironmentManifestResponseSchema = z
2046
+ export const DeleteAgentManifestResponseSchema = z
1499
2047
  .object({ name: z.string(), deleted: z.boolean() })
1500
2048
  .strict();
1501
2049
  /**
1502
- * `POST /v1/environments/{id}/fork` (Q15): how an Environment gets a new manifest version. The
1503
- * fork is a new Environment, made from the version, its disk started from a version of the
1504
- * source's disk and its secrets copied inside the Runtime. The source keeps what it runs, its
1505
- * disk and its sessions.
2050
+ * `POST /v1/agents/{id}/fork` (Q15): copies an Agent, with its disk and vault, into a new one,
2051
+ * made from `manifest` (default the source's manifest at its latest version): how an Agent
2052
+ * changes what is fixed for its life (its kind, harness, storage or manifest). The source keeps
2053
+ * what it runs, its disk and its sessions.
1506
2054
  */
1507
- export const ForkEnvironmentRequestSchema = z
2055
+ export const ForkAgentRequestSchema = z
1508
2056
  .object({
1509
2057
  requestId: RequestIdSchema.optional(),
1510
- /** The new Environment's id. */
1511
- id: EnvironmentIdSchema,
1512
- /** `name` or `name@n`; default the source's manifest at its latest version. */
1513
- manifest: EnvironmentManifestRefSchema.optional(),
2058
+ /** The new Agent's id. */
2059
+ id: AgentIdSchema,
2060
+ /** `name` or `name@n`; default the source's manifest name (tracking). */
2061
+ manifest: AgentManifestRefSchema.optional(),
1514
2062
  /** Where its disk starts: `latest` (a snapshot taken first; the default), a version, or `empty`. */
1515
2063
  disk: z.union([z.literal("latest"), z.literal("empty"), z.number().int().positive()]).optional(),
1516
- /** `copy` (the default): the source's secrets the new manifest declares (all, without slots). */
2064
+ /** `copy` (the default): the source's secrets the new manifest declares. */
1517
2065
  secrets: z.enum(["copy", "none"]).optional(),
1518
2066
  labels: EnvironmentLabelsSchema.optional(),
1519
- ownerUserId: z.string().min(1).nullable().optional(),
2067
+ owner: z.string().min(1).nullable().optional(),
1520
2068
  /** Answer the plan and make nothing. */
1521
2069
  dryRun: z.boolean().optional(),
1522
2070
  })
1523
2071
  .strict();
1524
2072
  /** What a fork does (or, with `dryRun`, would do). */
1525
- export const EnvironmentForkPlanSchema = z
2073
+ export const AgentForkPlanSchema = z
1526
2074
  .object({
1527
2075
  source: z.string(),
1528
2076
  id: z.string(),
1529
2077
  kind: z.enum(ENVIRONMENT_KINDS),
1530
- /** The manifest version it is made from, or `null` for the source's inline fields. */
1531
- manifest: z.object({ name: z.string(), version: z.number().int().positive() }).strict().nullable(),
2078
+ /** The manifest version it is made from. */
2079
+ manifest: z.object({ name: z.string(), version: z.number().int().positive() }).strict(),
1532
2080
  /** The disk version it starts from: `latest` in a dry run (the snapshot is taken at the fork); `null` for an empty disk. */
1533
2081
  disk: z.union([z.number().int().positive(), z.literal("latest")]).nullable(),
1534
2082
  /** Whether the new manifest's setup runs on the copied disk: it differs from what the source runs. */
@@ -1547,28 +2095,84 @@ export const EnvironmentForkPlanSchema = z
1547
2095
  changes: z.array(z.object({ path: z.string(), from: z.unknown().optional(), to: z.unknown().optional() }).strict()),
1548
2096
  /** The source's sessions: they stay on it. */
1549
2097
  sessions: z.number().int().nonnegative(),
2098
+ /** The source's memories (track T5): copied as they are now, each at version 1, with no history. */
2099
+ memories: z.number().int().nonnegative(),
1550
2100
  })
1551
2101
  .strict();
1552
- /** `POST /v1/environments/{id}/fork`: the new Environment and the plan it ran, or with `dryRun` the plan only. */
1553
- export const ForkEnvironmentResponseSchema = z.union([
1554
- z.object({ dryRun: z.literal(true), plan: EnvironmentForkPlanSchema }).strict(),
1555
- z.object({ environment: EnvironmentViewSchema, plan: EnvironmentForkPlanSchema }).strict(),
2102
+ /** `POST /v1/agents/{id}/fork`: the new Agent and the plan it ran, or with `dryRun` the plan only. */
2103
+ export const ForkAgentResponseSchema = z.union([
2104
+ z.object({ dryRun: z.literal(true), plan: AgentForkPlanSchema }).strict(),
2105
+ z.object({ agent: AgentViewSchema, plan: AgentForkPlanSchema }).strict(),
1556
2106
  ]);
2107
+ /**
2108
+ * `PUT /v1/agents/{id}?dryRun=true` on an existing Agent (track T3): what moving it to the
2109
+ * version `manifest` names would do, with nothing changed. `applies`: `none` (it runs that
2110
+ * version), `now` (turns that start from here run it), `next_start` (a runtime change: its pod's
2111
+ * next start applies it), `secrets` (it waits for a value of each of `missingSecrets`), or
2112
+ * `refused` (`refusals` names each fixed field it would change: `409 agent_fixed_field`).
2113
+ */
2114
+ export const AgentMovePlanSchema = z
2115
+ .object({
2116
+ agent: z.string(),
2117
+ manifest: z.string(),
2118
+ /** The version it runs now, and the one it would run. */
2119
+ from: z.number().int().positive(),
2120
+ to: z.number().int().positive(),
2121
+ /** How it names its manifest after the move. */
2122
+ tracking: z.enum(["tracking", "pinned"]),
2123
+ applies: z.enum(["none", "now", "next_start", "secrets", "refused"]),
2124
+ /** How the version differs from the one it runs, by section. */
2125
+ changes: z.array(z
2126
+ .object({
2127
+ section: z.enum(["manifest", "harness", "runtime"]),
2128
+ path: z.string(),
2129
+ op: z.enum(["add", "remove", "replace"]),
2130
+ from: z.unknown().optional(),
2131
+ to: z.unknown().optional(),
2132
+ })
2133
+ .strict()),
2134
+ /** Required secrets of the version with no value the version can use. */
2135
+ missingSecrets: z.array(z.string()),
2136
+ /** Its secrets the version does not declare: kept, and unused while it runs the version. */
2137
+ dormantSecrets: z.array(z.string()),
2138
+ /** What is fixed for its life that the version would change: kind, harness, storage. */
2139
+ refusals: z.array(z.object({ field: z.string(), from: z.unknown().optional(), to: z.unknown().optional() }).strict()),
2140
+ /** Its sessions: each takes the version at its next turn once it applies. */
2141
+ sessions: z.number().int().nonnegative(),
2142
+ })
2143
+ .strict();
2144
+ /**
2145
+ * `POST /v1/agents/{id}/restart` (track T3): applies a pending version now. A running pod stops,
2146
+ * so the next turn starts it on the version (a stopped one starts at once); `retry` first moves
2147
+ * it to the version that failed to start (`failedVersion`) again.
2148
+ */
2149
+ export const RestartAgentRequestSchema = z
2150
+ .object({ requestId: RequestIdSchema.optional(), retry: z.boolean().optional() })
2151
+ .strict();
2152
+ export const PutAgentDryRunResponseSchema = z
2153
+ .object({ dryRun: z.literal(true), plan: AgentMovePlanSchema })
2154
+ .strict();
1557
2155
  /**
1558
2156
  * What a model may read (protocol 12): `text` always; `image`, `pdf`, `office` (Word, Excel,
1559
2157
  * PowerPoint), `audio` and `video` when its catalog entry or the operator says so. In this order.
1560
2158
  */
1561
2159
  export const MODEL_INPUTS = ["text", "image", "pdf", "office", "audio", "video"];
1562
2160
  export const ModelInputSchema = z.enum(MODEL_INPUTS);
2161
+ /**
2162
+ * The defaults of a custom endpoint's `contextWindow` and `maxTokens` settings (and the window
2163
+ * assumed for a model the Runtime knows nothing of): small, since an early compaction beats a
2164
+ * failed call.
2165
+ */
2166
+ export const CUSTOM_MODEL_SETTING_DEFAULTS = Object.freeze({ contextWindow: 32_768, maxTokens: 8_192 });
1563
2167
  /**
1564
2168
  * What the Runtime cannot learn from a custom OpenAI-compatible endpoint (Model Calls §7):
1565
- * its context window and output limit, whether it reasons, what it reads (`inputs`; default text
1566
- * only) and pi-ai `compat` settings (`thinkingFormat`, `thinkingTokenBudgetField`,
1567
- * `chatTemplateKwargs`, …).
2169
+ * its context window and output limit (default `CUSTOM_MODEL_SETTING_DEFAULTS`), whether it
2170
+ * reasons, what it reads (`inputs`; default text only) and pi-ai `compat` settings
2171
+ * (`thinkingFormat`, `thinkingTokenBudgetField`, `chatTemplateKwargs`, …).
1568
2172
  */
1569
2173
  export const CustomModelSettingsSchema = z
1570
2174
  .object({
1571
- contextWindow: z.number().int().min(1024).optional(),
2175
+ contextWindow: z.number().int().min(1).optional(),
1572
2176
  maxTokens: z.number().int().min(1).optional(),
1573
2177
  reasoning: z.boolean().optional(),
1574
2178
  inputs: z.array(ModelInputSchema).optional(),
@@ -1619,7 +2223,7 @@ export const ENVIRONMENT_SECRET_TYPES = [
1619
2223
  * One credential of an Environment's vault, never its value: what it is bound to (the server
1620
2224
  * `url` for `bearer` and `headers`; the hosts and header for `environment_secret`).
1621
2225
  */
1622
- export const EnvironmentSecretViewSchema = z
2226
+ export const AgentSecretViewSchema = z
1623
2227
  .object({
1624
2228
  name: z.string(),
1625
2229
  type: z.enum(ENVIRONMENT_SECRET_TYPES),
@@ -1638,14 +2242,14 @@ export const EnvironmentSecretViewSchema = z
1638
2242
  rotatedAt: z.string().optional(),
1639
2243
  })
1640
2244
  .strict();
1641
- export const ListEnvironmentSecretsResponseSchema = z
1642
- .object({ secrets: z.array(EnvironmentSecretViewSchema) })
2245
+ export const ListAgentSecretsResponseSchema = z
2246
+ .object({ secrets: z.array(AgentSecretViewSchema) })
1643
2247
  .strict();
1644
2248
  /** The MCP transports a preview speaks: a manifest's remote server types. */
1645
2249
  export const MCP_PREVIEW_TYPES = ["streamable-http", "sse"];
1646
2250
  /**
1647
2251
  * `POST /v1/tenant/mcp/preview` (R2b C12): what a remote MCP server offers, before an agent
1648
- * names it. The Runtime connects with the credential for `url` in the vault of `environmentId`
2252
+ * names it. The Runtime connects with the credential for `url` in the vault of Agent `agentId`
1649
2253
  * (none without one), lists the tools and closes the connection; it never calls a tool.
1650
2254
  */
1651
2255
  export const McpPreviewRequestSchema = z
@@ -1674,7 +2278,7 @@ export const McpPreviewRequestSchema = z
1674
2278
  */
1675
2279
  name: modelFacingName("MCP server").optional(),
1676
2280
  /** The Environment whose vault's credential for `url` to send. Default: none is sent. */
1677
- environmentId: EnvironmentIdSchema.optional(),
2281
+ agentId: AgentIdSchema.optional(),
1678
2282
  })
1679
2283
  .strict();
1680
2284
  /** One tool a preview found. */
@@ -1683,8 +2287,9 @@ export const McpPreviewToolSchema = z
1683
2287
  /** The server's own name for the tool. */
1684
2288
  serverToolName: z.string(),
1685
2289
  /**
1686
- * What the model would call it (R2b C6); absent when the Runtime leaves the tool out (its
1687
- * input schema is not one the Runtime can use).
2290
+ * What the model would call it as Nylorun's engine names MCP tools (R2b C6); absent when the
2291
+ * engine leaves the tool out (its input schema is not one it can use). A harness of your own
2292
+ * names tools itself.
1688
2293
  */
1689
2294
  modelName: z.string().optional(),
1690
2295
  description: z.string().optional(),
@@ -1709,10 +2314,10 @@ export const McpPreviewSchema = z
1709
2314
  credentialSent: z.boolean(),
1710
2315
  /** The server's `initialize` answer: its name, version and title. */
1711
2316
  serverInfo: z.record(z.string(), z.unknown()).optional(),
1712
- /** The server's instructions from `initialize`, cut to 2,000 characters. */
2317
+ /** The server's instructions from `initialize`. */
1713
2318
  instructions: z.string().optional(),
1714
2319
  tools: z.array(McpPreviewToolSchema),
1715
- /** Tools the model knows by another name than `server__tool` (R2b C6). */
2320
+ /** Tools Nylorun's engine names otherwise than `server__tool` (R2b C6). */
1716
2321
  renamed: z.array(z.object({ serverToolName: z.string(), name: z.string() }).strict()),
1717
2322
  authRequired: z
1718
2323
  .object({
@@ -1726,24 +2331,22 @@ export const McpPreviewSchema = z
1726
2331
  })
1727
2332
  .strict();
1728
2333
  /**
1729
- * `POST /v1/tenant/credential-coverage`: which credential each of a saved agent's remote MCP
1730
- * servers and HTTP tools would get in a session that names `environmentId`, decided as the
1731
- * session's tool calls decide it (by URL). It reads no secret and calls no server.
2334
+ * `POST /v1/tenant/credential-coverage`: which credential each of an Agent's remote MCP servers
2335
+ * and HTTP tools (those of the manifest version it runs) would get in its sessions, decided as the
2336
+ * session's tool calls decide it (by URL) from the Agent's vault. It reads no secret and calls no
2337
+ * server.
1732
2338
  */
1733
2339
  export const CredentialCoverageRequestSchema = z
1734
2340
  .object({
1735
2341
  requestId: RequestIdSchema.optional(),
1736
- /** A saved agent or flow agent. */
1737
- agentId: z.string().min(1),
1738
- /** The Environment the session would name. Default: none (every entry is `missing`). */
1739
- environmentId: EnvironmentIdSchema.optional(),
2342
+ agentId: AgentIdSchema,
1740
2343
  })
1741
2344
  .strict();
1742
2345
  /** A credential coverage names: where it is, never its value. */
1743
2346
  export const CoverageCredentialSchema = z
1744
2347
  .object({
1745
- environmentId: z.string(),
1746
- /** The secret's name in the Environment's vault. */
2348
+ agentId: z.string(),
2349
+ /** The secret's name in the Agent's vault. */
1747
2350
  name: z.string(),
1748
2351
  /** Where the credential sends the requests instead of the URL (a gateway). */
1749
2352
  via: z.string().optional(),
@@ -1782,7 +2385,6 @@ export const CredentialCoverageEntrySchema = z
1782
2385
  export const CredentialCoverageSchema = z
1783
2386
  .object({
1784
2387
  agentId: z.string(),
1785
- environmentId: z.string().nullable(),
1786
2388
  /** True when every entry is `covered`. */
1787
2389
  complete: z.boolean(),
1788
2390
  /** One per declared MCP server and HTTP tool credential: the agent's, then its agents'. */
@@ -1793,14 +2395,19 @@ const commandBase = {
1793
2395
  requestId: RequestIdSchema,
1794
2396
  idempotencyKey: IdempotencyKeySchema,
1795
2397
  };
2398
+ /**
2399
+ * What a message to a busy session does (protocol 17, D76): `queue` waits for the running turn to
2400
+ * end and starts the next one; `reject` is refused with `409 session_busy`. A protocol 17 client's
2401
+ * default is `queue`, a protocol 16 client's `reject`.
2402
+ */
2403
+ export const MessageDeliverySchema = z.enum(["queue", "reject"]);
1796
2404
  const messageBase = {
1797
2405
  ...commandBase,
1798
2406
  type: z.literal("message"),
1799
2407
  /** Optional turn manifest (Loop patch); validated as a variant of the pinned agent. */
1800
2408
  manifest: AgentManifestSchema.optional(),
2409
+ delivery: MessageDeliverySchema.optional(),
1801
2410
  };
1802
- /** The most parts one message may carry (protocol 6). */
1803
- export const MAX_MESSAGE_PARTS = 32;
1804
2411
  /**
1805
2412
  * One part of a user message (protocol 6): text, or a file by artifact id. A file part without
1806
2413
  * `version` means the artifact's latest version when the message is accepted; the Runtime pins
@@ -1836,7 +2443,8 @@ export const MessageEventBodySchema = z.union([
1836
2443
  z
1837
2444
  .object({
1838
2445
  ...messageBase,
1839
- parts: z.array(MessagePartSchema).min(1).max(MAX_MESSAGE_PARTS),
2446
+ /** At most the Tenant's Runtime limit `messageParts`, checked when the message is accepted. */
2447
+ parts: z.array(MessagePartSchema).min(1),
1840
2448
  })
1841
2449
  .strict(),
1842
2450
  ]);
@@ -1917,7 +2525,8 @@ export const EvidenceClassSchema = z.enum([
1917
2525
  /** A command's sender (R4.9): from the request's credential, never from its body. */
1918
2526
  export const EventPrincipalSchema = z
1919
2527
  .object({
1920
- kind: z.enum(["application", "subject", "flow-host", "core"]),
2528
+ /** `trigger`: core, for an Agent's trigger (track T4); its id is the trigger's. */
2529
+ kind: z.enum(["application", "subject", "flow-host", "core", "trigger"]),
1921
2530
  id: z.string(),
1922
2531
  })
1923
2532
  .strict();
@@ -1974,6 +2583,19 @@ export const AcceptedResponseSchema = z.object({
1974
2583
  cursor: z.string().nullable(),
1975
2584
  requestId: z.string(),
1976
2585
  });
2586
+ /**
2587
+ * A message the session queued because a turn runs or waits (protocol 17): it starts the next
2588
+ * turn when this one ends. `position` counts from 1, the first to go.
2589
+ */
2590
+ export const QueuedResponseSchema = z.object({
2591
+ status: z.literal("queued"),
2592
+ queuedMessageId: z.string(),
2593
+ position: z.number().int().positive(),
2594
+ cursor: z.string().nullable(),
2595
+ requestId: z.string(),
2596
+ });
2597
+ /** What a session command answers: accepted, or, for a message, queued. */
2598
+ export const CommandResponseSchema = z.union([AcceptedResponseSchema, QueuedResponseSchema]);
1977
2599
  export const RejectedResponseSchema = z.object({
1978
2600
  status: z.literal("rejected"),
1979
2601
  code: z.enum(ERROR_CODES),
@@ -2088,9 +2710,10 @@ export const ModelFailedPayloadSchema = z
2088
2710
  })
2089
2711
  .passthrough();
2090
2712
  /**
2091
- * `context.compacted`: the engine summarized older history to fit the model's window
2092
- * (Model Calls §8). Token counts are estimates. `partial: true`: one summary call of several,
2093
- * in the log for its timing; only the last one (without `partial`) replaced the history.
2713
+ * `context.compacted`: the harness summarized older history to fit the model's window
2714
+ * (Model Calls §8), and said so with the transcript edit that replaced it (`kind: "compaction"`,
2715
+ * protocol 15). Token counts are the harness's estimates; `invocationId` and the model facts are
2716
+ * the last summary call's. Written once per compaction, when the segment's edit is recorded.
2094
2717
  */
2095
2718
  export const ContextCompactedPayloadSchema = z
2096
2719
  .object({
@@ -2098,20 +2721,19 @@ export const ContextCompactedPayloadSchema = z
2098
2721
  trigger: z.enum(["threshold", "overflow"]),
2099
2722
  tokensBefore: z.number().int().nonnegative(),
2100
2723
  tokensAfter: z.number().int().nonnegative(),
2101
- partial: z.literal(true).optional(),
2102
2724
  ...modelOutcomeFacts,
2103
2725
  ...eventAgent,
2104
2726
  })
2105
2727
  .passthrough();
2106
2728
  /** How a tool call ended (R5.1): the tool answered, the Runtime ended it, or a cancel did. */
2107
2729
  export const TOOL_CALL_STATUSES = ["completed", "failed", "cancelled"];
2108
- /** Where a tool call ran (R5.1): a remote MCP server, an HTTP tool, the sandbox, or core. */
2109
2730
  /**
2110
- * Where a tool call runs: an MCP server, an HTTP tool's URL, the session's sandbox, the Runtime
2111
- * itself (`platform`: the artifact, skill and deferred-tool tools), or the harness that runs the
2112
- * turn (`harness`: a tool it declared in `hello.features.tools`).
2731
+ * Where a tool call ran (R5.1), its effect's target kind (protocol 15): an MCP server, an HTTP
2732
+ * tool's URL, the session's sandbox, the harness that runs the turn (`harness`: a tool it runs
2733
+ * in its own process, such as our engine's skill, artifact and `tool_search` tools), or the
2734
+ * Runtime itself (`runtime`: `schedule_wake`, track T4).
2113
2735
  */
2114
- export const TOOL_CALL_KINDS = ["mcp", "http", "sandbox", "platform", "harness"];
2736
+ export const TOOL_CALL_KINDS = ["mcp", "http", "sandbox", "harness", "runtime"];
2115
2737
  /**
2116
2738
  * What the Tenant's tool policy did with a tool call (R5 step 2), when it did more than allow
2117
2739
  * it: `deny` refused it unsent; `ask` held it for a person, who approved it (`approvedBy`, when
@@ -2137,11 +2759,17 @@ export const ToolCompletedPayloadSchema = z
2137
2759
  ...toolIds,
2138
2760
  /** The tool call's effect id (R7.1). */
2139
2761
  effectId: z.string().min(1).optional(),
2762
+ /** The name the model called the tool by, as its harness named it: for display. */
2140
2763
  toolName: z.string().min(1),
2141
2764
  status: z.enum(TOOL_CALL_STATUSES).optional(),
2142
2765
  kind: z.enum(TOOL_CALL_KINDS).optional(),
2143
2766
  /** The MCP server, or the HTTP tool's URL host. */
2144
2767
  server: z.string().min(1).optional(),
2768
+ /**
2769
+ * The tool's identity (protocol 15): an MCP tool's own name on `server`, or the HTTP tool's
2770
+ * declared name. Tool policy and approval key on it.
2771
+ */
2772
+ tool: z.string().min(1).optional(),
2145
2773
  /**
2146
2774
  * The skill the call ran: `load_skill` and `read_skill_resource` name it, and a sandbox tool
2147
2775
  * whose input names its folder, `/skills/<name>@<hash>/`, ran its files.
@@ -2195,8 +2823,10 @@ export const EffectUncertainPayloadSchema = z
2195
2823
  const turnEndFacts = {
2196
2824
  durationMs: z.number().int().nonnegative().optional(),
2197
2825
  pausedMs: z.number().int().nonnegative().optional(),
2198
- /** The session's agent. */
2826
+ /** The session's Agent. */
2199
2827
  agentId: z.string().optional(),
2828
+ /** The agent manifest version the session runs (protocol 16): the agent the turn's span names. */
2829
+ manifest: z.object({ name: z.string(), version: z.number().int() }).passthrough().optional(),
2200
2830
  totals: z
2201
2831
  .object({
2202
2832
  steps: z.number().int().nonnegative(),
@@ -2238,6 +2868,26 @@ export const TurnFailedPayloadSchema = z
2238
2868
  export const TurnCancelledPayloadSchema = z
2239
2869
  .object({ reason: z.string().optional(), ...turnEndFacts })
2240
2870
  .passthrough();
2871
+ /**
2872
+ * `message.queued` (protocol 17): a message arrived while the session's turn ran or waited, and
2873
+ * waits in its queue. `position` counts from 1; the message's `command.message` is written when
2874
+ * a turn takes it.
2875
+ */
2876
+ export const MessageQueuedPayloadSchema = z
2877
+ .object({ queuedMessageId: z.string(), position: z.number().int().positive(), requestId: z.string() })
2878
+ .passthrough();
2879
+ /**
2880
+ * `wake.booked` (track T4, D77): the session's agent booked its next turn with `schedule_wake`,
2881
+ * at `at`, replacing any booking before. `wake.cancelled`: it cancelled its booking.
2882
+ */
2883
+ export const WakeBookedPayloadSchema = z
2884
+ .object({ at: z.string(), note: z.string(), effectId: z.string(), replaced: z.boolean() })
2885
+ .passthrough();
2886
+ export const WakeCancelledPayloadSchema = z.object({ effectId: z.string() }).passthrough();
2887
+ /** `queue.taken` (protocol 17): the turn that started with the queued messages, in order. */
2888
+ export const QueueTakenPayloadSchema = z
2889
+ .object({ turnId: z.string(), queuedMessageIds: z.array(z.string()).min(1) })
2890
+ .passthrough();
2241
2891
  /** Lifecycle of an agent used as a tool. `agent.delegationId` is the parent call's invocation. */
2242
2892
  export const DelegationPayloadSchema = z
2243
2893
  .object({
@@ -2270,6 +2920,17 @@ export const CommandMessagePayloadSchema = z
2270
2920
  parts: z.array(MessagePartSchema).optional(),
2271
2921
  /** The turn manifest the message carried, if any. */
2272
2922
  manifest: z.unknown().optional(),
2923
+ delivery: MessageDeliverySchema.optional(),
2924
+ /** Set when the message waited in the session's queue (protocol 17): its id there. */
2925
+ queuedMessageId: z.string().optional(),
2926
+ /**
2927
+ * What sent it, when not a client (track T4): a trigger's run (`trigger`, with the trigger
2928
+ * and run ids), or the session's own booked wake (`self`).
2929
+ */
2930
+ cause: z
2931
+ .object({ kind: z.enum(["trigger", "self"]), triggerId: z.string(), runId: z.string() })
2932
+ .strict()
2933
+ .optional(),
2273
2934
  /**
2274
2935
  * The W3C trace context the message was sent with (R7.4): the turn's trace is the caller's,
2275
2936
  * and its root span the child of the caller's span.
@@ -2313,11 +2974,11 @@ export const EnvironmentStatePayloadSchema = z
2313
2974
  })
2314
2975
  .passthrough();
2315
2976
  /**
2316
- * `environment.attached`: the session was opened on an Environment (`environment`). The
2317
- * Environment's own stream records the same attachment.
2977
+ * `agent.attached`: the session was opened on its Agent (protocol 16; `environment.attached`
2978
+ * before). The Agent's own stream records the same attachment.
2318
2979
  */
2319
- export const EnvironmentAttachedPayloadSchema = z
2320
- .object({ environmentId: z.string() })
2980
+ export const AgentAttachedPayloadSchema = z
2981
+ .object({ agentId: z.string() })
2321
2982
  .passthrough();
2322
2983
  /** `environment.exec`: one sandbox tool call finished. */
2323
2984
  export const EnvironmentExecPayloadSchema = z
@@ -2403,9 +3064,10 @@ export const TranscriptUpdatedPayloadSchema = z
2403
3064
  })
2404
3065
  .passthrough();
2405
3066
  /**
2406
- * Where an artifact version's bytes came from: a client's upload, our engine's `save_artifact`,
2407
- * or the turn-end export of a sandbox's outputs (F8.2), whose listing and bytes the harness
2408
- * holding the workspace supplied.
3067
+ * Where an artifact version's bytes came from: a client's upload, a harness over the artifact
3068
+ * seam (our engine's `save_artifact`, its tool results and its outputs folder), an Environment's
3069
+ * disk version (`snapshot`), or core's turn-end export of a sandbox's outputs, which versions
3070
+ * before protocol 15 name (`export`).
2409
3071
  */
2410
3072
  export const ArtifactSourceSchema = z.enum(["upload", "engine", "export", "snapshot"]);
2411
3073
  /**
@@ -2443,12 +3105,17 @@ export const ArtifactVersionPayloadSchema = z
2443
3105
  export const ArtifactDeletedPayloadSchema = z
2444
3106
  .object({ artifactId: z.string(), name: z.string() })
2445
3107
  .passthrough();
2446
- /** Why a turn-end export stored nothing although the sandbox had outputs (F8.2). */
3108
+ /**
3109
+ * Why the turn-end save of a session's outputs folder stored nothing although the sandbox had
3110
+ * outputs: our engine's claim (protocol 15), with the limit it met.
3111
+ */
2447
3112
  export const ArtifactExportSkipReasonSchema = z.enum([
2448
3113
  "too_many_files",
2449
3114
  "file_too_large",
2450
3115
  "too_large",
2451
3116
  "tenant_total",
3117
+ /** Past the session's Environment's own total (its manifest's `limits.artifacts.totalBytes`). */
3118
+ "environment_total",
2452
3119
  ]);
2453
3120
  /**
2454
3121
  * `artifact.export.skipped`: the turn's outputs were past a limit, so no folder version was
@@ -2467,8 +3134,9 @@ export const ArtifactExportSkippedPayloadSchema = z
2467
3134
  })
2468
3135
  .passthrough();
2469
3136
  /**
2470
- * `artifact.export.failed`: the turn-end export could not finish (the sandbox or the Object store
2471
- * failed). The turn itself completed; the next turn exports again.
3137
+ * `artifact.export.failed`: the turn-end save of the outputs folder could not finish (the sandbox
3138
+ * or the artifact seam failed), as our engine claims it. The turn itself completed; the next turn
3139
+ * saves again.
2472
3140
  */
2473
3141
  export const ArtifactExportFailedPayloadSchema = z
2474
3142
  .object({ name: z.string(), message: z.string() })
@@ -2484,13 +3152,8 @@ export const McpServerOutcomeSchema = z
2484
3152
  /** `refused`: the vault has no usable credential for it; `failed`: it could not be reached or listed. */
2485
3153
  outcome: z.enum(["connected", "refused", "failed"]),
2486
3154
  message: z.string(),
2487
- /** The tools it added to the session; 0 unless connected. */
3155
+ /** The tools it added to the session that its `tools` settings leave enabled; 0 unless connected. */
2488
3156
  tools: z.number().int().nonnegative(),
2489
- /**
2490
- * Of those, the tools out of the model's tool list, which it finds with `tool_search` and runs
2491
- * with `tool_call` (R2b C10); absent when none is.
2492
- */
2493
- deferred: z.number().int().positive().optional(),
2494
3157
  /** Listed tools the server's `tools` settings disable (R2b C9); absent when none. */
2495
3158
  disabled: z.number().int().positive().optional(),
2496
3159
  /**
@@ -2500,14 +3163,6 @@ export const McpServerOutcomeSchema = z
2500
3163
  unknownTools: z.array(z.string()).optional(),
2501
3164
  /** The credentials a refusal names. */
2502
3165
  credentialIds: z.array(z.string()).optional(),
2503
- /**
2504
- * Tools the model knows by another name (R2b C6): `server__tool` with characters outside
2505
- * `[A-Za-z0-9_-]` replaced by `_`, and shortened to 64 with a hash, or suffixed with the hash
2506
- * when that collides. The server is still called by `serverToolName`.
2507
- */
2508
- renamed: z
2509
- .array(z.object({ serverToolName: z.string(), name: z.string() }).passthrough())
2510
- .optional(),
2511
3166
  })
2512
3167
  .passthrough();
2513
3168
  /**
@@ -2536,6 +3191,11 @@ export const EVENT_CATALOG = {
2536
3191
  "turn.paused": { payload: TurnPausedPayloadSchema, source: "loop", version: 1 },
2537
3192
  "turn.failed": { payload: TurnFailedPayloadSchema, source: "loop", version: 1 },
2538
3193
  "turn.cancelled": { payload: TurnCancelledPayloadSchema, source: "api", version: 1 },
3194
+ "message.queued": { payload: MessageQueuedPayloadSchema, source: "api", version: 1 },
3195
+ "queue.taken": { payload: QueueTakenPayloadSchema, source: "api", version: 1 },
3196
+ "wake.booked": { payload: WakeBookedPayloadSchema, source: "api", version: 1 },
3197
+ "wake.cancelled": { payload: WakeCancelledPayloadSchema, source: "api", version: 1 },
3198
+ "memory.updated": { payload: MemoryUpdatedPayloadSchema, source: "api", version: 1 },
2539
3199
  "message.assistant": { payload: AssistantMessagePayloadSchema, source: "loop", version: 1 },
2540
3200
  "model.failed": { payload: ModelFailedPayloadSchema, source: "loop", version: 1 },
2541
3201
  "context.compacted": { payload: ContextCompactedPayloadSchema, source: "loop", version: 1 },
@@ -2546,7 +3206,7 @@ export const EVENT_CATALOG = {
2546
3206
  "mcp.discovered": { payload: McpDiscoveredPayloadSchema, source: "loop", version: 1 },
2547
3207
  "environment.state": { payload: EnvironmentStatePayloadSchema, source: "loop", version: 1 },
2548
3208
  "environment.exec": { payload: EnvironmentExecPayloadSchema, source: "loop", version: 1 },
2549
- "environment.attached": { payload: EnvironmentAttachedPayloadSchema, source: "api", version: 1 },
3209
+ "agent.attached": { payload: AgentAttachedPayloadSchema, source: "api", version: 1 },
2550
3210
  "node.started": { payload: NodeStartedPayloadSchema, source: "loop", version: 1 },
2551
3211
  "node.completed": { payload: NodeCompletedPayloadSchema, source: "loop", version: 1 },
2552
3212
  "node.agent": { payload: NodeAgentPayloadSchema, source: "loop", version: 1 },
@@ -2806,7 +3466,7 @@ export const TenantStatusSchema = z
2806
3466
  })
2807
3467
  .strict(),
2808
3468
  model: HostModelViewSchema,
2809
- /** The registered agents. */
3469
+ /** The Tenant's Agents, by id. */
2810
3470
  agents: z.array(z.object({ agentId: z.string() }).strict()),
2811
3471
  counts: z
2812
3472
  .object({
@@ -2902,22 +3562,22 @@ export const SeedTenantConfigResponseSchema = z
2902
3562
  export const ResetTenantRequestSchema = z
2903
3563
  .object({
2904
3564
  requestId: RequestIdSchema,
2905
- scope: z.enum(["sessions", "environments", "all"]),
3565
+ scope: z.enum(["sessions", "agents", "all"]),
2906
3566
  activeWork: z.enum(["drain", "cancel"]),
2907
3567
  })
2908
3568
  .strict();
2909
3569
  /**
2910
3570
  * Acting for a subject (Host feature `subject-headers`): what an application principal may
2911
3571
  * narrow a request to. `sessions:own` reaches only the subject's own sessions; the others reach
2912
- * Tenant-wide resources. `environments:write` creates, changes and deletes Environments and
2913
- * writes their secrets (protocol 11); a token caller's reach only the ids its Environment
2914
- * grants name.
3572
+ * Tenant-wide resources. `agents:write` creates, changes and deletes Agents and writes their
3573
+ * secrets (protocol 16; `environments:write` before); a token caller's reach only the ids its
3574
+ * Agent grants name. `agent-manifests:write` saves and deletes agent manifests.
2915
3575
  */
2916
3576
  export const SUBJECT_SCOPES = [
2917
3577
  "agents:read",
2918
3578
  "agents:write",
2919
3579
  "sessions:own",
2920
- "environments:write",
3580
+ "agent-manifests:write",
2921
3581
  ];
2922
3582
  /**
2923
3583
  * Retired scopes: `Nylorun-Scopes` may still name them (older clients do), and they grant
@@ -2925,7 +3585,12 @@ export const SUBJECT_SCOPES = [
2925
3585
  * settings moved to the Management API, which no subject reaches.
2926
3586
  */
2927
3587
  const RETIRED_SUBJECT_SCOPES = ["vaults:own", "tenant:settings"];
2928
- /** 1–200 visible ASCII characters; spaces only inside. */
3588
+ /**
3589
+ * 1–200 visible ASCII characters; spaces only inside.
3590
+ * An identifier's grammar is the protocol's (B15): it crosses the Runtime API, tokens and grants
3591
+ * and means the same in every installation, so its length is a constant of protocol 15, not a
3592
+ * setting.
3593
+ */
2929
3594
  const SUBJECT_PATTERN = /^[\x21-\x7e](?:[\x20-\x7e]{0,198}[\x21-\x7e])?$/;
2930
3595
  /**
2931
3596
  * The owner of a session opened for no person: an MCP server's or HTTP tool's identity header
@@ -2959,10 +3624,10 @@ export function parseSubjectHeaders(subject, scopes) {
2959
3624
  message: "Nylorun-Scopes is required with Nylorun-Subject",
2960
3625
  };
2961
3626
  const names = named.filter((name) => !RETIRED_SUBJECT_SCOPES.includes(name));
2962
- if (names.includes("sandboxes:write"))
3627
+ if (names.includes("sandboxes:write") || names.includes("environments:write"))
2963
3628
  return {
2964
3629
  ok: false,
2965
- message: "sandboxes:write was renamed environments:write in protocol 11",
3630
+ message: "environments:write was renamed agents:write in protocol 16 (sandboxes:write before protocol 11)",
2966
3631
  };
2967
3632
  const unknown = names.filter((name) => !SUBJECT_SCOPES.includes(name));
2968
3633
  if (unknown.length > 0)
@@ -2975,20 +3640,14 @@ export function parseSubjectHeaders(subject, scopes) {
2975
3640
  }
2976
3641
  // --- token callers (Host feature `trusted-issuers`) ------------------------------------------
2977
3642
  /**
2978
- * Scopes a token caller (a trusted issuer's token) may carry: never `agents:write`.
3643
+ * Scopes a token caller (a trusted issuer's token) may carry: never `agent-manifests:write`.
3644
+ * `agents:write` reaches only the Agents its grants name.
2979
3645
  */
2980
3646
  export const TOKEN_SCOPES = [
2981
3647
  "agents:read",
2982
3648
  "sessions:own",
2983
- "environments:write",
3649
+ "agents:write",
2984
3650
  ];
2985
- /** The most Environment grants one token caller carries. */
2986
- export const TOKEN_ENVIRONMENT_GRANTS_MAX = 16;
2987
- /**
2988
- * The longest a token the Runtime signs itself lives, in seconds (capability links): rotating
2989
- * signing keys revokes the previous key once the longest token it may have signed has expired.
2990
- */
2991
- export const TOKEN_TTL_MAX_SECONDS = 900;
2992
3651
  /**
2993
3652
  * The `iss` of every token a Tenant's Runtime signs itself: capability links, run, host and
2994
3653
  * egress tokens.
@@ -2996,6 +3655,7 @@ export const TOKEN_TTL_MAX_SECONDS = 900;
2996
3655
  export function tenantTokenIssuer(tenantId) {
2997
3656
  return `urn:nylorun:tenant:${tenantId}`;
2998
3657
  }
3658
+ /** The Agents a caller reaches: `*` for every one, or Agent grants (ids and `p/*` prefixes). */
2999
3659
  const AgentAllowlistSchema = z.union([
3000
3660
  z.literal("*"),
3001
3661
  z.array(z.string().min(1)),
@@ -3052,9 +3712,8 @@ export const CALLER_SCOPES = [...SUBJECT_SCOPES, "studio"];
3052
3712
  * `issuer:<name>` (a token from the identity file's issuer `name`).
3053
3713
  * - `subject` is the person the request acts for; absent for an application key alone.
3054
3714
  * - `scopes`: what the caller holds. An application key alone holds every subject scope.
3055
- * - `agents`: the agents it may reach, `*` for all.
3056
- * - `environments`: the Environment grants of a token caller (empty reaches none); absent for
3057
- * an application key, alone or acting for a subject, which no grant limits.
3715
+ * - `agents`: the Agents it may reach: `*` for all, else a token caller's Agent grants (ids
3716
+ * and `p/*` prefixes; empty reaches none).
3058
3717
  */
3059
3718
  export const MeResponseSchema = z
3060
3719
  .object({
@@ -3064,12 +3723,6 @@ export const MeResponseSchema = z
3064
3723
  .meta({ description: "The person the request acts for; absent for an application key alone" }),
3065
3724
  scopes: z.array(z.enum(CALLER_SCOPES)),
3066
3725
  agents: AgentAllowlistSchema,
3067
- environments: z
3068
- .array(z.string())
3069
- .optional()
3070
- .meta({
3071
- description: "A token caller's Environment grants (empty reaches none); absent when no grant limits the caller",
3072
- }),
3073
3726
  via: z.string().meta({
3074
3727
  description: "How the caller authenticated: `application:<principalId>`, `management:<principalId>`, `subject` or `issuer:<name>`",
3075
3728
  }),
@@ -3092,37 +3745,9 @@ export function isSerializedOrigin(value) {
3092
3745
  }
3093
3746
  // Successful answers of the Runtime and Management APIs that had no schema of their own. With the
3094
3747
  // request schemas above they describe every body the Runtime sends (its OpenAPI document).
3095
- /** `GET /v1/agents` with an application key: every definition, manifest included. */
3096
- export const AgentDefinitionViewSchema = z
3097
- .object({
3098
- agentId: z.string(),
3099
- manifest: z.record(z.string(), z.unknown()),
3100
- manifestHash: z.string(),
3101
- implementationVersion: z.string(),
3102
- })
3103
- .strict();
3748
+ /** `GET /v1/agents`: the Agents the caller reaches. */
3104
3749
  export const ListAgentsResponseSchema = z
3105
- .object({ agents: z.array(AgentDefinitionViewSchema) })
3106
- .strict();
3107
- /** `GET /v1/agents` with a token caller's credential: the allowed agents' names only. */
3108
- export const PublicAgentSchema = z
3109
- .object({
3110
- agentId: z.string(),
3111
- name: z.string().optional(),
3112
- description: z.string().optional(),
3113
- })
3114
- .strict();
3115
- export const ListPublicAgentsResponseSchema = z
3116
- .object({ agents: z.array(PublicAgentSchema) })
3117
- .strict();
3118
- export const PutAgentResponseSchema = z
3119
- .object({
3120
- agentId: z.string(),
3121
- manifestHash: z.string(),
3122
- implementationVersion: z.string(),
3123
- /** True for `?dryRun=true` (protocol 14): every check ran, and nothing was saved. */
3124
- dryRun: z.boolean().optional(),
3125
- })
3750
+ .object({ agents: z.array(AgentViewSchema) })
3126
3751
  .strict();
3127
3752
  export const SESSION_STATUSES = [
3128
3753
  "idle",
@@ -3138,6 +3763,7 @@ export const SESSION_STATUSES = [
3138
3763
  export const SessionSummarySchema = z
3139
3764
  .object({
3140
3765
  id: z.string(),
3766
+ /** The Agent the session runs on. */
3141
3767
  agentId: z.string(),
3142
3768
  ownerUserId: z.string(),
3143
3769
  status: z.enum(SESSION_STATUSES),
@@ -3151,34 +3777,28 @@ export const ListSessionsResponseSchema = z
3151
3777
  export const SessionViewSchema = z
3152
3778
  .object({
3153
3779
  id: z.string(),
3780
+ /** The Agent the session runs on (protocol 16). */
3154
3781
  agentId: z.string(),
3155
3782
  ownerUserId: z.string(),
3156
- manifestHash: z.string(),
3157
3783
  /**
3158
- * The hash of the definition the session was opened from (R2b C11). `manifestHash` differs
3159
- * from it when the Runtime pinned its `runtime` block on the definition: a sandbox's tools,
3160
- * the artifact tools and the skill tools. Compare this one with the registered
3161
- * definition's hash. Absent for a session opened before this release.
3784
+ * The agent manifest version the session pinned when it opened: the one its Agent runs.
3785
+ * Absent for a session closed by protocol 16, opened from a definition.
3162
3786
  */
3163
- definitionHash: z.string().optional(),
3164
- implementationVersion: z.string(),
3787
+ manifest: z.object({ name: z.string(), version: z.number().int().positive() }).strict().nullable(),
3788
+ /** The hash of the loop manifest the session pinned. */
3789
+ manifestHash: z.string(),
3165
3790
  status: z.enum(SESSION_STATUSES),
3166
3791
  activeTurnId: z.string().nullable(),
3167
- /**
3168
- * The Environment the session names, and its recipe version when the session opened (for
3169
- * reading only); `null` without one.
3170
- */
3171
- environment: z
3172
- .object({ id: z.string(), version: z.number().int().positive() })
3173
- .strict()
3174
- .nullable(),
3792
+ /** Messages waiting in the session's queue for the next turn (protocol 17). */
3793
+ queuedMessages: z.number().int().nonnegative(),
3175
3794
  /**
3176
3795
  * The harness that runs the session's turns, pinned when it opened (track R4): its
3177
- * Environment's harness, else `nylorun`.
3796
+ * manifest's `harness.id`, else `nylorun`.
3178
3797
  */
3179
3798
  harness: z.string(),
3180
3799
  /**
3181
- * Why the session takes no new turn, when it is closed: `protocol_13` for a session opened
3800
+ * Why the session takes no new turn, when it is closed: `protocol_16` for a session opened
3801
+ * before protocol 16 (from a definition), `protocol_13` for a session opened
3182
3802
  * before protocol 13, `protocol_11` for one opened before protocol 11 (a new turn is
3183
3803
  * `409 session_closed`; its history stays readable).
3184
3804
  */
@@ -3327,13 +3947,16 @@ export const TenantSandboxViewSchema = z
3327
3947
  .optional(),
3328
3948
  })
3329
3949
  .strict();
3330
- /** What a usage total or a budget covers: the whole Tenant, one agent, or one turn. */
3331
- export const ModelUsageScopeSchema = z.enum(["tenant", "agent", "turn"]);
3950
+ /**
3951
+ * What a usage total or a budget covers: the whole Tenant, the Agents made from one agent manifest
3952
+ * (`manifest`, by its name; scope `agent` keyed a definition id before protocol 16), or one turn.
3953
+ */
3954
+ export const ModelUsageScopeSchema = z.enum(["tenant", "manifest", "turn"]);
3332
3955
  /** `GET /v1/tenant/usage`: which rows of the model usage ledger to total. */
3333
3956
  export const ModelUsageQuerySchema = z
3334
3957
  .object({
3335
3958
  scope: ModelUsageScopeSchema.default("tenant"),
3336
- /** The agent or turn id; required for those scopes. */
3959
+ /** The manifest's name or the turn id; required for those scopes. */
3337
3960
  id: z.string().min(1).optional(),
3338
3961
  /** The current UTC day or month, or every row. */
3339
3962
  period: z.enum(["day", "month", "total"]).default("total"),
@@ -3360,11 +3983,14 @@ export const ModelUsageTotalsSchema = z
3360
3983
  */
3361
3984
  export const ModelBudgetSchema = z
3362
3985
  .object({
3363
- /** `turn` caps every turn; `agent` one agent's sessions; `tenant` all of them. */
3986
+ /**
3987
+ * `turn` caps every turn; `manifest` the sessions of every Agent made from one agent
3988
+ * manifest; `tenant` all of them.
3989
+ */
3364
3990
  scope: ModelUsageScopeSchema,
3365
- /** The agent's id; `agent` only. */
3991
+ /** The agent manifest's name; `manifest` only. */
3366
3992
  id: z.string().min(1).optional(),
3367
- /** The UTC period spend counts over; `agent` and `tenant` only. */
3993
+ /** The UTC period spend counts over; `manifest` and `tenant` only. */
3368
3994
  period: z.enum(["day", "month"]).optional(),
3369
3995
  /** pi-ai's catalog price; custom endpoints count as $0, so cap them in tokens. */
3370
3996
  limitUsd: z.number().positive().optional(),
@@ -3374,16 +4000,17 @@ export const ModelBudgetSchema = z
3374
4000
  .superRefine((budget, ctx) => {
3375
4001
  if (budget.limitUsd === undefined && budget.limitTokens === undefined)
3376
4002
  ctx.addIssue({ code: "custom", message: "A budget needs limitUsd, limitTokens or both" });
3377
- if ((budget.scope === "agent") !== (budget.id !== undefined))
3378
- ctx.addIssue({ code: "custom", message: "An agent budget names the agent in id; other scopes take no id" });
4003
+ if ((budget.scope === "manifest") !== (budget.id !== undefined))
4004
+ ctx.addIssue({ code: "custom", message: "A manifest budget names the agent manifest in id; other scopes take no id" });
3379
4005
  if ((budget.scope === "turn") === (budget.period !== undefined))
3380
- ctx.addIssue({ code: "custom", message: "A turn budget takes no period; agent and Tenant budgets need one" });
4006
+ ctx.addIssue({ code: "custom", message: "A turn budget takes no period; manifest and Tenant budgets need one" });
3381
4007
  });
3382
4008
  /** `PUT /v1/tenant/budgets`: replaces every budget. An empty list removes them all. */
3383
4009
  export const PutModelBudgetsRequestSchema = z
3384
4010
  .object({
3385
4011
  requestId: RequestIdSchema.optional(),
3386
- budgets: z.array(ModelBudgetSchema).max(100),
4012
+ /** At most the Tenant's Runtime limit `modelBudgets`, checked when they are put. */
4013
+ budgets: z.array(ModelBudgetSchema),
3387
4014
  })
3388
4015
  .strict()
3389
4016
  .superRefine((request, ctx) => {
@@ -3407,8 +4034,11 @@ export const ToolInputConditionSchema = z
3407
4034
  gte: z.number().optional(),
3408
4035
  lt: z.number().optional(),
3409
4036
  lte: z.number().optional(),
3410
- /** A regular expression the field's string value must match. */
3411
- matches: z.string().min(1).max(500).optional(),
4037
+ /**
4038
+ * A regular expression the field's string value must match: at most the Tenant's Runtime
4039
+ * limit `toolRuleTextChars`, checked when the policy is put.
4040
+ */
4041
+ matches: z.string().min(1).optional(),
3412
4042
  })
3413
4043
  .strict()
3414
4044
  .superRefine((condition, ctx) => {
@@ -3425,27 +4055,45 @@ export const ToolInputConditionSchema = z
3425
4055
  /**
3426
4056
  * One rule of the Tenant's tool policy (R5 step 2), applied at the Tool Gate to every MCP and
3427
4057
  * HTTP tool call of every harness. A rule matches a call when every selector it sets matches:
3428
- * `tool` (the name the model calls it by, `*` for any run of characters), `server` (an MCP
4058
+ * `tool` (the tool's identity: an MCP tool's own name on its server, or an HTTP tool's declared
4059
+ * name; never the name a harness gave the model; `*` for any run of characters), `server` (an MCP
3429
4060
  * server's name), `kind`, `agent` (the agent that calls it) and `when` (fields of the input, by
3430
4061
  * dotted path). The strictest matching rule decides: `deny` refuses the call before it is sent,
3431
4062
  * `ask` holds it until a person approves it on the session (`approve`), `allow` runs it. A call no
3432
4063
  * rule matches runs. Sandbox tools never cross the gate; their network side is egress policy.
4064
+ *
4065
+ * A `tool` with `__` in it is refused (protocol 15): no declared tool's name has one, so it can
4066
+ * only be an MCP tool's model-facing `server__tool` name. Name an MCP tool by `server` and `tool`.
3433
4067
  */
3434
4068
  export const ToolRuleSchema = z
3435
4069
  .object({
3436
4070
  effect: z.enum(TOOL_POLICY_EFFECTS),
3437
- tool: z.string().min(1).max(200).optional(),
3438
- server: z.string().min(1).max(200).optional(),
4071
+ // The selectors, and `when`'s paths, are at most the Tenant's Runtime limit
4072
+ // `toolRuleFieldChars` long; `reason` at most `toolRuleTextChars` (checked when put).
4073
+ tool: z.string().min(1).optional(),
4074
+ server: z.string().min(1).optional(),
3439
4075
  kind: z.enum(["mcp", "http"]).optional(),
3440
- agent: z.string().min(1).max(200).optional(),
3441
- when: z.record(z.string().min(1).max(200), ToolInputConditionSchema).optional(),
4076
+ agent: z.string().min(1).optional(),
4077
+ when: z.record(z.string().min(1), ToolInputConditionSchema).optional(),
3442
4078
  /** Why the rule exists: shown with a held or denied call. */
3443
- reason: z.string().min(1).max(500).optional(),
4079
+ reason: z.string().min(1).optional(),
3444
4080
  })
3445
- .strict();
4081
+ .strict()
4082
+ .superRefine((rule, ctx) => {
4083
+ if (rule.tool !== undefined && rule.tool.includes("__"))
4084
+ ctx.addIssue({
4085
+ code: "custom",
4086
+ path: ["tool"],
4087
+ message: `Name an MCP tool by \`server\` and \`tool\` (its own name on the server), not by a model-facing name such as '${rule.tool}'`,
4088
+ });
4089
+ });
3446
4090
  /** `PUT /v1/tenant/tool-policy`: replaces every rule. An empty list allows every call. */
3447
4091
  export const PutToolPolicyRequestSchema = z
3448
- .object({ requestId: RequestIdSchema.optional(), rules: z.array(ToolRuleSchema).max(200) })
4092
+ .object({
4093
+ requestId: RequestIdSchema.optional(),
4094
+ /** At most the Tenant's Runtime limit `toolRules`, checked when they are put. */
4095
+ rules: z.array(ToolRuleSchema),
4096
+ })
3449
4097
  .strict();
3450
4098
  /** The Tenant's tool policy; `updatedAt` is null until one is set. */
3451
4099
  export const ToolPolicySchema = z
@@ -3466,11 +4114,15 @@ export const StreamClosedFrameSchema = z
3466
4114
  */
3467
4115
  export const AgUiRunErrorCodeSchema = z.enum([
3468
4116
  ...ERROR_CODES,
3469
- "session_busy",
3470
4117
  "runtime_error",
3471
4118
  ]);
3472
4119
  // --- Studio embedding (Studio design §8) ---------------------------------------------------
3473
- /** A Tenant id as Studio's routes accept it. */
4120
+ /**
4121
+ * A Tenant id as Studio's routes accept it.
4122
+ * An identifier's grammar is the protocol's (B15): it crosses the Runtime API, tokens and grants
4123
+ * and means the same in every installation, so its length is a constant of protocol 15, not a
4124
+ * setting.
4125
+ */
3474
4126
  const STUDIO_TENANT_ID = /^[A-Za-z0-9_-]{1,128}$/;
3475
4127
  /** `POST /_studio/login-tokens` body. No `tenant` mints a Host-wide token (the CLI's `{}`). */
3476
4128
  export const StudioLoginTokenRequestSchema = z
@@ -3513,7 +4165,6 @@ export const StudioThemeSchema = z.object({
3513
4165
  });
3514
4166
  const EMBED_ROUTE = z
3515
4167
  .string()
3516
- .max(2048)
3517
4168
  .regex(/^\/tenants\/[^/?#\s]+(?:\/[^?#\s]*)?$/, "must be a Studio route under /tenants/");
3518
4169
  const EXTERNAL_URL = z.string().refine((value) => {
3519
4170
  try {
@@ -3595,20 +4246,31 @@ export function parseFrameAncestors(value) {
3595
4246
  // --- File artifacts (protocol 6, blueprint D35, F8.1) ----------------------------------------
3596
4247
  /** The JWT `typ` of a capability link's token (RFC 8725 explicit typing). */
3597
4248
  export const ARTIFACT_LINK_TOKEN_TYPE = "nylorun-artifact+jwt";
3598
- /** A capability link lives no longer than any token the Runtime signs (`TOKEN_TTL_MAX_SECONDS`). */
3599
- export const ARTIFACT_LINK_MAX_TTL_SECONDS = TOKEN_TTL_MAX_SECONDS;
4249
+ /**
4250
+ * How long a capability link lives when its request names no `expiresIn`: the request field's
4251
+ * default. A link lives no longer than any token the Runtime signs (the Host tuning's
4252
+ * `keys.tokenTtlMaxSeconds`, 900 s by default); a longer ask gets that.
4253
+ */
3600
4254
  export const ARTIFACT_LINK_DEFAULT_TTL_SECONDS = 300;
3601
4255
  /** A Tenant's limits when it sets none: 100 MiB per file, 10 GiB in all. */
3602
4256
  export const ARTIFACT_FILE_BYTES_DEFAULT = 100 * 1024 * 1024;
3603
4257
  export const ARTIFACT_TOTAL_BYTES_DEFAULT = 10 * 1024 * 1024 * 1024;
3604
- /** The longest artifact name, in characters. */
3605
- export const ARTIFACT_NAME_MAX = 255;
3606
- /** The longest path of a file in a folder artifact, in characters. */
3607
- export const ARTIFACT_PATH_MAX = 1024;
3608
- /** Labels: up to 32, keys 1–63 characters, values up to 256. */
3609
- export const ArtifactLabelsSchema = z
3610
- .record(z.string().min(1).max(63), z.string().max(256))
3611
- .refine((labels) => Object.keys(labels).length <= 32, { message: "At most 32 labels" });
4258
+ /**
4259
+ * The longest artifact name, in characters: the longest file name a workspace's file system takes
4260
+ * (`NAME_MAX`), since a name becomes one when the artifact is copied into a sandbox or downloaded.
4261
+ * A standard's constant, not a limit (B15).
4262
+ */
4263
+ export const ARTIFACT_NAME_MAX = FILE_NAME_MAX;
4264
+ /**
4265
+ * The longest path of a file in a folder artifact, in characters: the longest path a workspace's
4266
+ * file system takes (`PATH_MAX`), since the folder is unpacked there. A standard's constant.
4267
+ */
4268
+ export const ARTIFACT_PATH_MAX = FILE_PATH_MAX;
4269
+ /**
4270
+ * An artifact's labels. How many, and how long a key and a value may be, are the Tenant's Runtime
4271
+ * limits `artifactLabels`, `labelKeyChars` and `labelValueChars`, checked when they are set.
4272
+ */
4273
+ export const ArtifactLabelsSchema = z.record(z.string().min(1), z.string());
3612
4274
  /**
3613
4275
  * One version of an artifact: immutable once it exists. A folder version's `size` is the sum of
3614
4276
  * its files' sizes and its `sha256` is its manifest's.
@@ -3636,10 +4298,10 @@ export const ArtifactViewSchema = z
3636
4298
  /** The session it belongs to; absent for a Tenant-wide artifact an application made. */
3637
4299
  sessionId: z.string().optional(),
3638
4300
  /**
3639
- * The Environment whose disk versions it holds (R2d step 3); absent otherwise. Such an
3640
- * artifact changes only through `/v1/environments/{id}/snapshot` and its versions routes.
4301
+ * The Agent whose disk versions it holds (R2d step 3); absent otherwise. Such an artifact
4302
+ * changes only through `/v1/agents/{id}/snapshot` and its versions routes.
3641
4303
  */
3642
- environmentId: z.string().optional(),
4304
+ agentId: z.string().optional(),
3643
4305
  latestVersion: z.number().int().positive(),
3644
4306
  labels: z.record(z.string(), z.string()).optional(),
3645
4307
  createdAt: z.string(),
@@ -3667,7 +4329,7 @@ export const UploadArtifactResponseSchema = z
3667
4329
  export const DefinitionFileViewSchema = z
3668
4330
  .object({
3669
4331
  sha256: z.string().regex(/^sha256:[0-9a-f]{64}$/),
3670
- size: z.number().int().nonnegative().max(DEFINITION_FILE_MAX_BYTES),
4332
+ size: z.number().int().nonnegative(),
3671
4333
  })
3672
4334
  .strict();
3673
4335
  export const DeleteArtifactResponseSchema = z
@@ -3679,8 +4341,8 @@ export const CreateArtifactLinkRequestSchema = z
3679
4341
  requestId: RequestIdSchema.optional(),
3680
4342
  /** The version to open. Default: the latest. */
3681
4343
  version: z.number().int().positive().optional(),
3682
- /** Seconds until the link stops working. Default 300, at most 900. */
3683
- expiresIn: z.number().int().min(1).max(ARTIFACT_LINK_MAX_TTL_SECONDS).optional(),
4344
+ /** Seconds until the link stops working. Default 300; a link lives at most the Host's `keys.tokenTtlMaxSeconds` (900 s by default). */
4345
+ expiresIn: z.number().int().min(1).optional(),
3684
4346
  /**
3685
4347
  * A folder's file, by its path in the folder: the link opens that one file. Without it, a
3686
4348
  * folder's link opens its zip.
@@ -3710,12 +4372,8 @@ export const FOLDER_MANIFEST_FORMAT = "nylorun.folder.v1";
3710
4372
  * modes and modification times, symbolic links and empty directories. Readers accept both.
3711
4373
  */
3712
4374
  export const FOLDER_MANIFEST_FORMAT_V2 = "nylorun.folder.v2";
3713
- /** The folder artifact a session's turn-end export writes, one per session. */
4375
+ /** The folder artifact our engine saves a session's outputs to at each turn's end, one per session. */
3714
4376
  export const OUTPUTS_ARTIFACT_NAME = "outputs";
3715
- /** The most files one turn-end export stores; past it the export is skipped. */
3716
- export const EXPORT_MAX_FILES = 10_000;
3717
- /** The most bytes one turn-end export stores (before dedupe); past it the export is skipped. */
3718
- export const EXPORT_MAX_BYTES = 1024 * 1024 * 1024;
3719
4377
  /**
3720
4378
  * One file of a folder: its path in the folder (`/`-separated, relative), size, hash and type.
3721
4379
  * In a v2 manifest an entry may also be a symbolic link (`type: "link"`, its `target`) or an
@@ -3735,7 +4393,7 @@ export const FolderEntrySchema = z
3735
4393
  /** v2: the modification time, ms since the epoch. */
3736
4394
  mtimeMs: z.number().nonnegative().optional(),
3737
4395
  /** v2: a link's target, as stored on the disk. */
3738
- target: z.string().max(4096).optional(),
4396
+ target: z.string().max(LINK_TARGET_MAX).optional(),
3739
4397
  })
3740
4398
  .strict();
3741
4399
  /**
@@ -3800,10 +4458,46 @@ export const TenantArtifactsViewSchema = z
3800
4458
  usedBytes: z.number().int().nonnegative(),
3801
4459
  })
3802
4460
  .strict();
4461
+ /**
4462
+ * A Tenant's skill limits, stored as Tenant setting `skills.config`: the most bytes one skill's
4463
+ * files may hold together. Unset, it is `SKILL_TOTAL_BYTES_DEFAULT` (2 GiB).
4464
+ */
4465
+ export const TenantSkillsConfigSchema = z
4466
+ .object({
4467
+ limits: z
4468
+ .object({
4469
+ /** The most bytes one skill's files may hold together. Default 2 GiB. */
4470
+ totalBytes: z.number().int().positive().optional(),
4471
+ })
4472
+ .strict()
4473
+ .optional(),
4474
+ })
4475
+ .strict();
4476
+ /** `PUT /v1/tenant/skills`: replaces the Tenant's skill configuration. */
4477
+ export const PutTenantSkillsRequestSchema = TenantSkillsConfigSchema.extend({
4478
+ requestId: RequestIdSchema.optional(),
4479
+ }).strict();
4480
+ export const TenantSkillsViewSchema = z
4481
+ .object({ limits: z.object({ totalBytes: z.number().int() }).strict() })
4482
+ .strict();
4483
+ /**
4484
+ * A Tenant's Runtime limits (harness boundary S0), stored as Tenant setting `limits.config`: what
4485
+ * one record entry, model call, model file, tool answer, harness state and Harness API chunk may
4486
+ * hold. Each limit left out is its default (`RUNTIME_LIMIT_DEFAULTS`); none may pass its ceiling
4487
+ * (`RUNTIME_LIMIT_CEILINGS`, a `400` naming it).
4488
+ */
4489
+ export const TenantLimitsConfigSchema = z
4490
+ .object({ limits: RuntimeLimitsSchema.partial().strict().optional() })
4491
+ .strict();
4492
+ /** `PUT /v1/tenant/limits`: replaces the Tenant's Runtime limits. */
4493
+ export const PutTenantLimitsRequestSchema = TenantLimitsConfigSchema.extend({
4494
+ requestId: RequestIdSchema.optional(),
4495
+ }).strict();
4496
+ /** The Runtime limits in force: the Tenant's, with the default for each it leaves out. */
4497
+ export const TenantLimitsViewSchema = z.object({ limits: RuntimeLimitsSchema }).strict();
3803
4498
  /** Opt-in session reads (Host feature `session-reads`). */
3804
4499
  export const SessionListItemSchema = SessionSummarySchema.extend({
3805
4500
  lastTurnId: z.string().nullable(),
3806
- environmentId: z.string().nullable(),
3807
4501
  createdAt: z.string().nullable(),
3808
4502
  lastEventAt: z.string().nullable(),
3809
4503
  }).strict();
@@ -3813,9 +4507,12 @@ export const SessionPageSchema = z
3813
4507
  export const SessionManifestViewSchema = z
3814
4508
  .object({
3815
4509
  sessionId: z.string(),
4510
+ /** The Agent the session runs on. */
3816
4511
  agentId: z.string(),
4512
+ /** The agent manifest version it pinned; `null` for a session closed by protocol 16. */
4513
+ definition: z.object({ name: z.string(), version: z.number().int().positive() }).strict().nullable(),
3817
4514
  manifestHash: z.string(),
3818
- implementationVersion: z.string(),
4515
+ /** The loop manifest it pinned: that version's harness section, as the harness runs it. */
3819
4516
  manifest: z.record(z.string(), z.unknown()),
3820
4517
  })
3821
4518
  .strict();
@@ -3852,7 +4549,8 @@ export const ModelCallSchema = z
3852
4549
  effectId: z.string(),
3853
4550
  sessionId: z.string(),
3854
4551
  turnId: z.string(),
3855
- agentId: z.string(),
4552
+ /** The agent manifest the calling agent came from (protocol 16; `agentId` before). */
4553
+ manifestName: z.string(),
3856
4554
  provider: z.string().nullable(),
3857
4555
  model: z.string().nullable(),
3858
4556
  at: z.string(),
@@ -3889,9 +4587,12 @@ export const ToolCallSchema = z
3889
4587
  effectId: z.string(),
3890
4588
  turnId: z.string(),
3891
4589
  callId: z.string().nullable(),
4590
+ /** The name the model called it by: for display. */
3892
4591
  toolName: z.string().nullable(),
3893
4592
  kind: z.enum(TOOL_CALL_KINDS).nullable(),
3894
4593
  server: z.string().nullable(),
4594
+ /** Its identity (see `tool.completed`): an MCP tool's name on `server`, an HTTP tool's declared name. */
4595
+ tool: z.string().nullable(),
3895
4596
  /** The skill the call ran (see `tool.completed`). */
3896
4597
  skill: z.string().nullable(),
3897
4598
  /** The Agent Plugin that brought its MCP server or skill. */
@@ -3949,6 +4650,6 @@ export const TurnTraceSchema = z
3949
4650
  .passthrough()),
3950
4651
  })
3951
4652
  .passthrough();
3952
- export const EnvironmentPageSchema = z
3953
- .object({ environments: z.array(EnvironmentViewSchema), nextCursor: z.string().nullable() })
4653
+ export const AgentPageSchema = z
4654
+ .object({ agents: z.array(AgentViewSchema), nextCursor: z.string().nullable() })
3954
4655
  .strict();