@nylorun/core 0.19.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 +115 -0
  2. package/dist/compatibility.d.ts +74 -32
  3. package/dist/compatibility.js +80 -33
  4. package/dist/contracts.d.ts +1496 -495
  5. package/dist/contracts.js +889 -374
  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 +353 -31
  35. package/dist/harness-api/schema.js +138 -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
@@ -1002,78 +1153,66 @@ const EnvironmentValueSchema = z
1002
1153
  .min(1)
1003
1154
  .max(8192)
1004
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}$/;
1005
1158
  /**
1006
- * A credential for the server at `url` (the URL a manifest names): `bearer` sends
1007
- * `Authorization: Bearer <token>`, `headers` its header map (R2b C2). The header names may not be
1008
- * the MCP transport's headers or `Nylorun-*`.
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`.
1009
1166
  */
1010
- export const CreateCredentialRequestSchema = z
1011
- .object({
1012
- ...vaultWriteBase,
1013
- name: z.string().min(1),
1014
- auth: z.discriminatedUnion("type", [
1015
- z
1016
- .object({
1017
- type: z.literal("bearer"),
1018
- url: z.string().min(1),
1019
- token: z.string().min(1),
1020
- ...credentialRouting,
1021
- })
1022
- .strict(),
1023
- z
1024
- .object({
1025
- type: z.literal("headers"),
1026
- url: z.string().min(1),
1027
- headers: CredentialHeadersSchema,
1028
- ...credentialRouting,
1029
- })
1030
- .strict(),
1031
- z
1032
- .object({
1033
- type: z.literal("environment_secret"),
1034
- secretName: EnvironmentNameSchema,
1035
- secretValue: EnvironmentValueSchema,
1036
- allowedHosts: AllowedHostsSchema,
1037
- inject: EnvironmentSecretInjectSchema.optional(),
1038
- })
1039
- .strict(),
1040
- z
1041
- .object({
1042
- type: z.literal("environment_variable"),
1043
- variableName: EnvironmentNameSchema,
1044
- variableValue: EnvironmentValueSchema,
1045
- })
1046
- .strict(),
1047
- ]),
1048
- })
1049
- .strict();
1050
- /**
1051
- * Replaces a credential's secret; its type and URL stay. `via` and `identity` are kept unless
1052
- * given (`null` removes one).
1053
- */
1054
- export const RotateCredentialRequestSchema = z
1055
- .object({
1056
- ...vaultWriteBase,
1057
- auth: z.discriminatedUnion("type", [
1058
- z
1059
- .object({
1060
- type: z.literal("bearer"),
1061
- token: z.string().min(1),
1062
- ...credentialRoutingChange,
1063
- })
1064
- .strict(),
1065
- z
1066
- .object({
1067
- type: z.literal("headers"),
1068
- headers: CredentialHeadersSchema,
1069
- ...credentialRoutingChange,
1070
- })
1071
- .strict(),
1072
- z.object({ type: z.literal("environment_secret"), secretValue: EnvironmentValueSchema }).strict(),
1073
- z.object({ type: z.literal("environment_variable"), variableValue: EnvironmentValueSchema }).strict(),
1074
- ]),
1075
- })
1076
- .strict();
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
+ }
1077
1216
  /**
1078
1217
  * What the Runtime cannot learn from a custom OpenAI-compatible endpoint (Model Calls §7):
1079
1218
  * its context window and output limit, whether it reasons, and pi-ai `compat` settings
@@ -1121,34 +1260,25 @@ export const SelectHostModelRequestSchema = z
1121
1260
  baseUrl: z.string().min(1).optional(),
1122
1261
  })
1123
1262
  .strict();
1124
- export const VaultInfoSchema = 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
1125
1274
  .object({
1126
- id: z.string(),
1127
1275
  name: z.string(),
1128
- ownerUserId: z.string(),
1129
- metadata: z.record(z.string(), z.string()).optional(),
1130
- createdAt: z.string(),
1131
- })
1132
- .strict();
1133
- export const CredentialInfoSchema = z
1134
- .object({
1135
- id: z.string(),
1136
- vaultId: z.string(),
1137
- name: z.string(),
1138
- type: z.enum(["bearer", "headers", "environment_secret", "environment_variable"]),
1139
- /**
1140
- * What the credential is bound to: the server `url` for `bearer` and `headers`; the variable
1141
- * name and hosts for `environment_secret` (R2c); the name and its plain value for
1142
- * `environment_variable`, which is not a secret. A secret's value is never shown.
1143
- */
1276
+ type: z.enum(ENVIRONMENT_SECRET_TYPES),
1144
1277
  binding: z
