@nylorun/core 0.23.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.
package/dist/contracts.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /** Public wire contracts only. Never import checkpoint or engine modules here. */
2
2
  import { z } from "zod";
3
3
  import { SANDBOX_NETWORK_PRESETS, isSandboxHostPattern, parseSandboxDuration, parseSandboxSize, } from "./utils/sandbox.js";
4
- import { REMOVED_MANIFEST_FIELDS, manifestVersionIssue, workflowVersionIssue, } from "./definition/removed.js";
4
+ import { REMOVED_MANIFEST_FIELDS, REMOVED_RUNTIME_SECTION_FIELDS, agentManifestVersionIssue, manifestVersionIssue, workflowVersionIssue, } from "./definition/removed.js";
5
5
  import { DELEGATE_INPUT_SCHEMA, DELEGATE_NAME_PATTERN } from "./definition/delegate.js";
6
6
  import { stdioMcpRefusal } from "./definition/mcp.js";
7
7
  import { APPROVAL_MODES, HTTP_TOOL_METHODS, httpInputIssue, httpUrlIssue, httpUrlTemplateIssue, httpVerifierIssue, } from "./definition/http-tool.js";
@@ -11,6 +11,8 @@ export { FILE_NAME_MAX, FILE_PATH_MAX } from "./utils/file-systems.js";
11
11
  import { DEFAULT_HARNESS, HARNESS_ID_PATTERN, isHarnessId } from "./utils/harness-id.js";
12
12
  export { DEFAULT_HARNESS, HARNESS_ID_PATTERN, isHarnessId };
13
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";
14
16
  export { PROTOCOL_VERSION, ERROR_CODES } from "./compatibility.js";
15
17
  export { SKILL_TOTAL_BYTES_DEFAULT, definitionFilesOf, isDefinitionFileHash, skillsOf, } from "./utils/definition-files.js";
16
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";
@@ -457,19 +459,15 @@ function referencedAgents(node) {
457
459
  }
458
460
  /** Workflow definition document. `kind: "workflow"`; a missing `kind` is never a workflow. */
459
461
  export const WorkflowManifestSchema = workflowManifestSchema;
460
- /** 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
+ */
461
467
  export const DefinitionDocumentSchema = z.union([
462
468
  AgentManifestSchema,
463
469
  WorkflowManifestSchema,
464
470
  ]);
465
- export const PutAgentRequestSchema = z
466
- .object({
467
- requestId: RequestIdSchema,
468
- /** Agent or workflow document. Registry `kind` is carried on the document. */
469
- manifest: DefinitionDocumentSchema,
470
- implementationVersion: z.string().min(1),
471
- })
472
- .strict();
473
471
  const hostPatternSchema = z.string().refine(isSandboxHostPattern, {
474
472
  message: "network.allowedHosts entries must be host names such as api.github.com or *.example.com",
475
473
  });
@@ -490,34 +488,35 @@ const resourcesSchema = z
490
488
  .strict();
491
489
  // --- Environments (protocol 11, R2d, blueprint D55 and D56) --------------------------------
492
490
  /**
493
- * An Environment id: 1–200 characters, one or more `/`-separated segments of letters, digits,
494
- * `.`, `_` and `-`, each starting with a letter or digit (`user-42`, `users/alice/web`). Ids are
495
- * 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/*`).
496
495
  */
497
- const ENVIRONMENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
496
+ const AGENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
498
497
  /**
499
498
  * An identifier's grammar is the protocol's (B15): it crosses the Runtime API, tokens and grants
500
- * and means the same in every installation, so its length is a constant of protocol 15, not a
499
+ * and means the same in every installation, so its length is a constant of the protocol, not a
501
500
  * setting.
502
501
  */
503
- export const ENVIRONMENT_ID_MAX_LENGTH = 200;
504
- export function isEnvironmentId(value) {
505
- return (typeof value === "string" &&
506
- value.length <= ENVIRONMENT_ID_MAX_LENGTH &&
507
- ENVIRONMENT_ID_PATTERN.test(value));
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);
508
505
  }
