@nylorun/core 0.8.0-beta → 0.10.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 (41) hide show
  1. package/CHANGELOG.md +258 -0
  2. package/dist/compatibility.d.ts +58 -6
  3. package/dist/compatibility.js +82 -9
  4. package/dist/contracts.d.ts +2335 -377
  5. package/dist/contracts.js +1225 -173
  6. package/dist/define.d.ts +5 -5
  7. package/dist/define.js +3 -2
  8. package/dist/definition/assemble.js +15 -20
  9. package/dist/definition/bind-tool.js +1 -0
  10. package/dist/definition/bound.d.ts +2 -0
  11. package/dist/definition/builder.d.ts +4 -10
  12. package/dist/definition/builder.js +2 -26
  13. package/dist/definition/declaration.js +6 -2
  14. package/dist/definition/flow/compile.d.ts +0 -2
  15. package/dist/definition/flow/compile.js +1 -29
  16. package/dist/definition/flow/types.d.ts +1 -3
  17. package/dist/definition/model-failure.d.ts +4 -0
  18. package/dist/definition/model-failure.js +23 -0
  19. package/dist/definition/sandbox-capability.d.ts +12 -0
  20. package/dist/definition/sandbox-capability.js +33 -0
  21. package/dist/definition/schema.js +3 -0
  22. package/dist/definition/workflow/build.d.ts +3 -13
  23. package/dist/definition/workflow/build.js +3 -25
  24. package/dist/definition/workflow/chain.js +0 -1
  25. package/dist/definition/workflow/loop.js +0 -2
  26. package/dist/definition/workflow/map.js +0 -1
  27. package/dist/definition/workflow/parallel.js +0 -1
  28. package/dist/definition/workflow/runnable.d.ts +0 -4
  29. package/dist/definition/workflow/runnable.js +0 -34
  30. package/dist/definition/workflow/switch.js +0 -2
  31. package/dist/errors.d.ts +3 -1
  32. package/dist/types/middleware.d.ts +1 -3
  33. package/dist/types/model.d.ts +34 -1
  34. package/dist/types/observe.d.ts +7 -1
  35. package/dist/types/tool.d.ts +6 -0
  36. package/dist/types/transcript.d.ts +14 -1
  37. package/dist/utils/sandbox.d.ts +0 -4
  38. package/dist/utils/sandbox.js +0 -16
  39. package/package.json +1 -1
  40. package/dist/definition/sandbox.d.ts +0 -29
  41. package/dist/definition/sandbox.js +0 -93
package/dist/contracts.js CHANGED
@@ -5,19 +5,22 @@ import { hookListIssue } from "./definition/hooks.js";
5
5
  import { DELEGATE_INPUT_SCHEMA } from "./definition/delegate.js";
6
6
  import { canonical } from "./utils/canonical.js";
7
7
  export { PROTOCOL_VERSION, ERROR_CODES } from "./compatibility.js";
8
- import { DERIVED_PRINCIPAL_ID_PATTERN } from "./compatibility.js";
9
8
  import { ERROR_CODES } from "./compatibility.js";
10
9
  export const RequestIdSchema = z.string().min(1);
11
10
  export const IdempotencyKeySchema = z.string().min(1).max(256);
12
11
  const jsonObject = z.record(z.string(), z.unknown());
13
- const jsonValue = z.lazy(() => z.union([
12
+ // Recursive schemas carry an `id`: a document generated from them (the Runtime's OpenAPI)
13
+ // refers back to the named schema instead of expanding it forever.
14
+ const jsonValue = z
15
+ .lazy(() => z.union([
14
16
  z.string(),
15
17
  z.number(),
16
18
  z.boolean(),
17
19
  z.null(),
18
20
  z.array(jsonValue),
19
21
  z.record(z.string(), jsonValue),
20
- ]));
22
+ ]))
23
+ .meta({ id: "JsonValue" });
21
24
  const mcpServerSchema = z.discriminatedUnion("type", [
22
25
  z
23
26
  .object({
@@ -94,6 +97,7 @@ const toolManifestSchema = z
94
97
  outputSchema: jsonObject.optional(),
95
98
  agent: z
96
99
  .lazy(() => z.union([workflowV2ManifestSchema, AgentManifestSchema]))
100
+ .meta({ id: "ToolAgentManifest" })
97
101
  .optional(),
98
102
  })
99
103
  .strict();
@@ -348,7 +352,7 @@ const workflowNodeSchema = z.lazy(() => z.union([
348
352
  .strict(),
349
353
  })
350
354
  .strict(),
351
- ]));
355
+ ])).meta({ id: "WorkflowNode" });
352
356
  const workflowV1ManifestSchema = z
353
357
  .object({
354
358
  kind: z.literal("workflow"),
@@ -426,7 +430,7 @@ const workflowNodeV2Schema = z.lazy(() => z.union([
426
430
  ...workflowNodeOptionsV2,
427
431
  })
428
432
  .strict(),
429
- ]));
433
+ ])).meta({ id: "WorkflowNodeV2" });
430
434
  const workflowV2ManifestSchema = z.lazy(() => z
431
435
  .object({
432
436
  kind: z.literal("workflow"),
@@ -459,7 +463,7 @@ const workflowV2ManifestSchema = z.lazy(() => z
459
463
  message: `Embedded agent '${agent.id}' must be keyed by its id`,
460
464
  });
461
465
  }
462
- }));
466
+ })).meta({ id: "WorkflowV2Manifest" });
463
467
  function referencedAgents(node) {
464
468
  const out = [];
465
469
  const visit = (child) => {
@@ -510,6 +514,40 @@ export const CredentialSelectionSchema = z
510
514
  credentialId: z.string().min(1),
511
515
  })
512
516
  .strict();
517
+ const sandboxHostSchema = z.string().refine(isSandboxHostPattern, {
518
+ message: "network.allow entries must be host names such as api.github.com or *.example.com",
519
+ });
520
+ const sandboxResourcesSchema = z
521
+ .object({
522
+ cpus: z.number().int().min(1).max(64).optional(),
523
+ memory: z
524
+ .string()
525
+ .refine((value) => parseSandboxSize(value) !== undefined, {
526
+ message: "resources.memory must be a size such as 512MiB or 2GiB",
527
+ })
528
+ .optional(),
529
+ })
530
+ .strict();
531
+ /**
532
+ * A sandbox defined when a session is opened. No `network.allow` means no egress. The Runtime
533
+ * checks it against the Tenant's limits and pins the result on the session.
534
+ */
535
+ export const SandboxInlineRequestSchema = z
536
+ .object({
537
+ image: z.string().min(1).optional(),
538
+ network: z.object({ allow: z.array(sandboxHostSchema).optional() }).strict().optional(),
539
+ resources: sandboxResourcesSchema.optional(),
540
+ })
541
+ .strict();
542
+ /**
543
+ * `PutSessionRequest.sandbox`: `false` for none, `{ session }` to share another session's
544
+ * sandbox, or an inline sandbox. Omitted means the Tenant's default.
545
+ */
546
+ export const SandboxRequestSchema = z.union([
547
+ z.literal(false),
548
+ z.object({ session: z.string().min(1) }).strict(),
549
+ SandboxInlineRequestSchema,
550
+ ]);
513
551
  export const PutSessionRequestSchema = z
514
552
  .object({
515
553
  requestId: RequestIdSchema,
@@ -518,10 +556,44 @@ export const PutSessionRequestSchema = z
518
556
  info: jsonObject.optional(),
519
557
  vaultIds: z.array(z.string().min(1)).optional(),
520
558
  credentialSelections: z.array(CredentialSelectionSchema).optional(),
521
- /** Share another session's sandbox (same owner, Tenant, and identical specs). */
522
- sandbox: z.object({ session: z.string().min(1) }).strict().optional(),
559
+ /** The session's sandbox; see `SandboxRequestSchema`. Fixed once the session exists. */
560
+ sandbox: SandboxRequestSchema.optional(),
561
+ })
562
+ .strict();
563
+ /**
564
+ * A Tenant's sandbox configuration (Tenant setting `sandbox.config`): what a session gets when
565
+ * it names no sandbox, and the limits every session's sandbox must fit.
566
+ */
567
+ export const TenantSandboxConfigSchema = z
568
+ .object({
569
+ /** `none` (the default when unset), `virtual`, or an inline sandbox. */
570
+ default: z
571
+ .union([z.literal("none"), z.literal("virtual"), SandboxInlineRequestSchema])
572
+ .optional(),
573
+ limits: z
574
+ .object({
575
+ /** Hosts a sandbox may allow. Default: package registries and code hosts. */
576
+ network: z.array(sandboxHostSchema).optional(),
577
+ /** The most a session may ask for. */
578
+ resources: sandboxResourcesSchema.optional(),
579
+ /** What a session gets when it asks for nothing. */
580
+ defaultResources: sandboxResourcesSchema.optional(),
581
+ /** Stop compute after this long without use. */
582
+ idle: z
583
+ .string()
584
+ .refine((value) => parseSandboxDuration(value) !== undefined, {
585
+ message: "idle must be a duration such as 30s, 15m or 1h",
586
+ })
587
+ .optional(),
588
+ })
589
+ .strict()
590
+ .optional(),
523
591
  })
524
592
  .strict();
593
+ /** `PUT /v1/tenant/sandbox`: replaces the Tenant's sandbox configuration. */
594
+ export const PutTenantSandboxRequestSchema = TenantSandboxConfigSchema.extend({
595
+ requestId: RequestIdSchema.optional(),
596
+ }).strict();
525
597
  const vaultWriteBase = {
526
598
  requestId: RequestIdSchema,
527
599
  idempotencyKey: IdempotencyKeySchema,
@@ -601,12 +673,26 @@ export const RotateCredentialRequestSchema = z
601
673
  ]),
602
674
  })
603
675
  .strict();
676
+ /**
677
+ * What the Runtime cannot learn from a custom OpenAI-compatible endpoint (Model Calls §7):
678
+ * its context window and output limit, whether it reasons, and pi-ai `compat` settings
679
+ * (`thinkingFormat`, `thinkingTokenBudgetField`, `chatTemplateKwargs`, …).
680
+ */
681
+ export const CustomModelSettingsSchema = z
682
+ .object({
683
+ contextWindow: z.number().int().min(1024).optional(),
684
+ maxTokens: z.number().int().min(1).optional(),
685
+ reasoning: z.boolean().optional(),
686
+ compat: z.record(z.string(), z.unknown()).optional(),
687
+ })
688
+ .strict();
604
689
  export const PutHostModelRequestSchema = z
