@nylorun/core 0.18.0-beta → 0.20.0-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/dist/compatibility.d.ts +78 -30
  3. package/dist/compatibility.js +83 -30
  4. package/dist/contracts.d.ts +1531 -461
  5. package/dist/contracts.js +972 -344
  6. package/dist/define.d.ts +1 -0
  7. package/dist/define.js +1 -0
  8. package/dist/definition/approval.d.ts +16 -0
  9. package/dist/definition/approval.js +35 -0
  10. package/dist/definition/code-tools.d.ts +1 -1
  11. package/dist/definition/code-tools.js +1 -1
  12. package/dist/definition/flow/compile.js +0 -2
  13. package/dist/definition/http-tool.d.ts +7 -4
  14. package/dist/definition/http-tool.js +6 -10
  15. package/dist/definition/manifest.js +1 -0
  16. package/dist/definition/mcp.d.ts +4 -4
  17. package/dist/definition/mcp.js +15 -12
  18. package/dist/definition/removed.js +1 -1
  19. package/dist/definition/variant.d.ts +1 -1
  20. package/dist/definition/variant.js +6 -5
  21. package/dist/harness-api/entries.d.ts +241 -0
  22. package/dist/harness-api/entries.js +117 -0
  23. package/dist/harness-api/gates.d.ts +172 -0
  24. package/dist/harness-api/gates.js +119 -0
  25. package/dist/harness-api/harness-api.schema.json +5056 -0
  26. package/dist/harness-api/index.d.ts +19 -3
  27. package/dist/harness-api/index.js +16 -3
  28. package/dist/harness-api/json-schema.d.ts +12 -0
  29. package/dist/harness-api/json-schema.js +61 -0
  30. package/dist/harness-api/mcp.d.ts +61 -0
  31. package/dist/harness-api/mcp.js +41 -0
  32. package/dist/harness-api/messages.d.ts +12 -4
  33. package/dist/harness-api/messages.js +6 -2
  34. package/dist/harness-api/schema.d.ts +356 -31
  35. package/dist/harness-api/schema.js +147 -20
  36. package/dist/harness-api/transport.d.ts +55 -0
  37. package/dist/harness-api/transport.js +61 -0
  38. package/dist/types/manifest.d.ts +15 -9
  39. package/dist/types/observe.d.ts +3 -2
  40. package/dist/utils/harness-id.d.ts +9 -0
  41. package/dist/utils/harness-id.js +11 -0
  42. package/package.json +5 -4
package/dist/contracts.js CHANGED
@@ -6,10 +6,12 @@ import { DELEGATE_INPUT_SCHEMA, DELEGATE_NAME_PATTERN } from "./definition/deleg
6
6
  import { mcpToolSettingsVersionIssue, stdioMcpRefusal, usesMcpToolSettings, } from "./definition/mcp.js";
7
7
  import { APPROVAL_MODES, HTTP_TOOL_MAX_TIMEOUT_MS, HTTP_TOOL_METHODS, httpUrlIssue, } from "./definition/http-tool.js";
8
8
  import { canonical } from "./utils/canonical.js";
9
+ import { DEFAULT_HARNESS, HARNESS_ID_PATTERN, isHarnessId } from "./utils/harness-id.js";
10
+ export { DEFAULT_HARNESS, HARNESS_ID_PATTERN, isHarnessId };
9
11
  import { DEFINITION_FILE_MAX_BYTES, skillFilesIssue } from "./utils/definition-files.js";
10
12
  export { PROTOCOL_VERSION, ERROR_CODES } from "./compatibility.js";
11
13
  export { DEFINITION_FILE_MAX_BYTES, SKILL_FILES_MAX, definitionFilesOf, isDefinitionFileHash, } from "./utils/definition-files.js";
12
- import { ERROR_CODES } from "./compatibility.js";
14
+ import { ERROR_CODES, isArtifactId } from "./compatibility.js";
13
15
  export const RequestIdSchema = z.string().min(1);
14
16
  export const IdempotencyKeySchema = z.string().min(1).max(256);
15
17
  const jsonObject = z.record(z.string(), z.unknown());
@@ -504,19 +506,13 @@ export const PutAgentRequestSchema = z
504
506
  implementationVersion: z.string().min(1),
505
507
  })
506
508
  .strict();