509
- /** An Environment grant: an exact Environment id, or a prefix ending in `/*` (`team-a/*`). */
510
- export function isEnvironmentGrant(value) {
506
+ /** An Agent grant: an exact Agent id, or a prefix ending in `/*` (`team-a/*`). */
507
+ export function isAgentGrant(value) {
511
508
  if (typeof value !== "string")
512
509
  return false;
513
- return value.endsWith("/*") ? isEnvironmentId(value.slice(0, -2)) : isEnvironmentId(value);
510
+ return value === "*" || (value.endsWith("/*") ? isAgentId(value.slice(0, -2)) : isAgentId(value));
514
511
  }
515
512
  /**
516
- * Whether `grants` (a token caller's Environment grants) reach Environment `id`: an exact entry,
517
- * 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.
518
515
  */
519
- export function environmentGranted(grants, id) {
516
+ export function agentGranted(grants, id) {
520
517
  for (const grant of grants ?? []) {
518
+ if (grant === "*")
519
+ return true;
521
520
  if (grant.endsWith("/*")) {
522
521
  if (id.startsWith(grant.slice(0, -1)))
523
522
  return true;
@@ -527,14 +526,14 @@ export function environmentGranted(grants, id) {
527
526
  }
528
527
  return false;
529
528
  }
530
- export const EnvironmentIdSchema = z
529
+ export const AgentIdSchema = z
531
530
  .string()
532
- .refine(isEnvironmentId, {
533
- 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 '-'",
534
533
  })
535
- .meta({ description: "An Environment id, such as `user-42` or `users/alice/web`" });
536
- export const EnvironmentGrantSchema = z.string().refine(isEnvironmentGrant, {
537
- 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/*",
538
537
  });
539
538
  /**
540
539
  * `virtual`: a just-bash workspace in the harness container, no cluster (a local convenience).
@@ -632,42 +631,40 @@ export const EnvironmentFileSchema = z.union([
632
631
  .strict(),
633
632
  ]);
634
633
  /**
635
- * An environment manifest's name (protocol 14, D63): 1–64 letters, digits, `.`, `_` and `-`,
636
- * starting with a letter or digit, such as `analyst-box`; a version is at most 9 digits.
637
- * An identifier's grammar is the protocol's (B15): it crosses the Runtime API, tokens and grants
638
- * and means the same in every installation, so its length is a constant of protocol 15, not a
639
- * setting.
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.
640
637
  */
641
- const ENVIRONMENT_MANIFEST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
642
- export function isEnvironmentManifestName(value) {
643
- 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);
644
641
  }
645
- export const EnvironmentManifestNameSchema = z
642
+ export const AgentManifestNameSchema = z
646
643
  .string()
647
- .refine(isEnvironmentManifestName, {
648
- 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",
649
646
  })
650
- .meta({ description: "An environment manifest's name, such as `analyst-box`" });
647
+ .meta({ description: "An agent manifest's name, such as `triage`" });
651
648
  /**
652
- * Which manifest an Environment is made from: `name` (its latest version when the Environment is
653
- * 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`).
654
651
  */
655
- export function parseEnvironmentManifestRef(ref) {
652
+ export function parseAgentManifestRef(ref) {
656
653
  const at = ref.lastIndexOf("@");
657
654
  const name = at < 0 ? ref : ref.slice(0, at);
658
- if (!isEnvironmentManifestName(name))
655
+ if (!isAgentManifestName(name))
659
656
  return undefined;
660
657
  if (at < 0)
661
658
  return { name };
662
659
  const version = ref.slice(at + 1);
663
660
  return /^[1-9][0-9]{0,8}$/.test(version) ? { name, version: Number(version) } : undefined;
664
661
  }
665
- export const EnvironmentManifestRefSchema = z
662
+ export const AgentManifestRefSchema = z
666
663
  .string()
667
- .refine((value) => parseEnvironmentManifestRef(value) !== undefined, {
668
- 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",
669
666
  })
670
- .meta({ description: "`name` (the latest version when the Environment is created) or `name@n`" });
667
+ .meta({ description: "`name` (tracking) or `name@n` (pinned)" });
671
668
  /**
672
669
  * What an Environment's artifacts, its sessions' skills and its disk versions may hold: part of
673
670
  * its manifest, fixed for its life. Each limit left out is the Tenant's (`/v1/tenant/artifacts`,
@@ -705,26 +702,12 @@ export const EnvironmentLimitsSchema = z
705
702
  })
706
703
  .strict();
707
704
  /**
708
- * `PUT /v1/environments/{environmentId}`: creates the Environment and its vault, or finds the
709
- * one with this id, so "get or create" is one call. An Environment is made from one version of an
710
- * environment manifest (`manifest`) or from the inline manifest these fields make, and never
711
- * changes what it runs after that (protocol 14, D63): on an existing one, `labels` replace its
712
- * labels and `ownerUserId` sets or clears its owner guard, a field that matches what it runs is
713
- * accepted, and anything else is `409 environment_immutable`, naming the fork that makes a new
714
- * Environment instead.
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.
715
707
  */
716
- export const PutEnvironmentRequestSchema = z
717
- .object({
718
- requestId: RequestIdSchema.optional(),
719
- /**
720
- * The environment manifest to make the Environment from (Host feature
721
- * `environment-manifests`): `name` or `name@n`. With it, none of the inline fields below is
722
- * sent; `labels`, `ownerUserId` and `from` still are.
723
- */
724
- manifest: EnvironmentManifestRefSchema.optional(),
725
- /** Default `virtual`. `pod` needs sandbox pods (`nylorun local sandbox enable`). Fixed. */
726
- kind: z.enum(ENVIRONMENT_KINDS).optional(),
727
- labels: EnvironmentLabelsSchema.optional(),
708
+ const runtimeFields = {
709
+ /** `virtual`, `pod` (needs sandbox pods, `nylorun local sandbox enable`) or `none`. Fixed. */
710
+ kind: z.enum(ENVIRONMENT_KINDS),
728
711
  /** Pods only: the workload image (default the Tenant's, else `python:3.13-slim`). */
729
712
  image: z.string().min(1).optional(),
730
713
  resources: resourcesSchema.optional(),
@@ -740,47 +723,45 @@ export const PutEnvironmentRequestSchema = z
740
723
  .object({ allowedHosts: z.array(hostPatternSchema).optional() })
741
724
  .strict()
742
725
  .optional(),
743
- /**
744
- * The harness that runs the Environment's sessions (track R4): `nylorun` (ours, the default)
745
- * or the id of a custom harness. A pod Environment whose harness is not ours runs its
746
- * `image` as the harness: the image's own entrypoint, with nothing copied in. It is fixed
747
- * for the Environment's life (protocol 14): to run another harness, fork onto a manifest
748
- * version that names it. Each session pins the harness when it opens; a session whose
749
- * Environment id was deleted and made again with another harness fails its next turn with
750
- * `harness_mismatch`.
751
- */
752
- harness: HarnessIdSchema.optional(),
753
- /**
754
- * The owner guard: when set, only sessions of this owner may name the Environment (checked
755
- * when a session opens and at every turn start). `null` clears it.
756
- */
757
- ownerUserId: z.string().min(1).nullable().optional(),
758
726
  lifecycle: EnvironmentLifecycleSchema.optional(),
759
- /**
760
- * Pods only (Host feature `environment-setup`): commands run when the disk is made or reset,
761
- * before any turn. A change applies at the next reset.
762
- */
727
+ /** Pods only: commands run when the disk is made or reset, before any turn. */
763
728
  setup: z.array(EnvironmentSetupCommandSchema).optional(),
764
- /** Pods only: artifact versions copied in when the disk is made or reset, before `setup`. */
729
+ /** Pods only: artifact versions or files by hash copied in when the disk is made or reset, before `setup`. */
765
730
  files: z.array(EnvironmentFileSchema).optional(),
766
- /**
767
- * What its artifacts and its sessions' skills may hold, at most the Tenant's limits; a limit
768
- * left out is the Tenant's. Fixed.
769
- */
731
+ /** What its artifacts and its sessions' skills may hold, at most the Tenant's limits. Fixed. */
770
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,
771
752
  /**
772
- * The secrets an Environment of this kind needs, by name (D64): each slot's type, binding,
773
- * whether it is required and a description, never a value. With slots declared, a secret
774
- * 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.
775
755
  */
776
- secrets: z.lazy(() => EnvironmentSecretSlotsSchema).optional(),
756
+ owner: z.string().min(1).nullable().optional(),
757
+ labels: EnvironmentLabelsSchema.optional(),
777
758
  /**
778
- * Only when the `PUT` creates the Environment (Host feature `environment-disk-versions`): its
779
- * 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.
780
761
  */
781
762
  from: z
782
763
  .object({
783
- environment: EnvironmentIdSchema,
764
+ agent: AgentIdSchema,
784
765
  version: z.union([z.number().int().positive(), z.literal("latest")]),
785
766
  })
786
767
  .strict()
@@ -788,8 +769,9 @@ export const PutEnvironmentRequestSchema = z
788
769
  })
789
770
  .strict();
790
771
  /**
791
- * What an Environment runs (its inline manifest, called the recipe before protocol 14), resolved
792
- * 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.
793
775
  */
794
776
  export const EnvironmentRecipeSchema = z
795
777
  .object({
@@ -806,9 +788,14 @@ export const EnvironmentRecipeSchema = z
806
788
  secrets: z.lazy(() => EnvironmentSecretSlotsSchema).optional(),
807
789
  })
808
790
  .strict();
809
- /** A session that names an Environment, as the Environment's view lists it. */
810
- export const EnvironmentSessionSchema = z
811
- .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
+ })
812
799
  .strict();
813
800
  /** What the Runtime wants of a pod (`desired`) and what it last saw (`observed`). */
814
801
  export const POD_DESIRED = ["running", "suspended", "deleted"];
@@ -820,7 +807,7 @@ export const POD_OBSERVED = [
820
807
  "failed",
821
808
  "deleting",
822
809
  ];
823
- export const EnvironmentPodViewSchema = z
810
+ export const AgentPodViewSchema = z
824
811
  .object({
825
812
  desired: z.enum(POD_DESIRED),
826
813
  observed: z.enum(POD_OBSERVED),
@@ -838,27 +825,91 @@ export const EnvironmentPodViewSchema = z
838
825
  })
839
826
  .strict();
840
827
  /**
841
- * The compute states an Environment reports today: `ready` until a tool first runs in a virtual
842
- * one, then `creating`, `running` or `stopped`. An open set: clients must accept values they do
843
- * 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.
844
844
  */
845
- export const ENVIRONMENT_STATES = ["ready", "creating", "running", "stopped"];
846
- /** `PUT` and `GET /v1/environments/{environmentId}`. */
847
- 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
848
858
  .object({
849
859
  id: z.string(),
850
- kind: z.enum(ENVIRONMENT_KINDS),
851
- 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"]),
852
868
  /**
853
- * What it runs, fixed when it was made (protocol 14): its manifest's fields, or the inline
854
- * 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.
855
872
  */
856
- manifest: EnvironmentRecipeSchema,
857
- /** The environment manifest it was made from and its version, when it was made from one. */
858
- manifestName: z.string().optional(),
859
- manifestVersion: z.number().int().positive().optional(),
860
- /** The hash of what it runs (`manifest`). */
861
- 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(),
876
+ /**
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.
879
+ */
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() })
887
+ .strict()
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,
862
913
  /** The limits in force now: its manifest's, else the Tenant's, never above the Tenant's. */
863
914
  limits: z
864
915
  .object({
@@ -867,37 +918,17 @@ export const EnvironmentViewSchema = z
867
918
  disk: z.object({ versionBytes: z.number().int(), versionEntries: z.number().int() }).strict(),
868
919
  })
869
920
  .strict(),
870
- /**
871
- * The Environment it was forked from (`POST .../fork`, Q15), and the disk version it started
872
- * from (`null` for an empty disk).
873
- */
874
- forkedFrom: z
875
- .object({ environment: z.string(), disk: z.number().int().positive().nullable() })
876
- .strict()
877
- .optional(),
921
+ /** Its sessions (acting for a subject, only the subject's own). */
922
+ sessions: z.array(AgentSessionSchema),
878
923
  /** Each secret slot its manifest declares, and whether its vault holds a value for it. */
879
- slots: z
880
- .array(z
924
+ slots: z.array(z
881
925
  .object({
882
926
  name: z.string(),
883
927
  type: z.string(),
884
928
  required: z.boolean(),
885
929
  set: z.boolean(),
886
930
  })
887
- .strict())
888
- .optional(),
889
- /** Always 1 since protocol 14: an Environment never changes what it runs. */
890
- version: z.number().int().positive(),
891
- /** Always `version`. */
892
- appliedVersion: z.number().int().positive(),
893
- /** The owner guard, or `null`. */
894
- ownerUserId: z.string().nullable(),
895
- /** See `ENVIRONMENT_STATES`: an open set. */
896
- state: z.string().meta({ description: "ready, creating, running or stopped; an open set" }),
897
- /** Kind `pod`: what the Runtime wants of the pod and what it last saw. */
898
- pod: EnvironmentPodViewSchema.optional(),
899
- /** When it was last used: a turn, a recipe change, a secret write, a stop or a reset. */
900
- lastUsedAt: z.string(),
931
+ .strict()),
901
932
  /**
902
933
  * Its disk versions (Host feature `environment-disk-versions`): the latest, and the copy
903
934
  * that holds the disk now, if one does. Absent for kind `none`.
@@ -912,20 +943,25 @@ export const EnvironmentViewSchema = z
912
943
  startedAt: z.string(),
913
944
  })
914
945
  .strict()
915
- .optional(),
946
+ .nullable(),
916
947
  })
917
948
  .strict()
918
949
  .optional(),
919
- /** Sessions that name it (acting for a subject, only the subject's own). */
920
- 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(),
921
957
  createdAt: z.string(),
922
958
  updatedAt: z.string(),
923
959
  })
924
960
  .strict();
925
- /** `POST /v1/environments/{id}/snapshot`: a new version of the Environment's disk. */
926
- export const EnvironmentSnapshotSchema = z
961
+ /** `POST /v1/agents/{id}/snapshot`: a new version of the Agent's disk. */
962
+ export const AgentSnapshotSchema = z
927
963
  .object({
928
- environmentId: z.string(),
964
+ agentId: z.string(),
929
965
  artifactId: z.string(),
930
966
  version: z.number().int().positive(),
931
967
  format: z.string(),
@@ -941,29 +977,29 @@ export const EnvironmentSnapshotSchema = z
941
977
  createdAt: z.string(),
942
978
  })
943
979
  .strict();
944
- /** `POST /v1/environments/{id}/restore`: which version of its disk to put back. */
945
- export const RestoreEnvironmentRequestSchema = z
980
+ /** `POST /v1/agents/{id}/restore`: which version of its disk to put back. */
981
+ export const RestoreAgentRequestSchema = z
946
982
  .object({
947
983
  requestId: RequestIdSchema.optional(),
948
984
  version: z.union([z.number().int().positive(), z.literal("latest")]),
949
985
  })
950
986
  .strict();
951
- export const EnvironmentRestoreSchema = z
987
+ export const AgentRestoreSchema = z
952
988
  .object({
953
- environmentId: z.string(),
989
+ agentId: z.string(),
954
990
  restored: z.number().int().positive(),
955
991
  /**
956
- * `done` once the version is back (a virtual Environment); `pending` while a pod's new volume
957
- * 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).
958
994
  */
959
995
  status: z.enum(["done", "pending"]),
960
996
  volumeGeneration: z.number().int().nonnegative().optional(),
961
997
  })
962
998
  .strict();
963
- /** `GET /v1/environments/{id}/versions`: its disk versions, newest first. */
964
- export const EnvironmentVersionsSchema = z
999
+ /** `GET /v1/agents/{id}/versions`: its disk versions, newest first. */
1000
+ export const AgentDiskVersionsSchema = z
965
1001
  .object({
966
- environmentId: z.string(),
1002
+ agentId: z.string(),
967
1003
  /** The folder artifact that holds them (read trees, files and diffs through `/v1/artifacts`). */
968
1004
  artifactId: z.string().nullable(),
969
1005
  latest: z.number().int().positive().nullable(),
@@ -976,22 +1012,19 @@ export const EnvironmentVersionsSchema = z
976
1012
  .strict()),
977
1013
  })
978
1014
  .strict();
979
- export const ListEnvironmentsResponseSchema = z
980
- .object({ environments: z.array(EnvironmentViewSchema) })
981
- .strict();
982
- export const DeleteEnvironmentResponseSchema = z
1015
+ export const DeleteAgentResponseSchema = z
983
1016
  .object({ id: z.string(), deleted: z.boolean() })
984
1017
  .strict();
985
- /** 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). */
986
1019
  export const EgressRunningTurnSchema = z
987
1020
  .object({ sessionId: z.string(), turnId: z.string() })
988
1021
  .strict();
989
1022
  /**
990
- * One connection a pod Environment opened through egress-gate (track R7, Q6): written when it
991
- * closes, or at once when the gate refused it, to the Environment's own stream as
992
- * `environment.egress` (D67). The connection is the Environment's: its egress token names the pod,
993
- * and the Environment's sessions run turns in parallel (D66). `runningTurns` lists the turns
994
- * 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.
995
1028
  *
996
1029
  * `startedAt` is the gate's clock at CONNECT and `durationMs` runs from there to the close, so
997
1030
  * the span is the gate's own measurement. `bytesUp` is what the sandbox sent, `bytesDown` what it
@@ -1001,7 +1034,7 @@ export const EgressRunningTurnSchema = z
1001
1034
  */
1002
1035
  export const EgressConnectionPayloadSchema = z
1003
1036
  .object({
1004
- environmentId: z.string(),
1037
+ agentId: z.string(),
1005
1038
  host: z.string(),
1006
1039
  port: z.number().int(),
1007
1040
  outcome: z.enum(["allowed", "refused"]),
@@ -1020,100 +1053,172 @@ export const EgressConnectionPayloadSchema = z
1020
1053
  runningTurns: z.array(EgressRunningTurnSchema).max(16),
1021
1054
  })
1022
1055
  .passthrough();
1023
- /** The schema id of an Environment's lifecycle events (its stream in the record). */
1024
- export const ENVIRONMENT_EVENT_SCHEMA = "nylorun.environment-event/1";
1025
- export const ENVIRONMENT_EVENT_TYPES = [
1026
- "environment.created",
1027
- "environment.attached",
1028
- "environment.detached",
1029
- "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",
1030
1076
  // Kind `pod` (Host feature `sandbox-pods`).
1031
- "environment.running",
1032
- "environment.suspended",
1033
- "environment.relaunched",
1034
- "environment.lost",
1035
- "environment.reset",
1036
- "environment.failed",
1037
- // Forked into a new Environment (Q15).
1038
- "environment.forked",
1039
- // egress-gate: every connection the Environment opens (R7, D67).
1040
- "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",
1041
1098
  ];
1042
- /** The payload of each Environment lifecycle event. */
1043
- export const ENVIRONMENT_EVENT_PAYLOADS = {
1044
- "environment.created": z
1099
+ /** The payload of each Agent lifecycle event. */
1100
+ export const AGENT_EVENT_PAYLOADS = {
1101
+ "agent.created": z
1045
1102
  .object({
1046
1103
  kind: z.enum(ENVIRONMENT_KINDS),
1047
1104
  labels: z.record(z.string(), z.string()),
1048
- /** The environment manifest and version it was made from (protocol 14, D63). */
1049
- manifest: z.object({ name: z.string(), version: z.number().int().positive() }).strict().optional(),
1050
- /** 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). */
1051
1110
  forkedFrom: z
1052
- .object({ environment: z.string(), disk: z.number().int().positive().nullable() })
1111
+ .object({ agent: z.string(), disk: z.number().int().positive().nullable() })
1053
1112
  .strict()
1054
1113
  .optional(),
1055
1114
  })
1056
1115
  .passthrough(),
1057
- "environment.attached": z.object({ sessionId: z.string() }).passthrough(),
1058
- "environment.detached": z
1116
+ "agent.attached": z.object({ sessionId: z.string() }).passthrough(),
1117
+ "agent.detached": z
1059
1118
  .object({ sessionId: z.string(), reason: z.enum(["reset"]) })
1060
1119
  .passthrough(),
1061
1120
  /** Deleted by a `DELETE`, or by the sweep once `lifecycle.deleteAfter` passed (`reason`). */
1062
- "environment.deleted": z
1121
+ "agent.deleted": z
1063
1122
  .object({ reason: z.enum(["delete", "deleteAfter"]).optional() })
1064
1123
  .passthrough(),
1065
- /** A pod joined and serves the Environment. */
1066
- "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(),
1067
1126
  /** Stopped (`POST .../stop`, or idle): the volume is kept; the next turn starts it again. */
1068
- "environment.suspended": z.object({ reason: z.enum(["stop", "idle"]) }).passthrough(),
1127
+ "agent.suspended": z.object({ reason: z.enum(["stop", "idle", "restart"]) }).passthrough(),
1069
1128
  /** Its pod was replaced (same volume): the old pod's host token no longer works. */
1070
- "environment.relaunched": z.object({ hostEpoch: z.number().int() }).passthrough(),
1129
+ "agent.relaunched": z.object({ hostEpoch: z.number().int() }).passthrough(),
1071
1130
  /** Its volume or node is gone: turns are refused until a reset. */
1072
- "environment.lost": z.object({ reason: z.string() }).passthrough(),
1131
+ "agent.lost": z.object({ reason: z.string() }).passthrough(),
1073
1132
  /** Reset: a new pod on a new, empty volume. */
1074
- "environment.reset": z.object({ volumeGeneration: z.number().int() }).passthrough(),
1133
+ "agent.reset": z.object({ volumeGeneration: z.number().int() }).passthrough(),
1075
1134
  /** The pod did not become ready. */
1076
- "environment.failed": z.object({ reason: z.string() }).passthrough(),
1077
- /** Forked into Environment `to`: its disk started from version `disk`, `secrets` were copied. */
1078
- "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
1079
1138
  .object({
1080
1139
  to: z.string(),
1081
1140
  disk: z.number().int().positive().nullable(),
1082
- 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(),
1083
1142
  secrets: z.number().int().nonnegative(),
1084
1143
  })
1085
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(),
1086
1172
  /** A connection through egress-gate, with the turns running as it opened (D67). */
1087
- "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() }),
1088
1192
  };
1089
- /** One lifecycle event on an Environment's stream, numbered from 0. */
1090
- export const EnvironmentEventSchema = z
1193
+ /** One lifecycle event on an Agent's stream, numbered from 0. */
1194
+ export const AgentEventSchema = z
1091
1195
  .object({
1092
- schema: z.literal(ENVIRONMENT_EVENT_SCHEMA),
1196
+ schema: z.literal(AGENT_EVENT_SCHEMA),
1093
1197
  eventId: z.string(),
1094
1198
  tenantId: z.string(),
1095
- environmentId: z.string(),
1199
+ agentId: z.string(),
1096
1200
  seq: z.number().int().nonnegative(),
1097
1201
  time: z.string(),
1098
- type: z.enum(ENVIRONMENT_EVENT_TYPES),
1202
+ type: z.enum(AGENT_EVENT_TYPES),
1099
1203
  payload: z.record(z.string(), z.unknown()),
1100
1204
  })
1101
1205
  .strict();
1102
- export const ListEnvironmentEventsResponseSchema = z
1103
- .object({ events: z.array(EnvironmentEventSchema) })
1206
+ export const ListAgentEventsResponseSchema = z
1207
+ .object({ events: z.array(AgentEventSchema) })
1104
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
+ */
1105
1215
  export const PutSessionRequestSchema = z
1106
1216
  .object({
1107
1217
  requestId: RequestIdSchema,
1108
- agentId: z.string().min(1),
1218
+ /** The Agent the session runs on. Fixed once the session exists. */
1219
+ agent: AgentIdSchema,
1109
1220
  ownerUserId: z.string().min(1),
1110
1221
  info: jsonObject.optional(),
1111
- /**
1112
- * The Environment the session runs in: its sandbox, and its vault's credentials for the
1113
- * session's shell, MCP servers and HTTP tools. Omitted: no sandbox and no credentials.
1114
- * Fixed once the session exists.
1115
- */
1116
- environment: EnvironmentIdSchema.optional(),
1117
1222
  })
1118
1223
  .strict();
1119
1224
  /** The hosts a harness can run on (blueprint D38). */
@@ -1310,7 +1415,7 @@ const EnvironmentValueSchema = z
1310
1415
  */
1311
1416
  export const TOOL_SECRET_NAME_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
1312
1417
  /**
1313
- * `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
1314
1419
  * in the Environment's vault. For `environment_secret` and `environment_variable` the name is
1315
1420
  * the variable's name (a POSIX name, not reserved); for `bearer` and `headers` it is a label.
1316
1421
  * The same name and type keeps the credential and re-seals its value and binding; another type
@@ -1318,7 +1423,7 @@ export const TOOL_SECRET_NAME_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
1318
1423
  * credentials bound to one host, or two `bearer`/`headers` credentials for one URL, are
1319
1424
  * `409 credential_conflict`.
1320
1425
  */
1321
- export const PutEnvironmentSecretRequestSchema = z.discriminatedUnion("type", [
1426
+ export const PutAgentSecretRequestSchema = z.discriminatedUnion("type", [
1322
1427
  z
1323
1428
  .object({
1324
1429
  requestId: RequestIdSchema.optional(),
@@ -1358,7 +1463,7 @@ export const PutEnvironmentSecretRequestSchema = z.discriminatedUnion("type", [
1358
1463
  * A secret write on an Environment whose manifest declares the secret's slot (D64): only the
1359
1464
  * value, `value` (or `headers` for a `headers` slot). Its type and binding come from the slot.
1360
1465
  */
1361
- export const PutEnvironmentSecretValueRequestSchema = z
1466
+ export const PutAgentSecretValueRequestSchema = z
1362
1467
  .object({
1363
1468
  requestId: RequestIdSchema.optional(),
1364
1469
  value: z.string().min(1).optional(),
@@ -1390,7 +1495,7 @@ const slotBase = {
1390
1495
  };
1391
1496
  /**
1392
1497
  * One secret an Environment of a kind needs (D64): its type and binding, never its value. The
1393
- * 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}`
1394
1499
  * with `{ value }`, or `{ headers }` for `headers`), and the binding comes from here.
1395
1500
  */
1396
1501
  export const EnvironmentSecretSlotSchema = z.discriminatedUnion("type", [
@@ -1416,62 +1521,462 @@ export const EnvironmentSecretSlotsSchema = z
1416
1521
  ctx.addIssue({ code: "custom", path: [name], message: error });
1417
1522
  }
1418
1523
  });
1419
- /** The schema version of an environment manifest; the Runtime refuses one it does not know. */
1420
- export const ENVIRONMENT_MANIFEST_SCHEMA_VERSION = 1;
1421
- 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" });
1562
+ /**
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.
1565
+ */
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
1626
+ .object({
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();
1422
1803
  /**
1423
- * An environment manifest (protocol 14, D63): a named, versioned definition of a kind of
1424
- * Environment, saved like an agent (`PUT /v1/environment-manifests/{name}`). It holds what every
1425
- * Environment made from it shares; an Environment's id, labels, owner guard, disk and secret
1426
- * values are its own. Written as a JSON file with `$schema`, which clients drop before saving.
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.
1427
1808
  */
1428
- export const EnvironmentManifestSchema = z
1809
+ export const PutMemoryRequestSchema = z
1429
1810
  .object({
1430
- manifestSchemaVersion: z.literal(ENVIRONMENT_MANIFEST_SCHEMA_VERSION, {
1431
- error: (issue) => `manifestSchemaVersion ${JSON.stringify(issue.input)} is not one this Runtime reads: use ${ENVIRONMENT_MANIFEST_SCHEMA_VERSION}`,
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(", ")}`,
1432
1853
  }),
1433
- name: EnvironmentManifestNameSchema,
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,
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,
1434
1886
  /** At most the Tenant's Runtime limit `manifestDescriptionChars`, checked when it is saved. */
1435
1887
  description: z.string().optional(),
1436
- kind: environmentFields.kind,
1437
- image: environmentFields.image,
1438
- resources: environmentFields.resources,
1439
- storage: environmentFields.storage,
1440
- network: environmentFields.network,
1441
- harness: environmentFields.harness,
1442
- lifecycle: environmentFields.lifecycle,
1443
- setup: environmentFields.setup,
1444
- files: environmentFields.files,
1445
- limits: environmentFields.limits,
1446
- secrets: EnvironmentSecretSlotsSchema.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(),
1447
1923
  })
1448
1924
  .strict();
1449
- /** `PUT /v1/environment-manifests/{name}`: the manifest, whose `name` is the path's. */
1450
- export const PutEnvironmentManifestRequestSchema = EnvironmentManifestSchema.extend({
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(),
1952
+ })
1953
+ .strict();
1954
+ /** `PUT /v1/agent-manifests/{name}`: the manifest, whose `name` is the path's. */
1955
+ export const PutAgentManifestRequestSchema = AgentManifestV8Schema.extend({
1451
1956
  requestId: RequestIdSchema.optional(),
1452
1957
  }).strict();
1453
1958
  /** Who saved a version: the subject a request acted for, else `application`. */
1454
- export const EnvironmentManifestSavedBySchema = z.object({ actor: z.string() }).strict();
1455
- /** One version of an environment manifest. */
1456
- 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
1457
1962
  .object({
1458
1963
  name: z.string(),
1459
1964
  version: z.number().int().positive(),
1460
1965
  /** The hash of `manifest`: equal manifests have equal hashes. */
1461
1966
  hash: z.string(),
1462
- manifest: EnvironmentManifestSchema,
1463
- savedBy: EnvironmentManifestSavedBySchema,
1967
+ manifest: AgentManifestV8Schema,
1968
+ savedBy: AgentManifestSavedBySchema,
1464
1969
  createdAt: z.string(),
1465
- /** How many Environments were made from this version. */
1466
- environments: z.number().int().nonnegative(),
1970
+ /** How many Agents were made from this version. */
1971
+ agents: z.number().int().nonnegative(),
1467
1972
  })
1468
1973
  .strict();
1469
- /** `GET /v1/environment-manifests`: each manifest's latest version, by name. */
1470
- export const ListEnvironmentManifestsResponseSchema = z
1471
- .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) })
1472
1977
  .strict();
1473
- /** `GET /v1/environment-manifests/{name}/versions`: every version, newest first. */
1474
- export const EnvironmentManifestVersionsSchema = z
1978
+ /** `GET /v1/agent-manifests/{name}/versions`: every version, newest first. */
1979
+ export const AgentManifestVersionsSchema = z
1475
1980
  .object({
1476
1981
  name: z.string(),
1477
1982
  latest: z.number().int().positive(),
@@ -1479,24 +1984,36 @@ export const EnvironmentManifestVersionsSchema = z
1479
1984
  .object({
1480
1985
  version: z.number().int().positive(),
1481
1986
  hash: z.string(),
1482
- savedBy: EnvironmentManifestSavedBySchema,
1987
+ savedBy: AgentManifestSavedBySchema,
1483
1988
  createdAt: z.string(),
1484
- environments: z.number().int().nonnegative(),
1989
+ agents: z.number().int().nonnegative(),
1485
1990
  })
1486
1991
  .strict()),
1487
1992
  })
1488
1993
  .strict();
1489
1994
  /** Something a save would do that the saver should know: never a refusal. */
1490
- export const EnvironmentManifestWarningSchema = z
1995
+ export const AgentManifestWarningSchema = z
1491
1996
  .object({ code: z.string(), message: z.string() })
1492
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();
1493
2009
  /**
1494
- * `PUT /v1/environment-manifests/{name}?dryRun=true`: what saving it would do, with nothing
1495
- * saved. `errors` lists every reason the Runtime would refuse it (the Tenant's limits, for one);
1496
- * a save with errors is `400`. `behind` counts the Environments made from an older version than
1497
- * 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.
1498
2015
  */
1499
- export const EnvironmentManifestPlanSchema = z
2016
+ export const AgentManifestPlanSchema = z
1500
2017
  .object({
1501
2018
  name: z.string(),
1502
2019
  /** The latest version now, or `null` for a new manifest. */
@@ -1504,54 +2021,62 @@ export const EnvironmentManifestPlanSchema = z
1504
2021
  /** The version a save would answer: `from` when nothing changed. */
1505
2022
  to: z.number().int().positive(),
1506
2023
  unchanged: z.boolean(),
1507
- changes: z.array(z.object({ path: z.string(), from: z.unknown().optional(), to: z.unknown().optional() }).strict()),
1508
- warnings: z.array(EnvironmentManifestWarningSchema),
2024
+ changes: z.array(AgentManifestChangeSchema),
2025
+ warnings: z.array(AgentManifestWarningSchema),
1509
2026
  errors: z.array(z.string()),
1510
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(),
1511
2036
  })
1512
2037
  .strict();
1513
- /** `PUT /v1/environment-manifests/{name}`: the version saved (or the latest, unchanged). */
1514
- export const SaveEnvironmentManifestResponseSchema = z
2038
+ /** `PUT /v1/agent-manifests/{name}`: the version saved (or the latest, unchanged). */
2039
+ export const SaveAgentManifestResponseSchema = z
1515
2040
  .object({
1516
- manifest: EnvironmentManifestViewSchema,
2041
+ manifest: AgentManifestViewSchema,
1517
2042
  unchanged: z.boolean(),
1518
- warnings: z.array(EnvironmentManifestWarningSchema),
2043
+ warnings: z.array(AgentManifestWarningSchema),
1519
2044
  })
1520
2045
  .strict();
1521
- export const DeleteEnvironmentManifestResponseSchema = z
2046
+ export const DeleteAgentManifestResponseSchema = z
1522
2047
  .object({ name: z.string(), deleted: z.boolean() })
1523
2048
  .strict();
1524
2049
  /**
1525
- * `POST /v1/environments/{id}/fork` (Q15): how an Environment gets a new manifest version. The
1526
- * fork is a new Environment, made from the version, its disk started from a version of the
1527
- * source's disk and its secrets copied inside the Runtime. The source keeps what it runs, its
1528
- * 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.
1529
2054
  */
1530
- export const ForkEnvironmentRequestSchema = z
2055
+ export const ForkAgentRequestSchema = z
1531
2056
  .object({
1532
2057
  requestId: RequestIdSchema.optional(),
1533
- /** The new Environment's id. */
1534
- id: EnvironmentIdSchema,
1535
- /** `name` or `name@n`; default the source's manifest at its latest version. */
1536
- 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(),
1537
2062
  /** Where its disk starts: `latest` (a snapshot taken first; the default), a version, or `empty`. */
1538
2063
  disk: z.union([z.literal("latest"), z.literal("empty"), z.number().int().positive()]).optional(),
1539
- /** `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. */
1540
2065
  secrets: z.enum(["copy", "none"]).optional(),
1541
2066
  labels: EnvironmentLabelsSchema.optional(),
1542
- ownerUserId: z.string().min(1).nullable().optional(),
2067
+ owner: z.string().min(1).nullable().optional(),
1543
2068
  /** Answer the plan and make nothing. */
1544
2069
  dryRun: z.boolean().optional(),
1545
2070
  })
1546
2071
  .strict();
1547
2072
  /** What a fork does (or, with `dryRun`, would do). */
1548
- export const EnvironmentForkPlanSchema = z
2073
+ export const AgentForkPlanSchema = z
1549
2074
  .object({
1550
2075
  source: z.string(),
1551
2076
  id: z.string(),
1552
2077
  kind: z.enum(ENVIRONMENT_KINDS),
1553
- /** The manifest version it is made from, or `null` for the source's inline fields. */
1554
- 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(),
1555
2080
  /** The disk version it starts from: `latest` in a dry run (the snapshot is taken at the fork); `null` for an empty disk. */
1556
2081
  disk: z.union([z.number().int().positive(), z.literal("latest")]).nullable(),
1557
2082
  /** Whether the new manifest's setup runs on the copied disk: it differs from what the source runs. */
@@ -1570,13 +2095,63 @@ export const EnvironmentForkPlanSchema = z
1570
2095
  changes: z.array(z.object({ path: z.string(), from: z.unknown().optional(), to: z.unknown().optional() }).strict()),
1571
2096
  /** The source's sessions: they stay on it. */
1572
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(),
1573
2100
  })
1574
2101
  .strict();
1575
- /** `POST /v1/environments/{id}/fork`: the new Environment and the plan it ran, or with `dryRun` the plan only. */
1576
- export const ForkEnvironmentResponseSchema = z.union([
1577
- z.object({ dryRun: z.literal(true), plan: EnvironmentForkPlanSchema }).strict(),
1578
- 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(),
1579
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();
1580
2155
  /**
1581
2156
  * What a model may read (protocol 12): `text` always; `image`, `pdf`, `office` (Word, Excel,
1582
2157
  * PowerPoint), `audio` and `video` when its catalog entry or the operator says so. In this order.
@@ -1648,7 +2223,7 @@ export const ENVIRONMENT_SECRET_TYPES = [
1648
2223
  * One credential of an Environment's vault, never its value: what it is bound to (the server
1649
2224
  * `url` for `bearer` and `headers`; the hosts and header for `environment_secret`).
1650
2225
  */
1651
- export const EnvironmentSecretViewSchema = z
2226
+ export const AgentSecretViewSchema = z
1652
2227
  .object({
1653
2228
  name: z.string(),
1654
2229
  type: z.enum(ENVIRONMENT_SECRET_TYPES),
@@ -1667,14 +2242,14 @@ export const EnvironmentSecretViewSchema = z
1667
2242
  rotatedAt: z.string().optional(),
1668
2243
  })
1669
2244
  .strict();
1670
- export const ListEnvironmentSecretsResponseSchema = z
1671
- .object({ secrets: z.array(EnvironmentSecretViewSchema) })
2245
+ export const ListAgentSecretsResponseSchema = z
2246
+ .object({ secrets: z.array(AgentSecretViewSchema) })
1672
2247
  .strict();
1673
2248
  /** The MCP transports a preview speaks: a manifest's remote server types. */
1674
2249
  export const MCP_PREVIEW_TYPES = ["streamable-http", "sse"];
1675
2250
  /**
1676
2251
  * `POST /v1/tenant/mcp/preview` (R2b C12): what a remote MCP server offers, before an agent
1677
- * 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`
1678
2253
  * (none without one), lists the tools and closes the connection; it never calls a tool.
1679
2254
  */
1680
2255
  export const McpPreviewRequestSchema = z
@@ -1703,7 +2278,7 @@ export const McpPreviewRequestSchema = z
1703
2278
  */
1704
2279
  name: modelFacingName("MCP server").optional(),
1705
2280
  /** The Environment whose vault's credential for `url` to send. Default: none is sent. */
1706
- environmentId: EnvironmentIdSchema.optional(),
2281
+ agentId: AgentIdSchema.optional(),
1707
2282
  })
1708
2283
  .strict();
1709
2284
  /** One tool a preview found. */
@@ -1756,24 +2331,22 @@ export const McpPreviewSchema = z
1756
2331
  })
1757
2332
  .strict();
1758
2333
  /**
1759
- * `POST /v1/tenant/credential-coverage`: which credential each of a saved agent's remote MCP
1760
- * servers and HTTP tools would get in a session that names `environmentId`, decided as the
1761
- * 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.
1762
2338
  */
1763
2339
  export const CredentialCoverageRequestSchema = z
1764
2340
  .object({
1765
2341
  requestId: RequestIdSchema.optional(),
1766
- /** A saved agent or flow agent. */
1767
- agentId: z.string().min(1),
1768
- /** The Environment the session would name. Default: none (every entry is `missing`). */
1769
- environmentId: EnvironmentIdSchema.optional(),
2342
+ agentId: AgentIdSchema,
1770
2343
  })
1771
2344
  .strict();
1772
2345
  /** A credential coverage names: where it is, never its value. */
1773
2346
  export const CoverageCredentialSchema = z
1774
2347
  .object({
1775
- environmentId: z.string(),
1776
- /** The secret's name in the Environment's vault. */
2348
+ agentId: z.string(),
2349
+ /** The secret's name in the Agent's vault. */
1777
2350
  name: z.string(),
1778
2351
  /** Where the credential sends the requests instead of the URL (a gateway). */
1779
2352
  via: z.string().optional(),
@@ -1812,7 +2385,6 @@ export const CredentialCoverageEntrySchema = z
1812
2385
  export const CredentialCoverageSchema = z
1813
2386
  .object({
1814
2387
  agentId: z.string(),
1815
- environmentId: z.string().nullable(),
1816
2388
  /** True when every entry is `covered`. */
1817
2389
  complete: z.boolean(),
1818
2390
  /** One per declared MCP server and HTTP tool credential: the agent's, then its agents'. */
@@ -1823,11 +2395,18 @@ const commandBase = {
1823
2395
  requestId: RequestIdSchema,
1824
2396
  idempotencyKey: IdempotencyKeySchema,
1825
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"]);
1826
2404
  const messageBase = {
1827
2405
  ...commandBase,
1828
2406
  type: z.literal("message"),
1829
2407
  /** Optional turn manifest (Loop patch); validated as a variant of the pinned agent. */
1830
2408
  manifest: AgentManifestSchema.optional(),
2409
+ delivery: MessageDeliverySchema.optional(),
1831
2410
  };
1832
2411
  /**
1833
2412
  * One part of a user message (protocol 6): text, or a file by artifact id. A file part without
@@ -1946,7 +2525,8 @@ export const EvidenceClassSchema = z.enum([
1946
2525
  /** A command's sender (R4.9): from the request's credential, never from its body. */
1947
2526
  export const EventPrincipalSchema = z
1948
2527
  .object({
1949
- 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"]),
1950
2530
  id: z.string(),
1951
2531
  })
1952
2532
  .strict();
@@ -2003,6 +2583,19 @@ export const AcceptedResponseSchema = z.object({
2003
2583
  cursor: z.string().nullable(),
2004
2584
  requestId: z.string(),
2005
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]);
2006
2599
  export const RejectedResponseSchema = z.object({
2007
2600
  status: z.literal("rejected"),
2008
2601
  code: z.enum(ERROR_CODES),
@@ -2136,10 +2729,11 @@ export const ContextCompactedPayloadSchema = z
2136
2729
  export const TOOL_CALL_STATUSES = ["completed", "failed", "cancelled"];
2137
2730
  /**
2138
2731
  * Where a tool call ran (R5.1), its effect's target kind (protocol 15): an MCP server, an HTTP
2139
- * tool's URL, the session's sandbox, or the harness that runs the turn (`harness`: a tool it runs
2140
- * in its own process, such as our engine's skill, artifact and `tool_search` tools).
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).
2141
2735
  */
2142
- export const TOOL_CALL_KINDS = ["mcp", "http", "sandbox", "harness"];
2736
+ export const TOOL_CALL_KINDS = ["mcp", "http", "sandbox", "harness", "runtime"];
2143
2737
  /**
2144
2738
  * What the Tenant's tool policy did with a tool call (R5 step 2), when it did more than allow
2145
2739
  * it: `deny` refused it unsent; `ask` held it for a person, who approved it (`approvedBy`, when
@@ -2229,8 +2823,10 @@ export const EffectUncertainPayloadSchema = z
2229
2823
  const turnEndFacts = {
2230
2824
  durationMs: z.number().int().nonnegative().optional(),
2231
2825
  pausedMs: z.number().int().nonnegative().optional(),
2232
- /** The session's agent. */
2826
+ /** The session's Agent. */
2233
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(),
2234
2830
  totals: z
2235
2831
  .object({
2236
2832
  steps: z.number().int().nonnegative(),
@@ -2272,6 +2868,26 @@ export const TurnFailedPayloadSchema = z
2272
2868
  export const TurnCancelledPayloadSchema = z
2273
2869
  .object({ reason: z.string().optional(), ...turnEndFacts })
2274
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();
2275
2891
  /** Lifecycle of an agent used as a tool. `agent.delegationId` is the parent call's invocation. */
2276
2892
  export const DelegationPayloadSchema = z
2277
2893
  .object({
@@ -2304,6 +2920,17 @@ export const CommandMessagePayloadSchema = z
2304
2920
  parts: z.array(MessagePartSchema).optional(),
2305
2921
  /** The turn manifest the message carried, if any. */
2306
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(),
2307
2934
  /**
2308
2935
  * The W3C trace context the message was sent with (R7.4): the turn's trace is the caller's,
2309
2936
  * and its root span the child of the caller's span.
@@ -2347,11 +2974,11 @@ export const EnvironmentStatePayloadSchema = z
2347
2974
  })
2348
2975
  .passthrough();
2349
2976
  /**
2350
- * `environment.attached`: the session was opened on an Environment (`environment`). The
2351
- * 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.
2352
2979
  */
2353
- export const EnvironmentAttachedPayloadSchema = z
2354
- .object({ environmentId: z.string() })
2980
+ export const AgentAttachedPayloadSchema = z
2981
+ .object({ agentId: z.string() })
2355
2982
  .passthrough();
2356
2983
  /** `environment.exec`: one sandbox tool call finished. */
2357
2984
  export const EnvironmentExecPayloadSchema = z
@@ -2564,6 +3191,11 @@ export const EVENT_CATALOG = {
2564
3191
  "turn.paused": { payload: TurnPausedPayloadSchema, source: "loop", version: 1 },
2565
3192
  "turn.failed": { payload: TurnFailedPayloadSchema, source: "loop", version: 1 },
2566
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 },
2567
3199
  "message.assistant": { payload: AssistantMessagePayloadSchema, source: "loop", version: 1 },
2568
3200
  "model.failed": { payload: ModelFailedPayloadSchema, source: "loop", version: 1 },
2569
3201
  "context.compacted": { payload: ContextCompactedPayloadSchema, source: "loop", version: 1 },
@@ -2574,7 +3206,7 @@ export const EVENT_CATALOG = {
2574
3206
  "mcp.discovered": { payload: McpDiscoveredPayloadSchema, source: "loop", version: 1 },
2575
3207
  "environment.state": { payload: EnvironmentStatePayloadSchema, source: "loop", version: 1 },
2576
3208
  "environment.exec": { payload: EnvironmentExecPayloadSchema, source: "loop", version: 1 },
2577
- "environment.attached": { payload: EnvironmentAttachedPayloadSchema, source: "api", version: 1 },
3209
+ "agent.attached": { payload: AgentAttachedPayloadSchema, source: "api", version: 1 },
2578
3210
  "node.started": { payload: NodeStartedPayloadSchema, source: "loop", version: 1 },
2579
3211
  "node.completed": { payload: NodeCompletedPayloadSchema, source: "loop", version: 1 },
2580
3212
  "node.agent": { payload: NodeAgentPayloadSchema, source: "loop", version: 1 },
@@ -2834,7 +3466,7 @@ export const TenantStatusSchema = z
2834
3466
  })
2835
3467
  .strict(),
2836
3468
  model: HostModelViewSchema,
2837
- /** The registered agents. */
3469
+ /** The Tenant's Agents, by id. */
2838
3470
  agents: z.array(z.object({ agentId: z.string() }).strict()),
2839
3471
  counts: z
2840
3472
  .object({
@@ -2930,22 +3562,22 @@ export const SeedTenantConfigResponseSchema = z
2930
3562
  export const ResetTenantRequestSchema = z
2931
3563
  .object({
2932
3564
  requestId: RequestIdSchema,
2933
- scope: z.enum(["sessions", "environments", "all"]),
3565
+ scope: z.enum(["sessions", "agents", "all"]),
2934
3566
  activeWork: z.enum(["drain", "cancel"]),
2935
3567
  })
2936
3568
  .strict();
2937
3569
  /**
2938
3570
  * Acting for a subject (Host feature `subject-headers`): what an application principal may
2939
3571
  * narrow a request to. `sessions:own` reaches only the subject's own sessions; the others reach
2940
- * Tenant-wide resources. `environments:write` creates, changes and deletes Environments and
2941
- * writes their secrets (protocol 11); a token caller's reach only the ids its Environment
2942
- * 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.
2943
3575
  */
2944
3576
  export const SUBJECT_SCOPES = [
2945
3577
  "agents:read",
2946
3578
  "agents:write",
2947
3579
  "sessions:own",
2948
- "environments:write",
3580
+ "agent-manifests:write",
2949
3581
  ];
2950
3582
  /**
2951
3583
  * Retired scopes: `Nylorun-Scopes` may still name them (older clients do), and they grant
@@ -2992,10 +3624,10 @@ export function parseSubjectHeaders(subject, scopes) {
2992
3624
  message: "Nylorun-Scopes is required with Nylorun-Subject",
2993
3625
  };
2994
3626
  const names = named.filter((name) => !RETIRED_SUBJECT_SCOPES.includes(name));
2995
- if (names.includes("sandboxes:write"))
3627
+ if (names.includes("sandboxes:write") || names.includes("environments:write"))
2996
3628
  return {
2997
3629
  ok: false,
2998
- 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)",
2999
3631
  };
3000
3632
  const unknown = names.filter((name) => !SUBJECT_SCOPES.includes(name));
3001
3633
  if (unknown.length > 0)
@@ -3008,12 +3640,13 @@ export function parseSubjectHeaders(subject, scopes) {
3008
3640
  }
3009
3641
  // --- token callers (Host feature `trusted-issuers`) ------------------------------------------
3010
3642
  /**
3011
- * 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.
3012
3645
  */
3013
3646
  export const TOKEN_SCOPES = [
3014
3647
  "agents:read",
3015
3648
  "sessions:own",
3016
- "environments:write",
3649
+ "agents:write",
3017
3650
  ];
3018
3651
  /**
3019
3652
  * The `iss` of every token a Tenant's Runtime signs itself: capability links, run, host and
@@ -3022,6 +3655,7 @@ export const TOKEN_SCOPES = [
3022
3655
  export function tenantTokenIssuer(tenantId) {
3023
3656
  return `urn:nylorun:tenant:${tenantId}`;
3024
3657
  }
3658
+ /** The Agents a caller reaches: `*` for every one, or Agent grants (ids and `p/*` prefixes). */
3025
3659
  const AgentAllowlistSchema = z.union([
3026
3660
  z.literal("*"),
3027
3661
  z.array(z.string().min(1)),
@@ -3078,9 +3712,8 @@ export const CALLER_SCOPES = [...SUBJECT_SCOPES, "studio"];
3078
3712
  * `issuer:<name>` (a token from the identity file's issuer `name`).
3079
3713
  * - `subject` is the person the request acts for; absent for an application key alone.
3080
3714
  * - `scopes`: what the caller holds. An application key alone holds every subject scope.
3081
- * - `agents`: the agents it may reach, `*` for all.
3082
- * - `environments`: the Environment grants of a token caller (empty reaches none); absent for
3083
- * 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).
3084
3717
  */
3085
3718
  export const MeResponseSchema = z
3086
3719
  .object({
@@ -3090,12 +3723,6 @@ export const MeResponseSchema = z
3090
3723
  .meta({ description: "The person the request acts for; absent for an application key alone" }),
3091
3724
  scopes: z.array(z.enum(CALLER_SCOPES)),
3092
3725
  agents: AgentAllowlistSchema,
3093
- environments: z
3094
- .array(z.string())
3095
- .optional()
3096
- .meta({
3097
- description: "A token caller's Environment grants (empty reaches none); absent when no grant limits the caller",
3098
- }),
3099
3726
  via: z.string().meta({
3100
3727
  description: "How the caller authenticated: `application:<principalId>`, `management:<principalId>`, `subject` or `issuer:<name>`",
3101
3728
  }),
@@ -3118,37 +3745,9 @@ export function isSerializedOrigin(value) {
3118
3745
  }
3119
3746
  // Successful answers of the Runtime and Management APIs that had no schema of their own. With the
3120
3747
  // request schemas above they describe every body the Runtime sends (its OpenAPI document).
3121
- /** `GET /v1/agents` with an application key: every definition, manifest included. */
3122
- export const AgentDefinitionViewSchema = z
3123
- .object({
3124
- agentId: z.string(),
3125
- manifest: z.record(z.string(), z.unknown()),
3126
- manifestHash: z.string(),
3127
- implementationVersion: z.string(),
3128
- })
3129
- .strict();
3748
+ /** `GET /v1/agents`: the Agents the caller reaches. */
3130
3749
  export const ListAgentsResponseSchema = z
3131
- .object({ agents: z.array(AgentDefinitionViewSchema) })
3132
- .strict();
3133
- /** `GET /v1/agents` with a token caller's credential: the allowed agents' names only. */
3134
- export const PublicAgentSchema = z
3135
- .object({
3136
- agentId: z.string(),
3137
- name: z.string().optional(),
3138
- description: z.string().optional(),
3139
- })
3140
- .strict();
3141
- export const ListPublicAgentsResponseSchema = z
3142
- .object({ agents: z.array(PublicAgentSchema) })
3143
- .strict();
3144
- export const PutAgentResponseSchema = z
3145
- .object({
3146
- agentId: z.string(),
3147
- manifestHash: z.string(),
3148
- implementationVersion: z.string(),
3149
- /** True for `?dryRun=true` (protocol 14): every check ran, and nothing was saved. */
3150
- dryRun: z.boolean().optional(),
3151
- })
3750
+ .object({ agents: z.array(AgentViewSchema) })
3152
3751
  .strict();
3153
3752
  export const SESSION_STATUSES = [
3154
3753
  "idle",
@@ -3164,6 +3763,7 @@ export const SESSION_STATUSES = [
3164
3763
  export const SessionSummarySchema = z
3165
3764
  .object({
3166
3765
  id: z.string(),
3766
+ /** The Agent the session runs on. */
3167
3767
  agentId: z.string(),
3168
3768
  ownerUserId: z.string(),
3169
3769
  status: z.enum(SESSION_STATUSES),
@@ -3177,33 +3777,28 @@ export const ListSessionsResponseSchema = z
3177
3777
  export const SessionViewSchema = z
3178
3778
  .object({
3179
3779
  id: z.string(),
3780
+ /** The Agent the session runs on (protocol 16). */
3180
3781
  agentId: z.string(),
3181
3782
  ownerUserId: z.string(),
3182
- manifestHash: z.string(),
3183
3783
  /**
3184
- * The hash of the definition the session was opened from (R2b C11). Since protocol 15 the
3185
- * session pins its definition as registered, so it equals `manifestHash`. Absent for a
3186
- * session opened before R2b C11.
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.
3187
3786
  */
3188
- definitionHash: z.string().optional(),
3189
- 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(),
3190
3790
  status: z.enum(SESSION_STATUSES),
3191
3791
  activeTurnId: z.string().nullable(),
3192
- /**
3193
- * The Environment the session names, and its recipe version when the session opened (for
3194
- * reading only); `null` without one.
3195
- */
3196
- environment: z
3197
- .object({ id: z.string(), version: z.number().int().positive() })
3198
- .strict()
3199
- .nullable(),
3792
+ /** Messages waiting in the session's queue for the next turn (protocol 17). */
3793
+ queuedMessages: z.number().int().nonnegative(),
3200
3794
  /**
3201
3795
  * The harness that runs the session's turns, pinned when it opened (track R4): its
3202
- * Environment's harness, else `nylorun`.
3796
+ * manifest's `harness.id`, else `nylorun`.
3203
3797
  */
3204
3798
  harness: z.string(),
3205
3799
  /**
3206
- * 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
3207
3802
  * before protocol 13, `protocol_11` for one opened before protocol 11 (a new turn is
3208
3803
  * `409 session_closed`; its history stays readable).
3209
3804
  */
@@ -3352,13 +3947,16 @@ export const TenantSandboxViewSchema = z
3352
3947
  .optional(),
3353
3948
  })
3354
3949
  .strict();
3355
- /** What a usage total or a budget covers: the whole Tenant, one agent, or one turn. */
3356
- 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"]);
3357
3955
  /** `GET /v1/tenant/usage`: which rows of the model usage ledger to total. */
3358
3956
  export const ModelUsageQuerySchema = z
3359
3957
  .object({
3360
3958
  scope: ModelUsageScopeSchema.default("tenant"),
3361
- /** The agent or turn id; required for those scopes. */
3959
+ /** The manifest's name or the turn id; required for those scopes. */
3362
3960
  id: z.string().min(1).optional(),
3363
3961
  /** The current UTC day or month, or every row. */
3364
3962
  period: z.enum(["day", "month", "total"]).default("total"),
@@ -3385,11 +3983,14 @@ export const ModelUsageTotalsSchema = z
3385
3983
  */
3386
3984
  export const ModelBudgetSchema = z
3387
3985
  .object({
3388
- /** `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
+ */
3389
3990
  scope: ModelUsageScopeSchema,
3390
- /** The agent's id; `agent` only. */
3991
+ /** The agent manifest's name; `manifest` only. */
3391
3992
  id: z.string().min(1).optional(),
3392
- /** The UTC period spend counts over; `agent` and `tenant` only. */
3993
+ /** The UTC period spend counts over; `manifest` and `tenant` only. */
3393
3994
  period: z.enum(["day", "month"]).optional(),
3394
3995
  /** pi-ai's catalog price; custom endpoints count as $0, so cap them in tokens. */
3395
3996
  limitUsd: z.number().positive().optional(),
@@ -3399,10 +4000,10 @@ export const ModelBudgetSchema = z
3399
4000
  .superRefine((budget, ctx) => {
3400
4001
  if (budget.limitUsd === undefined && budget.limitTokens === undefined)
3401
4002
  ctx.addIssue({ code: "custom", message: "A budget needs limitUsd, limitTokens or both" });
3402
- if ((budget.scope === "agent") !== (budget.id !== undefined))
3403
- 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" });
3404
4005
  if ((budget.scope === "turn") === (budget.period !== undefined))
3405
- 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" });
3406
4007
  });
3407
4008
  /** `PUT /v1/tenant/budgets`: replaces every budget. An empty list removes them all. */
3408
4009
  export const PutModelBudgetsRequestSchema = z
@@ -3513,7 +4114,6 @@ export const StreamClosedFrameSchema = z
3513
4114
  */
3514
4115
  export const AgUiRunErrorCodeSchema = z.enum([
3515
4116
  ...ERROR_CODES,
3516
- "session_busy",
3517
4117
  "runtime_error",
3518
4118
  ]);
3519
4119
  // --- Studio embedding (Studio design §8) ---------------------------------------------------
@@ -3698,10 +4298,10 @@ export const ArtifactViewSchema = z
3698
4298
  /** The session it belongs to; absent for a Tenant-wide artifact an application made. */
3699
4299
  sessionId: z.string().optional(),
3700
4300
  /**
3701
- * The Environment whose disk versions it holds (R2d step 3); absent otherwise. Such an
3702
- * 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.
3703
4303
  */
3704
- environmentId: z.string().optional(),
4304
+ agentId: z.string().optional(),
3705
4305
  latestVersion: z.number().int().positive(),
3706
4306
  labels: z.record(z.string(), z.string()).optional(),
3707
4307
  createdAt: z.string(),
@@ -3898,7 +4498,6 @@ export const TenantLimitsViewSchema = z.object({ limits: RuntimeLimitsSchema }).
3898
4498
  /** Opt-in session reads (Host feature `session-reads`). */
3899
4499
  export const SessionListItemSchema = SessionSummarySchema.extend({
3900
4500
  lastTurnId: z.string().nullable(),
3901
- environmentId: z.string().nullable(),
3902
4501
  createdAt: z.string().nullable(),
3903
4502
  lastEventAt: z.string().nullable(),
3904
4503
  }).strict();
@@ -3908,9 +4507,12 @@ export const SessionPageSchema = z
3908
4507
  export const SessionManifestViewSchema = z
3909
4508
  .object({
3910
4509
  sessionId: z.string(),
4510
+ /** The Agent the session runs on. */
3911
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(),
3912
4514
  manifestHash: z.string(),
3913
- implementationVersion: z.string(),
4515
+ /** The loop manifest it pinned: that version's harness section, as the harness runs it. */
3914
4516
  manifest: z.record(z.string(), z.unknown()),
3915
4517
  })
3916
4518
  .strict();
@@ -3947,7 +4549,8 @@ export const ModelCallSchema = z
3947
4549
  effectId: z.string(),
3948
4550
  sessionId: z.string(),
3949
4551
  turnId: z.string(),
3950
- agentId: z.string(),
4552
+ /** The agent manifest the calling agent came from (protocol 16; `agentId` before). */
4553
+ manifestName: z.string(),
3951
4554
  provider: z.string().nullable(),
3952
4555
  model: z.string().nullable(),
3953
4556
  at: z.string(),
@@ -4047,6 +4650,6 @@ export const TurnTraceSchema = z
4047
4650
  .passthrough()),
4048
4651
  })
4049
4652
  .passthrough();
4050
- export const EnvironmentPageSchema = z
4051
- .object({ environments: z.array(EnvironmentViewSchema), nextCursor: z.string().nullable() })
4653
+ export const AgentPageSchema = z
4654
+ .object({ agents: z.array(AgentViewSchema), nextCursor: z.string().nullable() })
4052
4655
  .strict();