605
690
  .object({
606
691
  ...vaultWriteBase,
607
692
  provider: z.string().min(1),
608
693
  model: z.string().min(1),
609
694
  baseUrl: z.string().min(1).optional(),
695
+ settings: CustomModelSettingsSchema.optional(),
610
696
  auth: z.discriminatedUnion("type", [
611
697
  z
612
698
  .object({
@@ -634,6 +720,27 @@ export const SelectHostModelRequestSchema = z
634
720
  baseUrl: z.string().min(1).optional(),
635
721
  })
636
722
  .strict();
723
+ export const VaultInfoSchema = z
724
+ .object({
725
+ id: z.string(),
726
+ name: z.string(),
727
+ ownerUserId: z.string(),
728
+ metadata: z.record(z.string(), z.string()).optional(),
729
+ createdAt: z.string(),
730
+ })
731
+ .strict();
732
+ export const CredentialInfoSchema = z
733
+ .object({
734
+ id: z.string(),
735
+ vaultId: z.string(),
736
+ name: z.string(),
737
+ type: z.enum(["bearer", "oauth"]),
738
+ binding: z.object({ url: z.string() }).strict(),
739
+ expiresAt: z.string().optional(),
740
+ createdAt: z.string(),
741
+ rotatedAt: z.string().optional(),
742
+ })
743
+ .strict();
637
744
  const commandBase = {
638
745
  requestId: RequestIdSchema,
639
746
  idempotencyKey: IdempotencyKeySchema,
@@ -665,16 +772,6 @@ export const ActionOutcomeSchema = z
665
772
  statePatch: jsonObject.optional(),
666
773
  })
667
774
  .strict();
668
- export const ActionResultCommandSchema = z
669
- .object({
670
- ...commandBase,
671
- type: z.literal("action_result"),
672
- actionId: z.string().min(1),
673
- claimId: z.string().min(1),
674
- generation: z.number().int().positive(),
675
- outcome: ActionOutcomeSchema,
676
- })
677
- .strict();
678
775
  export const SessionCommandSchema = z.union([
679
776
  MessageEventBodySchema,
680
777
  z
@@ -700,24 +797,79 @@ export const SessionCommandSchema = z.union([
700
797
  reason: z.string().optional(),
701
798
  })
702
799
  .strict(),
703
- ActionResultCommandSchema,
704
800
  ]);
705
801
  export const SessionEventBodySchema = SessionCommandSchema;
706
- export const LiveEventSchema = z
707
- .object({
802
+ /** The envelope every session event carries (`nylorun.event/2`, Durable Streams §9.5). */
803
+ export const EVENT_SCHEMA = "nylorun.event/2";
804
+ /** Who wrote an event. v1 writes `loop` (the engine) and `api` (commands and results). */
805
+ export const EventSourceKindSchema = z.enum([
806
+ "model-gate",
807
+ "tool-gate",
808
+ "egress-gate",
809
+ "sandboxd",
810
+ "edge",
811
+ "init",
812
+ "controller",
813
+ "loop",
814
+ "supervisor",
815
+ "harness",
816
+ "evidence",
817
+ "operator",
818
+ "human",
819
+ "api",
820
+ ]);
821
+ /** How far an event can be trusted, by who could forge it. v1 writes `observed` only. */
822
+ export const EvidenceClassSchema = z.enum([
823
+ "observed",
824
+ "measured",
825
+ "attested",
826
+ "claimed",
827
+ "asserted",
828
+ ]);
829
+ /**
830
+ * The envelope fields. Not strict: a client strips fields it does not know, so the envelope
831
+ * can grow without a protocol bump.
832
+ */
833
+ const eventEnvelope = {
834
+ schema: z.literal(EVENT_SCHEMA),
708
835
  eventId: z.string(),
709
- sessionId: z.string(),
710
836
  tenantId: z.string().min(1),
837
+ sessionId: z.string(),
838
+ /** The run the event belongs to; null until runs exist. */
839
+ runId: z.string().nullable(),
711
840
  turnId: z.string().nullable(),
841
+ /** The session's restore incarnation; 0 until restores exist. */
842
+ incarnation: z.number().int().nonnegative(),
843
+ /** The session's ownership epoch when the event was written. */
844
+ epoch: z.number().int().nonnegative(),
845
+ /** Position in the session's log, from 0, in commit order. */
846
+ seq: z.number().int().nonnegative(),
847
+ /** `base64url(sessionId:seq)`: resume from here with `Last-Event-ID` or `?cursor=`. */
712
848
  cursor: z.string(),
713
- createdAt: z.string(),
714
- type: z.string(),
849
+ /** When the event was written (ISO 8601). */
850
+ time: z.string(),
851
+ /** The version of the event type's payload schema. */
852
+ schemaVersion: z.number().int().positive(),
853
+ source: z.object({ kind: EventSourceKindSchema, id: z.string() }),
854
+ evidence: EvidenceClassSchema,
855
+ trace: z
856
+ .object({
857
+ traceId: z.string(),
858
+ spanId: z.string(),
859
+ parentSpanId: z.string().optional(),
860
+ })
861
+ .optional(),
862
+ visibility: z.enum(["public", "internal", "restricted"]),
863
+ retention: z.enum(["full", "metadata"]),
864
+ };
865
+ /**
866
+ * Any session event: the envelope with an open `type` and `payload`. Clients read an event of
867
+ * a type they do not know as this; `SessionEventSchema` types the known ones.
868
+ */
869
+ export const LiveEventSchema = z.object({
870
+ ...eventEnvelope,
871
+ type: z.string().min(1),
715
872
  payload: z.unknown(),
716
- })
717
- .strict();
718
- export const SessionItemsResponseSchema = z.object({
719
- items: z.array(LiveEventSchema),
720
- cursor: z.string().nullable(),
721
873
  });
722
874
  export const AcceptedResponseSchema = z.object({
723
875
  status: z.literal("accepted"),
@@ -750,10 +902,12 @@ const actionBase = {
750
902
  implementationVersion: z.string(),
751
903
  input: z.unknown(),
752
904
  context: jsonObject,
753
- status: z.enum(["pending", "claimed", "completed", "uncertain", "cancelled"]),
905
+ /** `delivering`: sent to the agent's Action endpoint, not answered yet. */
906
+ status: z.enum(["pending", "delivering", "completed", "uncertain", "cancelled"]),
907
+ /** How many times it was delivered; a delivery token names the one it is for. */
754
908
  generation: z.number().int().nonnegative(),
755
- claimId: z.string().nullable(),
756
- leaseExpiresAt: z.string().nullable(),
909
+ /** When an unanswered delivery counts as lost. Set only while `delivering`. */
910
+ deadlineAt: z.string().nullable().optional(),
757
911
  agent: AgentRefSchema.optional(),
758
912
  };
759
913
  /** The hook point an action runs, and the capabilities that registered it (manifest order). */
@@ -817,7 +971,7 @@ export const ActionSchema = z.union([
817
971
  ]);
818
972
  /**
819
973
  * Transcript events (Host feature `transcript-events`): the log entries a chat UI
820
- * renders. `LiveEvent.payload` stays `unknown` on the wire; `parseTranscriptEvent`
974
+ * renders. They are part of the event catalog (`EVENT_CATALOG`); `parseTranscriptEvent`
821
975
  * types the ones a client reads. Objects pass unknown fields through, so a newer
822
976
  * Host can add fields without breaking older clients.
823
977
  */
@@ -828,11 +982,20 @@ const toolIds = {
828
982
  /** The harness invocation of the call; interactions refer to it. */
829
983
  invocationId: z.string().min(1),
830
984
  };
831
- /** `message.assistant`: one completed model step. `invocationId` is the model call's. */
985
+ /**
986
+ * `message.assistant`: one completed model step. `invocationId` is the model call's.
987
+ * `model`, `finishReason` and `usage` are present when the provider reported them.
988
+ */
832
989
  export const AssistantMessagePayloadSchema = z
833
990
  .object({
834
991
  invocationId: z.string().min(1),
835
992
  text: z.string(),
993
+ model: z
994
+ .object({ provider: z.string(), model: z.string() })
995
+ .passthrough()
996
+ .optional(),
997
+ finishReason: z.string().optional(),
998
+ usage: z.record(z.string(), z.number()).optional(),
836
999
  toolCalls: z.array(z
837
1000
  .object({
838
1001
  callId: z.string().min(1),
@@ -843,6 +1006,32 @@ export const AssistantMessagePayloadSchema = z
843
1006
  ...eventAgent,
844
1007
  })
845
1008
  .passthrough();
1009
+ /**
1010
+ * `model.failed`: a model call that failed in a known way (Model Calls §6.4). The turn
1011
+ * then fails with `model.<code>`, or recovers.
1012
+ */
1013
+ export const ModelFailedPayloadSchema = z
1014
+ .object({
1015
+ invocationId: z.string().min(1).optional(),
1016
+ code: z.string().min(1),
1017
+ message: z.string(),
1018
+ retryable: z.boolean(),
1019
+ ...eventAgent,
1020
+ })
1021
+ .passthrough();
1022
+ /**
1023
+ * `context.compacted`: the engine summarized older history to fit the model's window
1024
+ * (Model Calls §8). Token counts are estimates.
1025
+ */
1026
+ export const ContextCompactedPayloadSchema = z
1027
+ .object({
1028
+ invocationId: z.string().min(1).optional(),
1029
+ trigger: z.enum(["threshold", "overflow"]),
1030
+ tokensBefore: z.number().int().nonnegative(),
1031
+ tokensAfter: z.number().int().nonnegative(),
1032
+ ...eventAgent,
1033
+ })
1034
+ .passthrough();
846
1035
  /** `tool.completed`: an MCP or sandbox tool the Runtime ran. `error` for a tool error. */
847
1036
  export const ToolCompletedPayloadSchema = z
848
1037
  .object({
@@ -859,6 +1048,9 @@ const actionEventBase = {
859
1048
  actionId: z.string().min(1),
860
1049
  kind: z.string(),
861
1050
  toolName: z.string().optional(),
1051
+ /** A workflow Action: its node's path and key. */
1052
+ path: z.string().optional(),
1053
+ key: z.string().optional(),
862
1054
  callId: z.string().optional(),
863
1055
  invocationId: z.string().optional(),
864
1056
  ...eventAgent,
@@ -913,6 +1105,8 @@ export const DelegationPayloadSchema = z
913
1105
  .passthrough();
914
1106
  const TRANSCRIPT_PAYLOADS = {
915
1107
  "message.assistant": AssistantMessagePayloadSchema,
1108
+ "model.failed": ModelFailedPayloadSchema,
1109
+ "context.compacted": ContextCompactedPayloadSchema,
916
1110
  "tool.completed": ToolCompletedPayloadSchema,
917
1111
  "action.pending": ActionPendingPayloadSchema,
918
1112
  "action.completed": ActionCompletedPayloadSchema,
@@ -926,68 +1120,226 @@ const TRANSCRIPT_PAYLOADS = {
926
1120
  "delegation.completed": DelegationPayloadSchema,
927
1121
  };
928
1122
  export const TRANSCRIPT_EVENT_TYPES = Object.keys(TRANSCRIPT_PAYLOADS);
929
- /** Types a transcript event's payload; `undefined` for other types or a malformed payload. */
930
- export function parseTranscriptEvent(event) {
931
- if (!Object.hasOwn(TRANSCRIPT_PAYLOADS, event.type))
932
- return undefined;
933
- const parsed = TRANSCRIPT_PAYLOADS[event.type].safeParse(event.payload);
934
- return parsed.success
935
- ? { ...event, payload: parsed.data }
936
- : undefined;
937
- }
938
- export const ActionClaimRequestSchema = z
1123
+ /** `command.message`: the message a client sent, as accepted. */
1124
+ export const CommandMessagePayloadSchema = z
939
1125
  .object({
940
- requestId: RequestIdSchema,
941
- implementationVersion: z.string().min(1),
1126
+ ...commandBase,
1127
+ type: z.literal("message"),
1128
+ content: z.string().optional(),
1129
+ data: jsonValue.optional(),
1130
+ /** The turn manifest the message carried, if any. */
1131
+ manifest: z.unknown().optional(),
942
1132
  })
943
- .strict();
944
- export const ActionHeartbeatRequestSchema = z
1133
+ .passthrough();
1134
+ /** `command.approve`: an answer to an approval interaction. */
1135
+ export const CommandApprovePayloadSchema = z
945
1136
  .object({
946
- requestId: RequestIdSchema,
947
- claimId: z.string().min(1),
1137
+ ...commandBase,
1138
+ type: z.literal("approve"),
1139
+ interactionId: z.string().min(1),
1140
+ approved: z.boolean(),
1141
+ })
1142
+ .passthrough();
1143
+ /** `command.respond`: an answer to an input interaction. */
1144
+ export const CommandRespondPayloadSchema = z
1145
+ .object({
1146
+ ...commandBase,
1147
+ type: z.literal("respond"),
1148
+ interactionId: z.string().min(1),
1149
+ value: z.unknown(),
1150
+ })
1151
+ .passthrough();
1152
+ /** `action.delivered`: the Runtime sent an Action to its endpoint. */
1153
+ export const ActionDeliveredPayloadSchema = z
1154
+ .object({
1155
+ actionId: z.string().min(1),
948
1156
  generation: z.number().int().positive(),
1157
+ ...eventAgent,
949
1158
  })
950
- .strict();
951
- export const ActionClaimResponseSchema = z.object({
952
- action: ActionSchema,
953
- claimId: z.string(),
1159
+ .passthrough();
1160
+ /** `action.delivery_failed`: a delivery did not reach its endpoint, or was refused; it is retried. */
1161
+ export const ActionDeliveryFailedPayloadSchema = z
1162
+ .object({
1163
+ actionId: z.string().min(1),
954
1164
  generation: z.number().int().positive(),
955
- leaseExpiresAt: z.string(),
956
- });
957
- export const ExecutorNotificationSchema = z.object({
958
- type: z.literal("work_available"),
959
- });
960
- export const ExecutorRegistrationSchema = z
1165
+ reason: z.string(),
1166
+ message: z.string().optional(),
1167
+ retryInMs: z.number().int().nonnegative(),
1168
+ })
1169
+ .passthrough();
1170
+ /** `sandbox.state`: the session's sandbox changed state. */
1171
+ export const SandboxStatePayloadSchema = z
961
1172
  .object({
962
- agentId: z.string().min(1),
963
- implementationVersion: z.string().min(1),
964
- manifestHash: z.string().min(1).optional(),
965
- token: z.string().min(16),
1173
+ state: z.enum(["creating", "running", "stopped"]),
1174
+ backend: z.string(),
1175
+ isolation: z.string().optional(),
1176
+ image: z.string().optional(),
1177
+ network: z.unknown().optional(),
1178
+ reattach: z.boolean().optional(),
1179
+ lost: z.boolean().optional(),
1180
+ note: z.string().optional(),
1181
+ error: z.string().optional(),
966
1182
  })
967
- .strict();
968
- export const RegisterExecutorsRequestSchema = z
1183
+ .passthrough();
1184
+ /** `sandbox.exec`: one sandbox tool call finished. */
1185
+ export const SandboxExecPayloadSchema = z
969
1186
  .object({
970
- executors: z.array(ExecutorRegistrationSchema).min(1).max(64),
1187
+ tool: z.string(),
1188
+ command: z.string().optional(),
1189
+ outcome: z.string(),
1190
+ code: z.string().optional(),
1191
+ durationMs: z.number().nonnegative(),
971
1192
  })
972
- .strict();
973
- export const RegisterExecutorsResponseSchema = z.object({
974
- executors: z.array(z.object({
975
- agentId: z.string(),
976
- implementationVersion: z.string(),
977
- rotated: z.boolean(),
978
- replacedBy: z.literal("different-credential").optional(),
979
- })),
980
- });
981
- export const ExecutorSummarySchema = z.object({
982
- agentId: z.string(),
983
- implementationVersion: z.string(),
1193
+ .passthrough();
1194
+ /** `node.started`: a workflow node that runs an Action started. */
1195
+ export const NodeStartedPayloadSchema = z
1196
+ .object({
1197
+ path: z.string(),
1198
+ kind: z.string(),
1199
+ key: z.string(),
1200
+ iterations: z.string().optional(),
1201
+ })
1202
+ .passthrough();
1203
+ /** `node.agent`: a workflow node runs as a linked agent session. */
1204
+ export const NodeAgentPayloadSchema = z
1205
+ .object({
1206
+ path: z.string(),
1207
+ iterations: z.string().optional(),
1208
+ sessionId: z.string(),
1209
+ turnId: z.string().nullable().optional(),
1210
+ })
1211
+ .passthrough();
1212
+ /** `loop.iteration`: a Loop started its `n`th agent turn. */
1213
+ export const LoopIterationPayloadSchema = z
1214
+ .object({
1215
+ path: z.string(),
1216
+ n: z.number().int(),
1217
+ sessionId: z.string().optional(),
1218
+ turnId: z.string().optional(),
984
1219
  manifestHash: z.string().optional(),
985
- connected: z.boolean(),
986
- updatedAt: z.string(),
987
- });
988
- export const ListExecutorsResponseSchema = z.object({
989
- executors: z.array(ExecutorSummarySchema),
1220
+ })
1221
+ .passthrough();
1222
+ /** `loop.verified`: a Loop's verifier judged iteration `n`. */
1223
+ export const LoopVerifiedPayloadSchema = z
1224
+ .object({
1225
+ path: z.string(),
1226
+ n: z.number().int(),
1227
+ pass: z.boolean(),
1228
+ feedback: z.string().optional(),
1229
+ data: z.unknown().optional(),
1230
+ })
1231
+ .passthrough();
1232
+ /** `loop.decided`: a Loop's decide step chose to iterate again (`input`) or finish (`output`). */
1233
+ export const LoopDecidedPayloadSchema = z
1234
+ .object({
1235
+ path: z.string(),
1236
+ n: z.number().int(),
1237
+ next: z.enum(["input", "output"]),
1238
+ patched: z.boolean(),
1239
+ })
1240
+ .passthrough();
1241
+ /**
1242
+ * `transcript.updated` (internal; blueprint P0.3): the own loop's model-facing transcript after a
1243
+ * settled segment, as an edit of the previous one: keep its first `keep` entries, then append
1244
+ * `entries`; the result has `length` entries. `keep` is 0 for a snapshot (after compaction, or
1245
+ * for a session written before transcripts were recorded). Large edits are split into
1246
+ * consecutive events, each appending to the last. Entries are the engine's `TranscriptEntry`
1247
+ * values, checked by the Runtime when it folds them. Never served to clients.
1248
+ */
1249
+ export const TranscriptUpdatedPayloadSchema = z
1250
+ .object({
1251
+ keep: z.number().int().nonnegative(),
1252
+ entries: z.array(z.unknown()),
1253
+ length: z.number().int().nonnegative(),
1254
+ })
1255
+ .passthrough();
1256
+ /**
1257
+ * The event catalog (Durable Streams §9.5): every session event type, its payload schema, its
1258
+ * payload schema version and who writes it. A type not listed here cannot be written. A type
1259
+ * with `visibility: "internal"` is recorded and folded by the Runtime but never served to
1260
+ * clients (SSE, history, AG-UI and A2A skip it).
1261
+ *
1262
+ * Evolution: new types and new optional payload fields are additive (clients ignore types
1263
+ * they do not know, and payloads pass unknown fields through). A breaking payload change is a
1264
+ * new type or a protocol version, never an edit in place.
1265
+ */
1266
+ export const EVENT_CATALOG = {
1267
+ "command.message": { payload: CommandMessagePayloadSchema, source: "api", version: 1 },
1268
+ "command.approve": { payload: CommandApprovePayloadSchema, source: "api", version: 1 },
1269
+ "command.respond": { payload: CommandRespondPayloadSchema, source: "api", version: 1 },
1270
+ "turn.completed": { payload: TurnCompletedPayloadSchema, source: "loop", version: 1 },
1271
+ "turn.paused": { payload: TurnPausedPayloadSchema, source: "loop", version: 1 },
1272
+ "turn.failed": { payload: TurnFailedPayloadSchema, source: "loop", version: 1 },
1273
+ "turn.cancelled": { payload: TurnCancelledPayloadSchema, source: "api", version: 1 },
1274
+ "message.assistant": { payload: AssistantMessagePayloadSchema, source: "loop", version: 1 },
1275
+ "model.failed": { payload: ModelFailedPayloadSchema, source: "loop", version: 1 },
1276
+ "context.compacted": { payload: ContextCompactedPayloadSchema, source: "loop", version: 1 },
1277
+ "tool.completed": { payload: ToolCompletedPayloadSchema, source: "loop", version: 1 },
1278
+ "action.pending": { payload: ActionPendingPayloadSchema, source: "loop", version: 1 },
1279
+ "action.delivered": { payload: ActionDeliveredPayloadSchema, source: "loop", version: 1 },
1280
+ "action.delivery_failed": {
1281
+ payload: ActionDeliveryFailedPayloadSchema,
1282
+ source: "loop",
1283
+ version: 1,
1284
+ },
1285
+ "action.completed": { payload: ActionCompletedPayloadSchema, source: "api", version: 1 },
1286
+ "action.uncertain": { payload: ActionUncertainPayloadSchema, source: "loop", version: 1 },
1287
+ "effect.uncertain": { payload: EffectUncertainPayloadSchema, source: "loop", version: 1 },
1288
+ "delegation.started": { payload: DelegationPayloadSchema, source: "loop", version: 1 },
1289
+ "delegation.completed": { payload: DelegationPayloadSchema, source: "loop", version: 1 },
1290
+ "sandbox.state": { payload: SandboxStatePayloadSchema, source: "loop", version: 1 },
1291
+ "sandbox.exec": { payload: SandboxExecPayloadSchema, source: "loop", version: 1 },
1292
+ "node.started": { payload: NodeStartedPayloadSchema, source: "loop", version: 1 },
1293
+ "node.agent": { payload: NodeAgentPayloadSchema, source: "loop", version: 1 },
1294
+ "loop.iteration": { payload: LoopIterationPayloadSchema, source: "loop", version: 1 },
1295
+ "loop.verified": { payload: LoopVerifiedPayloadSchema, source: "api", version: 1 },
1296
+ "loop.decided": { payload: LoopDecidedPayloadSchema, source: "api", version: 1 },
1297
+ "transcript.updated": {
1298
+ payload: TranscriptUpdatedPayloadSchema,
1299
+ source: "loop",
1300
+ version: 1,
1301
+ visibility: "internal",
1302
+ },
1303
+ };
1304
+ export const EVENT_TYPES = Object.keys(EVENT_CATALOG);
1305
+ export function isEventType(type) {
1306
+ return Object.hasOwn(EVENT_CATALOG, type);
1307
+ }
1308
+ function eventSchema(type) {
1309
+ return z.object({
1310
+ ...eventEnvelope,
1311
+ type: z.literal(type),
1312
+ payload: EVENT_CATALOG[type].payload,
1313
+ });
1314
+ }
1315
+ /** One schema per event type, keyed by type (the OpenAPI components). */
1316
+ export const EVENT_SCHEMAS = Object.fromEntries(EVENT_TYPES.map((type) => [type, eventSchema(type)]));
1317
+ /** A session event of a known type, discriminated on `type`. */
1318
+ export const SessionEventSchema = z.discriminatedUnion("type", EVENT_TYPES.map((type) => EVENT_SCHEMAS[type]));
1319
+ /**
1320
+ * Reads one event from the wire: typed when its type is in the catalog and it matches, else
1321
+ * the bare envelope (a newer Runtime's type, which a client ignores). Throws only when even
1322
+ * the envelope does not match.
1323
+ */
1324
+ export function parseSessionEvent(value) {
1325
+ const known = SessionEventSchema.safeParse(value);
1326
+ if (known.success)
1327
+ return known.data;
1328
+ return LiveEventSchema.parse(value);
1329
+ }
1330
+ export const SessionItemsResponseSchema = z.object({
1331
+ items: z.array(SessionEventSchema),
1332
+ cursor: z.string().nullable(),
990
1333
  });
1334
+ /** Types a transcript event's payload; `undefined` for other types or a malformed payload. */
1335
+ export function parseTranscriptEvent(event) {
1336
+ if (!Object.hasOwn(TRANSCRIPT_PAYLOADS, event.type))
1337
+ return undefined;
1338
+ const parsed = TRANSCRIPT_PAYLOADS[event.type].safeParse(event.payload);
1339
+ return parsed.success
1340
+ ? { ...event, payload: parsed.data }
1341
+ : undefined;
1342
+ }
991
1343
  export const ProtocolRangeSchema = z
992
1344
  .object({
993
1345
  min: z.number().int(),
@@ -1027,71 +1379,13 @@ export const TenantEnvelopeSchema = z
1027
1379
  schemaVersion: z.number().int(),
1028
1380
  })
1029
1381
  .strict();
1030
- export const CreateTenantRequestSchema = z
1031
- .object({
1032
- tenantId: z.string().min(1),
1033
- name: z.string().min(1),
1034
- /** `studio` is reserved for the derived Studio principal. */
1035
- principalId: z
1036
- .string()
1037
- .min(1)
1038
- .refine((id) => id !== "studio", "principalId `studio` is reserved"),
1039
- credentialHash: z.string().regex(/^[0-9a-f]{64}$/),
1040
- idempotencyKey: IdempotencyKeySchema,
1041
- /** SHA-256 of the derived Studio key; registers principal `studio` (feature `studio-principal`). */
1042
- studioCredentialHash: z
1043
- .string()
1044
- .regex(/^[0-9a-f]{64}$/)
1045
- .optional(),
1046
- /**
1047
- * SHA-256 of each derived principal's key (feature `derived-principals`): application
1048
- * principals whose keys the admin key derives, so their clients store no key.
1049
- */
1050
- derivedPrincipals: z
1051
- .array(z
1052
- .object({
1053
- id: z
1054
- .string()
1055
- .regex(DERIVED_PRINCIPAL_ID_PATTERN)
1056
- .refine((id) => id !== "studio", "principal id `studio` is reserved"),
1057
- credentialHash: z.string().regex(/^[0-9a-f]{64}$/),
1058
- })
1059
- .strict())
1060
- .max(16)
1061
- .optional(),
1062
- })
1063
- .strict()
1064
- .superRefine((body, ctx) => {
1065
- const ids = new Set([body.principalId]);
1066
- const hashes = new Set([body.credentialHash]);
1067
- if (body.studioCredentialHash)
1068
- hashes.add(body.studioCredentialHash);
1069
- for (const [index, principal] of (body.derivedPrincipals ?? []).entries()) {
1070
- if (ids.has(principal.id))
1071
- ctx.addIssue({
1072
- code: "custom",
1073
- path: ["derivedPrincipals", index, "id"],
1074
- message: `Principal id ${principal.id} is used twice`,
1075
- });
1076
- if (hashes.has(principal.credentialHash))
1077
- ctx.addIssue({
1078
- code: "custom",
1079
- path: ["derivedPrincipals", index, "credentialHash"],
1080
- message: "Every principal needs its own credential",
1081
- });
1082
- ids.add(principal.id);
1083
- hashes.add(principal.credentialHash);
1084
- }
1085
- });
1086
- export const AdminTenantSchema = z
1087
- .object({
1088
- id: z.string().min(1),
1089
- name: z.string().nullable(),
1090
- state: z.enum(["open", "quarantined"]),
1091
- envelope: TenantEnvelopeSchema.nullable(),
1092
- })
1093
- .strict();
1094
- export const QuarantineSchema = z
1382
+ /**
1383
+ * Why a Host's Tenant is not open (`HostTenant.cause`): it could not be opened, and the Host
1384
+ * fails readiness until the cause is repaired and the Host restarted. `database-layout-old`:
1385
+ * the database was written by a Runtime from before one Tenant per installation; this release
1386
+ * starts fresh on a new database.
1387
+ */
1388
+ export const TenantCauseSchema = z
1095
1389
  .object({
1096
1390
  code: z.enum([
1097
1391
  "kek-missing",
@@ -1101,24 +1395,53 @@ export const QuarantineSchema = z
1101
1395
  "envelope-invalid",
1102
1396
  "open-timeout",
1103
1397
  "open-failed",
1398
+ "database-layout-old",
1104
1399
  ]),
1105
1400
  message: z.string(),
1106
1401
  repair: z.string(),
1107
1402
  })
1108
1403
  .strict();
1109
- export const AdminTenantStatusSchema = AdminTenantSchema.extend({
1110
- quarantine: QuarantineSchema.optional(),
1111
- });
1404
+ /**
1405
+ * The Host's one Tenant, as `/v1/admin/status` reports it. `unavailable` while it opens, when
1406
+ * opening it failed (`cause`), or when it is closing.
1407
+ */
1408
+ export const HostTenantSchema = z
1409
+ .object({
1410
+ /** Null until the Tenant row has been read (an old or newer database). */
1411
+ id: z.string().min(1).nullable(),
1412
+ name: z.string().nullable(),
1413
+ state: z.enum(["open", "unavailable"]),
1414
+ envelope: TenantEnvelopeSchema.nullable(),
1415
+ cause: TenantCauseSchema.optional(),
1416
+ })
1417
+ .strict();
1418
+ /** A stream relay's state (Durable Streams §7). */
1419
+ export const StreamRelayStatusSchema = z
1420
+ .object({
1421
+ /** This process holds the replication slot (one process per slot does). */
1422
+ active: z.boolean(),
1423
+ /** Committed transactions not yet fully in S2. */
1424
+ pendingTxs: z.number().int().nonnegative(),
1425
+ /** Events queued for S2. */
1426
+ pendingRows: z.number().int().nonnegative(),
1427
+ /** The last position acknowledged to the slot. */
1428
+ confirmed: z.string().nullable(),
1429
+ /** Reconciliations of the record with S2 since start (a new or lost slot). */
1430
+ reconciliations: z.number().int().nonnegative(),
1431
+ lastError: z.string().nullable(),
1432
+ /** WAL bytes the slot holds that the relay has not confirmed, when known. */
1433
+ lagBytes: z.number().nonnegative().optional(),
1434
+ })
1435
+ .strict();
1112
1436
  export const HostAggregateSchema = z
1113
1437
  .object({
1114
1438
  runningSessions: z.number().int().nonnegative(),
1115
- connectedExecutors: z.number().int().nonnegative(),
1439
+ /** Deliveries to Action endpoints in flight on this Host. */
1440
+ inFlightDeliveries: z.number().int().nonnegative(),
1116
1441
  pendingActions: z.number().int().nonnegative(),
1117
1442
  uncertainEffects: z.number().int().nonnegative(),
1118
- /** Events committed but not yet relayed to Durable Streams, over the open Tenants. */
1119
- outboxDepth: z.number().int().nonnegative().optional(),
1120
- /** The largest relay lag of an open Tenant: its oldest unrelayed event's age. */
1121
- relayLagMs: z.number().nonnegative().optional(),
1443
+ /** This process's stream relay, when it runs one (a Host with S2). */
1444
+ relay: StreamRelayStatusSchema.optional(),
1122
1445
  })
1123
1446
  .strict();
1124
1447
  export const AdminHostStatusSchema = z
@@ -1128,7 +1451,7 @@ export const AdminHostStatusSchema = z
1128
1451
  pid: z.number().int(),
1129
1452
  version: z.string().min(1),
1130
1453
  protocol: ProtocolRangeSchema,
1131
- tenants: z.array(AdminTenantSchema),
1454
+ tenant: HostTenantSchema,
1132
1455
  aggregate: HostAggregateSchema,
1133
1456
  })
1134
1457
  .strict();
@@ -1138,7 +1461,8 @@ export const AdminStatusSchema = z
1138
1461
  service: z.string().min(1),
1139
1462
  version: z.string().min(1),
1140
1463
  protocol: ProtocolRangeSchema,
1141
- tenants: z.array(AdminTenantSchema),
1464
+ /** The Tenant this installation serves. */
1465
+ tenant: HostTenantSchema,
1142
1466
  aggregate: HostAggregateSchema,
1143
1467
  host: z
1144
1468
  .object({
@@ -1150,12 +1474,20 @@ export const AdminStatusSchema = z
1150
1474
  .optional(),
1151
1475
  })
1152
1476
  .strict();
1477
+ /**
1478
+ * `.nylorun/link.json`: the installation a Project uses. Format 2 (one Tenant per
1479
+ * installation) names the local `stack` that `nylorun start` created or attached; `tenantId`
1480
+ * is information only, since nothing in a request selects a Tenant. Formats 0 and 1 named a
1481
+ * Tenant on a multi-Tenant Host of an older Runtime.
1482
+ */
1153
1483
  export const ProjectLinkFileSchema = z
1154
1484
  .object({
1155
- format: z.union([z.literal(0), z.literal(1)]).default(0),
1485
+ format: z.union([z.literal(0), z.literal(1), z.literal(2)]).default(0),
1486
+ /** The local stack's name (format 2); absent for an installation that is not a stack. */
1487
+ stack: z.string().min(1).optional(),
1156
1488
  hostUrl: z.string().min(1),
1157
1489
  hostId: z.string().min(1),
1158
- tenantId: z.string().min(1),
1490
+ tenantId: z.string().min(1).optional(),
1159
1491
  })
1160
1492
  .passthrough();
1161
1493
  export const ProjectCredentialsFileSchema = z
@@ -1174,6 +1506,7 @@ export const HostModelViewSchema = z.union([
1174
1506
  model: z.string(),
1175
1507
  authType: z.enum(["api_key", "oauth"]),
1176
1508
  baseUrl: z.string().optional(),
1509
+ settings: CustomModelSettingsSchema.optional(),
1177
1510
  })
1178
1511
  .strict(),
1179
1512
  ]);
@@ -1186,7 +1519,7 @@ export const TenantStatusSchema = z
1186
1519
  store: z.boolean(),
1187
1520
  scheduler: z.boolean(),
1188
1521
  model: z.boolean(),
1189
- executors: z.boolean(),
1522
+ endpoints: z.boolean(),
1190
1523
  schema: z.boolean(),
1191
1524
  })
1192
1525
  .strict(),
@@ -1195,7 +1528,8 @@ export const TenantStatusSchema = z
1195
1528
  .object({
1196
1529
  agentId: z.string(),
1197
1530
  registered: z.boolean(),
1198
- connected: z.boolean(),
1531
+ /** The agent has a registered Action endpoint. */
1532
+ endpoint: z.boolean(),
1199
1533
  })
1200
1534
  .strict()),
1201
1535
  counts: z
@@ -1249,14 +1583,10 @@ export const TenantStatusSchema = z
1249
1583
  lastError: z.string().nullable(),
1250
1584
  })
1251
1585
  .strict(),
1252
- outbox: z
1253
- .object({
1254
- depth: z.number().int().nonnegative(),
1255
- oldestAgeMs: z.number().nonnegative().nullable(),
1256
- })
1257
- .strict(),
1258
- relayLagMs: z.number().nonnegative(),
1259
- collectionPending: z.boolean(),
1586
+ /** The basin generation session streams are in (a reset moves to the next). */
1587
+ generation: z.number().int().nonnegative(),
1588
+ /** The Tenant's own relay; null when the Host's relay serves it. */
1589
+ relay: StreamRelayStatusSchema.nullable(),
1260
1590
  })
1261
1591
  .strict()
1262
1592
  .optional(),
@@ -1271,14 +1601,16 @@ export const SeedTenantConfigRequestSchema = z
1271
1601
  requestId: RequestIdSchema,
1272
1602
  sandbox: z
1273
1603
  .object({
1274
- backend: z.enum(["auto", "virtual"]),
1604
+ backend: z.enum(["auto", "virtual"]).optional(),
1605
+ /** Seeds Tenant setting `sandbox.config` when it is absent. */
1606
+ config: TenantSandboxConfigSchema.optional(),
1275
1607
  })
1276
1608
  .strict()
1277
1609
  .optional(),
1278
1610
  model: seedModelSchema.optional(),
1279
1611
  /**
1280
1612
  * The Tenant's model calls use the Runtime's deterministic fixture model instead of its
1281
- * host model, e.g. for a temporary test Tenant (scripts/lib/temporary-tenant.mjs). Stored
1613
+ * host model, e.g. for the stack Tenant a smoke check resets (scripts/lib/stack-tenant.mjs). Stored
1282
1614
  * as Tenant setting `model.fixture`. Host feature `tenant-fixture-model`.
1283
1615
  */
1284
1616
  fixtureModel: z.literal(true).optional(),
@@ -1313,6 +1645,12 @@ export const SUBJECT_SCOPES = [
1313
1645
  const SUBJECT_PATTERN = /^[\x21-\x7e](?:[\x20-\x7e]{0,198}[\x21-\x7e])?$/;
1314
1646
  /** Owner ids the Runtime uses itself: the host model's vault is owned by `host`. */
1315
1647
  const RESERVED_SUBJECTS = new Set(["host"]);
1648
+ /** A valid subject: 1–200 visible ASCII characters, not reserved by the Runtime. */
1649
+ export function isSubject(value) {
1650
+ return (typeof value === "string" &&
1651
+ SUBJECT_PATTERN.test(value) &&
1652
+ !RESERVED_SUBJECTS.has(value));
1653
+ }
1316
1654
  /**
1317
1655
  * Validates `Nylorun-Subject` and `Nylorun-Scopes`. Returns the subject and its scopes, or a
1318
1656
  * message naming what is wrong. Scopes are required: the Runtime never grants a default.
@@ -1340,3 +1678,717 @@ export function parseSubjectHeaders(subject, scopes) {
1340
1678
  scopes: new Set(names),
1341
1679
  };
1342
1680
  }
1681
+ // --- subject tokens and the access policy (Host feature `subject-tokens`) ------------------
1682
+ /** Scopes a subject token may carry: never `agents:write` or `tenant:settings`. */
1683
+ export const TOKEN_SCOPES = ["agents:read", "sessions:own", "vaults:own"];
1684
+ const TokenScopeSchema = z.enum(TOKEN_SCOPES);
1685
+ /** The JWT `typ` of a subject token (RFC 8725 explicit typing). */
1686
+ export const SUBJECT_TOKEN_TYPE = "nylorun-subject+jwt";
1687
+ /** The `aud` of every subject token. */
1688
+ export const SUBJECT_TOKEN_AUDIENCE = "nylorun";
1689
+ /** The `iss` of a Tenant's subject tokens. */
1690
+ export function subjectTokenIssuer(tenantId) {
1691
+ return `urn:nylorun:tenant:${tenantId}`;
1692
+ }
1693
+ /** Token lifetimes, in seconds. */
1694
+ export const TOKEN_TTL_MIN_SECONDS = 60;
1695
+ export const TOKEN_TTL_MAX_SECONDS = 900;
1696
+ export const TOKEN_TTL_DEFAULT_SECONDS = 600;
1697
+ /** A role's name in the access policy; `anon` is reserved for publishable keys. */
1698
+ export const ROLE_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,31}$/;
1699
+ const AgentAllowlistSchema = z.union([
1700
+ z.literal("*"),
1701
+ z.array(z.string().min(1)),
1702
+ ]);
1703
+ export const RoleLimitsSchema = z
1704
+ .object({
1705
+ turnsPerHour: z.number().int().min(1).max(100_000).optional(),
1706
+ concurrentTurns: z.number().int().min(1).max(1000).optional(),
1707
+ })
1708
+ .strict();
1709
+ export const AccessRoleSchema = z
1710
+ .object({
1711
+ scopes: z.array(TokenScopeSchema).min(1),
1712
+ agents: AgentAllowlistSchema,
1713
+ limits: RoleLimitsSchema.optional(),
1714
+ })
1715
+ .strict();
1716
+ /**
1717
+ * The Tenant's access policy: what each role may do with a subject token, what a publishable
1718
+ * key grants alone (`anon`), and how long tokens live. Without roles nothing can be minted.
1719
+ */
1720
+ export const AccessPolicySchema = z
1721
+ .object({
1722
+ version: z.literal(1),
1723
+ roles: z
1724
+ .record(z.string(), AccessRoleSchema)
1725
+ .superRefine((roles, issue) => {
1726
+ for (const name of Object.keys(roles))
1727
+ if (!ROLE_NAME_PATTERN.test(name) || name === "anon")
1728
+ issue.addIssue({
1729
+ code: "custom",
1730
+ message: `Role name ${name} is invalid or reserved`,
1731
+ path: [name],
1732
+ });
1733
+ }),
1734
+ anon: z
1735
+ .object({
1736
+ scopes: z.array(z.literal("agents:read")),
1737
+ agents: AgentAllowlistSchema,
1738
+ })
1739
+ .strict(),
1740
+ tokens: z
1741
+ .object({
1742
+ maxTtlSeconds: z
1743
+ .number()
1744
+ .int()
1745
+ .min(TOKEN_TTL_MIN_SECONDS)
1746
+ .max(TOKEN_TTL_MAX_SECONDS),
1747
+ })
1748
+ .strict(),
1749
+ })
1750
+ .strict();
1751
+ /** The policy of a Tenant that never set one: no roles, nothing for `anon`. */
1752
+ export const DEFAULT_ACCESS_POLICY = Object.freeze({
1753
+ version: 1,
1754
+ roles: {},
1755
+ anon: { scopes: [], agents: [] },
1756
+ tokens: { maxTtlSeconds: TOKEN_TTL_DEFAULT_SECONDS },
1757
+ });
1758
+ export const PutAccessPolicyRequestSchema = z
1759
+ .object({ requestId: RequestIdSchema, policy: AccessPolicySchema })
1760
+ .strict();
1761
+ export const CreateTokenRequestSchema = z
1762
+ .object({
1763
+ requestId: RequestIdSchema,
1764
+ subject: z.string().refine(isSubject, "subject must be 1-200 visible ASCII characters and not reserved"),
1765
+ role: z.string().regex(ROLE_NAME_PATTERN),
1766
+ scopes: z.array(TokenScopeSchema).min(1).optional(),
1767
+ agents: z.array(z.string().min(1)).optional(),
1768
+ ttlSeconds: z
1769
+ .number()
1770
+ .int()
1771
+ .min(TOKEN_TTL_MIN_SECONDS)
1772
+ .max(TOKEN_TTL_MAX_SECONDS)
1773
+ .optional(),
1774
+ })
1775
+ .strict();
1776
+ export const CreateTokenResponseSchema = z
1777
+ .object({
1778
+ token: z.string().min(1),
1779
+ /** ISO time the token stops being accepted. */
1780
+ expiresAt: z.string().min(1),
1781
+ subject: z.string(),
1782
+ role: z.string(),
1783
+ scopes: z.array(TokenScopeSchema),
1784
+ agents: AgentAllowlistSchema,
1785
+ keyId: z.string(),
1786
+ })
1787
+ .strict();
1788
+ export const SIGNING_KEY_STATES = ["standby", "current", "previous", "revoked"];
1789
+ /** A public JSON Web Key as the JWKS publishes it. */
1790
+ export const PublicJwkSchema = z
1791
+ .object({
1792
+ kty: z.literal("EC"),
1793
+ crv: z.literal("P-256"),
1794
+ x: z.string(),
1795
+ y: z.string(),
1796
+ kid: z.string(),
1797
+ alg: z.literal("ES256"),
1798
+ use: z.literal("sig"),
1799
+ })
1800
+ .strict();
1801
+ export const SigningKeyViewSchema = z
1802
+ .object({
1803
+ id: z.string(),
1804
+ state: z.enum(SIGNING_KEY_STATES),
1805
+ alg: z.literal("ES256"),
1806
+ publicKey: PublicJwkSchema,
1807
+ createdAt: z.string(),
1808
+ activatedAt: z.string().nullable(),
1809
+ retiredAt: z.string().nullable(),
1810
+ revokedAt: z.string().nullable(),
1811
+ })
1812
+ .strict();
1813
+ export const SigningKeyListSchema = z
1814
+ .object({ keys: z.array(SigningKeyViewSchema) })
1815
+ .strict();
1816
+ export const JwksSchema = z.object({ keys: z.array(PublicJwkSchema) }).strict();
1817
+ export const RotateSigningKeysRequestSchema = z
1818
+ .object({ requestId: RequestIdSchema, force: z.boolean().optional() })
1819
+ .strict();
1820
+ export const RevokeSigningKeyRequestSchema = z
1821
+ .object({ requestId: RequestIdSchema })
1822
+ .strict();
1823
+ export const RevokeSubjectRequestSchema = z
1824
+ .object({
1825
+ requestId: RequestIdSchema,
1826
+ subject: z.string().refine(isSubject, "subject must be 1-200 visible ASCII characters and not reserved"),
1827
+ })
1828
+ .strict();
1829
+ export const RevokeSubjectResponseSchema = z
1830
+ .object({ subject: z.string(), epoch: z.number().int().nonnegative() })
1831
+ .strict();
1832
+ // --- publishable keys (Host feature `browser-access`) --------------------------------------
1833
+ /** Loopback origins with any port, for development: `http://localhost:*`, `http://127.0.0.1:*`. */
1834
+ export const LOOPBACK_ORIGIN_WILDCARDS = ["http://localhost:*", "http://127.0.0.1:*"];
1835
+ /** True for a serialized web origin: `scheme://host[:port]`, lowercase, no path. */
1836
+ export function isSerializedOrigin(value) {
1837
+ let url;
1838
+ try {
1839
+ url = new URL(value);
1840
+ }
1841
+ catch {
1842
+ return false;
1843
+ }
1844
+ return ((url.protocol === "https:" || url.protocol === "http:") &&
1845
+ url.origin === value &&
1846
+ // Host names only: no wildcards or other characters URL parsing lets through.
1847
+ /^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])$/.test(url.hostname));
1848
+ }
1849
+ /** An origin allowlist entry: an exact origin or a loopback wildcard. */
1850
+ export const OriginEntrySchema = z
1851
+ .string()
1852
+ .refine((value) => LOOPBACK_ORIGIN_WILDCARDS.includes(value) ||
1853
+ isSerializedOrigin(value), "must be an origin such as https://app.example.com, or http://localhost:*");
1854
+ /** True when `origin` (a request's `Origin`) is allowed by `origins`. */
1855
+ export function originAllowed(origins, origin) {
1856
+ if (!isSerializedOrigin(origin))
1857
+ return false;
1858
+ for (const entry of origins) {
1859
+ if (entry === origin)
1860
+ return true;
1861
+ if (entry.endsWith(":*")) {
1862
+ const prefix = entry.slice(0, -1);
1863
+ if (origin.startsWith(prefix) && /^\d{1,5}$/.test(origin.slice(prefix.length)))
1864
+ return true;
1865
+ }
1866
+ }
1867
+ return false;
1868
+ }
1869
+ export const PublishableKeySchema = z
1870
+ .object({
1871
+ id: z.string(),
1872
+ name: z.string(),
1873
+ key: z.string(),
1874
+ origins: z.array(z.string()),
1875
+ createdAt: z.string(),
1876
+ revokedAt: z.string().nullable(),
1877
+ })
1878
+ .strict();
1879
+ export const CreatePublishableKeyRequestSchema = z
1880
+ .object({
1881
+ requestId: RequestIdSchema,
1882
+ name: z.string().min(1).max(100),
1883
+ /** `[]` allows native apps only (no `Origin`). */
1884
+ origins: z.array(OriginEntrySchema).max(100),
1885
+ })
1886
+ .strict();
1887
+ export const UpdatePublishableKeyRequestSchema = z
1888
+ .object({
1889
+ requestId: RequestIdSchema,
1890
+ origins: z.array(OriginEntrySchema).max(100),
1891
+ })
1892
+ .strict();
1893
+ // Successful answers of the Tenant and Admin APIs that had no schema of their own. With the
1894
+ // request schemas above they describe every body the Runtime sends (its OpenAPI document).
1895
+ /** `GET /v1/agents` with an application key: every definition, manifest included. */
1896
+ export const AgentDefinitionViewSchema = z
1897
+ .object({
1898
+ agentId: z.string(),
1899
+ manifest: z.record(z.string(), z.unknown()),
1900
+ manifestHash: z.string(),
1901
+ implementationVersion: z.string(),
1902
+ })
1903
+ .strict();
1904
+ export const ListAgentsResponseSchema = z
1905
+ .object({ agents: z.array(AgentDefinitionViewSchema) })
1906
+ .strict();
1907
+ /** `GET /v1/agents` with a subject token or publishable key: the allowed agents' names only. */
1908
+ export const PublicAgentSchema = z
1909
+ .object({
1910
+ agentId: z.string(),
1911
+ name: z.string().optional(),
1912
+ description: z.string().optional(),
1913
+ })
1914
+ .strict();
1915
+ export const ListPublicAgentsResponseSchema = z
1916
+ .object({ agents: z.array(PublicAgentSchema) })
1917
+ .strict();
1918
+ export const PutAgentResponseSchema = z
1919
+ .object({
1920
+ agentId: z.string(),
1921
+ manifestHash: z.string(),
1922
+ implementationVersion: z.string(),
1923
+ })
1924
+ .strict();
1925
+ export const SESSION_STATUSES = [
1926
+ "idle",
1927
+ "runnable",
1928
+ "running",
1929
+ "waiting",
1930
+ "paused",
1931
+ "uncertain",
1932
+ "completed",
1933
+ "failed",
1934
+ "cancelled",
1935
+ ];
1936
+ export const SessionSummarySchema = z
1937
+ .object({
1938
+ id: z.string(),
1939
+ agentId: z.string(),
1940
+ ownerUserId: z.string(),
1941
+ status: z.enum(SESSION_STATUSES),
1942
+ activeTurnId: z.string().nullable(),
1943
+ })
1944
+ .strict();
1945
+ export const ListSessionsResponseSchema = z
1946
+ .object({ sessions: z.array(SessionSummarySchema) })
1947
+ .strict();
1948
+ /** `PUT` and `GET /v1/sessions/:id`. */
1949
+ export const SessionViewSchema = z
1950
+ .object({
1951
+ id: z.string(),
1952
+ agentId: z.string(),
1953
+ ownerUserId: z.string(),
1954
+ manifestHash: z.string(),
1955
+ implementationVersion: z.string(),
1956
+ status: z.enum(SESSION_STATUSES),
1957
+ activeTurnId: z.string().nullable(),
1958
+ vaultIds: z.array(z.string()),
1959
+ credentialSelections: z.array(CredentialSelectionSchema),
1960
+ /** The session whose sandbox this one shares; `null` when it owns its own. */
1961
+ sandboxOwnerId: z.string().nullable(),
1962
+ /** The sandbox pinned when the session was opened, or `null`. */
1963
+ sandbox: z.record(z.string(), z.unknown()).nullable(),
1964
+ sandboxSource: z.enum(["default", "inline", "shared"]).optional(),
1965
+ mcpSnapshot: z.record(z.string(), z.unknown()).nullable(),
1966
+ mcpDiagnostics: z.array(z.record(z.string(), z.unknown())),
1967
+ /** What the session waits on: interactions, approvals, timers. */
1968
+ waits: z.unknown().optional(),
1969
+ error: z.string().optional(),
1970
+ /** Its Actions that are pending, being delivered or uncertain. */
1971
+ actions: z.array(ActionSchema),
1972
+ uncertainEffects: z.array(z
1973
+ .object({
1974
+ effectId: z.string(),
1975
+ turnId: z.string(),
1976
+ kind: z.string(),
1977
+ error: z.unknown(),
1978
+ })
1979
+ .strict()),
1980
+ })
1981
+ .strict();
1982
+ /** A sandbox tool call's answer (`POST …/sandbox/:tool`): its output, or why it failed. */
1983
+ export const SandboxToolOutcomeSchema = z.discriminatedUnion("kind", [
1984
+ z.object({ kind: z.literal("completed"), output: z.unknown() }).strict(),
1985
+ z
1986
+ .object({ kind: z.literal("failed"), code: z.string(), message: z.string() })
1987
+ .strict(),
1988
+ ]);
1989
+ export const ResetTenantResponseSchema = z.object({ ok: z.literal(true) }).strict();
1990
+ /** `GET /v1/tenant/models`: public provider and model names, no credentials. */
1991
+ export const HostModelCatalogSchema = z
1992
+ .object({
1993
+ providers: z.array(z
1994
+ .object({
1995
+ id: z.string(),
1996
+ name: z.string(),
1997
+ models: z.array(z.object({ id: z.string(), name: z.string() }).strict()),
1998
+ })
1999
+ .strict()),
2000
+ })
2001
+ .strict();
2002
+ export const HostModelProviderInfoSchema = z
2003
+ .object({
2004
+ id: z.string(),
2005
+ name: z.string(),
2006
+ model: z.string(),
2007
+ authType: z.enum(["api_key", "oauth"]),
2008
+ baseUrl: z.string().optional(),
2009
+ settings: CustomModelSettingsSchema.optional(),
2010
+ lastUpdated: z.string(),
2011
+ active: z.boolean(),
2012
+ })
2013
+ .strict();
2014
+ export const ListProvidersResponseSchema = z
2015
+ .object({ providers: z.array(HostModelProviderInfoSchema) })
2016
+ .strict();
2017
+ const SandboxResourcesLimitSchema = z
2018
+ .object({ cpus: z.number(), memoryMiB: z.number() })
2019
+ .strict();
2020
+ /** A Tenant's sandbox configuration with every default applied (sizes in MiB). */
2021
+ export const EffectiveSandboxConfigSchema = z
2022
+ .object({
2023
+ default: z.union([z.literal("none"), z.literal("virtual"), SandboxInlineRequestSchema]),
2024
+ limits: z
2025
+ .object({
2026
+ network: z.array(z.string()),
2027
+ resources: SandboxResourcesLimitSchema,
2028
+ defaultResources: SandboxResourcesLimitSchema,
2029
+ idle: z.string(),
2030
+ })
2031
+ .strict(),
2032
+ })
2033
+ .strict();
2034
+ const SandboxBackendNameSchema = z.enum(["virtual"]);
2035
+ const SandboxIsolationSchema = z.enum(["process", "container"]);
2036
+ /** `GET` and `PUT /v1/tenant/sandbox`: the backend chosen, and the configuration in force. */
2037
+ export const TenantSandboxViewSchema = z
2038
+ .object({
2039
+ preference: z.union([z.literal("auto"), SandboxBackendNameSchema]),
2040
+ backend: SandboxBackendNameSchema.nullable(),
2041
+ isolation: SandboxIsolationSchema.nullable(),
2042
+ reason: z.string(),
2043
+ probes: z.array(z
2044
+ .object({
2045
+ name: SandboxBackendNameSchema,
2046
+ available: z.boolean(),
2047
+ isolation: SandboxIsolationSchema,
2048
+ reason: z.string().optional(),
2049
+ version: z.string().optional(),
2050
+ })
2051
+ .strict()),
2052
+ defaultImage: z.string(),
2053
+ config: EffectiveSandboxConfigSchema,
2054
+ })
2055
+ .strict();
2056
+ /** What a usage total or a budget covers: the whole Tenant, one agent, or one turn. */
2057
+ export const ModelUsageScopeSchema = z.enum(["tenant", "agent", "turn"]);
2058
+ /** `GET /v1/tenant/usage`: which rows of the model usage ledger to total. */
2059
+ export const ModelUsageQuerySchema = z
2060
+ .object({
2061
+ scope: ModelUsageScopeSchema.default("tenant"),
2062
+ /** The agent or turn id; required for those scopes. */
2063
+ id: z.string().min(1).optional(),
2064
+ /** The current UTC day or month, or every row. */
2065
+ period: z.enum(["day", "month", "total"]).default("total"),
2066
+ })
2067
+ .strict();
2068
+ /** The model calls the ledger recorded for one scope and period, and what they cost. */
2069
+ export const ModelUsageTotalsSchema = z
2070
+ .object({
2071
+ scope: ModelUsageScopeSchema,
2072
+ id: z.string().optional(),
2073
+ period: z.enum(["day", "month", "total"]),
2074
+ /** When the period started (ISO); absent for `total`. */
2075
+ since: z.string().optional(),
2076
+ calls: z.number().int().nonnegative(),
2077
+ tokens: z.number().int().nonnegative(),
2078
+ /** pi-ai's catalog price; custom endpoints count as $0. */
2079
+ costUsd: z.number().nonnegative(),
2080
+ })
2081
+ .strict();
2082
+ /**
2083
+ * A hard cap on model spend. Before each call the model gate checks the scope's spend (and its
2084
+ * calls in flight) against the cap; once it is reached the call fails with `budget_exhausted`
2085
+ * and the turn with `model.budget_exhausted`.
2086
+ */
2087
+ export const ModelBudgetSchema = z
2088
+ .object({
2089
+ /** `turn` caps every turn; `agent` one agent's sessions; `tenant` all of them. */
2090
+ scope: ModelUsageScopeSchema,
2091
+ /** The agent's id; `agent` only. */
2092
+ id: z.string().min(1).optional(),
2093
+ /** The UTC period spend counts over; `agent` and `tenant` only. */
2094
+ period: z.enum(["day", "month"]).optional(),
2095
+ /** pi-ai's catalog price; custom endpoints count as $0, so cap them in tokens. */
2096
+ limitUsd: z.number().positive().optional(),
2097
+ limitTokens: z.number().int().positive().optional(),
2098
+ })
2099
+ .strict()
2100
+ .superRefine((budget, ctx) => {
2101
+ if (budget.limitUsd === undefined && budget.limitTokens === undefined)
2102
+ ctx.addIssue({ code: "custom", message: "A budget needs limitUsd, limitTokens or both" });
2103
+ if ((budget.scope === "agent") !== (budget.id !== undefined))
2104
+ ctx.addIssue({ code: "custom", message: "An agent budget names the agent in id; other scopes take no id" });
2105
+ if ((budget.scope === "turn") === (budget.period !== undefined))
2106
+ ctx.addIssue({ code: "custom", message: "A turn budget takes no period; agent and Tenant budgets need one" });
2107
+ });
2108
+ /** `PUT /v1/tenant/budgets`: replaces every budget. An empty list removes them all. */
2109
+ export const PutModelBudgetsRequestSchema = z
2110
+ .object({
2111
+ requestId: RequestIdSchema.optional(),
2112
+ budgets: z.array(ModelBudgetSchema).max(100),
2113
+ })
2114
+ .strict()
2115
+ .superRefine((request, ctx) => {
2116
+ const seen = new Set();
2117
+ for (const budget of request.budgets) {
2118
+ const key = `${budget.scope}:${budget.id ?? "*"}`;
2119
+ if (seen.has(key))
2120
+ ctx.addIssue({ code: "custom", message: `Two budgets for ${key}; set one per scope` });
2121
+ seen.add(key);
2122
+ }
2123
+ });
2124
+ export const ModelBudgetsSchema = z.object({ budgets: z.array(ModelBudgetSchema) }).strict();
2125
+ export const ListVaultsResponseSchema = z.object({ vaults: z.array(VaultInfoSchema) }).strict();
2126
+ export const ListCredentialsResponseSchema = z
2127
+ .object({ credentials: z.array(CredentialInfoSchema) })
2128
+ .strict();
2129
+ /** A deleted vault or credential. */
2130
+ export const DeletedResponseSchema = z.object({ id: z.string() }).strict();
2131
+ export const AccessPolicyResponseSchema = z.object({ policy: AccessPolicySchema }).strict();
2132
+ export const ListPublishableKeysResponseSchema = z
2133
+ .object({ keys: z.array(PublishableKeySchema) })
2134
+ .strict();
2135
+ export const HostShutdownResponseSchema = z
2136
+ .object({ status: z.literal("shutting_down") })
2137
+ .strict();
2138
+ /** The last frame of a session stream the Runtime ends: `event: nylorun.closed`. */
2139
+ export const StreamClosedFrameSchema = z
2140
+ .object({ reason: z.enum(["token_expired", "revoked"]) })
2141
+ .strict();
2142
+ /**
2143
+ * The `code` of an AG-UI `RUN_ERROR` the Runtime sends: a rejection's code, or `session_busy`
2144
+ * (another turn is running) or `runtime_error` (the Runtime failed). Never an HTTP body's code.
2145
+ */
2146
+ export const AgUiRunErrorCodeSchema = z.enum([
2147
+ ...ERROR_CODES,
2148
+ "session_busy",
2149
+ "runtime_error",
2150
+ ]);
2151
+ // --- Action endpoints: the Runtime delivers Actions over HTTP ------------------------------
2152
+ /** The JWT `typ` of a delivery token (RFC 8725 explicit typing). */
2153
+ export const DELIVERY_TOKEN_TYPE = "nylorun-delivery+jwt";
2154
+ /**
2155
+ * A delivery token lives no longer than a subject token: rotating signing keys revokes the
2156
+ * previous key once the longest token it may have signed has expired.
2157
+ */
2158
+ export const DELIVERY_TOKEN_MAX_TTL_SECONDS = TOKEN_TTL_MAX_SECONDS;
2159
+ /** Inline delivery timeouts, in milliseconds. The maximum keeps a token within its lifetime. */
2160
+ export const ENDPOINT_TIMEOUT_DEFAULT_MS = 60_000;
2161
+ export const ENDPOINT_TIMEOUT_MAX_MS = (DELIVERY_TOKEN_MAX_TTL_SECONDS - 60) * 1000;
2162
+ /** In-flight deliveries per endpoint when the registration does not say. */
2163
+ export const ENDPOINT_MAX_CONCURRENT_DEFAULT = 16;
2164
+ const isEndpointUrl = (value) => {
2165
+ try {
2166
+ const url = new URL(value);
2167
+ return ((url.protocol === "http:" || url.protocol === "https:") &&
2168
+ !url.username &&
2169
+ !url.password &&
2170
+ !url.hash);
2171
+ }
2172
+ catch {
2173
+ return false;
2174
+ }
2175
+ };
2176
+ const EndpointUrlSchema = z
2177
+ .string()
2178
+ .max(2048)
2179
+ .refine(isEndpointUrl, {
2180
+ message: "An endpoint URL is an http or https URL without credentials or a fragment",
2181
+ });
2182
+ /** One agent's or workflow's Action endpoint, as the application registers it. */
2183
+ export const EndpointRegistrationSchema = z
2184
+ .object({
2185
+ agentId: z.string().min(1),
2186
+ url: EndpointUrlSchema,
2187
+ implementationVersion: z.string().min(1),
2188
+ manifestHash: z.string().min(1).optional(),
2189
+ timeoutMs: z.number().int().min(1000).max(ENDPOINT_TIMEOUT_MAX_MS).optional(),
2190
+ maxConcurrent: z.number().int().min(1).max(256).optional(),
2191
+ })
2192
+ .strict();
2193
+ export const PutEndpointsRequestSchema = z
2194
+ .object({
2195
+ endpoints: z
2196
+ .array(EndpointRegistrationSchema)
2197
+ .min(1)
2198
+ .max(64)
2199
+ .refine((endpoints) => new Set(endpoints.map((e) => e.agentId)).size === endpoints.length, { message: "Endpoint registrations must be unique per agent" }),
2200
+ })
2201
+ .strict();
2202
+ /** What recent deliveries and the last ping say about an endpoint. */
2203
+ export const EndpointHealthSchema = z
2204
+ .object({
2205
+ lastDeliveryAt: z.string().optional(),
2206
+ lastSuccessAt: z.string().optional(),
2207
+ lastError: z.object({ code: z.string(), message: z.string() }).optional(),
2208
+ consecutiveFailures: z.number().int().nonnegative(),
2209
+ /** What the handler reported serving on the last ping. */
2210
+ served: z
2211
+ .object({
2212
+ implementationVersion: z.string(),
2213
+ manifestHash: z.string().optional(),
2214
+ })
2215
+ .strict()
2216
+ .optional(),
2217
+ })
2218
+ .strict();
2219
+ export const EndpointSchema = z
2220
+ .object({
2221
+ agentId: z.string(),
2222
+ url: z.string(),
2223
+ implementationVersion: z.string(),
2224
+ manifestHash: z.string().optional(),
2225
+ timeoutMs: z.number().int(),
2226
+ maxConcurrent: z.number().int(),
2227
+ health: EndpointHealthSchema,
2228
+ updatedAt: z.string(),
2229
+ })
2230
+ .strict();
2231
+ export const ListEndpointsResponseSchema = z
2232
+ .object({
2233
+ endpoints: z.array(EndpointSchema),
2234
+ })
2235
+ .strict();
2236
+ export const DeleteEndpointResponseSchema = z
2237
+ .object({ agentId: z.string(), deleted: z.literal(true) })
2238
+ .strict();
2239
+ /** The body the Runtime POSTs to an Action endpoint. */
2240
+ export const ActionDeliverySchema = z.discriminatedUnion("type", [
2241
+ z
2242
+ .object({
2243
+ type: z.literal("action"),
2244
+ action: ActionSchema,
2245
+ /** The Action's session has a sandbox, so `ctx.sandbox` is available. */
2246
+ sandbox: z.boolean(),
2247
+ })
2248
+ .strict(),
2249
+ z
2250
+ .object({
2251
+ type: z.literal("ping"),
2252
+ agentId: z.string().min(1),
2253
+ manifestHash: z.string().min(1).optional(),
2254
+ })
2255
+ .strict(),
2256
+ ]);
2257
+ /** An Action endpoint's answer to a ping. */
2258
+ export const EndpointPingResponseSchema = z.object({
2259
+ agentId: z.string(),
2260
+ implementationVersion: z.string(),
2261
+ manifestHash: z.string().optional(),
2262
+ });
2263
+ /** The answer to a background delivery's heartbeat: a fresh token and the new deadline. */
2264
+ export const DeliveryHeartbeatResponseSchema = z.object({
2265
+ token: z.string().min(1),
2266
+ deadlineAt: z.string(),
2267
+ });
2268
+ /**
2269
+ * The receipt of a background result (`POST /v1/actions/:id/result`): a session command's
2270
+ * receipt without `requestId`, since the result carries none. The same result again returns it.
2271
+ */
2272
+ export const ActionResultReceiptSchema = AcceptedResponseSchema.omit({ requestId: true });
2273
+ // --- Studio embedding (Studio design §8) ---------------------------------------------------
2274
+ /** A Tenant id as Studio's routes accept it. */
2275
+ const STUDIO_TENANT_ID = /^[A-Za-z0-9_-]{1,128}$/;
2276
+ /** `POST /_studio/login-tokens` body. No `tenant` mints a Host-wide token (the CLI's `{}`). */
2277
+ export const StudioLoginTokenRequestSchema = z
2278
+ .object({
2279
+ tenant: z.string().regex(STUDIO_TENANT_ID, "must be a Tenant id").optional(),
2280
+ subject: z
2281
+ .string()
2282
+ .refine(isSubject, "must be 1–200 visible ASCII characters")
2283
+ .optional(),
2284
+ })
2285
+ .strict();
2286
+ export const StudioLoginTokenResponseSchema = z.object({
2287
+ /** Single-use, valid for two minutes. */
2288
+ token: z.string().min(1),
2289
+ /** The cookie login URL; refused for a token limited to a Tenant. */
2290
+ url: z.string().min(1),
2291
+ expiresAt: z.string().min(1),
2292
+ tenant: z.string().nullable(),
2293
+ subject: z.string().nullable(),
2294
+ });
2295
+ /** `POST /_studio/sessions` body: the login token an embedder passed in `init`. */
2296
+ export const StudioSessionRequestSchema = z.object({ token: z.string().min(1) }).strict();
2297
+ export const StudioSessionResponseSchema = z.object({
2298
+ /** Bearer for every `/_studio/*` request; kept in memory only. */
2299
+ sessionToken: z.string().min(1),
2300
+ tenant: z.string().nullable(),
2301
+ subject: z.string().nullable(),
2302
+ expiresAt: z.string().min(1),
2303
+ });
2304
+ /** Message protocol versions this release speaks. */
2305
+ export const STUDIO_EMBED_PROTOCOLS = [1];
2306
+ export const STUDIO_EMBED_MESSAGE_TYPE = "nylorun.studio";
2307
+ const HEX_COLOR = z.string().regex(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/);
2308
+ /** The embedder's theme. Unknown keys are dropped, not rejected. */
2309
+ export const StudioThemeSchema = z.object({
2310
+ mode: z.enum(["light", "dark"]),
2311
+ accent: HEX_COLOR.optional(),
2312
+ background: HEX_COLOR.optional(),
2313
+ foreground: HEX_COLOR.optional(),
2314
+ });
2315
+ const EMBED_ROUTE = z
2316
+ .string()
2317
+ .max(2048)
2318
+ .regex(/^\/tenants\/[^/?#\s]+(?:\/[^?#\s]*)?$/, "must be a Studio route under /tenants/");
2319
+ const EXTERNAL_URL = z.string().refine((value) => {
2320
+ try {
2321
+ const url = new URL(value);
2322
+ return url.protocol === "https:" || url.protocol === "http:";
2323
+ }
2324
+ catch {
2325
+ return false;
2326
+ }
2327
+ }, "must be an http or https URL");
2328
+ function embed(kind, shape) {
2329
+ return z.object({
2330
+ type: z.literal(STUDIO_EMBED_MESSAGE_TYPE),
2331
+ protocol: z.number().int().positive(),
2332
+ kind: z.literal(kind),
2333
+ ...shape,
2334
+ });
2335
+ }
2336
+ /** Every message between an embedder and Studio (Studio design §8.8). */
2337
+ export const StudioEmbedMessageSchema = z.discriminatedUnion("kind", [
2338
+ embed("ready", {
2339
+ protocols: z.array(z.number().int().positive()).min(1),
2340
+ studioVersion: z.string(),
2341
+ }),
2342
+ embed("init", {
2343
+ token: z.string().min(1),
2344
+ theme: StudioThemeSchema.optional(),
2345
+ route: EMBED_ROUTE.optional(),
2346
+ }),
2347
+ embed("token.refresh", { token: z.string().min(1) }),
2348
+ embed("theme.changed", { theme: StudioThemeSchema }),
2349
+ embed("navigate", { route: EMBED_ROUTE }),
2350
+ embed("session", {
2351
+ tenant: z.string().nullable(),
2352
+ subject: z.string().nullable(),
2353
+ expiresAt: z.string(),
2354
+ }),
2355
+ embed("token.expiring", { expiresAt: z.string().nullable() }),
2356
+ embed("route.changed", { route: z.string() }),
2357
+ embed("open.external", { url: EXTERNAL_URL }),
2358
+ embed("open.babai", { sessionId: z.string().min(1) }),
2359
+ embed("error", { code: z.string().min(1), message: z.string() }),
2360
+ ]);
2361
+ /** Schemes that never name an embedder. */
2362
+ const NON_EMBEDDER_SCHEMES = new Set([
2363
+ "about",
2364
+ "blob",
2365
+ "data",
2366
+ "file",
2367
+ "filesystem",
2368
+ "javascript",
2369
+ "ws",
2370
+ "wss",
2371
+ ]);
2372
+ const CUSTOM_ORIGIN = /^([a-z][a-z0-9+.-]*):\/\/([a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::(\d{1,5}))?$/;
2373
+ /** True for one exact embedder origin: `https://…`, `http://…` or `<custom>://host[:port]`. */
2374
+ export function isFrameAncestor(value) {
2375
+ if (value.startsWith("http://") || value.startsWith("https://"))
2376
+ return isSerializedOrigin(value);
2377
+ const match = CUSTOM_ORIGIN.exec(value);
2378
+ if (!match)
2379
+ return false;
2380
+ if (NON_EMBEDDER_SCHEMES.has(match[1]))
2381
+ return false;
2382
+ return match[3] === undefined || Number(match[3]) <= 65535;
2383
+ }
2384
+ /**
2385
+ * Parses `NYLORUN_STUDIO_FRAME_ANCESTORS`: exact origins separated by whitespace. Wildcards,
2386
+ * keywords, scheme-only entries and paths are refused with the entry named. Empty gives `[]`.
2387
+ */
2388
+ export function parseFrameAncestors(value) {
2389
+ const entries = value.split(/\s+/).filter((entry) => entry !== "");
2390
+ for (const entry of entries)
2391
+ if (!isFrameAncestor(entry))
2392
+ throw new Error(`${entry} is not an exact origin. Use origins such as nylorun://localhost or https://app.example.com, with no wildcards or paths.`);
2393
+ return [...new Set(entries)];
2394
+ }