1145
1278
  .object({
1146
1279
  url: z.string().optional(),
1147
- secretName: z.string().optional(),
1148
1280
  allowedHosts: z.array(z.string()).optional(),
1149
1281
  inject: EnvironmentSecretInjectSchema.optional(),
1150
- variableName: z.string().optional(),
1151
- variableValue: z.string().optional(),
1152
1282
  })
1153
1283
  .strict(),
1154
1284
  /** A `headers` credential's header names (lower case), never their values. */
@@ -1159,13 +1289,15 @@ export const CredentialInfoSchema = z
1159
1289
  rotatedAt: z.string().optional(),
1160
1290
  })
1161
1291
  .strict();
1292
+ export const ListEnvironmentSecretsResponseSchema = z
1293
+ .object({ secrets: z.array(EnvironmentSecretViewSchema) })
1294
+ .strict();
1162
1295
  /** The MCP transports a preview speaks: a manifest's remote server types. */
1163
1296
  export const MCP_PREVIEW_TYPES = ["streamable-http", "sse"];
1164
1297
  /**
1165
1298
  * `POST /v1/tenant/mcp/preview` (R2b C12): what a remote MCP server offers, before an agent
1166
- * names it. The Runtime connects with the installation vault's credential for `url` (one
1167
- * credential across the installation vaults, or the one in `vaultId`), lists the tools and
1168
- * 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.
1169
1301
  */
1170
1302
  export const McpPreviewRequestSchema = z
1171
1303
  .object({
@@ -1192,8 +1324,8 @@ export const McpPreviewRequestSchema = z
1192
1324
  * host's name before its top-level domain (`linear` for `mcp.linear.app`).
1193
1325
  */
1194
1326
  name: modelFacingName("MCP server").optional(),
1195
- /** The installation vault whose credential to send. Default: every installation vault. */
1196
- 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(),
1197
1329
  })
1198
1330
  .strict();
1199
1331
  /** One tool a preview found. */
@@ -1216,7 +1348,7 @@ export const McpPreviewToolSchema = z
1216
1348
  /**
1217
1349
  * A preview (R2b C12). A server that answered `401` is `authRequired`, with its RFC 9728
1218
1350
  * protected-resource metadata when it publishes any: it needs a person's sign-in or a key the
1219
- * 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`).
1220
1352
  */
1221
1353
  export const McpPreviewSchema = z
1222
1354
  .object({
@@ -1224,7 +1356,7 @@ export const McpPreviewSchema = z
1224
1356
  name: z.string(),
1225
1357
  url: z.string(),
1226
1358
  type: z.enum(MCP_PREVIEW_TYPES),
1227
- /** True when an installation vault's credential was sent. */
1359
+ /** True when a credential of the Environment's vault was sent. */
1228
1360
  credentialSent: z.boolean(),
1229
1361
  /** The server's `initialize` answer: its name, version and title. */
1230
1362
  serverInfo: z.record(z.string(), z.unknown()).optional(),
@@ -1244,6 +1376,70 @@ export const McpPreviewSchema = z
1244
1376
  .optional(),
1245
1377
  })