507
- export const CredentialSelectionSchema = z
508
- .object({
509
- serverName: z.string().min(1),
510
- credentialId: z.string().min(1),
511
- })
512
- .strict();
513
- const sandboxHostSchema = z.string().refine(isSandboxHostPattern, {
514
- message: "network.allow entries must be host names such as api.github.com or *.example.com",
509
+ const hostPatternSchema = z.string().refine(isSandboxHostPattern, {
510
+ message: "network.allowedHosts entries must be host names such as api.github.com or *.example.com",
515
511
  });
516
- const sandboxDurationSchema = (name) => z.string().refine((value) => parseSandboxDuration(value) !== undefined, {
512
+ const durationSchema = (name) => z.string().refine((value) => parseSandboxDuration(value) !== undefined, {
517
513
  message: `${name} must be a duration such as 30s, 15m or 1h`,
518
514
  });
519
- const sandboxResourcesSchema = z
515
+ const resourcesSchema = z
520
516
  .object({
521
517
  cpus: z.number().int().min(1).max(64).optional(),
522
518
  memory: z
@@ -527,41 +523,30 @@ const sandboxResourcesSchema = z
527
523
  .optional(),
528
524
  })
529
525
  .strict();
526
+ // --- Environments (protocol 11, R2d, blueprint D55 and D56) --------------------------------
530
527
  /**
531
- * A sandbox defined when a session is opened. No `network.allow` means no egress. The Runtime
532
- * checks it against the Tenant's limits and pins the result on the session.
528
+ * An Environment id: 1–200 characters, one or more `/`-separated segments of letters, digits,
529
+ * `.`, `_` and `-`, each starting with a letter or digit (`user-42`, `users/alice/web`). Ids are
530
+ * hierarchical so a grant can name a family of them (`users/alice/*`).
533
531
  */
534
- export const SandboxInlineRequestSchema = z
535
- .object({
536
- image: z.string().min(1).optional(),
537
- network: z.object({ allow: z.array(sandboxHostSchema).optional() }).strict().optional(),
538
- resources: sandboxResourcesSchema.optional(),
539
- })
540
- .strict();
541
- // --- sandboxes as a resource (Host feature `sandboxes`, blueprint D39) ----------------------
542
- /**
543
- * A sandbox id: 1–200 characters, one or more `/`-separated segments of letters, digits, `.`,
544
- * `_` and `-`, each starting with a letter or digit (`user-42`, `team-a/proj-42`). Ids are
545
- * hierarchical so an `sbx` grant can name a family of them (`team-a/*`).
546
- */
547
- const SANDBOX_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
548
- export const SANDBOX_ID_MAX_LENGTH = 200;
549
- export function isSandboxId(value) {
532
+ const ENVIRONMENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
533
+ export const ENVIRONMENT_ID_MAX_LENGTH = 200;
534
+ export function isEnvironmentId(value) {
550
535
  return (typeof value === "string" &&
551
- value.length <= SANDBOX_ID_MAX_LENGTH &&
552
- SANDBOX_ID_PATTERN.test(value));
536
+ value.length <= ENVIRONMENT_ID_MAX_LENGTH &&
537
+ ENVIRONMENT_ID_PATTERN.test(value));
553
538
  }
554
- /** A sandbox grant: an exact sandbox id, or a prefix ending in `/*` (`team-a/*`). */
555
- export function isSandboxGrant(value) {
539
+ /** An Environment grant: an exact Environment id, or a prefix ending in `/*` (`team-a/*`). */
540
+ export function isEnvironmentGrant(value) {
556
541
  if (typeof value !== "string")
557
542
  return false;
558
- return value.endsWith("/*") ? isSandboxId(value.slice(0, -2)) : isSandboxId(value);
543
+ return value.endsWith("/*") ? isEnvironmentId(value.slice(0, -2)) : isEnvironmentId(value);
559
544
  }
560
545
  /**
561
- * Whether `grants` (a token caller's sandbox grants) reach sandbox `id`: an exact entry, or a prefix
562
- * entry `p/*` for any id below `p/`. No grants reach no sandbox.
546
+ * Whether `grants` (a token caller's Environment grants) reach Environment `id`: an exact entry,
547
+ * or a prefix entry `p/*` for any id below `p/`. No grants reach no Environment.
563
548
  */
564
- export function sandboxGranted(grants, id) {
549
+ export function environmentGranted(grants, id) {
565
550
  for (const grant of grants ?? []) {
566
551
  if (grant.endsWith("/*")) {
567
552
  if (id.startsWith(grant.slice(0, -1)))
@@ -572,245 +557,437 @@ export function sandboxGranted(grants, id) {
572
557
  }
573
558
  return false;
574
559
  }
575
- export const SandboxIdSchema = z
560
+ export const EnvironmentIdSchema = z
576
561
  .string()
577
- .refine(isSandboxId, {
578
- message: "A sandbox id is up to 200 characters: /-separated segments of letters, digits, '.', '_' and '-'",
562
+ .refine(isEnvironmentId, {
563
+ message: "An Environment id is up to 200 characters: /-separated segments of letters, digits, '.', '_' and '-'",
579
564
  })
580
- .meta({ description: "A sandbox id, such as `user-42` or `team-a/proj-42`" });
581
- export const SandboxGrantSchema = z.string().refine(isSandboxGrant, {
582
- message: "A sandbox grant is a sandbox id, or a prefix ending in /* such as team-a/*",
565
+ .meta({ description: "An Environment id, such as `user-42` or `users/alice/web`" });
566
+ export const EnvironmentGrantSchema = z.string().refine(isEnvironmentGrant, {
567
+ message: "An Environment grant is an Environment id, or a prefix ending in /* such as team-a/*",
583
568
  });
584
- /** `virtual`: a just-bash workspace, no cluster (F7.1). `pod`: an agent-sandbox pod (F7.2). */
585
- export const SANDBOX_KINDS = ["virtual", "pod"];
569
+ /**
570
+ * `virtual`: a just-bash workspace in the harness container, no cluster (a local convenience).
571
+ * `pod`: an agent-sandbox pod with its own volume (Host feature `sandbox-pods`). `none`: no
572
+ * compute, only the vault, for agents whose tools are remote MCP servers and HTTP tools.
573
+ */
574
+ export const ENVIRONMENT_KINDS = ["virtual", "pod", "none"];
586
575
  const LABEL_KEY_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._/-]{0,61}[A-Za-z0-9])?$/;
587
576
  const LABEL_VALUE_PATTERN = /^[\x20-\x7e]{0,256}$/;
588
- export const SANDBOX_LABELS_MAX = 32;
577
+ export const ENVIRONMENT_LABELS_MAX = 32;
589
578
  /** The developer's own key-value pairs; the Runtime stores and filters them, never reads them. */
590
- export const SandboxLabelsSchema = z
579
+ export const EnvironmentLabelsSchema = z
591
580
  .record(z.string().regex(LABEL_KEY_PATTERN, {
592
581
  message: "Label keys are 1-63 letters, digits, '.', '_', '/' and '-'",
593
582
  }), z.string().regex(LABEL_VALUE_PATTERN, {
594
583
  message: "Label values are up to 256 printable ASCII characters",
595
584
  }))
596
- .refine((labels) => Object.keys(labels).length <= SANDBOX_LABELS_MAX, {
597
- message: `At most ${SANDBOX_LABELS_MAX} labels`,
585
+ .refine((labels) => Object.keys(labels).length <= ENVIRONMENT_LABELS_MAX, {
586
+ message: `At most ${ENVIRONMENT_LABELS_MAX} labels`,
587
+ });
588
+ /** A harness id (track R4): what a harness names itself in `hello`. */
589
+ export const HarnessIdSchema = z.string().regex(HARNESS_ID_PATTERN, {
590
+ message: "harness must be a harness id: lowercase letters, digits and dashes, starting with a letter",
598
591
  });
599
592
  /**
600
- * `PUT /v1/sandboxes/{sandboxId}`: creates the sandbox, or finds the one with this id. The spec
601
- * (`kind`, `image`, `network`, `resources`, `storage`) is checked against the Tenant's limits
602
- * and fixed once the sandbox exists; `labels`, when sent, replace the sandbox's labels.
603
- *
604
- * Kind `pod` (Host feature `sandbox-pods`) is created at once on the Tenant's cluster. A `PUT`
605
- * on an existing pod sandbox also starts it again when it was stopped, and one with a
606
- * `lifecycle.ttl` other than its own sets a new expiry (counted from its creation), which
607
- * revives an expired sandbox.
593
+ * An Environment's lifecycle. `idle`: stop compute after this long without a turn, at most the
594
+ * Tenant's `limits.idle` (default the Tenant's). `deleteAfter`: delete the Environment, its vault
595
+ * and its disk once it has gone this long unused (no turn, recipe change, secret write, stop or
596
+ * reset); default never.
608
597
  */
609
- export const PutSandboxRequestSchema = z
598
+ export const EnvironmentLifecycleSchema = z
599
+ .object({
600
+ idle: durationSchema("lifecycle.idle").optional(),
601
+ deleteAfter: durationSchema("lifecycle.deleteAfter").optional(),
602
+ })
603
+ .strict();
604
+ /** The most setup commands and input files an Environment's recipe holds (step 2). */
605
+ export const ENVIRONMENT_SETUP_MAX = 16;
606
+ /** A setup command's longest timeout (default 10m). */
607
+ export const ENVIRONMENT_SETUP_TIMEOUT_MAX_MS = 30 * 60_000;
608
+ const absoluteWorkspacePath = (name) => z
609
+ .string()
610
+ .min(1)
611
+ .max(1024)
612
+ .refine((value) => (value === "/workspace" || value.startsWith("/workspace/")) &&
613
+ !value.split("/").some((segment) => segment === ".." || segment === "."), { message: `${name} must be /workspace or a path under it, without . or .. segments` });
614
+ /**
615
+ * One setup command (pods only): run with `/bin/sh -c` when the pod's disk is made or reset,
616
+ * before the engine takes a turn, with the Environment's variables, secrets (as the sentinel)
617
+ * and egress, as a turn's commands are.
618
+ */
619
+ export const EnvironmentSetupCommandSchema = z
620
+ .object({
621
+ command: z.string().min(1).max(4096),
622
+ /** Where it runs. Default `/workspace`. */
623
+ cwd: absoluteWorkspacePath("cwd").optional(),
624
+ /** Default 10m, at most 30m. */
625
+ timeout: durationSchema("timeout")
626
+ .refine((value) => (parseSandboxDuration(value) ?? 0) <= ENVIRONMENT_SETUP_TIMEOUT_MAX_MS, {
627
+ message: "timeout is at most 30m",
628
+ })
629
+ .optional(),
630
+ })
631
+ .strict();
632
+ /**
633
+ * One input file (pods only): a version of a Tenant-wide artifact, copied in when the pod's disk
634
+ * is made or reset, before the setup commands. A file artifact is written at `path`; a folder
635
+ * artifact is unpacked under it.
636
+ */
637
+ export const EnvironmentFileSchema = z
638
+ .object({
639
+ artifactId: z.string().refine(isArtifactId, { message: "artifactId must be an artifact id" }),
640
+ version: z.number().int().positive(),
641
+ path: absoluteWorkspacePath("path"),
642
+ })
643
+ .strict();
644
+ /**
645
+ * `PUT /v1/environments/{environmentId}`: creates the Environment and its vault, or finds the
646
+ * one with this id, so "get or create" is one call. On an existing one the fields sent are
647
+ * compared: `kind` and `storage` are fixed (a difference is `409`), `labels` replace its labels,
648
+ * and any other difference changes its recipe and bumps its `version`. Image and resources
649
+ * reach a pod when it next starts from stopped; `network.allowedHosts` applies within seconds.
650
+ * A `PUT` that changes nothing answers the view unchanged.
651
+ */
652
+ export const PutEnvironmentRequestSchema = z
610
653
  .object({
611
654
  requestId: RequestIdSchema.optional(),
612
- /** Default `virtual`. `pod` needs sandbox pods (`nylorun sandbox enable`). */
613
- kind: z.enum(SANDBOX_KINDS).optional(),
614
- labels: SandboxLabelsSchema.optional(),
655
+ /** Default `virtual`. `pod` needs sandbox pods (`nylorun sandbox enable`). Fixed. */
656
+ kind: z.enum(ENVIRONMENT_KINDS).optional(),
657
+ labels: EnvironmentLabelsSchema.optional(),
615
658
  /** Pods only: the workload image (default the Tenant's, else `python:3.13-slim`). */
616
659
  image: z.string().min(1).optional(),
617
- /** Hosts the sandbox may reach; pods also take `*.suffix` patterns. */
618
- network: z.object({ allow: z.array(sandboxHostSchema).optional() }).strict().optional(),
619
- resources: sandboxResourcesSchema.optional(),
620
- /** Pods only: the volume's size (default 5GiB), fixed once created. */
660
+ resources: resourcesSchema.optional(),
661
+ /** Pods only: the volume's size (default 5GiB). Fixed. */
621
662
  storage: z
622
663
  .string()
623
664
  .refine((value) => parseSandboxSize(value) !== undefined, {
624
665
  message: "storage must be a size such as 5GiB",
625
666
  })
626
667
  .optional(),
627
- /** Pods only. */
628
- lifecycle: z
668
+ /** Hosts the sandbox may reach; pods also take `*.suffix` patterns. */
669
+ network: z
670
+ .object({ allowedHosts: z.array(hostPatternSchema).optional() })
671
+ .strict()
672
+ .optional(),
673
+ /**
674
+ * The harness that runs the Environment's sessions (track R4): `nylorun` (ours, the default)
675
+ * or the id of a custom harness. A pod Environment whose harness is not ours runs its
676
+ * `image` as the harness: the image's own entrypoint, with nothing copied in. Each session
677
+ * pins the harness when it opens; a session whose Environment's harness changed later fails
678
+ * its next turn with `harness_mismatch`.
679
+ */
680
+ harness: HarnessIdSchema.optional(),
681
+ /**
682
+ * The owner guard: when set, only sessions of this owner may name the Environment (checked
683
+ * when a session opens and at every turn start). `null` clears it.
684
+ */
685
+ ownerUserId: z.string().min(1).nullable().optional(),
686
+ lifecycle: EnvironmentLifecycleSchema.optional(),
687
+ /**
688
+ * Pods only (Host feature `environment-setup`): commands run when the disk is made or reset,
689
+ * before any turn. A change applies at the next reset.
690
+ */
691
+ setup: z.array(EnvironmentSetupCommandSchema).max(ENVIRONMENT_SETUP_MAX).optional(),
692
+ /** Pods only: artifact versions copied in when the disk is made or reset, before `setup`. */
693
+ files: z.array(EnvironmentFileSchema).max(ENVIRONMENT_SETUP_MAX).optional(),
694
+ /**
695
+ * Only when the `PUT` creates the Environment (Host feature `environment-disk-versions`): its
696
+ * disk starts from this version of another Environment's disk. Its vault starts empty.
697
+ */
698
+ from: z
629
699
  .object({
630
- /** How long after its creation the sandbox expires; within the Tenant's `limits.ttl`. */
631
- ttl: sandboxDurationSchema("lifecycle.ttl").optional(),
700
+ environment: EnvironmentIdSchema,
701
+ version: z.union([z.number().int().positive(), z.literal("latest")]),
632
702
  })
633
703
  .strict()
634
704
  .optional(),
635
705
  })
636
706
  .strict();
637
- /** A session attached to a sandbox, as the sandbox's view lists it. */
638
- export const SandboxSessionSchema = z
707
+ /** An Environment's recipe, resolved against the Tenant's limits. */
708
+ export const EnvironmentRecipeSchema = z
709
+ .object({
710
+ image: z.string().optional(),
711
+ resources: z.object({ cpus: z.number().int(), memory: z.string() }).strict().optional(),
712
+ storage: z.string().optional(),
713
+ network: z.object({ allowedHosts: z.array(z.string()) }).strict().optional(),
714
+ harness: z.string(),
715
+ lifecycle: EnvironmentLifecycleSchema,
716
+ setup: z.array(EnvironmentSetupCommandSchema).optional(),
717
+ files: z.array(EnvironmentFileSchema).optional(),
718
+ })
719
+ .strict();
720
+ /** A session that names an Environment, as the Environment's view lists it. */
721
+ export const EnvironmentSessionSchema = z
639
722
  .object({ id: z.string(), activeTurnId: z.string().nullable() })
640
723
  .strict();
641
- /** What the Runtime wants of a pod sandbox (`desired`) and what it last saw (`observed`). */
642
- export const SANDBOX_POD_DESIRED = ["running", "suspended", "deleted"];
643
- export const SANDBOX_POD_OBSERVED = [
724
+ /** What the Runtime wants of a pod (`desired`) and what it last saw (`observed`). */
725
+ export const POD_DESIRED = ["running", "suspended", "deleted"];
726
+ export const POD_OBSERVED = [
644
727
  "creating",
645
728
  "running",
646
729
  "suspended",
647
- "expired",
648
730
  "lost",
649
731
  "failed",
650
732
  "deleting",
651
733
  ];
652
- export const SandboxPodViewSchema = z
734
+ export const EnvironmentPodViewSchema = z
653
735
  .object({
654
- desired: z.enum(SANDBOX_POD_DESIRED),
655
- observed: z.enum(SANDBOX_POD_OBSERVED),
736
+ desired: z.enum(POD_DESIRED),
737
+ observed: z.enum(POD_OBSERVED),
656
738
  /** Bumped by every reset: each generation has its own volume. */
657
739
  volumeGeneration: z.number().int().nonnegative(),
658
740
  /** Bumped each time a pod joins; a host token of an older epoch is refused. */
659
741
  hostEpoch: z.number().int().nonnegative(),
660
- /** When it expires (its TTL), if it has one. */
661
- expiresAt: z.string().optional(),
662
742
  /** Why it failed, or was lost. */
663
743
  reason: z.string().optional(),
664
744
  })
665
745
  .strict();
666
- /** `PUT` and `GET /v1/sandboxes/{sandboxId}`. */
667
- export const SandboxViewSchema = z
746
+ /**
747
+ * The compute states an Environment reports today: `ready` until a tool first runs in a virtual
748
+ * one, then `creating`, `running` or `stopped`. An open set: clients must accept values they do
749
+ * not know (a later release may add one, such as `cold`).
750
+ */
751
+ export const ENVIRONMENT_STATES = ["ready", "creating", "running", "stopped"];
752
+ /** `PUT` and `GET /v1/environments/{environmentId}`. */
753
+ export const EnvironmentViewSchema = z
668
754
  .object({
669
755
  id: z.string(),
670
- kind: z.enum(SANDBOX_KINDS),
756
+ kind: z.enum(ENVIRONMENT_KINDS),
671
757
  labels: z.record(z.string(), z.string()),
672
- /** The spec, resolved against the Tenant's limits when the sandbox was created. */
673
- spec: z.record(z.string(), z.unknown()),
758
+ /** What the app asked for, resolved against the Tenant's limits. */
759
+ recipe: EnvironmentRecipeSchema,
760
+ /** Bumped by every recipe change. */
761
+ version: z.number().int().positive(),
762
+ /** The recipe version the current pod (or virtual workspace) runs. */
763
+ appliedVersion: z.number().int().positive(),
764
+ /** The owner guard, or `null`. */
765
+ ownerUserId: z.string().nullable(),
766
+ /** See `ENVIRONMENT_STATES`: an open set. */
767
+ state: z.string().meta({ description: "ready, creating, running or stopped; an open set" }),
768
+ /** Kind `pod`: what the Runtime wants of the pod and what it last saw. */
769
+ pod: EnvironmentPodViewSchema.optional(),
770
+ /** When it was last used: a turn, a recipe change, a secret write, a stop or a reset. */
771
+ lastUsedAt: z.string(),
674
772
  /**
675
- * `ready` until a tool first runs in it, then the workspace's compute state. A virtual
676
- * sandbox has nothing to stop: `stopped` means only that its turn queue is idle.
773
+ * Its disk versions (Host feature `environment-disk-versions`): the latest, and the copy
774
+ * that holds the disk now, if one does. Absent for kind `none`.
677
775
  */
678
- state: z.enum(["ready", "creating", "running", "stopped"]),
679
- /** Kind `pod`: what the Runtime wants of the pod and what it last saw. */
680
- pod: SandboxPodViewSchema.optional(),
681
- /** Sessions attached to it (acting for a subject, only the subject's own). */
682
- sessions: z.array(SandboxSessionSchema),
776
+ disk: z
777
+ .object({
778
+ latestVersion: z.number().int().positive().nullable(),
779
+ operation: z
780
+ .object({
781
+ kind: z.enum(["snapshot", "restore", "seed"]),
782
+ version: z.number().int().positive().optional(),
783
+ startedAt: z.string(),
784
+ })
785
+ .strict()
786
+ .optional(),
787
+ })
788
+ .strict()
789
+ .optional(),
790
+ /** Sessions that name it (acting for a subject, only the subject's own). */
791
+ sessions: z.array(EnvironmentSessionSchema),
683
792
  createdAt: z.string(),
684
793
  updatedAt: z.string(),
685
794
  })
686
795
  .strict();
687
- export const ListSandboxesResponseSchema = z
688
- .object({ sandboxes: z.array(SandboxViewSchema) })
796
+ /** `POST /v1/environments/{id}/snapshot`: a new version of the Environment's disk. */
797
+ export const EnvironmentSnapshotSchema = z
798
+ .object({
799
+ environmentId: z.string(),
800
+ artifactId: z.string(),
801
+ version: z.number().int().positive(),
802
+ format: z.string(),
803
+ /** Entries in the version: files, links and empty directories. */
804
+ files: z.number().int().nonnegative(),
805
+ /** The files' bytes. */
806
+ bytes: z.number().int().nonnegative(),
807
+ /** Of those, the bytes stored now (the rest were stored already). */
808
+ storedBytes: z.number().int().nonnegative(),
809
+ durationMs: z.number().int().nonnegative(),
810
+ /** True when the disk had not changed: `version` is the latest, and nothing was stored. */
811
+ unchanged: z.boolean(),
812
+ createdAt: z.string(),
813
+ })
814
+ .strict();
815
+ /** `POST /v1/environments/{id}/restore`: which version of its disk to put back. */
816
+ export const RestoreEnvironmentRequestSchema = z
817
+ .object({
818
+ requestId: RequestIdSchema.optional(),
819
+ version: z.union([z.number().int().positive(), z.literal("latest")]),
820
+ })
821
+ .strict();
822
+ export const EnvironmentRestoreSchema = z
823
+ .object({
824
+ environmentId: z.string(),
825
+ restored: z.number().int().positive(),
826
+ /**
827
+ * `done` once the version is back (a virtual Environment); `pending` while a pod's new volume
828
+ * is seeded (`disk.operation` in the view until it ends; turns wait for it).
829
+ */
830
+ status: z.enum(["done", "pending"]),
831
+ volumeGeneration: z.number().int().nonnegative().optional(),
832
+ })
833
+ .strict();
834
+ /** `GET /v1/environments/{id}/versions`: its disk versions, newest first. */
835
+ export const EnvironmentVersionsSchema = z
836
+ .object({
837
+ environmentId: z.string(),
838
+ /** The folder artifact that holds them (read trees, files and diffs through `/v1/artifacts`). */
839
+ artifactId: z.string().nullable(),
840
+ latest: z.number().int().positive().nullable(),
841
+ versions: z.array(z
842
+ .object({
843
+ version: z.number().int().positive(),
844
+ bytes: z.number().int().nonnegative(),
845
+ createdAt: z.string(),
846
+ })
847
+ .strict()),
848
+ })
689
849
  .strict();
690
- export const DeleteSandboxResponseSchema = z
850
+ export const ListEnvironmentsResponseSchema = z
851
+ .object({ environments: z.array(EnvironmentViewSchema) })
852
+ .strict();
853
+ export const DeleteEnvironmentResponseSchema = z
691
854
  .object({ id: z.string(), deleted: z.boolean() })
692
855
  .strict();
693
- /** The schema id of a sandbox's lifecycle events (its stream in the record). */
694
- export const SANDBOX_EVENT_SCHEMA = "nylorun.sandbox-event/1";
695
- export const SANDBOX_EVENT_TYPES = [
696
- "sandbox.created",
697
- "sandbox.attached",
698
- "sandbox.detached",
699
- "sandbox.deleted",
856
+ /**
857
+ * One connection a pod Environment opened through egress-gate (track R7, Q6): written when it
858
+ * closes, or at once when the gate refused it. The session log of the turn holding the
859
+ * Environment when it opened gets it as `egress.connection`; with no turn holding it, the
860
+ * Environment's own stream gets it as `environment.egress` (Q7).
861
+ *
862
+ * `startedAt` is the gate's clock at CONNECT and `durationMs` runs from there to the close, so
863
+ * the span is the gate's own measurement. `bytesUp` is what the sandbox sent, `bytesDown` what it
864
+ * got. `mode: "credential"` is a host an `environment_secret` is bound to (R2c): the gate read
865
+ * each request (`requests`) and set a credential on it (`credentialIds`, ids only). It never
866
+ * carries a header value, a URL path or a body.
867
+ */
868
+ export const EgressConnectionPayloadSchema = z
869
+ .object({
870
+ environmentId: z.string(),
871
+ host: z.string(),
872
+ port: z.number().int(),
873
+ outcome: z.enum(["allowed", "refused"]),
874
+ /** Why the gate refused it, as in its `egress_refused` log line (`host_not_allowed`, …). */
875
+ reason: z.string().optional(),
876
+ /** The HTTP status a refusal answered the CONNECT with. */
877
+ status: z.number().int().optional(),
878
+ mode: z.enum(["tunnel", "credential"]),
879
+ credentialBound: z.boolean(),
880
+ credentialIds: z.array(z.string()).optional(),
881
+ requests: z.number().int().nonnegative().optional(),
882
+ bytesUp: z.number().int().nonnegative(),
883
+ bytesDown: z.number().int().nonnegative(),
884
+ durationMs: z.number().nonnegative(),
885
+ startedAt: z.string(),
886
+ })
887
+ .passthrough();
888
+ /** The schema id of an Environment's lifecycle events (its stream in the record). */
889
+ export const ENVIRONMENT_EVENT_SCHEMA = "nylorun.environment-event/1";
890
+ export const ENVIRONMENT_EVENT_TYPES = [
891
+ "environment.created",
892
+ "environment.attached",
893
+ "environment.detached",
894
+ "environment.deleted",
700
895
  // Kind `pod` (Host feature `sandbox-pods`).
701
- "sandbox.running",
702
- "sandbox.suspended",
703
- "sandbox.expired",
704
- "sandbox.relaunched",
705
- "sandbox.lost",
706
- "sandbox.reset",
707
- "sandbox.failed",
896
+ "environment.running",
897
+ "environment.suspended",
898
+ "environment.relaunched",
899
+ "environment.lost",
900
+ "environment.reset",
901
+ "environment.failed",
902
+ // egress-gate, while no turn holds the Environment (R7, Q7).
903
+ "environment.egress",
708
904
  ];
709
- /** The payload of each sandbox lifecycle event. */
710
- export const SANDBOX_EVENT_PAYLOADS = {
711
- "sandbox.created": z
712
- .object({ kind: z.enum(SANDBOX_KINDS), labels: z.record(z.string(), z.string()) })
905
+ /** The payload of each Environment lifecycle event. */
906
+ export const ENVIRONMENT_EVENT_PAYLOADS = {
907
+ "environment.created": z
908
+ .object({ kind: z.enum(ENVIRONMENT_KINDS), labels: z.record(z.string(), z.string()) })
713
909
  .passthrough(),
714
- "sandbox.attached": z.object({ sessionId: z.string() }).passthrough(),
715
- "sandbox.detached": z
910
+ "environment.attached": z.object({ sessionId: z.string() }).passthrough(),
911
+ "environment.detached": z
716
912
  .object({ sessionId: z.string(), reason: z.enum(["reset"]) })
717
913
  .passthrough(),
718
- "sandbox.deleted": z.object({}).passthrough(),
719
- /** A pod joined and serves the sandbox. */
720
- "sandbox.running": z.object({ hostEpoch: z.number().int() }).passthrough(),
914
+ /** Deleted by a `DELETE`, or by the sweep once `lifecycle.deleteAfter` passed (`reason`). */
915
+ "environment.deleted": z
916
+ .object({ reason: z.enum(["delete", "deleteAfter"]).optional() })
917
+ .passthrough(),
918
+ /** A pod joined and serves the Environment. */
919
+ "environment.running": z.object({ hostEpoch: z.number().int() }).passthrough(),
721
920
  /** Stopped (`POST .../stop`, or idle): the volume is kept; the next turn starts it again. */
722
- "sandbox.suspended": z.object({ reason: z.enum(["stop", "idle"]) }).passthrough(),
723
- /** Its TTL passed: turns are refused until a `PUT` sets a longer TTL. */
724
- "sandbox.expired": z.object({ onExpiry: z.enum(["retain", "delete"]) }).passthrough(),
921
+ "environment.suspended": z.object({ reason: z.enum(["stop", "idle"]) }).passthrough(),
725
922
  /** Its pod was replaced (same volume): the old pod's host token no longer works. */
726
- "sandbox.relaunched": z.object({ hostEpoch: z.number().int() }).passthrough(),
923
+ "environment.relaunched": z.object({ hostEpoch: z.number().int() }).passthrough(),
727
924
  /** Its volume or node is gone: turns are refused until a reset. */
728
- "sandbox.lost": z.object({ reason: z.string() }).passthrough(),
925
+ "environment.lost": z.object({ reason: z.string() }).passthrough(),
729
926
  /** Reset: a new pod on a new, empty volume. */
730
- "sandbox.reset": z.object({ volumeGeneration: z.number().int() }).passthrough(),
927
+ "environment.reset": z.object({ volumeGeneration: z.number().int() }).passthrough(),
731
928
  /** The pod did not become ready. */
732
- "sandbox.failed": z.object({ reason: z.string() }).passthrough(),
929
+ "environment.failed": z.object({ reason: z.string() }).passthrough(),
930
+ /** A connection through egress-gate while no turn held the Environment (`egress.connection`'s payload). */
931
+ "environment.egress": EgressConnectionPayloadSchema,
733
932
  };
734
- /** One lifecycle event on a sandbox's stream, numbered from 0. */
735
- export const SandboxEventSchema = z
933
+ /** One lifecycle event on an Environment's stream, numbered from 0. */
934
+ export const EnvironmentEventSchema = z
736
935
  .object({
737
- schema: z.literal(SANDBOX_EVENT_SCHEMA),
936
+ schema: z.literal(ENVIRONMENT_EVENT_SCHEMA),
738
937
  eventId: z.string(),
739
938
  tenantId: z.string(),
740
- sandboxId: z.string(),
939
+ environmentId: z.string(),
741
940
  seq: z.number().int().nonnegative(),
742
941
  time: z.string(),
743
- type: z.enum(SANDBOX_EVENT_TYPES),
942
+ type: z.enum(ENVIRONMENT_EVENT_TYPES),
744
943
  payload: z.record(z.string(), z.unknown()),
745
944
  })
746
945
  .strict();
747
- export const ListSandboxEventsResponseSchema = z
748
- .object({ events: z.array(SandboxEventSchema) })
946
+ export const ListEnvironmentEventsResponseSchema = z
947
+ .object({ events: z.array(EnvironmentEventSchema) })
749
948
  .strict();
750
- /**
751
- * `PutSessionRequest.sandbox`: `false` for none, `{ id }` to attach a sandbox resource (Host
752
- * feature `sandboxes`), `{ session }` to share another session's sandbox, or an inline sandbox.
753
- * Omitted means the Tenant's default.
754
- */
755
- export const SandboxRequestSchema = z.union([
756
- z.literal(false),
757
- z.object({ id: SandboxIdSchema }).strict(),
758
- z.object({ session: z.string().min(1) }).strict(),
759
- SandboxInlineRequestSchema,
760
- ]);
761
949
  export const PutSessionRequestSchema = z
762
950
  .object({
763
951
  requestId: RequestIdSchema,
764
952
  agentId: z.string().min(1),
765
953
  ownerUserId: z.string().min(1),
766
954
  info: jsonObject.optional(),
767
- vaultIds: z.array(z.string().min(1)).optional(),
768
- credentialSelections: z.array(CredentialSelectionSchema).optional(),
769
- /** The session's sandbox; see `SandboxRequestSchema`. Fixed once the session exists. */
770
- sandbox: SandboxRequestSchema.optional(),
955
+ /**
956
+ * The Environment the session runs in: its sandbox, and its vault's credentials for the
957
+ * session's shell, MCP servers and HTTP tools. Omitted: no sandbox and no credentials.
958
+ * Fixed once the session exists.
959
+ */
960
+ environment: EnvironmentIdSchema.optional(),
771
961
  })
772
962
  .strict();
773
963
  /** The hosts a harness can run on (blueprint D38). */
774
- export const SANDBOX_PLACEMENT_HOSTS = ["harness-container", "sandbox"];
964
+ export const PLACEMENT_HOSTS = ["harness-container", "sandbox"];
775
965
  /**
776
- * A Tenant's sandbox configuration (Tenant setting `sandbox.config`): what a session gets when
777
- * it names no sandbox, and the limits every session's sandbox must fit.
966
+ * A Tenant's Environment settings (Tenant setting `environments.config`): the limits every
967
+ * Environment's recipe must fit, the pods' stop grace, and where harnesses may run.
778
968
  */
779
- export const TenantSandboxConfigSchema = z
969
+ export const TenantEnvironmentsConfigSchema = z
780
970
  .object({
781
- /** `none` (the default when unset), `virtual`, or an inline sandbox. */
782
- default: z
783
- .union([z.literal("none"), z.literal("virtual"), SandboxInlineRequestSchema])
784
- .optional(),
785
971
  limits: z
786
972
  .object({
787
- /** Hosts a sandbox may allow. Default: package registries and code hosts. */
788
- network: z.array(sandboxHostSchema).optional(),
789
- /** The most a session may ask for. */
790
- resources: sandboxResourcesSchema.optional(),
791
- /** What a session gets when it asks for nothing. */
792
- defaultResources: sandboxResourcesSchema.optional(),
793
- /** Stop compute after this long without use. */
794
- idle: z
795
- .string()
796
- .refine((value) => parseSandboxDuration(value) !== undefined, {
797
- message: "idle must be a duration such as 30s, 15m or 1h",
798
- })
799
- .optional(),
800
- /** The most sandbox resources (`PUT /v1/sandboxes/{id}`) the Tenant may hold. Default 100. */
801
- sandboxes: z.number().int().min(0).max(100_000).optional(),
802
- /** Pods: the longest `lifecycle.ttl` a sandbox may ask for. Default none (no limit). */
803
- ttl: sandboxDurationSchema("limits.ttl").optional(),
973
+ /** Hosts an Environment may allow. Default: package registries and code hosts. */
974
+ network: z.array(hostPatternSchema).optional(),
975
+ /** The most an Environment may ask for. */
976
+ resources: resourcesSchema.optional(),
977
+ /** What an Environment gets when it asks for nothing. */
978
+ defaultResources: resourcesSchema.optional(),
979
+ /** Stop compute after this long without use; an Environment's `lifecycle.idle` is at most this. */
980
+ idle: durationSchema("limits.idle").optional(),
981
+ /** The most Environments the Tenant may hold. Default 100. */
982
+ environments: z.number().int().min(0).max(100_000).optional(),
804
983
  })
805
984
  .strict()
806
985
  .optional(),
807
- /** Pods: what happens at expiry and how long a pod has to stop. Read at every timer. */
986
+ /** Pods: how long a pod has to stop. Read at every timer. */
808
987
  lifecycle: z
809
988
  .object({
810
- /** `retain` (default) keeps the volume after the TTL; `delete` deletes the sandbox. */
811
- onExpiry: z.enum(["retain", "delete"]).optional(),
812
989
  /** The pod's grace period to stop, at most 30s. Default 10s. */
813
- stopGrace: sandboxDurationSchema("lifecycle.stopGrace")
990
+ stopGrace: durationSchema("lifecycle.stopGrace")
814
991
  .refine((value) => (parseSandboxDuration(value) ?? 0) <= 30_000, {
815
992
  message: "lifecycle.stopGrace is at most 30s",
816
993
  })
@@ -820,50 +997,24 @@ export const TenantSandboxConfigSchema = z
820
997
  .optional(),
821
998
  /**
822
999
  * Where each harness may run (blueprint D38), by harness id (`nylorun`, or `*` for the rest):
823
- * `harness-container` (the Runtime's harness) and `sandbox` (the engine in a pod sandbox).
1000
+ * `harness-container` (the Runtime's harness) and `sandbox` (the engine in a pod).
824
1001
  * Default `{ "*": { hosts: ["harness-container", "sandbox"] } }`. Checked when a session
825
- * opens; a host left out is refused (`placement_refused`).
1002
+ * opens; a host left out is refused (`placement_refused`). `"*": { hosts: [] }` refuses every
1003
+ * harness the map does not name.
826
1004
  */
827
1005
  placement: z
828
- .record(z.string().min(1), z.object({ hosts: z.array(z.enum(SANDBOX_PLACEMENT_HOSTS)).min(1) }).strict())
1006
+ .record(z.string().min(1), z.object({ hosts: z.array(z.enum(PLACEMENT_HOSTS)) }).strict())
829
1007
  .optional(),
830
1008
  })
831
1009
  .strict();
832
- /** `PUT /v1/tenant/sandbox`: replaces the Tenant's sandbox configuration. */
833
- export const PutTenantSandboxRequestSchema = TenantSandboxConfigSchema.extend({
1010
+ /** `PUT /v1/tenant/sandbox`: replaces the Tenant's Environment settings (`environments.config`). */
1011
+ export const PutTenantEnvironmentsRequestSchema = TenantEnvironmentsConfigSchema.extend({
834
1012
  requestId: RequestIdSchema.optional(),
835
1013
  }).strict();
836
1014
  const vaultWriteBase = {
837
1015
  requestId: RequestIdSchema,
838
1016
  idempotencyKey: IdempotencyKeySchema,
839
1017
  };
840
- /** The owner of every installation vault (`scope: "installation"`); a reserved subject. */
841
- export const INSTALLATION_OWNER = "installation";
842
- export const CreateVaultRequestSchema = z
843
- .object({
844
- ...vaultWriteBase,
845
- name: z.string().min(1),
846
- /**
847
- * `user` (the default): one person's vault, owned by `ownerUserId`. `installation`: the
848
- * installation's own vault, owned by `installation`, which any session may attach;
849
- * management keys only (the Management API).
850
- */
851
- scope: z.enum(["user", "installation"]).optional(),
852
- /** Required for a `user` vault; absent (or `installation`) for an installation vault. */
853
- ownerUserId: z.string().min(1).optional(),
854
- metadata: z.record(z.string(), z.string()).optional(),
855
- })
856
- .strict()
857
- .superRefine((value, ctx) => {
858
- if ((value.scope ?? "user") === "user") {
859
- if (value.ownerUserId === undefined)
860
- ctx.addIssue({ code: "custom", path: ["ownerUserId"], message: "ownerUserId is required for a user vault" });
861
- else if (value.ownerUserId === INSTALLATION_OWNER)
862
- ctx.addIssue({ code: "custom", path: ["ownerUserId"], message: "installation is reserved for installation vaults" });
863
- }
864
- else if (value.ownerUserId !== undefined && value.ownerUserId !== INSTALLATION_OWNER)
865
- ctx.addIssue({ code: "custom", path: ["ownerUserId"], message: "An installation vault is owned by installation" });
866
- });
867
1018
  /** An RFC 9110 field name. */
868
1019
  export const HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
869
1020
  const CredentialHeaderNameSchema = z
@@ -922,59 +1073,146 @@ const credentialRoutingChange = {
922
1073
  identity: CredentialIdentitySchema.nullable().optional(),
923
1074
  };
924
1075
  /**
925
- * A credential for the server at `url` (the URL a manifest names): `bearer` sends
926
- * `Authorization: Bearer <token>`, `headers` its header map (R2b C2). The header names may not be
927
- * the MCP transport's headers or `Nylorun-*`.
1076
+ * An environment variable name a shell secret or plain variable may take (R2c, D50): a POSIX
1077
+ * name. Names the sandbox needs for itself (the proxy, the trust store, `PATH`, `HOME`) and
1078
+ * `NYLORUN_*` are reserved.
928
1079
  */
929
- export const CreateCredentialRequestSchema = z
930
- .object({
931
- ...vaultWriteBase,
932
- name: z.string().min(1),
933
- auth: z.discriminatedUnion("type", [
934
- z
935
- .object({
936
- type: z.literal("bearer"),
937
- url: z.string().min(1),
938
- token: z.string().min(1),
939
- ...credentialRouting,
940
- })
941
- .strict(),
942
- z
943
- .object({
944
- type: z.literal("headers"),
945
- url: z.string().min(1),
946
- headers: CredentialHeadersSchema,
947
- ...credentialRouting,
948
- })
949
- .strict(),
950
- ]),
951
- })
952
- .strict();
1080
+ export const ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1081
+ export const RESERVED_ENVIRONMENT_NAMES = new Set([
1082
+ "PATH",
1083
+ "HOME",
1084
+ "PWD",
1085
+ "SHELL",
1086
+ "USER",
1087
+ "HTTPS_PROXY",
1088
+ "HTTP_PROXY",
1089
+ "NO_PROXY",
1090
+ "ALL_PROXY",
1091
+ "SSL_CERT_FILE",
1092
+ "SSL_CERT_DIR",
1093
+ "NODE_EXTRA_CA_CERTS",
1094
+ "REQUESTS_CA_BUNDLE",
1095
+ "CURL_CA_BUNDLE",
1096
+ "GIT_SSL_CAINFO",
1097
+ "AWS_CA_BUNDLE",
1098
+ ]);
1099
+ export function isReservedEnvironmentName(name) {
1100
+ const upper = name.toUpperCase();
1101
+ return RESERVED_ENVIRONMENT_NAMES.has(upper) || upper.startsWith("NYLORUN_");
1102
+ }
1103
+ const EnvironmentNameSchema = z
1104
+ .string()
1105
+ .regex(ENVIRONMENT_NAME_PATTERN, "An environment variable name is a letter or _ followed by letters, digits or _")
1106
+ .refine((name) => !isReservedEnvironmentName(name), "That environment variable name is reserved");
1107
+ /** The value a sandbox sees for every `environment_secret` (R2c, D50): never the secret. */
1108
+ export const ENVIRONMENT_SECRET_SENTINEL = "nylorun-managed";
953
1109
  /**
954
- * Replaces a credential's secret; its type and URL stay. `via` and `identity` are kept unless
955
- * given (`null` removes one).
1110
+ * How egress-gate writes an `environment_secret` into a request (R2c, D50): one header, set on
1111
+ * every request to a bound host. `format` is text with `{value}` once, optionally inside a
1112
+ * `{base64:…}` group, for example `Bearer {value}` (the default),
1113
+ * `Basic {base64:x-access-token:{value}}` or `{value}`.
956
1114
  */
957
- export const RotateCredentialRequestSchema = z
1115
+ export const ENVIRONMENT_SECRET_DEFAULT_INJECT = { header: "Authorization", format: "Bearer {value}" };
1116
+ const BASE64_GROUP = /\{base64:((?:[^{}]|\{value\})*)\}/g;
1117
+ export function isInjectFormat(format) {
1118
+ if (/[\r\n\0]/.test(format))
1119
+ return false;
1120
+ const values = format.match(/\{value\}/g)?.length ?? 0;
1121
+ const rest = format.replace(BASE64_GROUP, (_, inner) => inner.replace(/\{value\}/g, "")).replace(/\{value\}/g, "");
1122
+ return values === 1 && !/[{}]/.test(rest);
1123
+ }
1124
+ /** `format` with `{value}` replaced, and each `{base64:…}` group encoded. */
1125
+ export function renderInjectFormat(format, value) {
1126
+ return format
1127
+ .replace(BASE64_GROUP, (_, inner) => base64Utf8(inner.replace(/\{value\}/g, () => value)))
1128
+ .replace(/\{value\}/g, () => value);
1129
+ }
1130
+ function base64Utf8(text) {
1131
+ let binary = "";
1132
+ for (const byte of new TextEncoder().encode(text))
1133
+ binary += String.fromCharCode(byte);
1134
+ return btoa(binary);
1135
+ }
1136
+ export const EnvironmentSecretInjectSchema = z
958
1137
  .object({
959
- ...vaultWriteBase,
960
- auth: z.discriminatedUnion("type", [
961
- z
962
- .object({
963
- type: z.literal("bearer"),
964
- token: z.string().min(1),
965
- ...credentialRoutingChange,
966
- })
967
- .strict(),
968
- z
969
- .object({
970
- type: z.literal("headers"),
971
- headers: CredentialHeadersSchema,
972
- ...credentialRoutingChange,
973
- })
974
- .strict(),
975
- ]),
1138
+ header: CredentialHeaderNameSchema,
1139
+ format: z.string().min(1).refine(isInjectFormat, "format has {value} exactly once, optionally inside one {base64:…} group"),
976
1140
  })
977
1141
  .strict();
1142
+ /** Exact host names an `environment_secret` may be sent to: no wildcards, no IP literals. */
1143
+ const AllowedHostsSchema = z
1144
+ .array(z
1145
+ .string()
1146
+ .toLowerCase()
1147
+ .refine((host) => /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(host) && !/^\d+(\.\d+){3}$/.test(host), "allowedHosts takes exact host names such as api.github.com: no wildcard, port or IP address"))
1148
+ .min(1)
1149
+ .max(32)
1150
+ .refine((hosts) => new Set(hosts).size === hosts.length, "allowedHosts lists each host once");
1151
+ const EnvironmentValueSchema = z
1152
+ .string()
1153
+ .min(1)
1154
+ .max(8192)
1155
+ .refine((value) => !/[\r\n\0]/.test(value), "A value has no CR, LF or NUL");
1156
+ /** The name of a credential for a tool (`bearer` or `headers`): a label of 1–64 characters. */
1157
+ export const TOOL_SECRET_NAME_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
1158
+ /**
1159
+ * `PUT /v1/environments/{environmentId}/secrets/{name}` (D56): creates or replaces one credential
1160
+ * in the Environment's vault. For `environment_secret` and `environment_variable` the name is
1161
+ * the variable's name (a POSIX name, not reserved); for `bearer` and `headers` it is a label.
1162
+ * The same name and type keeps the credential and re-seals its value and binding; another type
1163
+ * replaces it. Values are write-only: no route reads them back. Two `environment_secret`
1164
+ * credentials bound to one host, or two `bearer`/`headers` credentials for one URL, are
1165
+ * `409 credential_conflict`.
1166
+ */
1167
+ export const PutEnvironmentSecretRequestSchema = z.discriminatedUnion("type", [
1168
+ z
1169
+ .object({
1170
+ requestId: RequestIdSchema.optional(),
1171
+ type: z.literal("environment_secret"),
1172
+ value: EnvironmentValueSchema,
1173
+ allowedHosts: AllowedHostsSchema,
1174
+ inject: EnvironmentSecretInjectSchema.optional(),
1175
+ })
1176
+ .strict(),
1177
+ z
1178
+ .object({
1179
+ requestId: RequestIdSchema.optional(),
1180
+ type: z.literal("environment_variable"),
1181
+ value: EnvironmentValueSchema,
1182
+ })
1183
+ .strict(),
1184
+ z
1185
+ .object({
1186
+ requestId: RequestIdSchema.optional(),
1187
+ type: z.literal("bearer"),
1188
+ url: z.string().min(1),
1189
+ value: z.string().min(1),
1190
+ ...credentialRouting,
1191
+ })
1192
+ .strict(),
1193
+ z
1194
+ .object({
1195
+ requestId: RequestIdSchema.optional(),
1196
+ type: z.literal("headers"),
1197
+ url: z.string().min(1),
1198
+ headers: CredentialHeadersSchema,
1199
+ ...credentialRouting,
1200
+ })
1201
+ .strict(),
1202
+ ]);
1203
+ /** Whether `name` may name a secret of `type` (`PUT .../secrets/{name}`); a message when not. */
1204
+ export function environmentSecretNameError(type, name) {
1205
+ if (type === "environment_secret" || type === "environment_variable") {
1206
+ if (!ENVIRONMENT_NAME_PATTERN.test(name))
1207
+ return "An environment variable name is a letter or _ followed by letters, digits or _";
1208
+ if (isReservedEnvironmentName(name))
1209
+ return `${name} is a reserved environment variable name`;
1210
+ return undefined;
1211
+ }
1212
+ return TOOL_SECRET_NAME_PATTERN.test(name)
1213
+ ? undefined
1214
+ : "A credential name is 1-64 letters, digits, '.', '_' and '-'";
1215
+ }
978
1216
  /**
979
1217
  * What the Runtime cannot learn from a custom OpenAI-compatible endpoint (Model Calls §7):
980
1218
  * its context window and output limit, whether it reasons, and pi-ai `compat` settings
@@ -1022,22 +1260,27 @@ export const SelectHostModelRequestSchema = z
1022
1260
  baseUrl: z.string().min(1).optional(),
1023
1261
  })
1024
1262
  .strict();
1025
- export const VaultInfoSchema = z
1026
- .object({
1027
- id: z.string(),
1028
- name: z.string(),
1029
- ownerUserId: z.string(),
1030
- metadata: z.record(z.string(), z.string()).optional(),
1031
- createdAt: z.string(),
1032
- })
1033
- .strict();
1034
- export const CredentialInfoSchema = z
1263
+ export const ENVIRONMENT_SECRET_TYPES = [
1264
+ "bearer",
1265
+ "headers",
1266
+ "environment_secret",
1267
+ "environment_variable",
1268
+ ];
1269
+ /**
1270
+ * One credential of an Environment's vault, never its value: what it is bound to (the server
1271
+ * `url` for `bearer` and `headers`; the hosts and header for `environment_secret`).
1272
+ */
1273
+ export const EnvironmentSecretViewSchema = z
1035
1274
  .object({
1036
- id: z.string(),
1037
- vaultId: z.string(),
1038
1275
  name: z.string(),
1039
- type: z.enum(["bearer", "headers"]),
1040
- binding: z.object({ url: z.string() }).strict(),
1276
+ type: z.enum(ENVIRONMENT_SECRET_TYPES),
1277
+ binding: z
1278
+ .object({
1279
+ url: z.string().optional(),
1280
+ allowedHosts: z.array(z.string()).optional(),
1281
+ inject: EnvironmentSecretInjectSchema.optional(),
1282
+ })
1283
+ .strict(),
1041
1284
  /** A `headers` credential's header names (lower case), never their values. */
1042
1285
  headerNames: z.array(z.string()).optional(),
1043
1286
  via: z.string().optional(),
@@ -1046,13 +1289,15 @@ export const CredentialInfoSchema = z
1046
1289
  rotatedAt: z.string().optional(),
1047
1290
  })
1048
1291
  .strict();
1292
+ export const ListEnvironmentSecretsResponseSchema = z
1293
+ .object({ secrets: z.array(EnvironmentSecretViewSchema) })
1294
+ .strict();
1049
1295
  /** The MCP transports a preview speaks: a manifest's remote server types. */
1050
1296
  export const MCP_PREVIEW_TYPES = ["streamable-http", "sse"];
1051
1297
  /**
1052
1298
  * `POST /v1/tenant/mcp/preview` (R2b C12): what a remote MCP server offers, before an agent
1053
- * names it. The Runtime connects with the installation vault's credential for `url` (one
1054
- * credential across the installation vaults, or the one in `vaultId`), lists the tools and
1055
- * closes the connection; it never calls a tool.
1299
+ * names it. The Runtime connects with the credential for `url` in the vault of `environmentId`
1300
+ * (none without one), lists the tools and closes the connection; it never calls a tool.
1056
1301
  */
1057
1302
  export const McpPreviewRequestSchema = z
1058
1303
  .object({
@@ -1079,8 +1324,8 @@ export const McpPreviewRequestSchema = z
1079
1324
  * host's name before its top-level domain (`linear` for `mcp.linear.app`).
1080
1325
  */
1081
1326
  name: modelFacingName("MCP server").optional(),
1082
- /** The installation vault whose credential to send. Default: every installation vault. */
1083
- vaultId: z.string().min(1).optional(),
1327
+ /** The Environment whose vault's credential for `url` to send. Default: none is sent. */
1328
+ environmentId: EnvironmentIdSchema.optional(),
1084
1329
  })
1085
1330
  .strict();
1086
1331
  /** One tool a preview found. */
@@ -1103,7 +1348,7 @@ export const McpPreviewToolSchema = z
1103
1348
  /**
1104
1349
  * A preview (R2b C12). A server that answered `401` is `authRequired`, with its RFC 9728
1105
1350
  * protected-resource metadata when it publishes any: it needs a person's sign-in or a key the
1106
- * installation vaults do not hold, so reach it with a key or through a gateway (`via`).
1351
+ * Environment's vault does not hold, so reach it with a key or through a gateway (`via`).
1107
1352
  */
1108
1353
  export const McpPreviewSchema = z
1109
1354
  .object({
@@ -1111,7 +1356,7 @@ export const McpPreviewSchema = z
1111
1356
  name: z.string(),
1112
1357
  url: z.string(),
1113
1358
  type: z.enum(MCP_PREVIEW_TYPES),
1114
- /** True when an installation vault's credential was sent. */
1359
+ /** True when a credential of the Environment's vault was sent. */
1115
1360
  credentialSent: z.boolean(),
1116
1361
  /** The server's `initialize` answer: its name, version and title. */
1117
1362
  serverInfo: z.record(z.string(), z.unknown()).optional(),
@@ -1131,6 +1376,70 @@ export const McpPreviewSchema = z
1131
1376
  .optional(),
1132
1377
  })
1133
1378
  .strict();
1379
+ /**
1380
+ * `POST /v1/tenant/credential-coverage`: which credential each of a saved agent's remote MCP
1381
+ * servers and HTTP tools would get in a session that names `environmentId`, decided as the
1382
+ * session's tool calls decide it (by URL). It reads no secret and calls no server.
1383
+ */
1384
+ export const CredentialCoverageRequestSchema = z
1385
+ .object({
1386
+ requestId: RequestIdSchema.optional(),
1387
+ /** A saved agent or flow agent. */
1388
+ agentId: z.string().min(1),
1389
+ /** The Environment the session would name. Default: none (every entry is `missing`). */
1390
+ environmentId: EnvironmentIdSchema.optional(),
1391
+ })
1392
+ .strict();
1393
+ /** A credential coverage names: where it is, never its value. */
1394
+ export const CoverageCredentialSchema = z
1395
+ .object({
1396
+ environmentId: z.string(),
1397
+ /** The secret's name in the Environment's vault. */
1398
+ name: z.string(),
1399
+ /** Where the credential sends the requests instead of the URL (a gateway). */
1400
+ via: z.string().optional(),
1401
+ })
1402
+ .strict();
1403
+ /**
1404
+ * What a session would send for one URL an agent declares:
1405
+ * - `covered`: the Environment's vault holds a credential for it (`credential`);
1406
+ * - `missing`: it holds none: an MCP server is called without a credential (a public server
1407
+ * needs none), an HTTP tool fails with `http.credential`.
1408
+ */
1409
+ export const COVERAGE_STATUSES = ["covered", "missing"];
1410
+ /** One remote MCP server or HTTP tool credential an agent declares. */
1411
+ export const CredentialCoverageEntrySchema = z
1412
+ .object({
1413
+ kind: z.enum(["mcp", "http"]),
1414
+ /** The agent that declares it: absent for the agent itself, else a subagent or a flow's agent. */
1415
+ agentId: z.string().optional(),
1416
+ /** A flow's HTTP stage or HTTP verifier: its stage key. */
1417
+ stage: z.string().optional(),
1418
+ /** The MCP server's name, or the HTTP tool's (or stage's) name. */
1419
+ name: z.string(),
1420
+ /** The server's name, or the HTTP tool's `credential`. */
1421
+ serverName: z.string(),
1422
+ /** The URL a credential must be bound to, as the vault compares it. */
1423
+ url: z.string(),
1424
+ /** True when the call fails without a credential (an HTTP tool's `credential`). */
1425
+ required: z.boolean(),
1426
+ status: z.enum(COVERAGE_STATUSES),
1427
+ /** The credential the session would send, when `covered`. */
1428
+ credential: CoverageCredentialSchema.optional(),
1429
+ /** What the session would do, in a sentence. */
1430
+ message: z.string(),
1431
+ })
1432
+ .strict();
1433
+ export const CredentialCoverageSchema = z
1434
+ .object({
1435
+ agentId: z.string(),
1436
+ environmentId: z.string().nullable(),
1437
+ /** True when every entry is `covered`. */
1438
+ complete: z.boolean(),
1439
+ /** One per declared MCP server and HTTP tool credential: the agent's, then its agents'. */
1440
+ entries: z.array(CredentialCoverageEntrySchema),
1441
+ })
1442
+ .strict();
1134
1443
  const commandBase = {
1135
1444
  requestId: RequestIdSchema,
1136
1445
  idempotencyKey: IdempotencyKeySchema,
@@ -1218,8 +1527,16 @@ export const SessionCommandSchema = z.union([
1218
1527
  export const SessionEventBodySchema = SessionCommandSchema;
1219
1528
  /** The envelope every session event carries (`nylorun.event/2`, Durable Streams §9.5). */
1220
1529
  export const EVENT_SCHEMA = "nylorun.event/2";
1221
- /** Who wrote an event. v1 writes `loop` (the engine) and `api` (commands and results). */
1530
+ /**
1531
+ * Who wrote an event (track R4, R4.9): the writer says so, not the event's type. `client` is a
1532
+ * command over the Runtime API (its `principal` says who sent it), `core` is core's own logic
1533
+ * (settle, sweeps, the flow host, exports, the tools core serves), `harness` is what a harness
1534
+ * reported (`source.id` is its harness id, `runId` its run), and the gates are themselves.
1535
+ * `loop` and `api` are what events written before R4 say.
1536
+ */
1222
1537
  export const EventSourceKindSchema = z.enum([
1538
+ "client",
1539
+ "core",
1223
1540
  "model-gate",
1224
1541
  "tool-gate",
1225
1542
  "egress-gate",
@@ -1235,7 +1552,12 @@ export const EventSourceKindSchema = z.enum([
1235
1552
  "human",
1236
1553
  "api",
1237
1554
  ]);
1238
- /** How far an event can be trusted, by who could forge it. v1 writes `observed` only. */
1555
+ /**
1556
+ * How far an event can be trusted, by who could forge it. `observed`: the Runtime saw it itself
1557
+ * (commands, the tools core serves, gate records, core's settle). `claimed`: a harness reported
1558
+ * it (an assistant message, a tool result it ran, its turn's end), so it is the harness's claim;
1559
+ * the Model Gate's usage row is the measured record of the same model call.
1560
+ */
1239
1561
  export const EvidenceClassSchema = z.enum([
1240
1562
  "observed",
1241
1563
  "measured",
@@ -1243,6 +1565,13 @@ export const EvidenceClassSchema = z.enum([
1243
1565
  "claimed",
1244
1566
  "asserted",
1245
1567
  ]);
1568
+ /** A command's sender (R4.9): from the request's credential, never from its body. */
1569
+ export const EventPrincipalSchema = z
1570
+ .object({
1571
+ kind: z.enum(["application", "subject", "flow-host", "core"]),
1572
+ id: z.string(),
1573
+ })
1574
+ .strict();
1246
1575
  /**
1247
1576
  * The envelope fields. Not strict: a client strips fields it does not know, so the envelope
1248
1577
  * can grow without a protocol bump.
@@ -1269,6 +1598,8 @@ const eventEnvelope = {
1269
1598
  schemaVersion: z.number().int().positive(),
1270
1599
  source: z.object({ kind: EventSourceKindSchema, id: z.string() }),
1271
1600
  evidence: EvidenceClassSchema,
1601
+ /** Who sent a command (`command.*`, a cancel's `turn.cancelled`), from its credential (R4.9). */
1602
+ principal: EventPrincipalSchema.optional(),
1272
1603
  trace: z
1273
1604
  .object({
1274
1605
  traceId: z.string(),
@@ -1323,9 +1654,49 @@ const toolIds = {
1323
1654
  /** The harness invocation of the call; interactions refer to it. */
1324
1655
  invocationId: z.string().min(1),
1325
1656
  };
1657
+ /**
1658
+ * When a gate served a call (R7.1): its own start and end, as it measured them. Absent when no
1659
+ * gate measured the call (a fixture model, a sandbox or core-served tool, a call refused before
1660
+ * it was sent).
1661
+ */
1662
+ export const GateTimesSchema = z
1663
+ .object({ startedAt: z.string(), endedAt: z.string() })
1664
+ .passthrough();
1665
+ /**
1666
+ * What the Model Gate's meter recorded for a model call (R7.1), from the usage ledger: the
1667
+ * tokens and cost the Runtime counts, beside the `usage` the harness reported. `cachedTokens`
1668
+ * and `costUsd` are absent when zero.
1669
+ */
1670
+ export const MeteredUsageSchema = z
1671
+ .object({
1672
+ inputTokens: z.number().int().nonnegative(),
1673
+ outputTokens: z.number().int().nonnegative(),
1674
+ totalTokens: z.number().int().nonnegative(),
1675
+ cachedTokens: z.number().int().nonnegative().optional(),
1676
+ costUsd: z.number().nonnegative().optional(),
1677
+ })
1678
+ .passthrough();
1679
+ /**
1680
+ * The timing of a model call's outcome (R7.1), on `message.assistant`, `model.failed` and
1681
+ * `context.compacted`. `durationMs` is the journal's window, from the intent to the outcome;
1682
+ * `gate`, `firstTokenMs` and `meteredUsage` are the meter's, absent when no gate metered the
1683
+ * call.
1684
+ */
1685
+ const modelOutcomeFacts = {
1686
+ /** The model call's effect id. */
1687
+ effectId: z.string().min(1).optional(),
1688
+ /** From the intent to the outcome, as the journal saw them. */
1689
+ durationMs: z.number().int().nonnegative().optional(),
1690
+ gate: GateTimesSchema.optional(),
1691
+ /** From the gate's start of the call to the provider's first stream event. */
1692
+ firstTokenMs: z.number().int().nonnegative().optional(),
1693
+ meteredUsage: MeteredUsageSchema.optional(),
1694
+ };
1326
1695
  /**
1327
1696
  * `message.assistant`: one completed model step. `invocationId` is the model call's.
1328
- * `model`, `finishReason` and `usage` are present when the provider reported them.
1697
+ * `model`, `finishReason` and `usage` are present when the provider reported them. A step that
1698
+ * said nothing (no text, no tool calls, as a structured answer) has `text: ""` and no tool
1699
+ * calls: it is in the log for its timing, and is never a message (`isEmptyAssistantMessage`).
1329
1700
  */
1330
1701
  export const AssistantMessagePayloadSchema = z
1331
1702
  .object({
@@ -1344,9 +1715,15 @@ export const AssistantMessagePayloadSchema = z
1344
1715
  input: z.unknown(),
1345
1716
  })
1346
1717
  .passthrough()),
1718
+ ...modelOutcomeFacts,
1347
1719
  ...eventAgent,
1348
1720
  })
1349
1721
  .passthrough();
1722
+ /** True when a `message.assistant` said nothing: no text and no tool calls (R7.1). */
1723
+ export function isEmptyAssistantMessage(payload) {
1724
+ return ((typeof payload.text !== "string" || payload.text === "") &&
1725
+ (payload.toolCalls?.length ?? 0) === 0);
1726
+ }
1350
1727
  /**
1351
1728
  * `model.failed`: a model call that failed in a known way (Model Calls §6.4). The turn
1352
1729
  * then fails with `model.<code>`, or recovers.
@@ -1357,12 +1734,14 @@ export const ModelFailedPayloadSchema = z
1357
1734
  code: z.string().min(1),
1358
1735
  message: z.string(),
1359
1736
  retryable: z.boolean(),
1737
+ ...modelOutcomeFacts,
1360
1738
  ...eventAgent,
1361
1739
  })
1362
1740
  .passthrough();
1363
1741
  /**
1364
1742
  * `context.compacted`: the engine summarized older history to fit the model's window
1365
- * (Model Calls §8). Token counts are estimates.
1743
+ * (Model Calls §8). Token counts are estimates. `partial: true`: one summary call of several,
1744
+ * in the log for its timing; only the last one (without `partial`) replaced the history.
1366
1745
  */
1367
1746
  export const ContextCompactedPayloadSchema = z
1368
1747
  .object({
@@ -1370,15 +1749,56 @@ export const ContextCompactedPayloadSchema = z
1370
1749
  trigger: z.enum(["threshold", "overflow"]),
1371
1750
  tokensBefore: z.number().int().nonnegative(),
1372
1751
  tokensAfter: z.number().int().nonnegative(),
1752
+ partial: z.literal(true).optional(),
1753
+ ...modelOutcomeFacts,
1373
1754
  ...eventAgent,
1374
1755
  })
1375
1756
  .passthrough();
1376
- /** `tool.completed`: a tool the Runtime ran (HTTP, MCP, sandbox, built-in). `error` for a tool error. */
1757
+ /** How a tool call ended (R5.1): the tool answered, the Runtime ended it, or a cancel did. */
1758
+ export const TOOL_CALL_STATUSES = ["completed", "failed", "cancelled"];
1759
+ /** Where a tool call ran (R5.1): a remote MCP server, an HTTP tool, the sandbox, or core. */
1760
+ export const TOOL_CALL_KINDS = ["mcp", "http", "sandbox", "platform"];
1761
+ /**
1762
+ * What the Tenant's tool policy did with a tool call (R5 step 2), when it did more than allow
1763
+ * it: `deny` refused it unsent; `ask` held it for a person, who approved it (`approvedBy`, when
1764
+ * known) or denied it.
1765
+ */
1766
+ export const ToolPolicyFactSchema = z
1767
+ .object({
1768
+ decision: z.enum(["ask", "deny"]),
1769
+ reason: z.string(),
1770
+ approvedBy: z.string().optional(),
1771
+ })
1772
+ .passthrough();
1773
+ /**
1774
+ * `tool.completed`: how one tool call ended, written once per call (R5.1). `status`
1775
+ * `completed`: the tool answered, with its output or the tool error it reported (`error`).
1776
+ * `failed`: the Runtime ended the call (`tool.disabled`, `tool.unavailable`, `tool.denied`, or
1777
+ * `tool.interrupted` for a call a crash interrupted, which may have run). `cancelled`: the turn
1778
+ * was cancelled while the call ran; it may have run. `attempts` above 1: the call was sent again
1779
+ * after a crash, with the same key.
1780
+ */
1377
1781
  export const ToolCompletedPayloadSchema = z
1378
1782
  .object({
1379
1783
  ...toolIds,
1784
+ /** The tool call's effect id (R7.1). */
1785
+ effectId: z.string().min(1).optional(),
1380
1786
  capabilityId: z.string().min(1),
1381
1787
  toolName: z.string().min(1),
1788
+ status: z.enum(TOOL_CALL_STATUSES).optional(),
1789
+ kind: z.enum(TOOL_CALL_KINDS).optional(),
1790
+ /** The MCP server, or the HTTP tool's capability. */
1791
+ server: z.string().min(1).optional(),
1792
+ /** How many times the call was sent: 0 when the Runtime refused it, above 1 after a crash re-sent it. */
1793
+ attempts: z.number().int().nonnegative().optional(),
1794
+ /** From the first send to the outcome; absent when the call never ran. */
1795
+ durationMs: z.number().int().nonnegative().optional(),
1796
+ /**
1797
+ * The Tool Gate's own start and end of the call's last send (R7.1): an MCP or HTTP tool
1798
+ * through the gateway. Absent for a sandbox or core-served tool.
1799
+ */
1800
+ gate: GateTimesSchema.optional(),
1801
+ policy: ToolPolicyFactSchema.optional(),
1382
1802
  output: z.unknown().optional(),
1383
1803
  error: z
1384
1804
  .object({
@@ -1389,8 +1809,6 @@ export const ToolCompletedPayloadSchema = z
1389
1809
  * whose server answered `401`.
1390
1810
  */
1391
1811
  server: z.string().optional(),
1392
- /** With `credential_rejected`: the scope of the vault whose credential was sent; absent when none was. */
1393
- vault: z.enum(["installation", "user"]).optional(),
1394
1812
  /** An MCP tool error (R2b C7): true when calling again may work, as for `mcp.unreachable`. */
1395
1813
  retryable: z.boolean().optional(),
1396
1814
  })
@@ -1407,8 +1825,29 @@ export const ToolCompletedPayloadSchema = z
1407
1825
  export const EffectUncertainPayloadSchema = z
1408
1826
  .object({ effectId: z.string().min(1), message: z.string().optional() })
1409
1827
  .passthrough();
1828
+ /**
1829
+ * How a turn that ended went (R7.1), on `turn.completed`, `turn.failed` and `turn.cancelled`:
1830
+ * `durationMs` from the turn's start to its end, waits for a person included, so the turn's span
1831
+ * holds every crossing in it; `pausedMs`, how much of that it waited paused; `totals` from the
1832
+ * usage ledger (`steps`: the model calls the gate metered). Absent on a turn
1833
+ * that started before the Runtime recorded them.
1834
+ */
1835
+ const turnEndFacts = {
1836
+ durationMs: z.number().int().nonnegative().optional(),
1837
+ pausedMs: z.number().int().nonnegative().optional(),
1838
+ /** The session's agent. */
1839
+ agentId: z.string().optional(),
1840
+ totals: z
1841
+ .object({
1842
+ steps: z.number().int().nonnegative(),
1843
+ tokens: z.number().int().nonnegative(),
1844
+ costUsd: z.number().nonnegative(),
1845
+ })
1846
+ .passthrough()
1847
+ .optional(),
1848
+ };
1410
1849
  export const TurnCompletedPayloadSchema = z
1411
- .object({ output: z.unknown() })
1850
+ .object({ output: z.unknown(), ...turnEndFacts })
1412
1851
  .passthrough();
1413
1852
  export const TurnPausedPayloadSchema = z
1414
1853
  .object({
@@ -1433,10 +1872,11 @@ export const TurnFailedPayloadSchema = z
1433
1872
  .passthrough()
1434
1873
  .optional(),
1435
1874
  message: z.string().optional(),
1875
+ ...turnEndFacts,
1436
1876
  })
1437
1877
  .passthrough();
1438
1878
  export const TurnCancelledPayloadSchema = z
1439
- .object({ reason: z.string().optional() })
1879
+ .object({ reason: z.string().optional(), ...turnEndFacts })
1440
1880
  .passthrough();
1441
1881
  /** Lifecycle of an agent used as a tool. `agent.delegationId` is the parent call's invocation. */
1442
1882
  export const DelegationPayloadSchema = z
@@ -1470,6 +1910,14 @@ export const CommandMessagePayloadSchema = z
1470
1910
  parts: z.array(MessagePartSchema).optional(),
1471
1911
  /** The turn manifest the message carried, if any. */
1472
1912
  manifest: z.unknown().optional(),
1913
+ /**
1914
+ * The W3C trace context the message was sent with (R7.4): the turn's trace is the caller's,
1915
+ * and its root span the child of the caller's span.
1916
+ */
1917
+ trace: z
1918
+ .object({ traceparent: z.string(), tracestate: z.string().optional() })
1919
+ .passthrough()
1920
+ .optional(),
1473
1921
  })
1474
1922
  .passthrough();
1475
1923
  /** `command.approve`: an answer to an approval interaction. */
@@ -1490,8 +1938,8 @@ export const CommandRespondPayloadSchema = z
1490
1938
  value: z.unknown(),
1491
1939
  })
1492
1940
  .passthrough();
1493
- /** `sandbox.state`: the session's sandbox changed state. */
1494
- export const SandboxStatePayloadSchema = z
1941
+ /** `environment.state`: the session's sandbox changed state. */
1942
+ export const EnvironmentStatePayloadSchema = z
1495
1943
  .object({
1496
1944
  state: z.enum(["creating", "running", "stopped"]),
1497
1945
  backend: z.string(),
@@ -1505,14 +1953,14 @@ export const SandboxStatePayloadSchema = z
1505
1953
  })
1506
1954
  .passthrough();
1507
1955
  /**
1508
- * `sandbox.attached`: the session was opened on a sandbox resource (`sandbox: { id }`). The
1509
- * sandbox's own stream records the same attachment.
1956
+ * `environment.attached`: the session was opened on an Environment (`environment`). The
1957
+ * Environment's own stream records the same attachment.
1510
1958
  */
1511
- export const SandboxAttachedPayloadSchema = z
1512
- .object({ sandboxId: z.string() })
1959
+ export const EnvironmentAttachedPayloadSchema = z
1960
+ .object({ environmentId: z.string() })
1513
1961
  .passthrough();
1514
- /** `sandbox.exec`: one sandbox tool call finished. */
1515
- export const SandboxExecPayloadSchema = z
1962
+ /** `environment.exec`: one sandbox tool call finished. */
1963
+ export const EnvironmentExecPayloadSchema = z
1516
1964
  .object({
1517
1965
  tool: z.string(),
1518
1966
  command: z.string().optional(),
@@ -1530,6 +1978,26 @@ export const NodeStartedPayloadSchema = z
1530
1978
  iterations: z.string().optional(),
1531
1979
  })
1532
1980
  .passthrough();
1981
+ /**
1982
+ * `node.completed`: a flow's HTTP stage or HTTP verifier ended, or a tool stage the Runtime
1983
+ * refused to run (R7.1), named as its `node.started` names it. `status` reads as
1984
+ * `tool.completed`'s: `completed` when the stage's server answered (an error answer included),
1985
+ * `failed` when the Runtime ended it, `cancelled` when a cancel did. `gate` is the Tool Gate's
1986
+ * own start and end of its last send.
1987
+ */
1988
+ export const NodeCompletedPayloadSchema = z
1989
+ .object({
1990
+ path: z.string(),
1991
+ kind: z.string(),
1992
+ key: z.string(),
1993
+ iterations: z.string().optional(),
1994
+ effectId: z.string().min(1),
1995
+ status: z.enum(TOOL_CALL_STATUSES),
1996
+ /** From the first send to the outcome; absent when the stage never ran. */
1997
+ durationMs: z.number().int().nonnegative().optional(),
1998
+ gate: GateTimesSchema.optional(),
1999
+ })
2000
+ .passthrough();
1533
2001
  /** `node.agent`: a workflow node runs as a linked agent session. */
1534
2002
  export const NodeAgentPayloadSchema = z
1535
2003
  .object({
@@ -1579,7 +2047,7 @@ export const TranscriptUpdatedPayloadSchema = z
1579
2047
  * or the turn-end export of a sandbox's outputs (F8.2), whose listing and bytes the harness
1580
2048
  * holding the workspace supplied.
1581
2049
  */
1582
- export const ArtifactSourceSchema = z.enum(["upload", "engine", "export"]);
2050
+ export const ArtifactSourceSchema = z.enum(["upload", "engine", "export", "snapshot"]);
1583
2051
  /**
1584
2052
  * What an artifact holds: one file, or a folder (F8.2), whose versions are manifests of paths to
1585
2053
  * content-addressed files.
@@ -1715,10 +2183,12 @@ export const EVENT_CATALOG = {
1715
2183
  "delegation.started": { payload: DelegationPayloadSchema, source: "loop", version: 1 },
1716
2184
  "delegation.completed": { payload: DelegationPayloadSchema, source: "loop", version: 1 },
1717
2185
  "mcp.discovered": { payload: McpDiscoveredPayloadSchema, source: "loop", version: 1 },
1718
- "sandbox.state": { payload: SandboxStatePayloadSchema, source: "loop", version: 1 },
1719
- "sandbox.exec": { payload: SandboxExecPayloadSchema, source: "loop", version: 1 },
1720
- "sandbox.attached": { payload: SandboxAttachedPayloadSchema, source: "api", version: 1 },
2186
+ "environment.state": { payload: EnvironmentStatePayloadSchema, source: "loop", version: 1 },
2187
+ "environment.exec": { payload: EnvironmentExecPayloadSchema, source: "loop", version: 1 },
2188
+ "environment.attached": { payload: EnvironmentAttachedPayloadSchema, source: "api", version: 1 },
2189
+ "egress.connection": { payload: EgressConnectionPayloadSchema, source: "egress-gate", version: 1 },
1721
2190
  "node.started": { payload: NodeStartedPayloadSchema, source: "loop", version: 1 },
2191
+ "node.completed": { payload: NodeCompletedPayloadSchema, source: "loop", version: 1 },
1722
2192
  "node.agent": { payload: NodeAgentPayloadSchema, source: "loop", version: 1 },
1723
2193
  "loop.iteration": { payload: LoopIterationPayloadSchema, source: "loop", version: 1 },
1724
2194
  "loop.verified": { payload: LoopVerifiedPayloadSchema, source: "api", version: 1 },
@@ -2049,8 +2519,8 @@ export const SeedTenantConfigRequestSchema = z
2049
2519
  sandbox: z
2050
2520
  .object({
2051
2521
  backend: z.enum(["auto", "virtual"]).optional(),
2052
- /** Seeds Tenant setting `sandbox.config` when it is absent. */
2053
- config: TenantSandboxConfigSchema.optional(),
2522
+ /** Seeds Tenant setting `environments.config` when it is absent. */
2523
+ config: TenantEnvironmentsConfigSchema.optional(),
2054
2524
  })
2055
2525
  .strict()
2056
2526
  .optional(),
@@ -2072,22 +2542,22 @@ export const SeedTenantConfigResponseSchema = z
2072
2542
  export const ResetTenantRequestSchema = z
2073
2543
  .object({
2074
2544
  requestId: RequestIdSchema,
2075
- scope: z.enum(["sessions", "sandboxes", "all"]),
2545
+ scope: z.enum(["sessions", "environments", "all"]),
2076
2546
  activeWork: z.enum(["drain", "cancel"]),
2077
2547
  })
2078
2548
  .strict();
2079
2549
  /**
2080
2550
  * Acting for a subject (Host feature `subject-headers`): what an application principal may
2081
2551
  * narrow a request to. `sessions:own` reaches only the subject's own sessions; the others reach
2082
- * Tenant-wide resources. `sandboxes:write` creates and deletes sandboxes (Host feature
2083
- * `sandboxes`); a token caller's reach only the ids its sandbox grants name. Vaults are the
2084
- * installation's, managed with management keys on the Management API (protocol 8).
2552
+ * Tenant-wide resources. `environments:write` creates, changes and deletes Environments and
2553
+ * writes their secrets (protocol 11); a token caller's reach only the ids its Environment
2554
+ * grants name.
2085
2555
  */
2086
2556
  export const SUBJECT_SCOPES = [
2087
2557
  "agents:read",
2088
2558
  "agents:write",
2089
2559
  "sessions:own",
2090
- "sandboxes:write",
2560
+ "environments:write",
2091
2561
  ];
2092
2562
  /**
2093
2563
  * Retired scopes: `Nylorun-Scopes` may still name them (older clients do), and they grant
@@ -2098,9 +2568,11 @@ const RETIRED_SUBJECT_SCOPES = ["vaults:own", "tenant:settings"];
2098
2568
  /** 1–200 visible ASCII characters; spaces only inside. */
2099
2569
  const SUBJECT_PATTERN = /^[\x21-\x7e](?:[\x20-\x7e]{0,198}[\x21-\x7e])?$/;
2100
2570
  /**
2101
- * Owner ids the Runtime uses itself: the host model's vault is owned by `host`, installation
2102
- * vaults by `installation`.
2571
+ * The owner of a session opened for no person: an MCP server's or HTTP tool's identity header
2572
+ * (R2b C2) names nobody for it. A reserved subject.
2103
2573
  */
2574
+ export const INSTALLATION_OWNER = "installation";
2575
+ /** Owner ids the Runtime uses itself: `host` (the model vault's) and `installation`. */
2104
2576
  const RESERVED_SUBJECTS = new Set(["host", INSTALLATION_OWNER]);
2105
2577
  /** A valid subject: 1–200 visible ASCII characters, not reserved by the Runtime. */
2106
2578
  export function isSubject(value) {
@@ -2127,6 +2599,11 @@ export function parseSubjectHeaders(subject, scopes) {
2127
2599
  message: "Nylorun-Scopes is required with Nylorun-Subject",
2128
2600
  };
2129
2601
  const names = named.filter((name) => !RETIRED_SUBJECT_SCOPES.includes(name));
2602
+ if (names.includes("sandboxes:write"))
2603
+ return {
2604
+ ok: false,
2605
+ message: "sandboxes:write was renamed environments:write in protocol 11",
2606
+ };
2130
2607
  const unknown = names.filter((name) => !SUBJECT_SCOPES.includes(name));
2131
2608
  if (unknown.length > 0)
2132
2609
  return { ok: false, message: `Unknown scope ${unknown.join(", ")}` };
@@ -2143,10 +2620,10 @@ export function parseSubjectHeaders(subject, scopes) {
2143
2620
  export const TOKEN_SCOPES = [
2144
2621
  "agents:read",
2145
2622
  "sessions:own",
2146
- "sandboxes:write",
2623
+ "environments:write",
2147
2624
  ];
2148
- /** The most sandbox grants one token caller carries. */
2149
- export const TOKEN_SANDBOX_GRANTS_MAX = 16;
2625
+ /** The most Environment grants one token caller carries. */
2626
+ export const TOKEN_ENVIRONMENT_GRANTS_MAX = 16;
2150
2627
  /**
2151
2628
  * The longest a token the Runtime signs itself lives, in seconds (capability links): rotating
2152
2629
  * signing keys revokes the previous key once the longest token it may have signed has expired.
@@ -2216,8 +2693,8 @@ export const CALLER_SCOPES = [...SUBJECT_SCOPES, "studio"];
2216
2693
  * - `subject` is the person the request acts for; absent for an application key alone.
2217
2694
  * - `scopes`: what the caller holds. An application key alone holds every subject scope.
2218
2695
  * - `agents`: the agents it may reach, `*` for all.
2219
- * - `sandboxes`: the sandbox grants of a token caller (empty reaches none); absent for an
2220
- * application key, alone or acting for a subject, which no grant limits.
2696
+ * - `environments`: the Environment grants of a token caller (empty reaches none); absent for
2697
+ * an application key, alone or acting for a subject, which no grant limits.
2221
2698
  */
2222
2699
  export const MeResponseSchema = z
2223
2700
  .object({
@@ -2227,11 +2704,11 @@ export const MeResponseSchema = z
2227
2704
  .meta({ description: "The person the request acts for; absent for an application key alone" }),
2228
2705
  scopes: z.array(z.enum(CALLER_SCOPES)),
2229
2706
  agents: AgentAllowlistSchema,
2230
- sandboxes: z
2707
+ environments: z
2231
2708
  .array(z.string())
2232
2709
  .optional()
2233
2710
  .meta({
2234
- description: "A token caller's sandbox grants (empty reaches none); absent when no grant limits the caller",
2711
+ description: "A token caller's Environment grants (empty reaches none); absent when no grant limits the caller",
2235
2712
  }),
2236
2713
  via: z.string().meta({
2237
2714
  description: "How the caller authenticated: `application:<principalId>`, `management:<principalId>`, `subject` or `issuer:<name>`",
@@ -2325,18 +2802,24 @@ export const SessionViewSchema = z
2325
2802
  implementationVersion: z.string(),
2326
2803
  status: z.enum(SESSION_STATUSES),
2327
2804
  activeTurnId: z.string().nullable(),
2328
- vaultIds: z.array(z.string()),
2329
- credentialSelections: z.array(CredentialSelectionSchema),
2330
2805
  /**
2331
- * The session whose sandbox this one shares; `null` when it owns its own. Deprecated: share
2332
- * a sandbox resource with `sandbox: { id }` (the client's `sandboxes.forSession()`).
2806
+ * The Environment the session names, and its recipe version when the session opened (for
2807
+ * reading only); `null` without one.
2808
+ */
2809
+ environment: z
2810
+ .object({ id: z.string(), version: z.number().int().positive() })
2811
+ .strict()
2812
+ .nullable(),
2813
+ /**
2814
+ * The harness that runs the session's turns, pinned when it opened (track R4): its
2815
+ * Environment's harness, else `nylorun`.
2333
2816
  */
2334
- sandboxOwnerId: z.string().nullable(),
2335
- /** The sandbox resource the session is attached to (`sandbox: { id }`), if any. */
2336
- sandboxId: z.string().optional(),
2337
- /** The sandbox pinned when the session was opened, or `null`. */
2338
- sandbox: z.record(z.string(), z.unknown()).nullable(),
2339
- sandboxSource: z.enum(["default", "inline", "shared", "sandbox"]).optional(),
2817
+ harness: z.string(),
2818
+ /**
2819
+ * Why the session takes no new turn, when it is closed: `protocol_11` for a session opened
2820
+ * before protocol 11 (a new turn is `409 session_closed`; its history stays readable).
2821
+ */
2822
+ closedReason: z.string().optional(),
2340
2823
  mcpSnapshot: z.record(z.string(), z.unknown()).nullable(),
2341
2824
  mcpDiagnostics: z.array(z.record(z.string(), z.unknown())),
2342
2825
  /** What the session waits on: interactions, approvals, timers. */
@@ -2390,30 +2873,24 @@ export const ListProvidersResponseSchema = z
2390
2873
  const SandboxResourcesLimitSchema = z
2391
2874
  .object({ cpus: z.number(), memoryMiB: z.number() })
2392
2875
  .strict();
2393
- /** A Tenant's sandbox configuration with every default applied (sizes in MiB). */
2876
+ /** A Tenant's Environment settings with every default applied (sizes in MiB). */
2394
2877
  export const EffectiveSandboxConfigSchema = z
2395
2878
  .object({
2396
- default: z.union([z.literal("none"), z.literal("virtual"), SandboxInlineRequestSchema]),
2397
2879
  limits: z
2398
2880
  .object({
2399
2881
  network: z.array(z.string()),
2400
2882
  resources: SandboxResourcesLimitSchema,
2401
2883
  defaultResources: SandboxResourcesLimitSchema,
2402
2884
  idle: z.string(),
2403
- /** The most sandbox resources the Tenant may hold. */
2404
- sandboxes: z.number().int().nonnegative().optional(),
2405
- /** Pods: the longest `lifecycle.ttl`, when the Tenant sets one. */
2406
- ttl: z.string().optional(),
2885
+ /** The most Environments the Tenant may hold. */
2886
+ environments: z.number().int().nonnegative().optional(),
2407
2887
  })
2408
2888
  .strict(),
2409
- /** Pods (Host feature `sandbox-pods`): what happens at expiry, and the pod's stop grace. */
2410
- lifecycle: z
2411
- .object({ onExpiry: z.enum(["retain", "delete"]), stopGrace: z.string() })
2412
- .strict()
2413
- .optional(),
2889
+ /** Pods (Host feature `sandbox-pods`): the pod's stop grace. */
2890
+ lifecycle: z.object({ stopGrace: z.string() }).strict().optional(),
2414
2891
  /** Where each harness may run (D38). */
2415
2892
  placement: z
2416
- .record(z.string(), z.object({ hosts: z.array(z.enum(SANDBOX_PLACEMENT_HOSTS)) }).strict())
2893
+ .record(z.string(), z.object({ hosts: z.array(z.enum(PLACEMENT_HOSTS)) }).strict())
2417
2894
  .optional(),
2418
2895
  })
2419
2896
  .strict();
@@ -2522,11 +2999,62 @@ export const PutModelBudgetsRequestSchema = z
2522
2999
  }
2523
3000
  });
2524
3001
  export const ModelBudgetsSchema = z.object({ budgets: z.array(ModelBudgetSchema) }).strict();
2525
- export const ListVaultsResponseSchema = z.object({ vaults: z.array(VaultInfoSchema) }).strict();
2526
- export const ListCredentialsResponseSchema = z
2527
- .object({ credentials: z.array(CredentialInfoSchema) })
3002
+ /** What a tool policy rule does to a call it matches (R5 step 2). */
3003
+ export const TOOL_POLICY_EFFECTS = ["allow", "ask", "deny"];
3004
+ /** A test of one field of a tool call's input; every test it sets must hold. */
3005
+ export const ToolInputConditionSchema = z
3006
+ .object({
3007
+ equals: jsonValue.optional(),
3008
+ in: z.array(jsonValue).min(1).optional(),
3009
+ gt: z.number().optional(),
3010
+ gte: z.number().optional(),
3011
+ lt: z.number().optional(),
3012
+ lte: z.number().optional(),
3013
+ /** A regular expression the field's string value must match. */
3014
+ matches: z.string().min(1).max(500).optional(),
3015
+ })
3016
+ .strict()
3017
+ .superRefine((condition, ctx) => {
3018
+ if (Object.keys(condition).length === 0)
3019
+ ctx.addIssue({ code: "custom", message: "A condition sets at least one of equals, in, gt, gte, lt, lte or matches" });
3020
+ if (condition.matches !== undefined)
3021
+ try {
3022
+ new RegExp(condition.matches);
3023
+ }
3024
+ catch {
3025
+ ctx.addIssue({ code: "custom", path: ["matches"], message: `matches is not a regular expression: ${condition.matches}` });
3026
+ }
3027
+ });
3028
+ /**
3029
+ * One rule of the Tenant's tool policy (R5 step 2), applied at the Tool Gate to every MCP and
3030
+ * HTTP tool call of every harness. A rule matches a call when every selector it sets matches:
3031
+ * `tool` (the name the model calls it by, `*` for any run of characters), `server` (an MCP
3032
+ * server's name), `kind`, `agent` (the agent that calls it) and `when` (fields of the input, by
3033
+ * dotted path). The strictest matching rule decides: `deny` refuses the call before it is sent,
3034
+ * `ask` holds it until a person approves it on the session (`approve`), `allow` runs it. A call no
3035
+ * rule matches runs. Sandbox tools never cross the gate; their network side is egress policy.
3036
+ */
3037
+ export const ToolRuleSchema = z
3038
+ .object({
3039
+ effect: z.enum(TOOL_POLICY_EFFECTS),
3040
+ tool: z.string().min(1).max(200).optional(),
3041
+ server: z.string().min(1).max(200).optional(),
3042
+ kind: z.enum(["mcp", "http"]).optional(),
3043
+ agent: z.string().min(1).max(200).optional(),
3044
+ when: z.record(z.string().min(1).max(200), ToolInputConditionSchema).optional(),
3045
+ /** Why the rule exists: shown with a held or denied call. */
3046
+ reason: z.string().min(1).max(500).optional(),
3047
+ })
3048
+ .strict();
3049
+ /** `PUT /v1/tenant/tool-policy`: replaces every rule. An empty list allows every call. */
3050
+ export const PutToolPolicyRequestSchema = z
3051
+ .object({ requestId: RequestIdSchema.optional(), rules: z.array(ToolRuleSchema).max(200) })
3052
+ .strict();
3053
+ /** The Tenant's tool policy; `updatedAt` is null until one is set. */
3054
+ export const ToolPolicySchema = z
3055
+ .object({ rules: z.array(ToolRuleSchema), updatedAt: z.string().nullable() })
2528
3056
  .strict();
2529
- /** A deleted vault or credential. */
3057
+ /** A deleted resource. */
2530
3058
  export const DeletedResponseSchema = z.object({ id: z.string() }).strict();
2531
3059
  /**
2532
3060
  * The last frame of a session stream the Runtime ends: `event: nylorun.closed`, when the
@@ -2710,6 +3238,11 @@ export const ArtifactViewSchema = z
2710
3238
  contentType: z.string().meta({ description: "The latest version's media type" }),
2711
3239
  /** The session it belongs to; absent for a Tenant-wide artifact an application made. */
2712
3240
  sessionId: z.string().optional(),
3241
+ /**
3242
+ * The Environment whose disk versions it holds (R2d step 3); absent otherwise. Such an
3243
+ * artifact changes only through `/v1/environments/{id}/snapshot` and its versions routes.
3244
+ */
3245
+ environmentId: z.string().optional(),
2713
3246
  latestVersion: z.number().int().positive(),
2714
3247
  labels: z.record(z.string(), z.string()).optional(),
2715
3248
  createdAt: z.string(),
@@ -2721,6 +3254,11 @@ export const ArtifactViewSchema = z
2721
3254
  export const ListArtifactsResponseSchema = z
2722
3255
  .object({ artifacts: z.array(ArtifactViewSchema) })
2723
3256
  .strict();
3257
+ /** Paged metadata only; read the artifact separately for its version history and bytes. */
3258
+ export const ArtifactListItemSchema = ArtifactViewSchema.omit({ versions: true });
3259
+ export const ArtifactPageSchema = z
3260
+ .object({ artifacts: z.array(ArtifactListItemSchema), nextCursor: z.string().nullable() })
3261
+ .strict();
2724
3262
  /** What an upload answers: the artifact, and the version the upload created. */
2725
3263
  export const UploadArtifactResponseSchema = z
2726
3264
  .object({ artifact: ArtifactViewSchema, version: ArtifactVersionViewSchema })
@@ -2770,19 +3308,37 @@ export const ArtifactLinkSchema = z
2770
3308
  export const FOLDER_CONTENT_TYPE = "application/vnd.nylorun.folder+json";
2771
3309
  /** The manifest format a folder version is stored as. */
2772
3310
  export const FOLDER_MANIFEST_FORMAT = "nylorun.folder.v1";
3311
+ /**
3312
+ * The manifest format of an Environment's disk versions (R2d step 3): v1's entries, plus file
3313
+ * modes and modification times, symbolic links and empty directories. Readers accept both.
3314
+ */
3315
+ export const FOLDER_MANIFEST_FORMAT_V2 = "nylorun.folder.v2";
2773
3316
  /** The folder artifact a session's turn-end export writes, one per session. */
2774
3317
  export const OUTPUTS_ARTIFACT_NAME = "outputs";
2775
3318
  /** The most files one turn-end export stores; past it the export is skipped. */
2776
3319
  export const EXPORT_MAX_FILES = 10_000;
2777
3320
  /** The most bytes one turn-end export stores (before dedupe); past it the export is skipped. */
2778
3321
  export const EXPORT_MAX_BYTES = 1024 * 1024 * 1024;
2779
- /** One file of a folder: its path in the folder (`/`-separated, relative), size, hash and type. */
3322
+ /**
3323
+ * One file of a folder: its path in the folder (`/`-separated, relative), size, hash and type.
3324
+ * In a v2 manifest an entry may also be a symbolic link (`type: "link"`, its `target`) or an
3325
+ * empty directory (`type: "dir"`), with no bytes (`size` 0, `sha256` and `contentType` empty),
3326
+ * and any entry may carry its `mode` and `mtimeMs`.
3327
+ */
2780
3328
  export const FolderEntrySchema = z
2781
3329
  .object({
2782
3330
  path: z.string().min(1).max(ARTIFACT_PATH_MAX),
2783
3331
  size: z.number().int().nonnegative(),
2784
3332
  sha256: z.string().meta({ description: "SHA-256 of the file's bytes, lowercase hex" }),
2785
3333
  contentType: z.string(),
3334
+ /** v2: absent for a file. */
3335
+ type: z.enum(["link", "dir"]).optional(),
3336
+ /** v2: the permission bits (`0o755` is 493). */
3337
+ mode: z.number().int().nonnegative().max(0o7777).optional(),
3338
+ /** v2: the modification time, ms since the epoch. */
3339
+ mtimeMs: z.number().nonnegative().optional(),
3340
+ /** v2: a link's target, as stored on the disk. */
3341
+ target: z.string().max(4096).optional(),
2786
3342
  })
2787
3343
  .strict();
2788
3344
  /**
@@ -2791,7 +3347,7 @@ export const FolderEntrySchema = z
2791
3347
  */
2792
3348
  export const FolderManifestSchema = z
2793
3349
  .object({
2794
- format: z.literal(FOLDER_MANIFEST_FORMAT),
3350
+ format: z.enum([FOLDER_MANIFEST_FORMAT, FOLDER_MANIFEST_FORMAT_V2]),
2795
3351
  entries: z.array(FolderEntrySchema),
2796
3352
  })
2797
3353
  .strict();
@@ -2850,7 +3406,7 @@ export const TenantArtifactsViewSchema = z
2850
3406
  /** Opt-in session reads (Host feature `session-reads`). */
2851
3407
  export const SessionListItemSchema = SessionSummarySchema.extend({
2852
3408
  lastTurnId: z.string().nullable(),
2853
- sandboxId: z.string().nullable(),
3409
+ environmentId: z.string().nullable(),
2854
3410
  createdAt: z.string().nullable(),
2855
3411
  lastEventAt: z.string().nullable(),
2856
3412
  }).strict();
@@ -2892,6 +3448,11 @@ export const SessionUsageTotalsSchema = z
2892
3448
  export const ModelCallSchema = z
2893
3449
  .object({
2894
3450
  id: z.string(),
3451
+ /**
3452
+ * The model effect the call served: the effect id its harness sent as `Idempotency-Key`
3453
+ * (track R4), so a call is joined to the journal.
3454
+ */
3455
+ effectId: z.string(),
2895
3456
  sessionId: z.string(),
2896
3457
  turnId: z.string(),
2897
3458
  agentId: z.string(),
@@ -2921,6 +3482,73 @@ export const ModelCallExportPageSchema = z
2921
3482
  asOf: z.string(),
2922
3483
  })
2923
3484
  .strict();
2924
- export const SandboxPageSchema = z
2925
- .object({ sandboxes: z.array(SandboxViewSchema), nextCursor: z.string().nullable() })
3485
+ /**
3486
+ * One tool call of a session (R5.2), read from the effect journal: what ran, with what input,
3487
+ * how many sends, and how it ended. `invoking` while it runs. `uncertain` only for a call
3488
+ * recorded before R5. The output is in the session's log (`tool.completed`).
3489
+ */
3490
+ export const ToolCallSchema = z
3491
+ .object({
3492
+ effectId: z.string(),
3493
+ turnId: z.string(),
3494
+ callId: z.string().nullable(),
3495
+ capabilityId: z.string().nullable(),
3496
+ toolName: z.string().nullable(),
3497
+ kind: z.enum(TOOL_CALL_KINDS).nullable(),
3498
+ server: z.string().nullable(),
3499
+ /** `held`: the Tool Gate holds it for a person's approval (R5 step 2). */
3500
+ status: z.enum(["invoking", "held", ...TOOL_CALL_STATUSES, "uncertain"]),
3501
+ attempts: z.number().int().nonnegative(),
3502
+ input: z.unknown(),
3503
+ error: z.object({ code: z.string(), message: z.string() }).strict().nullable(),
3504
+ startedAt: z.string().nullable(),
3505
+ settledAt: z.string().nullable(),
3506
+ durationMs: z.number().int().nonnegative().nullable(),
3507
+ })
3508
+ .strict();
3509
+ export const ToolCallsPageSchema = z
3510
+ .object({ calls: z.array(ToolCallSchema), nextCursor: z.string().nullable(), asOf: z.string() })
3511
+ .strict();
3512
+ /** One OTLP attribute (R7.5): a key and an `AnyValue` (`stringValue`, `intValue`, …). */
3513
+ export const OtlpKeyValueSchema = z
3514
+ .object({ key: z.string(), value: z.record(z.string(), z.unknown()) })
3515
+ .passthrough();
3516
+ /**
3517
+ * One span as OTLP/HTTP JSON encodes it (R7.5): hex ids, times in nanoseconds as decimal strings,
3518
+ * `kind` (1 internal, 3 client) and `status.code` (0 unset, 1 ok, 2 error) as numbers.
3519
+ */
3520
+ export const OtlpSpanSchema = z
3521
+ .object({
3522
+ traceId: z.string(),
3523
+ spanId: z.string(),
3524
+ parentSpanId: z.string().optional(),
3525
+ name: z.string(),
3526
+ kind: z.number().int(),
3527
+ startTimeUnixNano: z.string(),
3528
+ endTimeUnixNano: z.string(),
3529
+ attributes: z.array(OtlpKeyValueSchema),
3530
+ status: z.object({ code: z.number().int(), message: z.string().optional() }).passthrough(),
3531
+ })
3532
+ .passthrough();
3533
+ /**
3534
+ * A turn's trace (R7.5, feature `traces`): the OTLP `ExportTraceServiceRequest` JSON the Runtime
3535
+ * posts to a collector, built from the turn's log rows. One resource, one scope.
3536
+ */
3537
+ export const TurnTraceSchema = z
3538
+ .object({
3539
+ resourceSpans: z.array(z
3540
+ .object({
3541
+ resource: z.object({ attributes: z.array(OtlpKeyValueSchema) }).passthrough(),
3542
+ scopeSpans: z.array(z
3543
+ .object({
3544
+ scope: z.object({ name: z.string(), version: z.string().optional() }).passthrough(),
3545
+ spans: z.array(OtlpSpanSchema),
3546
+ })
3547
+ .passthrough()),
3548
+ })
3549
+ .passthrough()),
3550
+ })
3551
+ .passthrough();
3552
+ export const EnvironmentPageSchema = z
3553
+ .object({ environments: z.array(EnvironmentViewSchema), nextCursor: z.string().nullable() })
2926
3554
  .strict();