1246
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();
1247
1443
  const commandBase = {
1248
1444
  requestId: RequestIdSchema,
1249
1445
  idempotencyKey: IdempotencyKeySchema,
@@ -1331,8 +1527,16 @@ export const SessionCommandSchema = z.union([
1331
1527
  export const SessionEventBodySchema = SessionCommandSchema;
1332
1528
  /** The envelope every session event carries (`nylorun.event/2`, Durable Streams §9.5). */
1333
1529
  export const EVENT_SCHEMA = "nylorun.event/2";
1334
- /** 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
+ */
1335
1537
  export const EventSourceKindSchema = z.enum([
1538
+ "client",
1539
+ "core",
1336
1540
  "model-gate",
1337
1541
  "tool-gate",
1338
1542
  "egress-gate",
@@ -1348,7 +1552,12 @@ export const EventSourceKindSchema = z.enum([
1348
1552
  "human",
1349
1553
  "api",
1350
1554
  ]);
1351
- /** 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
+ */
1352
1561
  export const EvidenceClassSchema = z.enum([
1353
1562
  "observed",
1354
1563
  "measured",
@@ -1356,6 +1565,13 @@ export const EvidenceClassSchema = z.enum([
1356
1565
  "claimed",
1357
1566
  "asserted",
1358
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();
1359
1575
  /**
1360
1576
  * The envelope fields. Not strict: a client strips fields it does not know, so the envelope
1361
1577
  * can grow without a protocol bump.
@@ -1382,6 +1598,8 @@ const eventEnvelope = {
1382
1598
  schemaVersion: z.number().int().positive(),
1383
1599
  source: z.object({ kind: EventSourceKindSchema, id: z.string() }),
1384
1600
  evidence: EvidenceClassSchema,
1601
+ /** Who sent a command (`command.*`, a cancel's `turn.cancelled`), from its credential (R4.9). */
1602
+ principal: EventPrincipalSchema.optional(),
1385
1603
  trace: z
1386
1604
  .object({
1387
1605
  traceId: z.string(),
@@ -1436,9 +1654,49 @@ const toolIds = {
1436
1654
  /** The harness invocation of the call; interactions refer to it. */
1437
1655
  invocationId: z.string().min(1),
1438
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
+ };
1439
1695
  /**
1440
1696
  * `message.assistant`: one completed model step. `invocationId` is the model call's.
1441
- * `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`).
1442
1700
  */
1443
1701
  export const AssistantMessagePayloadSchema = z
1444
1702
  .object({
@@ -1457,9 +1715,15 @@ export const AssistantMessagePayloadSchema = z
1457
1715
  input: z.unknown(),
1458
1716
  })
1459
1717
  .passthrough()),
1718
+ ...modelOutcomeFacts,
1460
1719
  ...eventAgent,
1461
1720
  })
1462
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
+ }
1463
1727
  /**
1464
1728
  * `model.failed`: a model call that failed in a known way (Model Calls §6.4). The turn
1465
1729
  * then fails with `model.<code>`, or recovers.
@@ -1470,12 +1734,14 @@ export const ModelFailedPayloadSchema = z
1470
1734
  code: z.string().min(1),
1471
1735
  message: z.string(),
1472
1736
  retryable: z.boolean(),
1737
+ ...modelOutcomeFacts,
1473
1738
  ...eventAgent,
1474
1739
  })
1475
1740
  .passthrough();
1476
1741
  /**
1477
1742
  * `context.compacted`: the engine summarized older history to fit the model's window
1478
- * (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.
1479
1745
  */
1480
1746
  export const ContextCompactedPayloadSchema = z
1481
1747
  .object({
@@ -1483,15 +1749,56 @@ export const ContextCompactedPayloadSchema = z
1483
1749
  trigger: z.enum(["threshold", "overflow"]),
1484
1750
  tokensBefore: z.number().int().nonnegative(),
1485
1751
  tokensAfter: z.number().int().nonnegative(),
1752
+ partial: z.literal(true).optional(),
1753
+ ...modelOutcomeFacts,
1486
1754
  ...eventAgent,
1487
1755
  })
1488
1756
  .passthrough();
1489
- /** `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
+ */
1490
1781
  export const ToolCompletedPayloadSchema = z
1491
1782
  .object({
1492
1783
  ...toolIds,
1784
+ /** The tool call's effect id (R7.1). */
1785
+ effectId: z.string().min(1).optional(),
1493
1786
  capabilityId: z.string().min(1),
1494
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(),
1495
1802
  output: z.unknown().optional(),
1496
1803
  error: z
1497
1804
  .object({
@@ -1502,8 +1809,6 @@ export const ToolCompletedPayloadSchema = z
1502
1809
  * whose server answered `401`.
1503
1810
  */
1504
1811
  server: z.string().optional(),
1505
- /** With `credential_rejected`: the scope of the vault whose credential was sent; absent when none was. */
1506
- vault: z.enum(["installation", "user"]).optional(),
1507
1812
  /** An MCP tool error (R2b C7): true when calling again may work, as for `mcp.unreachable`. */
1508
1813
  retryable: z.boolean().optional(),
1509
1814
  })
@@ -1520,8 +1825,29 @@ export const ToolCompletedPayloadSchema = z
1520
1825
  export const EffectUncertainPayloadSchema = z
1521
1826
  .object({ effectId: z.string().min(1), message: z.string().optional() })
1522
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
+ };
1523
1849
  export const TurnCompletedPayloadSchema = z
1524
- .object({ output: z.unknown() })
1850
+ .object({ output: z.unknown(), ...turnEndFacts })
1525
1851
  .passthrough();
1526
1852
  export const TurnPausedPayloadSchema = z
1527
1853
  .object({
@@ -1546,10 +1872,11 @@ export const TurnFailedPayloadSchema = z
1546
1872
  .passthrough()
1547
1873
  .optional(),
1548
1874
  message: z.string().optional(),
1875
+ ...turnEndFacts,
1549
1876
  })
1550
1877
  .passthrough();
1551
1878
  export const TurnCancelledPayloadSchema = z
1552
- .object({ reason: z.string().optional() })
1879
+ .object({ reason: z.string().optional(), ...turnEndFacts })
1553
1880
  .passthrough();
1554
1881
  /** Lifecycle of an agent used as a tool. `agent.delegationId` is the parent call's invocation. */
1555
1882
  export const DelegationPayloadSchema = z
@@ -1583,6 +1910,14 @@ export const CommandMessagePayloadSchema = z
1583
1910
  parts: z.array(MessagePartSchema).optional(),
1584
1911
  /** The turn manifest the message carried, if any. */
1585
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(),
1586
1921
  })
1587
1922
  .passthrough();
1588
1923
  /** `command.approve`: an answer to an approval interaction. */
@@ -1603,8 +1938,8 @@ export const CommandRespondPayloadSchema = z
1603
1938
  value: z.unknown(),
1604
1939
  })
1605
1940
  .passthrough();
1606
- /** `sandbox.state`: the session's sandbox changed state. */
1607
- export const SandboxStatePayloadSchema = z
1941
+ /** `environment.state`: the session's sandbox changed state. */
1942
+ export const EnvironmentStatePayloadSchema = z
1608
1943
  .object({
1609
1944
  state: z.enum(["creating", "running", "stopped"]),
1610
1945
  backend: z.string(),
@@ -1618,14 +1953,14 @@ export const SandboxStatePayloadSchema = z
1618
1953
  })
1619
1954
  .passthrough();
1620
1955
  /**
1621
- * `sandbox.attached`: the session was opened on a sandbox resource (`sandbox: { id }`). The
1622
- * 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.
1623
1958
  */
1624
- export const SandboxAttachedPayloadSchema = z
1625
- .object({ sandboxId: z.string() })
1959
+ export const EnvironmentAttachedPayloadSchema = z
1960
+ .object({ environmentId: z.string() })
1626
1961
  .passthrough();
1627
- /** `sandbox.exec`: one sandbox tool call finished. */
1628
- export const SandboxExecPayloadSchema = z
1962
+ /** `environment.exec`: one sandbox tool call finished. */
1963
+ export const EnvironmentExecPayloadSchema = z
1629
1964
  .object({
1630
1965
  tool: z.string(),
1631
1966
  command: z.string().optional(),
@@ -1643,6 +1978,26 @@ export const NodeStartedPayloadSchema = z
1643
1978
  iterations: z.string().optional(),
1644
1979
  })
1645
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();
1646
2001
  /** `node.agent`: a workflow node runs as a linked agent session. */
1647
2002
  export const NodeAgentPayloadSchema = z
1648
2003
  .object({
@@ -1692,7 +2047,7 @@ export const TranscriptUpdatedPayloadSchema = z
1692
2047
  * or the turn-end export of a sandbox's outputs (F8.2), whose listing and bytes the harness
1693
2048
  * holding the workspace supplied.
1694
2049
  */
1695
- export const ArtifactSourceSchema = z.enum(["upload", "engine", "export"]);
2050
+ export const ArtifactSourceSchema = z.enum(["upload", "engine", "export", "snapshot"]);
1696
2051
  /**
1697
2052
  * What an artifact holds: one file, or a folder (F8.2), whose versions are manifests of paths to
1698
2053
  * content-addressed files.
@@ -1828,10 +2183,12 @@ export const EVENT_CATALOG = {
1828
2183
  "delegation.started": { payload: DelegationPayloadSchema, source: "loop", version: 1 },
1829
2184
  "delegation.completed": { payload: DelegationPayloadSchema, source: "loop", version: 1 },
1830
2185
  "mcp.discovered": { payload: McpDiscoveredPayloadSchema, source: "loop", version: 1 },
1831
- "sandbox.state": { payload: SandboxStatePayloadSchema, source: "loop", version: 1 },
1832
- "sandbox.exec": { payload: SandboxExecPayloadSchema, source: "loop", version: 1 },
1833
- "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 },
1834
2190
  "node.started": { payload: NodeStartedPayloadSchema, source: "loop", version: 1 },
2191
+ "node.completed": { payload: NodeCompletedPayloadSchema, source: "loop", version: 1 },
1835
2192
  "node.agent": { payload: NodeAgentPayloadSchema, source: "loop", version: 1 },
1836
2193
  "loop.iteration": { payload: LoopIterationPayloadSchema, source: "loop", version: 1 },
1837
2194
  "loop.verified": { payload: LoopVerifiedPayloadSchema, source: "api", version: 1 },
@@ -2162,8 +2519,8 @@ export const SeedTenantConfigRequestSchema = z
2162
2519
  sandbox: z
2163
2520
  .object({
2164
2521
  backend: z.enum(["auto", "virtual"]).optional(),
2165
- /** Seeds Tenant setting `sandbox.config` when it is absent. */
2166
- config: TenantSandboxConfigSchema.optional(),
2522
+ /** Seeds Tenant setting `environments.config` when it is absent. */
2523
+ config: TenantEnvironmentsConfigSchema.optional(),
2167
2524
  })
2168
2525
  .strict()
2169
2526
  .optional(),
@@ -2185,22 +2542,22 @@ export const SeedTenantConfigResponseSchema = z
2185
2542
  export const ResetTenantRequestSchema = z
2186
2543
  .object({
2187
2544
  requestId: RequestIdSchema,
2188
- scope: z.enum(["sessions", "sandboxes", "all"]),
2545
+ scope: z.enum(["sessions", "environments", "all"]),
2189
2546
  activeWork: z.enum(["drain", "cancel"]),
2190
2547
  })
2191
2548
  .strict();
2192
2549
  /**
2193
2550
  * Acting for a subject (Host feature `subject-headers`): what an application principal may
2194
2551
  * narrow a request to. `sessions:own` reaches only the subject's own sessions; the others reach
2195
- * Tenant-wide resources. `sandboxes:write` creates and deletes sandboxes (Host feature
2196
- * `sandboxes`); a token caller's reach only the ids its sandbox grants name. Vaults are the
2197
- * 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.
2198
2555
  */
2199
2556
  export const SUBJECT_SCOPES = [
2200
2557
  "agents:read",
2201
2558
  "agents:write",
2202
2559
  "sessions:own",
2203
- "sandboxes:write",
2560
+ "environments:write",
2204
2561
  ];
2205
2562
  /**
2206
2563
  * Retired scopes: `Nylorun-Scopes` may still name them (older clients do), and they grant
@@ -2211,9 +2568,11 @@ const RETIRED_SUBJECT_SCOPES = ["vaults:own", "tenant:settings"];
2211
2568
  /** 1–200 visible ASCII characters; spaces only inside. */
2212
2569
  const SUBJECT_PATTERN = /^[\x21-\x7e](?:[\x20-\x7e]{0,198}[\x21-\x7e])?$/;
2213
2570
  /**
2214
- * Owner ids the Runtime uses itself: the host model's vault is owned by `host`, installation
2215
- * 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.
2216
2573
  */
2574
+ export const INSTALLATION_OWNER = "installation";
2575
+ /** Owner ids the Runtime uses itself: `host` (the model vault's) and `installation`. */
2217
2576
  const RESERVED_SUBJECTS = new Set(["host", INSTALLATION_OWNER]);
2218
2577
  /** A valid subject: 1–200 visible ASCII characters, not reserved by the Runtime. */
2219
2578
  export function isSubject(value) {
@@ -2240,6 +2599,11 @@ export function parseSubjectHeaders(subject, scopes) {
2240
2599
  message: "Nylorun-Scopes is required with Nylorun-Subject",
2241
2600
  };
2242
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
+ };
2243
2607
  const unknown = names.filter((name) => !SUBJECT_SCOPES.includes(name));
2244
2608
  if (unknown.length > 0)
2245
2609
  return { ok: false, message: `Unknown scope ${unknown.join(", ")}` };
@@ -2256,10 +2620,10 @@ export function parseSubjectHeaders(subject, scopes) {
2256
2620
  export const TOKEN_SCOPES = [
2257
2621
  "agents:read",
2258
2622
  "sessions:own",
2259
- "sandboxes:write",
2623
+ "environments:write",
2260
2624
  ];
2261
- /** The most sandbox grants one token caller carries. */
2262
- export const TOKEN_SANDBOX_GRANTS_MAX = 16;
2625
+ /** The most Environment grants one token caller carries. */
2626
+ export const TOKEN_ENVIRONMENT_GRANTS_MAX = 16;
2263
2627
  /**
2264
2628
  * The longest a token the Runtime signs itself lives, in seconds (capability links): rotating
2265
2629
  * signing keys revokes the previous key once the longest token it may have signed has expired.
@@ -2329,8 +2693,8 @@ export const CALLER_SCOPES = [...SUBJECT_SCOPES, "studio"];
2329
2693
  * - `subject` is the person the request acts for; absent for an application key alone.
2330
2694
  * - `scopes`: what the caller holds. An application key alone holds every subject scope.
2331
2695
  * - `agents`: the agents it may reach, `*` for all.
2332
- * - `sandboxes`: the sandbox grants of a token caller (empty reaches none); absent for an
2333
- * 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.
2334
2698
  */
2335
2699
  export const MeResponseSchema = z
2336
2700
  .object({
@@ -2340,11 +2704,11 @@ export const MeResponseSchema = z
2340
2704
  .meta({ description: "The person the request acts for; absent for an application key alone" }),
2341
2705
  scopes: z.array(z.enum(CALLER_SCOPES)),
2342
2706
  agents: AgentAllowlistSchema,
2343
- sandboxes: z
2707
+ environments: z
2344
2708
  .array(z.string())
2345
2709
  .optional()
2346
2710
  .meta({
2347
- 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",
2348
2712
  }),
2349
2713
  via: z.string().meta({
2350
2714
  description: "How the caller authenticated: `application:<principalId>`, `management:<principalId>`, `subject` or `issuer:<name>`",
@@ -2438,18 +2802,24 @@ export const SessionViewSchema = z
2438
2802
  implementationVersion: z.string(),
2439
2803
  status: z.enum(SESSION_STATUSES),
2440
2804
  activeTurnId: z.string().nullable(),
2441
- vaultIds: z.array(z.string()),
2442
- credentialSelections: z.array(CredentialSelectionSchema),
2443
2805
  /**
2444
- * The session whose sandbox this one shares; `null` when it owns its own. Deprecated: share
2445
- * 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`.
2446
2816
  */
2447
- sandboxOwnerId: z.string().nullable(),
2448
- /** The sandbox resource the session is attached to (`sandbox: { id }`), if any. */
2449
- sandboxId: z.string().optional(),
2450
- /** The sandbox pinned when the session was opened, or `null`. */
2451
- sandbox: z.record(z.string(), z.unknown()).nullable(),
2452
- 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(),
2453
2823
  mcpSnapshot: z.record(z.string(), z.unknown()).nullable(),
2454
2824
  mcpDiagnostics: z.array(z.record(z.string(), z.unknown())),
2455
2825
  /** What the session waits on: interactions, approvals, timers. */
@@ -2503,30 +2873,24 @@ export const ListProvidersResponseSchema = z
2503
2873
  const SandboxResourcesLimitSchema = z
2504
2874
  .object({ cpus: z.number(), memoryMiB: z.number() })
2505
2875
  .strict();
2506
- /** 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). */
2507
2877
  export const EffectiveSandboxConfigSchema = z
2508
2878
  .object({
2509
- default: z.union([z.literal("none"), z.literal("virtual"), SandboxInlineRequestSchema]),
2510
2879
  limits: z
2511
2880
  .object({
2512
2881
  network: z.array(z.string()),
2513
2882
  resources: SandboxResourcesLimitSchema,
2514
2883
  defaultResources: SandboxResourcesLimitSchema,
2515
2884
  idle: z.string(),
2516
- /** The most sandbox resources the Tenant may hold. */
2517
- sandboxes: z.number().int().nonnegative().optional(),
2518
- /** Pods: the longest `lifecycle.ttl`, when the Tenant sets one. */
2519
- ttl: z.string().optional(),
2885
+ /** The most Environments the Tenant may hold. */
2886
+ environments: z.number().int().nonnegative().optional(),
2520
2887
  })
2521
2888
  .strict(),
2522
- /** Pods (Host feature `sandbox-pods`): what happens at expiry, and the pod's stop grace. */
2523
- lifecycle: z
2524
- .object({ onExpiry: z.enum(["retain", "delete"]), stopGrace: z.string() })
2525
- .strict()
2526
- .optional(),
2889
+ /** Pods (Host feature `sandbox-pods`): the pod's stop grace. */
2890
+ lifecycle: z.object({ stopGrace: z.string() }).strict().optional(),
2527
2891
  /** Where each harness may run (D38). */
2528
2892
  placement: z
2529
- .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())
2530
2894
  .optional(),
2531
2895
  })
2532
2896
  .strict();
@@ -2635,11 +2999,62 @@ export const PutModelBudgetsRequestSchema = z
2635
2999
  }
2636
3000
  });
2637
3001
  export const ModelBudgetsSchema = z.object({ budgets: z.array(ModelBudgetSchema) }).strict();
2638
- export const ListVaultsResponseSchema = z.object({ vaults: z.array(VaultInfoSchema) }).strict();
2639
- export const ListCredentialsResponseSchema = z
2640
- .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() })
2641
3056
  .strict();
2642
- /** A deleted vault or credential. */
3057
+ /** A deleted resource. */
2643
3058
  export const DeletedResponseSchema = z.object({ id: z.string() }).strict();
2644
3059
  /**
2645
3060
  * The last frame of a session stream the Runtime ends: `event: nylorun.closed`, when the
@@ -2823,6 +3238,11 @@ export const ArtifactViewSchema = z
2823
3238
  contentType: z.string().meta({ description: "The latest version's media type" }),
2824
3239
  /** The session it belongs to; absent for a Tenant-wide artifact an application made. */
2825
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(),
2826
3246
  latestVersion: z.number().int().positive(),
2827
3247
  labels: z.record(z.string(), z.string()).optional(),
2828
3248
  createdAt: z.string(),
@@ -2834,6 +3254,11 @@ export const ArtifactViewSchema = z
2834
3254
  export const ListArtifactsResponseSchema = z
2835
3255
  .object({ artifacts: z.array(ArtifactViewSchema) })
2836
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();
2837
3262
  /** What an upload answers: the artifact, and the version the upload created. */
2838
3263
  export const UploadArtifactResponseSchema = z
2839
3264
  .object({ artifact: ArtifactViewSchema, version: ArtifactVersionViewSchema })
@@ -2883,19 +3308,37 @@ export const ArtifactLinkSchema = z
2883
3308
  export const FOLDER_CONTENT_TYPE = "application/vnd.nylorun.folder+json";
2884
3309
  /** The manifest format a folder version is stored as. */
2885
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";
2886
3316
  /** The folder artifact a session's turn-end export writes, one per session. */
2887
3317
  export const OUTPUTS_ARTIFACT_NAME = "outputs";
2888
3318
  /** The most files one turn-end export stores; past it the export is skipped. */
2889
3319
  export const EXPORT_MAX_FILES = 10_000;
2890
3320
  /** The most bytes one turn-end export stores (before dedupe); past it the export is skipped. */
2891
3321
  export const EXPORT_MAX_BYTES = 1024 * 1024 * 1024;
2892
- /** 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
+ */
2893
3328
  export const FolderEntrySchema = z
2894
3329
  .object({
2895
3330
  path: z.string().min(1).max(ARTIFACT_PATH_MAX),
2896
3331
  size: z.number().int().nonnegative(),
2897
3332
  sha256: z.string().meta({ description: "SHA-256 of the file's bytes, lowercase hex" }),
2898
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(),
2899
3342
  })
2900
3343
  .strict();
2901
3344
  /**
@@ -2904,7 +3347,7 @@ export const FolderEntrySchema = z
2904
3347
  */
2905
3348
  export const FolderManifestSchema = z
2906
3349
  .object({
2907
- format: z.literal(FOLDER_MANIFEST_FORMAT),
3350
+ format: z.enum([FOLDER_MANIFEST_FORMAT, FOLDER_MANIFEST_FORMAT_V2]),
2908
3351
  entries: z.array(FolderEntrySchema),
2909
3352
  })
2910
3353
  .strict();
@@ -2963,7 +3406,7 @@ export const TenantArtifactsViewSchema = z
2963
3406
  /** Opt-in session reads (Host feature `session-reads`). */
2964
3407
  export const SessionListItemSchema = SessionSummarySchema.extend({
2965
3408
  lastTurnId: z.string().nullable(),
2966
- sandboxId: z.string().nullable(),
3409
+ environmentId: z.string().nullable(),
2967
3410
  createdAt: z.string().nullable(),
2968
3411
  lastEventAt: z.string().nullable(),
2969
3412
  }).strict();
@@ -3005,6 +3448,11 @@ export const SessionUsageTotalsSchema = z
3005
3448
  export const ModelCallSchema = z
3006
3449
  .object({
3007
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(),
3008
3456
  sessionId: z.string(),
3009
3457
  turnId: z.string(),
3010
3458
  agentId: z.string(),
@@ -3034,6 +3482,73 @@ export const ModelCallExportPageSchema = z
3034
3482
  asOf: z.string(),
3035
3483
  })
3036
3484
  .strict();
3037
- export const SandboxPageSchema = z
3038
- .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() })
3039
3554
  .strict();