@nylorun/core 0.7.0-beta → 0.9.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 (61) hide show
  1. package/CHANGELOG.md +249 -0
  2. package/dist/compatibility.d.ts +42 -4
  3. package/dist/compatibility.js +65 -3
  4. package/dist/contracts.d.ts +2165 -328
  5. package/dist/contracts.js +1246 -100
  6. package/dist/define.d.ts +13 -5
  7. package/dist/define.js +7 -2
  8. package/dist/definition/assemble.js +16 -14
  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 +116 -16
  12. package/dist/definition/builder.js +330 -53
  13. package/dist/definition/capability.d.ts +55 -0
  14. package/dist/definition/capability.js +104 -0
  15. package/dist/definition/declaration.js +6 -2
  16. package/dist/definition/delegate.d.ts +25 -4
  17. package/dist/definition/delegate.js +34 -6
  18. package/dist/definition/flow/compile.d.ts +23 -0
  19. package/dist/definition/flow/compile.js +274 -0
  20. package/dist/definition/flow/from.d.ts +11 -0
  21. package/dist/definition/flow/from.js +78 -0
  22. package/dist/definition/flow/index.d.ts +11 -0
  23. package/dist/definition/flow/index.js +11 -0
  24. package/dist/definition/flow/paths.d.ts +60 -0
  25. package/dist/definition/flow/paths.js +90 -0
  26. package/dist/definition/flow/spec.d.ts +66 -0
  27. package/dist/definition/flow/spec.js +130 -0
  28. package/dist/definition/flow/types.d.ts +157 -0
  29. package/dist/definition/flow/types.js +1 -0
  30. package/dist/definition/from.js +5 -1
  31. package/dist/definition/helpers.d.ts +1 -16
  32. package/dist/definition/helpers.js +1 -30
  33. package/dist/definition/mcp.d.ts +37 -0
  34. package/dist/definition/mcp.js +81 -0
  35. package/dist/definition/model-failure.d.ts +4 -0
  36. package/dist/definition/model-failure.js +22 -0
  37. package/dist/definition/sandbox-capability.d.ts +12 -0
  38. package/dist/definition/sandbox-capability.js +33 -0
  39. package/dist/definition/schema.js +3 -0
  40. package/dist/definition/workflow/build.d.ts +3 -13
  41. package/dist/definition/workflow/build.js +3 -25
  42. package/dist/definition/workflow/chain.js +0 -1
  43. package/dist/definition/workflow/loop.js +2 -4
  44. package/dist/definition/workflow/map.js +0 -1
  45. package/dist/definition/workflow/parallel.js +0 -1
  46. package/dist/definition/workflow/runnable.d.ts +13 -5
  47. package/dist/definition/workflow/runnable.js +11 -41
  48. package/dist/definition/workflow/switch.js +0 -2
  49. package/dist/errors.d.ts +3 -1
  50. package/dist/types/manifest.d.ts +4 -2
  51. package/dist/types/middleware.d.ts +1 -3
  52. package/dist/types/model.d.ts +32 -1
  53. package/dist/types/observe.d.ts +7 -1
  54. package/dist/types/tool.d.ts +6 -0
  55. package/dist/types/transcript.d.ts +14 -1
  56. package/dist/types/workflow.d.ts +72 -3
  57. package/dist/utils/deprecate.d.ts +3 -0
  58. package/dist/utils/deprecate.js +25 -0
  59. package/dist/utils/sandbox.d.ts +0 -4
  60. package/dist/utils/sandbox.js +0 -16
  61. package/package.json +1 -1
package/dist/contracts.js CHANGED
@@ -10,14 +10,18 @@ import { ERROR_CODES } from "./compatibility.js";
10
10
  export const RequestIdSchema = z.string().min(1);
11
11
  export const IdempotencyKeySchema = z.string().min(1).max(256);
12
12
  const jsonObject = z.record(z.string(), z.unknown());
13
- const jsonValue = z.lazy(() => z.union([
13
+ // Recursive schemas carry an `id`: a document generated from them (the Runtime's OpenAPI)
14
+ // refers back to the named schema instead of expanding it forever.
15
+ const jsonValue = z
16
+ .lazy(() => z.union([
14
17
  z.string(),
15
18
  z.number(),
16
19
  z.boolean(),
17
20
  z.null(),
18
21
  z.array(jsonValue),
19
22
  z.record(z.string(), jsonValue),
20
- ]));
23
+ ]))
24
+ .meta({ id: "JsonValue" });
21
25
  const mcpServerSchema = z.discriminatedUnion("type", [
22
26
  z
23
27
  .object({
@@ -92,7 +96,10 @@ const toolManifestSchema = z
92
96
  description: z.string().optional(),
93
97
  inputSchema: jsonObject,
94
98
  outputSchema: jsonObject.optional(),
95
- agent: z.lazy(() => AgentManifestSchema).optional(),
99
+ agent: z
100
+ .lazy(() => z.union([workflowV2ManifestSchema, AgentManifestSchema]))
101
+ .meta({ id: "ToolAgentManifest" })
102
+ .optional(),
96
103
  })
97
104
  .strict();
98
105
  const hookPointSchema = z
@@ -220,6 +227,20 @@ function delegationIssues(manifest, issue) {
220
227
  const child = tool.agent;
221
228
  if (!child)
222
229
  continue;
230
+ if ("kind" in child) {
231
+ // A flow agent runs in its own linked session; its leaves may delegate in turn.
232
+ if (tool.name !== child.id)
233
+ issue(`Tool '${tool.name}' must be named after the agent it runs ('${child.id}')`);
234
+ if (!child.description?.trim() || tool.description !== child.description)
235
+ issue(`Agent tool '${tool.name}' must carry the agent's non-empty description`);
236
+ if (canonical(tool.inputSchema) !== canonical(DELEGATE_INPUT_SCHEMA))
237
+ issue(`Agent tool '${tool.name}' must take the standard { task } input`);
238
+ if (tool.outputSchema !== undefined)
239
+ issue(`Agent tool '${tool.name}' must not declare outputSchema; the agent's outputSchema applies`);
240
+ if (child.sandbox !== undefined && Object.keys(child.sandbox).length > 0)
241
+ sandboxes.add(canonical(child.sandbox));
242
+ continue;
243
+ }
223
244
  if (tool.name !== child.id)
224
245
  issue(`Tool '${tool.name}' must be named after the agent it runs ('${child.id}')`);
225
246
  if (!child.description?.trim() || tool.description !== child.description)
@@ -332,9 +353,8 @@ const workflowNodeSchema = z.lazy(() => z.union([
332
353
  .strict(),
333
354
  })
334
355
  .strict(),
335
- ]));
336
- /** Workflow definition document. `kind: "workflow"`; a missing `kind` is never a workflow. */
337
- export const WorkflowManifestSchema = z
356
+ ])).meta({ id: "WorkflowNode" });
357
+ const workflowV1ManifestSchema = z
338
358
  .object({
339
359
  kind: z.literal("workflow"),
340
360
  workflowSchemaVersion: z.literal(1),
@@ -343,6 +363,138 @@ export const WorkflowManifestSchema = z
343
363
  sandbox: sandboxManifestSchema.optional(),
344
364
  })
345
365
  .strict();
366
+ // v2 (Flow Agents): `id` and `input` on any node, no slots, embedded agents.
367
+ const workflowNodeOptionsV2 = {
368
+ id: z.string().min(1).optional(),
369
+ input: workflowFnRefSchema.optional(),
370
+ };
371
+ const workflowAgentNodeV2Schema = z
372
+ .object({ agent: z.string().min(1), ...workflowNodeOptionsV2 })
373
+ .strict();
374
+ const workflowNodeV2Schema = z.lazy(() => z.union([
375
+ workflowAgentNodeV2Schema,
376
+ z
377
+ .object({
378
+ tool: z
379
+ .object({
380
+ name: z.string().min(1),
381
+ description: z.string().optional(),
382
+ inputSchema: jsonObject.optional(),
383
+ outputSchema: jsonObject.optional(),
384
+ })
385
+ .strict(),
386
+ ...workflowNodeOptionsV2,
387
+ })
388
+ .strict(),
389
+ z.object({ chain: z.array(workflowNodeV2Schema).min(1), ...workflowNodeOptionsV2 }).strict(),
390
+ z
391
+ .object({
392
+ switch: z
393
+ .object({
394
+ on: workflowFnRefSchema,
395
+ cases: z.record(z.string(), workflowNodeV2Schema),
396
+ default: workflowNodeV2Schema.optional(),
397
+ })
398
+ .strict(),
399
+ ...workflowNodeOptionsV2,
400
+ })
401
+ .strict(),
402
+ z
403
+ .object({
404
+ parallel: z
405
+ .record(z.string(), workflowNodeV2Schema)
406
+ .refine((branches) => Object.keys(branches).length > 0, {
407
+ message: "parallel needs at least one branch",
408
+ }),
409
+ ...workflowNodeOptionsV2,
410
+ })
411
+ .strict(),
412
+ z
413
+ .object({
414
+ map: z.object({ each: workflowNodeV2Schema }).strict(),
415
+ ...workflowNodeOptionsV2,
416
+ })
417
+ .strict(),
418
+ z
419
+ .object({
420
+ loop: z
421
+ .object({
422
+ run: workflowNodeV2Schema,
423
+ verify: z.union([workflowFnRefSchema, workflowAgentNodeV2Schema]),
424
+ max: z.number().int().positive().optional(),
425
+ decide: workflowFnRefSchema.optional(),
426
+ })
427
+ .strict()
428
+ .refine((loop) => loop.max !== undefined || loop.decide !== undefined, {
429
+ message: "loop needs max or decide",
430
+ }),
431
+ ...workflowNodeOptionsV2,
432
+ })
433
+ .strict(),
434
+ ])).meta({ id: "WorkflowNodeV2" });
435
+ const workflowV2ManifestSchema = z.lazy(() => z
436
+ .object({
437
+ kind: z.literal("workflow"),
438
+ workflowSchemaVersion: z.literal(2),
439
+ id: z.string().min(1),
440
+ name: z.string().min(1).optional(),
441
+ description: z.string().optional(),
442
+ metadata: jsonObject.optional(),
443
+ inputSchema: jsonObject.optional(),
444
+ outputSchema: jsonObject.optional(),
445
+ sandbox: sandboxManifestSchema.optional(),
446
+ root: workflowNodeV2Schema,
447
+ agents: z.record(z.string().min(1), z.union([workflowV2ManifestSchema, AgentManifestSchema])),
448
+ })
449
+ .strict()
450
+ .superRefine((manifest, ctx) => {
451
+ for (const agentId of referencedAgents(manifest.root)) {
452
+ if (!(agentId in manifest.agents))
453
+ ctx.addIssue({
454
+ code: "custom",
455
+ path: ["agents"],
456
+ message: `Agent '${agentId}' is used in the flow but not embedded in agents`,
457
+ });
458
+ }
459
+ for (const [key, agent] of Object.entries(manifest.agents)) {
460
+ if (agent.id !== key)
461
+ ctx.addIssue({
462
+ code: "custom",
463
+ path: ["agents", key],
464
+ message: `Embedded agent '${agent.id}' must be keyed by its id`,
465
+ });
466
+ }
467
+ })).meta({ id: "WorkflowV2Manifest" });
468
+ function referencedAgents(node) {
469
+ const out = [];
470
+ const visit = (child) => {
471
+ if ("agent" in child)
472
+ out.push(child.agent);
473
+ else if ("chain" in child)
474
+ child.chain.forEach(visit);
475
+ else if ("switch" in child) {
476
+ Object.values(child.switch.cases).forEach(visit);
477
+ if (child.switch.default)
478
+ visit(child.switch.default);
479
+ }
480
+ else if ("parallel" in child)
481
+ Object.values(child.parallel).forEach(visit);
482
+ else if ("map" in child)
483
+ visit(child.map.each);
484
+ else if ("loop" in child) {
485
+ visit(child.loop.run);
486
+ if ("agent" in child.loop.verify)
487
+ visit(child.loop.verify);
488
+ }
489
+ };
490
+ visit(node);
491
+ return out;
492
+ }
493
+ /** Workflow definition document. `kind: "workflow"`; a missing `kind` is never a workflow. */
494
+ export const WorkflowManifestSchema = z.union([
495
+ workflowV1ManifestSchema,
496
+ workflowV2ManifestSchema,
497
+ ]);
346
498
  /** Registry document: agent (no `kind`, or legacy) or workflow (`kind: "workflow"`). */
347
499
  export const DefinitionDocumentSchema = z.union([
348
500
  AgentManifestSchema,
@@ -363,6 +515,40 @@ export const CredentialSelectionSchema = z
363
515
  credentialId: z.string().min(1),
364
516
  })
365
517
  .strict();
518
+ const sandboxHostSchema = z.string().refine(isSandboxHostPattern, {
519
+ message: "network.allow entries must be host names such as api.github.com or *.example.com",
520
+ });
521
+ const sandboxResourcesSchema = z
522
+ .object({
523
+ cpus: z.number().int().min(1).max(64).optional(),
524
+ memory: z
525
+ .string()
526
+ .refine((value) => parseSandboxSize(value) !== undefined, {
527
+ message: "resources.memory must be a size such as 512MiB or 2GiB",
528
+ })
529
+ .optional(),
530
+ })
531
+ .strict();
532
+ /**
533
+ * A sandbox defined when a session is opened. No `network.allow` means no egress. The Runtime
534
+ * checks it against the Tenant's limits and pins the result on the session.
535
+ */
536
+ export const SandboxInlineRequestSchema = z
537
+ .object({
538
+ image: z.string().min(1).optional(),
539
+ network: z.object({ allow: z.array(sandboxHostSchema).optional() }).strict().optional(),
540
+ resources: sandboxResourcesSchema.optional(),
541
+ })
542
+ .strict();
543
+ /**
544
+ * `PutSessionRequest.sandbox`: `false` for none, `{ session }` to share another session's
545
+ * sandbox, or an inline sandbox. Omitted means the Tenant's default.
546
+ */
547
+ export const SandboxRequestSchema = z.union([
548
+ z.literal(false),
549
+ z.object({ session: z.string().min(1) }).strict(),
550
+ SandboxInlineRequestSchema,
551
+ ]);
366
552
  export const PutSessionRequestSchema = z
367
553
  .object({
368
554
  requestId: RequestIdSchema,
@@ -371,10 +557,44 @@ export const PutSessionRequestSchema = z
371
557
  info: jsonObject.optional(),
372
558
  vaultIds: z.array(z.string().min(1)).optional(),
373
559
  credentialSelections: z.array(CredentialSelectionSchema).optional(),
374
- /** Share another session's sandbox (same owner, Tenant, and identical specs). */
375
- sandbox: z.object({ session: z.string().min(1) }).strict().optional(),
560
+ /** The session's sandbox; see `SandboxRequestSchema`. Fixed once the session exists. */
561
+ sandbox: SandboxRequestSchema.optional(),
562
+ })
563
+ .strict();
564
+ /**
565
+ * A Tenant's sandbox configuration (Tenant setting `sandbox.config`): what a session gets when
566
+ * it names no sandbox, and the limits every session's sandbox must fit.
567
+ */
568
+ export const TenantSandboxConfigSchema = z
569
+ .object({
570
+ /** `none` (the default when unset), `virtual`, or an inline sandbox. */
571
+ default: z
572
+ .union([z.literal("none"), z.literal("virtual"), SandboxInlineRequestSchema])
573
+ .optional(),
574
+ limits: z
575
+ .object({
576
+ /** Hosts a sandbox may allow. Default: package registries and code hosts. */
577
+ network: z.array(sandboxHostSchema).optional(),
578
+ /** The most a session may ask for. */
579
+ resources: sandboxResourcesSchema.optional(),
580
+ /** What a session gets when it asks for nothing. */
581
+ defaultResources: sandboxResourcesSchema.optional(),
582
+ /** Stop compute after this long without use. */
583
+ idle: z
584
+ .string()
585
+ .refine((value) => parseSandboxDuration(value) !== undefined, {
586
+ message: "idle must be a duration such as 30s, 15m or 1h",
587
+ })
588
+ .optional(),
589
+ })
590
+ .strict()
591
+ .optional(),
376
592
  })
377
593
  .strict();
594
+ /** `PUT /v1/tenant/sandbox`: replaces the Tenant's sandbox configuration. */
595
+ export const PutTenantSandboxRequestSchema = TenantSandboxConfigSchema.extend({
596
+ requestId: RequestIdSchema.optional(),
597
+ }).strict();
378
598
  const vaultWriteBase = {
379
599
  requestId: RequestIdSchema,
380
600
  idempotencyKey: IdempotencyKeySchema,
@@ -454,12 +674,26 @@ export const RotateCredentialRequestSchema = z
454
674
  ]),
455
675
  })
456
676
  .strict();
677
+ /**
678
+ * What the Runtime cannot learn from a custom OpenAI-compatible endpoint (Model Calls §7):
679
+ * its context window and output limit, whether it reasons, and pi-ai `compat` settings
680
+ * (`thinkingFormat`, `thinkingTokenBudgetField`, `chatTemplateKwargs`, …).
681
+ */
682
+ export const CustomModelSettingsSchema = z
683
+ .object({
684
+ contextWindow: z.number().int().min(1024).optional(),
685
+ maxTokens: z.number().int().min(1).optional(),
686
+ reasoning: z.boolean().optional(),
687
+ compat: z.record(z.string(), z.unknown()).optional(),
688
+ })
689
+ .strict();
457
690
  export const PutHostModelRequestSchema = z
458
691
  .object({
459
692
  ...vaultWriteBase,
460
693
  provider: z.string().min(1),
461
694
  model: z.string().min(1),
462
695
  baseUrl: z.string().min(1).optional(),
696
+ settings: CustomModelSettingsSchema.optional(),
463
697
  auth: z.discriminatedUnion("type", [
464
698
  z
465
699
  .object({
@@ -487,6 +721,27 @@ export const SelectHostModelRequestSchema = z
487
721
  baseUrl: z.string().min(1).optional(),
488
722
  })
489
723
  .strict();
724
+ export const VaultInfoSchema = z
725
+ .object({
726
+ id: z.string(),
727
+ name: z.string(),
728
+ ownerUserId: z.string(),
729
+ metadata: z.record(z.string(), z.string()).optional(),
730
+ createdAt: z.string(),
731
+ })
732
+ .strict();
733
+ export const CredentialInfoSchema = z
734
+ .object({
735
+ id: z.string(),
736
+ vaultId: z.string(),
737
+ name: z.string(),
738
+ type: z.enum(["bearer", "oauth"]),
739
+ binding: z.object({ url: z.string() }).strict(),
740
+ expiresAt: z.string().optional(),
741
+ createdAt: z.string(),
742
+ rotatedAt: z.string().optional(),
743
+ })
744
+ .strict();
490
745
  const commandBase = {
491
746
  requestId: RequestIdSchema,
492
747
  idempotencyKey: IdempotencyKeySchema,
@@ -518,16 +773,6 @@ export const ActionOutcomeSchema = z
518
773
  statePatch: jsonObject.optional(),
519
774
  })
520
775
  .strict();
521
- export const ActionResultCommandSchema = z
522
- .object({
523
- ...commandBase,
524
- type: z.literal("action_result"),
525
- actionId: z.string().min(1),
526
- claimId: z.string().min(1),
527
- generation: z.number().int().positive(),
528
- outcome: ActionOutcomeSchema,
529
- })
530
- .strict();
531
776
  export const SessionCommandSchema = z.union([
532
777
  MessageEventBodySchema,
533
778
  z
@@ -553,24 +798,79 @@ export const SessionCommandSchema = z.union([
553
798
  reason: z.string().optional(),
554
799
  })
555
800
  .strict(),
556
- ActionResultCommandSchema,
557
801
  ]);
558
802
  export const SessionEventBodySchema = SessionCommandSchema;
559
- export const LiveEventSchema = z
560
- .object({
803
+ /** The envelope every session event carries (`nylorun.event/2`, Durable Streams §9.5). */
804
+ export const EVENT_SCHEMA = "nylorun.event/2";
805
+ /** Who wrote an event. v1 writes `loop` (the engine) and `api` (commands and results). */
806
+ export const EventSourceKindSchema = z.enum([
807
+ "model-gate",
808
+ "tool-gate",
809
+ "egress-gate",
810
+ "sandboxd",
811
+ "edge",
812
+ "init",
813
+ "controller",
814
+ "loop",
815
+ "supervisor",
816
+ "harness",
817
+ "evidence",
818
+ "operator",
819
+ "human",
820
+ "api",
821
+ ]);
822
+ /** How far an event can be trusted, by who could forge it. v1 writes `observed` only. */
823
+ export const EvidenceClassSchema = z.enum([
824
+ "observed",
825
+ "measured",
826
+ "attested",
827
+ "claimed",
828
+ "asserted",
829
+ ]);
830
+ /**
831
+ * The envelope fields. Not strict: a client strips fields it does not know, so the envelope
832
+ * can grow without a protocol bump.
833
+ */
834
+ const eventEnvelope = {
835
+ schema: z.literal(EVENT_SCHEMA),
561
836
  eventId: z.string(),
562
- sessionId: z.string(),
563
837
  tenantId: z.string().min(1),
838
+ sessionId: z.string(),
839
+ /** The run the event belongs to; null until runs exist. */
840
+ runId: z.string().nullable(),
564
841
  turnId: z.string().nullable(),
842
+ /** The session's restore incarnation; 0 until restores exist. */
843
+ incarnation: z.number().int().nonnegative(),
844
+ /** The session's ownership epoch when the event was written. */
845
+ epoch: z.number().int().nonnegative(),
846
+ /** Position in the session's log, from 0, in commit order. */
847
+ seq: z.number().int().nonnegative(),
848
+ /** `base64url(sessionId:seq)`: resume from here with `Last-Event-ID` or `?cursor=`. */
565
849
  cursor: z.string(),
566
- createdAt: z.string(),
567
- type: z.string(),
850
+ /** When the event was written (ISO 8601). */
851
+ time: z.string(),
852
+ /** The version of the event type's payload schema. */
853
+ schemaVersion: z.number().int().positive(),
854
+ source: z.object({ kind: EventSourceKindSchema, id: z.string() }),
855
+ evidence: EvidenceClassSchema,
856
+ trace: z
857
+ .object({
858
+ traceId: z.string(),
859
+ spanId: z.string(),
860
+ parentSpanId: z.string().optional(),
861
+ })
862
+ .optional(),
863
+ visibility: z.enum(["public", "internal", "restricted"]),
864
+ retention: z.enum(["full", "metadata"]),
865
+ };
866
+ /**
867
+ * Any session event: the envelope with an open `type` and `payload`. Clients read an event of
868
+ * a type they do not know as this; `SessionEventSchema` types the known ones.
869
+ */
870
+ export const LiveEventSchema = z.object({
871
+ ...eventEnvelope,
872
+ type: z.string().min(1),
568
873
  payload: z.unknown(),
569
- })
570
- .strict();
571
- export const SessionItemsResponseSchema = z.object({
572
- items: z.array(LiveEventSchema),
573
- cursor: z.string().nullable(),
574
874
  });
575
875
  export const AcceptedResponseSchema = z.object({
576
876
  status: z.literal("accepted"),
@@ -603,10 +903,12 @@ const actionBase = {
603
903
  implementationVersion: z.string(),
604
904
  input: z.unknown(),
605
905
  context: jsonObject,
606
- status: z.enum(["pending", "claimed", "completed", "uncertain", "cancelled"]),
906
+ /** `delivering`: sent to the agent's Action endpoint, not answered yet. */
907
+ status: z.enum(["pending", "delivering", "completed", "uncertain", "cancelled"]),
908
+ /** How many times it was delivered; a delivery token names the one it is for. */
607
909
  generation: z.number().int().nonnegative(),
608
- claimId: z.string().nullable(),
609
- leaseExpiresAt: z.string().nullable(),
910
+ /** When an unanswered delivery counts as lost. Set only while `delivering`. */
911
+ deadlineAt: z.string().nullable().optional(),
610
912
  agent: AgentRefSchema.optional(),
611
913
  };
612
914
  /** The hook point an action runs, and the capabilities that registered it (manifest order). */
@@ -670,7 +972,7 @@ export const ActionSchema = z.union([
670
972
  ]);
671
973
  /**
672
974
  * Transcript events (Host feature `transcript-events`): the log entries a chat UI
673
- * renders. `LiveEvent.payload` stays `unknown` on the wire; `parseTranscriptEvent`
975
+ * renders. They are part of the event catalog (`EVENT_CATALOG`); `parseTranscriptEvent`
674
976
  * types the ones a client reads. Objects pass unknown fields through, so a newer
675
977
  * Host can add fields without breaking older clients.
676
978
  */
@@ -681,11 +983,20 @@ const toolIds = {
681
983
  /** The harness invocation of the call; interactions refer to it. */
682
984
  invocationId: z.string().min(1),
683
985
  };
684
- /** `message.assistant`: one completed model step. `invocationId` is the model call's. */
986
+ /**
987
+ * `message.assistant`: one completed model step. `invocationId` is the model call's.
988
+ * `model`, `finishReason` and `usage` are present when the provider reported them.
989
+ */
685
990
  export const AssistantMessagePayloadSchema = z
686
991
  .object({
687
992
  invocationId: z.string().min(1),
688
993
  text: z.string(),
994
+ model: z
995
+ .object({ provider: z.string(), model: z.string() })
996
+ .passthrough()
997
+ .optional(),
998
+ finishReason: z.string().optional(),
999
+ usage: z.record(z.string(), z.number()).optional(),
689
1000
  toolCalls: z.array(z
690
1001
  .object({
691
1002
  callId: z.string().min(1),
@@ -696,6 +1007,32 @@ export const AssistantMessagePayloadSchema = z
696
1007
  ...eventAgent,
697
1008
  })
698
1009
  .passthrough();
1010
+ /**
1011
+ * `model.failed`: a model call that failed in a known way (Model Calls §6.4). The turn
1012
+ * then fails with `model.<code>`, or recovers.
1013
+ */
1014
+ export const ModelFailedPayloadSchema = z
1015
+ .object({
1016
+ invocationId: z.string().min(1).optional(),
1017
+ code: z.string().min(1),
1018
+ message: z.string(),
1019
+ retryable: z.boolean(),
1020
+ ...eventAgent,
1021
+ })
1022
+ .passthrough();
1023
+ /**
1024
+ * `context.compacted`: the engine summarized older history to fit the model's window
1025
+ * (Model Calls §8). Token counts are estimates.
1026
+ */
1027
+ export const ContextCompactedPayloadSchema = z
1028
+ .object({
1029
+ invocationId: z.string().min(1).optional(),
1030
+ trigger: z.enum(["threshold", "overflow"]),
1031
+ tokensBefore: z.number().int().nonnegative(),
1032
+ tokensAfter: z.number().int().nonnegative(),
1033
+ ...eventAgent,
1034
+ })
1035
+ .passthrough();
699
1036
  /** `tool.completed`: an MCP or sandbox tool the Runtime ran. `error` for a tool error. */
700
1037
  export const ToolCompletedPayloadSchema = z
701
1038
  .object({
@@ -712,6 +1049,9 @@ const actionEventBase = {
712
1049
  actionId: z.string().min(1),
713
1050
  kind: z.string(),
714
1051
  toolName: z.string().optional(),
1052
+ /** A workflow Action: its node's path and key. */
1053
+ path: z.string().optional(),
1054
+ key: z.string().optional(),
715
1055
  callId: z.string().optional(),
716
1056
  invocationId: z.string().optional(),
717
1057
  ...eventAgent,
@@ -766,6 +1106,8 @@ export const DelegationPayloadSchema = z
766
1106
  .passthrough();
767
1107
  const TRANSCRIPT_PAYLOADS = {
768
1108
  "message.assistant": AssistantMessagePayloadSchema,
1109
+ "model.failed": ModelFailedPayloadSchema,
1110
+ "context.compacted": ContextCompactedPayloadSchema,
769
1111
  "tool.completed": ToolCompletedPayloadSchema,
770
1112
  "action.pending": ActionPendingPayloadSchema,
771
1113
  "action.completed": ActionCompletedPayloadSchema,
@@ -779,68 +1121,203 @@ const TRANSCRIPT_PAYLOADS = {
779
1121
  "delegation.completed": DelegationPayloadSchema,
780
1122
  };
781
1123
  export const TRANSCRIPT_EVENT_TYPES = Object.keys(TRANSCRIPT_PAYLOADS);
782
- /** Types a transcript event's payload; `undefined` for other types or a malformed payload. */
783
- export function parseTranscriptEvent(event) {
784
- if (!Object.hasOwn(TRANSCRIPT_PAYLOADS, event.type))
785
- return undefined;
786
- const parsed = TRANSCRIPT_PAYLOADS[event.type].safeParse(event.payload);
787
- return parsed.success
788
- ? { ...event, payload: parsed.data }
789
- : undefined;
790
- }
791
- export const ActionClaimRequestSchema = z
1124
+ /** `command.message`: the message a client sent, as accepted. */
1125
+ export const CommandMessagePayloadSchema = z
792
1126
  .object({
793
- requestId: RequestIdSchema,
794
- implementationVersion: z.string().min(1),
1127
+ ...commandBase,
1128
+ type: z.literal("message"),
1129
+ content: z.string().optional(),
1130
+ data: jsonValue.optional(),
1131
+ /** The turn manifest the message carried, if any. */
1132
+ manifest: z.unknown().optional(),
795
1133
  })
796
- .strict();
797
- export const ActionHeartbeatRequestSchema = z
1134
+ .passthrough();
1135
+ /** `command.approve`: an answer to an approval interaction. */
1136
+ export const CommandApprovePayloadSchema = z
798
1137
  .object({
799
- requestId: RequestIdSchema,
800
- claimId: z.string().min(1),
1138
+ ...commandBase,
1139
+ type: z.literal("approve"),
1140
+ interactionId: z.string().min(1),
1141
+ approved: z.boolean(),
1142
+ })
1143
+ .passthrough();
1144
+ /** `command.respond`: an answer to an input interaction. */
1145
+ export const CommandRespondPayloadSchema = z
1146
+ .object({
1147
+ ...commandBase,
1148
+ type: z.literal("respond"),
1149
+ interactionId: z.string().min(1),
1150
+ value: z.unknown(),
1151
+ })
1152
+ .passthrough();
1153
+ /** `action.delivered`: the Runtime sent an Action to its endpoint. */
1154
+ export const ActionDeliveredPayloadSchema = z
1155
+ .object({
1156
+ actionId: z.string().min(1),
801
1157
  generation: z.number().int().positive(),
1158
+ ...eventAgent,
802
1159
  })
803
- .strict();
804
- export const ActionClaimResponseSchema = z.object({
805
- action: ActionSchema,
806
- claimId: z.string(),
1160
+ .passthrough();
1161
+ /** `action.delivery_failed`: a delivery did not reach its endpoint, or was refused; it is retried. */
1162
+ export const ActionDeliveryFailedPayloadSchema = z
1163
+ .object({
1164
+ actionId: z.string().min(1),
807
1165
  generation: z.number().int().positive(),
808
- leaseExpiresAt: z.string(),
809
- });
810
- export const ExecutorNotificationSchema = z.object({
811
- type: z.literal("work_available"),
812
- });
813
- export const ExecutorRegistrationSchema = z
1166
+ reason: z.string(),
1167
+ message: z.string().optional(),
1168
+ retryInMs: z.number().int().nonnegative(),
1169
+ })
1170
+ .passthrough();
1171
+ /** `sandbox.state`: the session's sandbox changed state. */
1172
+ export const SandboxStatePayloadSchema = z
814
1173
  .object({
815
- agentId: z.string().min(1),
816
- implementationVersion: z.string().min(1),
817
- manifestHash: z.string().min(1).optional(),
818
- token: z.string().min(16),
1174
+ state: z.enum(["creating", "running", "stopped"]),
1175
+ backend: z.string(),
1176
+ isolation: z.string().optional(),
1177
+ image: z.string().optional(),
1178
+ network: z.unknown().optional(),
1179
+ reattach: z.boolean().optional(),
1180
+ lost: z.boolean().optional(),
1181
+ note: z.string().optional(),
1182
+ error: z.string().optional(),
819
1183
  })
820
- .strict();
821
- export const RegisterExecutorsRequestSchema = z
1184
+ .passthrough();
1185
+ /** `sandbox.exec`: one sandbox tool call finished. */
1186
+ export const SandboxExecPayloadSchema = z
822
1187
  .object({
823
- executors: z.array(ExecutorRegistrationSchema).min(1).max(64),
1188
+ tool: z.string(),
1189
+ command: z.string().optional(),
1190
+ outcome: z.string(),
1191
+ code: z.string().optional(),
1192
+ durationMs: z.number().nonnegative(),
824
1193
  })
825
- .strict();
826
- export const RegisterExecutorsResponseSchema = z.object({
827
- executors: z.array(z.object({
828
- agentId: z.string(),
829
- implementationVersion: z.string(),
830
- rotated: z.boolean(),
831
- replacedBy: z.literal("different-credential").optional(),
832
- })),
833
- });
834
- export const ExecutorSummarySchema = z.object({
835
- agentId: z.string(),
836
- implementationVersion: z.string(),
1194
+ .passthrough();
1195
+ /** `node.started`: a workflow node that runs an Action started. */
1196
+ export const NodeStartedPayloadSchema = z
1197
+ .object({
1198
+ path: z.string(),
1199
+ kind: z.string(),
1200
+ key: z.string(),
1201
+ iterations: z.string().optional(),
1202
+ })
1203
+ .passthrough();
1204
+ /** `node.agent`: a workflow node runs as a linked agent session. */
1205
+ export const NodeAgentPayloadSchema = z
1206
+ .object({
1207
+ path: z.string(),
1208
+ iterations: z.string().optional(),
1209
+ sessionId: z.string(),
1210
+ turnId: z.string().nullable().optional(),
1211
+ })
1212
+ .passthrough();
1213
+ /** `loop.iteration`: a Loop started its `n`th agent turn. */
1214
+ export const LoopIterationPayloadSchema = z
1215
+ .object({
1216
+ path: z.string(),
1217
+ n: z.number().int(),
1218
+ sessionId: z.string().optional(),
1219
+ turnId: z.string().optional(),
837
1220
  manifestHash: z.string().optional(),
838
- connected: z.boolean(),
839
- updatedAt: z.string(),
840
- });
841
- export const ListExecutorsResponseSchema = z.object({
842
- executors: z.array(ExecutorSummarySchema),
1221
+ })
1222
+ .passthrough();
1223
+ /** `loop.verified`: a Loop's verifier judged iteration `n`. */
1224
+ export const LoopVerifiedPayloadSchema = z
1225
+ .object({
1226
+ path: z.string(),
1227
+ n: z.number().int(),
1228
+ pass: z.boolean(),
1229
+ feedback: z.string().optional(),
1230
+ data: z.unknown().optional(),
1231
+ })
1232
+ .passthrough();
1233
+ /** `loop.decided`: a Loop's decide step chose to iterate again (`input`) or finish (`output`). */
1234
+ export const LoopDecidedPayloadSchema = z
1235
+ .object({
1236
+ path: z.string(),
1237
+ n: z.number().int(),
1238
+ next: z.enum(["input", "output"]),
1239
+ patched: z.boolean(),
1240
+ })
1241
+ .passthrough();
1242
+ /**
1243
+ * The event catalog (Durable Streams §9.5): every session event type, its payload schema, its
1244
+ * payload schema version and who writes it. A type not listed here cannot be written.
1245
+ *
1246
+ * Evolution: new types and new optional payload fields are additive (clients ignore types
1247
+ * they do not know, and payloads pass unknown fields through). A breaking payload change is a
1248
+ * new type or a protocol version, never an edit in place.
1249
+ */
1250
+ export const EVENT_CATALOG = {
1251
+ "command.message": { payload: CommandMessagePayloadSchema, source: "api", version: 1 },
1252
+ "command.approve": { payload: CommandApprovePayloadSchema, source: "api", version: 1 },
1253
+ "command.respond": { payload: CommandRespondPayloadSchema, source: "api", version: 1 },
1254
+ "turn.completed": { payload: TurnCompletedPayloadSchema, source: "loop", version: 1 },
1255
+ "turn.paused": { payload: TurnPausedPayloadSchema, source: "loop", version: 1 },
1256
+ "turn.failed": { payload: TurnFailedPayloadSchema, source: "loop", version: 1 },
1257
+ "turn.cancelled": { payload: TurnCancelledPayloadSchema, source: "api", version: 1 },
1258
+ "message.assistant": { payload: AssistantMessagePayloadSchema, source: "loop", version: 1 },
1259
+ "model.failed": { payload: ModelFailedPayloadSchema, source: "loop", version: 1 },
1260
+ "context.compacted": { payload: ContextCompactedPayloadSchema, source: "loop", version: 1 },
1261
+ "tool.completed": { payload: ToolCompletedPayloadSchema, source: "loop", version: 1 },
1262
+ "action.pending": { payload: ActionPendingPayloadSchema, source: "loop", version: 1 },
1263
+ "action.delivered": { payload: ActionDeliveredPayloadSchema, source: "loop", version: 1 },
1264
+ "action.delivery_failed": {
1265
+ payload: ActionDeliveryFailedPayloadSchema,
1266
+ source: "loop",
1267
+ version: 1,
1268
+ },
1269
+ "action.completed": { payload: ActionCompletedPayloadSchema, source: "api", version: 1 },
1270
+ "action.uncertain": { payload: ActionUncertainPayloadSchema, source: "loop", version: 1 },
1271
+ "effect.uncertain": { payload: EffectUncertainPayloadSchema, source: "loop", version: 1 },
1272
+ "delegation.started": { payload: DelegationPayloadSchema, source: "loop", version: 1 },
1273
+ "delegation.completed": { payload: DelegationPayloadSchema, source: "loop", version: 1 },
1274
+ "sandbox.state": { payload: SandboxStatePayloadSchema, source: "loop", version: 1 },
1275
+ "sandbox.exec": { payload: SandboxExecPayloadSchema, source: "loop", version: 1 },
1276
+ "node.started": { payload: NodeStartedPayloadSchema, source: "loop", version: 1 },
1277
+ "node.agent": { payload: NodeAgentPayloadSchema, source: "loop", version: 1 },
1278
+ "loop.iteration": { payload: LoopIterationPayloadSchema, source: "loop", version: 1 },
1279
+ "loop.verified": { payload: LoopVerifiedPayloadSchema, source: "api", version: 1 },
1280
+ "loop.decided": { payload: LoopDecidedPayloadSchema, source: "api", version: 1 },
1281
+ };
1282
+ export const EVENT_TYPES = Object.keys(EVENT_CATALOG);
1283
+ export function isEventType(type) {
1284
+ return Object.hasOwn(EVENT_CATALOG, type);
1285
+ }
1286
+ function eventSchema(type) {
1287
+ return z.object({
1288
+ ...eventEnvelope,
1289
+ type: z.literal(type),
1290
+ payload: EVENT_CATALOG[type].payload,
1291
+ });
1292
+ }
1293
+ /** One schema per event type, keyed by type (the OpenAPI components). */
1294
+ export const EVENT_SCHEMAS = Object.fromEntries(EVENT_TYPES.map((type) => [type, eventSchema(type)]));
1295
+ /** A session event of a known type, discriminated on `type`. */
1296
+ export const SessionEventSchema = z.discriminatedUnion("type", EVENT_TYPES.map((type) => EVENT_SCHEMAS[type]));
1297
+ /**
1298
+ * Reads one event from the wire: typed when its type is in the catalog and it matches, else
1299
+ * the bare envelope (a newer Runtime's type, which a client ignores). Throws only when even
1300
+ * the envelope does not match.
1301
+ */
1302
+ export function parseSessionEvent(value) {
1303
+ const known = SessionEventSchema.safeParse(value);
1304
+ if (known.success)
1305
+ return known.data;
1306
+ return LiveEventSchema.parse(value);
1307
+ }
1308
+ export const SessionItemsResponseSchema = z.object({
1309
+ items: z.array(SessionEventSchema),
1310
+ cursor: z.string().nullable(),
843
1311
  });
1312
+ /** Types a transcript event's payload; `undefined` for other types or a malformed payload. */
1313
+ export function parseTranscriptEvent(event) {
1314
+ if (!Object.hasOwn(TRANSCRIPT_PAYLOADS, event.type))
1315
+ return undefined;
1316
+ const parsed = TRANSCRIPT_PAYLOADS[event.type].safeParse(event.payload);
1317
+ return parsed.success
1318
+ ? { ...event, payload: parsed.data }
1319
+ : undefined;
1320
+ }
844
1321
  export const ProtocolRangeSchema = z
845
1322
  .object({
846
1323
  min: z.number().int(),
@@ -962,16 +1439,33 @@ export const QuarantineSchema = z
962
1439
  export const AdminTenantStatusSchema = AdminTenantSchema.extend({
963
1440
  quarantine: QuarantineSchema.optional(),
964
1441
  });
1442
+ /** A stream relay's state (Durable Streams §7). */
1443
+ export const StreamRelayStatusSchema = z
1444
+ .object({
1445
+ /** This process holds the replication slot (one process per slot does). */
1446
+ active: z.boolean(),
1447
+ /** Committed transactions not yet fully in S2. */
1448
+ pendingTxs: z.number().int().nonnegative(),
1449
+ /** Events queued for S2. */
1450
+ pendingRows: z.number().int().nonnegative(),
1451
+ /** The last position acknowledged to the slot. */
1452
+ confirmed: z.string().nullable(),
1453
+ /** Reconciliations of the record with S2 since start (a new or lost slot). */
1454
+ reconciliations: z.number().int().nonnegative(),
1455
+ lastError: z.string().nullable(),
1456
+ /** WAL bytes the slot holds that the relay has not confirmed, when known. */
1457
+ lagBytes: z.number().nonnegative().optional(),
1458
+ })
1459
+ .strict();
965
1460
  export const HostAggregateSchema = z
966
1461
  .object({
967
1462
  runningSessions: z.number().int().nonnegative(),
968
- connectedExecutors: z.number().int().nonnegative(),
1463
+ /** Deliveries to Action endpoints in flight on this Host's open Tenants. */
1464
+ inFlightDeliveries: z.number().int().nonnegative(),
969
1465
  pendingActions: z.number().int().nonnegative(),
970
1466
  uncertainEffects: z.number().int().nonnegative(),
971
- /** Events committed but not yet relayed to Durable Streams, over the open Tenants. */
972
- outboxDepth: z.number().int().nonnegative().optional(),
973
- /** The largest relay lag of an open Tenant: its oldest unrelayed event's age. */
974
- relayLagMs: z.number().nonnegative().optional(),
1467
+ /** This process's stream relay, when it runs one (a Host with S2). */
1468
+ relay: StreamRelayStatusSchema.optional(),
975
1469
  })
976
1470
  .strict();
977
1471
  export const AdminHostStatusSchema = z
@@ -1027,6 +1521,7 @@ export const HostModelViewSchema = z.union([
1027
1521
  model: z.string(),
1028
1522
  authType: z.enum(["api_key", "oauth"]),
1029
1523
  baseUrl: z.string().optional(),
1524
+ settings: CustomModelSettingsSchema.optional(),
1030
1525
  })
1031
1526
  .strict(),
1032
1527
  ]);
@@ -1039,7 +1534,7 @@ export const TenantStatusSchema = z
1039
1534
  store: z.boolean(),
1040
1535
  scheduler: z.boolean(),
1041
1536
  model: z.boolean(),
1042
- executors: z.boolean(),
1537
+ endpoints: z.boolean(),
1043
1538
  schema: z.boolean(),
1044
1539
  })
1045
1540
  .strict(),
@@ -1048,7 +1543,8 @@ export const TenantStatusSchema = z
1048
1543
  .object({
1049
1544
  agentId: z.string(),
1050
1545
  registered: z.boolean(),
1051
- connected: z.boolean(),
1546
+ /** The agent has a registered Action endpoint. */
1547
+ endpoint: z.boolean(),
1052
1548
  })
1053
1549
  .strict()),
1054
1550
  counts: z
@@ -1102,14 +1598,10 @@ export const TenantStatusSchema = z
1102
1598
  lastError: z.string().nullable(),
1103
1599
  })
1104
1600
  .strict(),
1105
- outbox: z
1106
- .object({
1107
- depth: z.number().int().nonnegative(),
1108
- oldestAgeMs: z.number().nonnegative().nullable(),
1109
- })
1110
- .strict(),
1111
- relayLagMs: z.number().nonnegative(),
1112
- collectionPending: z.boolean(),
1601
+ /** The basin generation session streams are in (a reset moves to the next). */
1602
+ generation: z.number().int().nonnegative(),
1603
+ /** The Tenant's own relay; null when the Host's relay serves it. */
1604
+ relay: StreamRelayStatusSchema.nullable(),
1113
1605
  })
1114
1606
  .strict()
1115
1607
  .optional(),
@@ -1124,7 +1616,9 @@ export const SeedTenantConfigRequestSchema = z
1124
1616
  requestId: RequestIdSchema,
1125
1617
  sandbox: z
1126
1618
  .object({
1127
- backend: z.enum(["auto", "virtual"]),
1619
+ backend: z.enum(["auto", "virtual"]).optional(),
1620
+ /** Seeds Tenant setting `sandbox.config` when it is absent. */
1621
+ config: TenantSandboxConfigSchema.optional(),
1128
1622
  })
1129
1623
  .strict()
1130
1624
  .optional(),
@@ -1166,6 +1660,12 @@ export const SUBJECT_SCOPES = [
1166
1660
  const SUBJECT_PATTERN = /^[\x21-\x7e](?:[\x20-\x7e]{0,198}[\x21-\x7e])?$/;
1167
1661
  /** Owner ids the Runtime uses itself: the host model's vault is owned by `host`. */
1168
1662
  const RESERVED_SUBJECTS = new Set(["host"]);
1663
+ /** A valid subject: 1–200 visible ASCII characters, not reserved by the Runtime. */
1664
+ export function isSubject(value) {
1665
+ return (typeof value === "string" &&
1666
+ SUBJECT_PATTERN.test(value) &&
1667
+ !RESERVED_SUBJECTS.has(value));
1668
+ }
1169
1669
  /**
1170
1670
  * Validates `Nylorun-Subject` and `Nylorun-Scopes`. Returns the subject and its scopes, or a
1171
1671
  * message naming what is wrong. Scopes are required: the Runtime never grants a default.
@@ -1193,3 +1693,649 @@ export function parseSubjectHeaders(subject, scopes) {
1193
1693
  scopes: new Set(names),
1194
1694
  };
1195
1695
  }
1696
+ // --- subject tokens and the access policy (Host feature `subject-tokens`) ------------------
1697
+ /** Scopes a subject token may carry: never `agents:write` or `tenant:settings`. */
1698
+ export const TOKEN_SCOPES = ["agents:read", "sessions:own", "vaults:own"];
1699
+ const TokenScopeSchema = z.enum(TOKEN_SCOPES);
1700
+ /** The JWT `typ` of a subject token (RFC 8725 explicit typing). */
1701
+ export const SUBJECT_TOKEN_TYPE = "nylorun-subject+jwt";
1702
+ /** The `aud` of every subject token. */
1703
+ export const SUBJECT_TOKEN_AUDIENCE = "nylorun";
1704
+ /** The `iss` of a Tenant's subject tokens. */
1705
+ export function subjectTokenIssuer(tenantId) {
1706
+ return `urn:nylorun:tenant:${tenantId}`;
1707
+ }
1708
+ /** Token lifetimes, in seconds. */
1709
+ export const TOKEN_TTL_MIN_SECONDS = 60;
1710
+ export const TOKEN_TTL_MAX_SECONDS = 900;
1711
+ export const TOKEN_TTL_DEFAULT_SECONDS = 600;
1712
+ /** A role's name in the access policy; `anon` is reserved for publishable keys. */
1713
+ export const ROLE_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,31}$/;
1714
+ const AgentAllowlistSchema = z.union([
1715
+ z.literal("*"),
1716
+ z.array(z.string().min(1)),
1717
+ ]);
1718
+ export const RoleLimitsSchema = z
1719
+ .object({
1720
+ turnsPerHour: z.number().int().min(1).max(100_000).optional(),
1721
+ concurrentTurns: z.number().int().min(1).max(1000).optional(),
1722
+ })
1723
+ .strict();
1724
+ export const AccessRoleSchema = z
1725
+ .object({
1726
+ scopes: z.array(TokenScopeSchema).min(1),
1727
+ agents: AgentAllowlistSchema,
1728
+ limits: RoleLimitsSchema.optional(),
1729
+ })
1730
+ .strict();
1731
+ /**
1732
+ * The Tenant's access policy: what each role may do with a subject token, what a publishable
1733
+ * key grants alone (`anon`), and how long tokens live. Without roles nothing can be minted.
1734
+ */
1735
+ export const AccessPolicySchema = z
1736
+ .object({
1737
+ version: z.literal(1),
1738
+ roles: z
1739
+ .record(z.string(), AccessRoleSchema)
1740
+ .superRefine((roles, issue) => {
1741
+ for (const name of Object.keys(roles))
1742
+ if (!ROLE_NAME_PATTERN.test(name) || name === "anon")
1743
+ issue.addIssue({
1744
+ code: "custom",
1745
+ message: `Role name ${name} is invalid or reserved`,
1746
+ path: [name],
1747
+ });
1748
+ }),
1749
+ anon: z
1750
+ .object({
1751
+ scopes: z.array(z.literal("agents:read")),
1752
+ agents: AgentAllowlistSchema,
1753
+ })
1754
+ .strict(),
1755
+ tokens: z
1756
+ .object({
1757
+ maxTtlSeconds: z
1758
+ .number()
1759
+ .int()
1760
+ .min(TOKEN_TTL_MIN_SECONDS)
1761
+ .max(TOKEN_TTL_MAX_SECONDS),
1762
+ })
1763
+ .strict(),
1764
+ })
1765
+ .strict();
1766
+ /** The policy of a Tenant that never set one: no roles, nothing for `anon`. */
1767
+ export const DEFAULT_ACCESS_POLICY = Object.freeze({
1768
+ version: 1,
1769
+ roles: {},
1770
+ anon: { scopes: [], agents: [] },
1771
+ tokens: { maxTtlSeconds: TOKEN_TTL_DEFAULT_SECONDS },
1772
+ });
1773
+ export const PutAccessPolicyRequestSchema = z
1774
+ .object({ requestId: RequestIdSchema, policy: AccessPolicySchema })
1775
+ .strict();
1776
+ export const CreateTokenRequestSchema = z
1777
+ .object({
1778
+ requestId: RequestIdSchema,
1779
+ subject: z.string().refine(isSubject, "subject must be 1-200 visible ASCII characters and not reserved"),
1780
+ role: z.string().regex(ROLE_NAME_PATTERN),
1781
+ scopes: z.array(TokenScopeSchema).min(1).optional(),
1782
+ agents: z.array(z.string().min(1)).optional(),
1783
+ ttlSeconds: z
1784
+ .number()
1785
+ .int()
1786
+ .min(TOKEN_TTL_MIN_SECONDS)
1787
+ .max(TOKEN_TTL_MAX_SECONDS)
1788
+ .optional(),
1789
+ })
1790
+ .strict();
1791
+ export const CreateTokenResponseSchema = z
1792
+ .object({
1793
+ token: z.string().min(1),
1794
+ /** ISO time the token stops being accepted. */
1795
+ expiresAt: z.string().min(1),
1796
+ subject: z.string(),
1797
+ role: z.string(),
1798
+ scopes: z.array(TokenScopeSchema),
1799
+ agents: AgentAllowlistSchema,
1800
+ keyId: z.string(),
1801
+ })
1802
+ .strict();
1803
+ export const SIGNING_KEY_STATES = ["standby", "current", "previous", "revoked"];
1804
+ /** A public JSON Web Key as the JWKS publishes it. */
1805
+ export const PublicJwkSchema = z
1806
+ .object({
1807
+ kty: z.literal("EC"),
1808
+ crv: z.literal("P-256"),
1809
+ x: z.string(),
1810
+ y: z.string(),
1811
+ kid: z.string(),
1812
+ alg: z.literal("ES256"),
1813
+ use: z.literal("sig"),
1814
+ })
1815
+ .strict();
1816
+ export const SigningKeyViewSchema = z
1817
+ .object({
1818
+ id: z.string(),
1819
+ state: z.enum(SIGNING_KEY_STATES),
1820
+ alg: z.literal("ES256"),
1821
+ publicKey: PublicJwkSchema,
1822
+ createdAt: z.string(),
1823
+ activatedAt: z.string().nullable(),
1824
+ retiredAt: z.string().nullable(),
1825
+ revokedAt: z.string().nullable(),
1826
+ })
1827
+ .strict();
1828
+ export const SigningKeyListSchema = z
1829
+ .object({ keys: z.array(SigningKeyViewSchema) })
1830
+ .strict();
1831
+ export const JwksSchema = z.object({ keys: z.array(PublicJwkSchema) }).strict();
1832
+ export const RotateSigningKeysRequestSchema = z
1833
+ .object({ requestId: RequestIdSchema, force: z.boolean().optional() })
1834
+ .strict();
1835
+ export const RevokeSigningKeyRequestSchema = z
1836
+ .object({ requestId: RequestIdSchema })
1837
+ .strict();
1838
+ export const RevokeSubjectRequestSchema = z
1839
+ .object({
1840
+ requestId: RequestIdSchema,
1841
+ subject: z.string().refine(isSubject, "subject must be 1-200 visible ASCII characters and not reserved"),
1842
+ })
1843
+ .strict();
1844
+ export const RevokeSubjectResponseSchema = z
1845
+ .object({ subject: z.string(), epoch: z.number().int().nonnegative() })
1846
+ .strict();
1847
+ // --- publishable keys (Host feature `browser-access`) --------------------------------------
1848
+ /** Loopback origins with any port, for development: `http://localhost:*`, `http://127.0.0.1:*`. */
1849
+ export const LOOPBACK_ORIGIN_WILDCARDS = ["http://localhost:*", "http://127.0.0.1:*"];
1850
+ /** True for a serialized web origin: `scheme://host[:port]`, lowercase, no path. */
1851
+ export function isSerializedOrigin(value) {
1852
+ let url;
1853
+ try {
1854
+ url = new URL(value);
1855
+ }
1856
+ catch {
1857
+ return false;
1858
+ }
1859
+ return ((url.protocol === "https:" || url.protocol === "http:") &&
1860
+ url.origin === value &&
1861
+ // Host names only: no wildcards or other characters URL parsing lets through.
1862
+ /^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])$/.test(url.hostname));
1863
+ }
1864
+ /** An origin allowlist entry: an exact origin or a loopback wildcard. */
1865
+ export const OriginEntrySchema = z
1866
+ .string()
1867
+ .refine((value) => LOOPBACK_ORIGIN_WILDCARDS.includes(value) ||
1868
+ isSerializedOrigin(value), "must be an origin such as https://app.example.com, or http://localhost:*");
1869
+ /** True when `origin` (a request's `Origin`) is allowed by `origins`. */
1870
+ export function originAllowed(origins, origin) {
1871
+ if (!isSerializedOrigin(origin))
1872
+ return false;
1873
+ for (const entry of origins) {
1874
+ if (entry === origin)
1875
+ return true;
1876
+ if (entry.endsWith(":*")) {
1877
+ const prefix = entry.slice(0, -1);
1878
+ if (origin.startsWith(prefix) && /^\d{1,5}$/.test(origin.slice(prefix.length)))
1879
+ return true;
1880
+ }
1881
+ }
1882
+ return false;
1883
+ }
1884
+ export const PublishableKeySchema = z
1885
+ .object({
1886
+ id: z.string(),
1887
+ name: z.string(),
1888
+ key: z.string(),
1889
+ origins: z.array(z.string()),
1890
+ createdAt: z.string(),
1891
+ revokedAt: z.string().nullable(),
1892
+ })
1893
+ .strict();
1894
+ export const CreatePublishableKeyRequestSchema = z
1895
+ .object({
1896
+ requestId: RequestIdSchema,
1897
+ name: z.string().min(1).max(100),
1898
+ /** `[]` allows native apps only (no `Origin`). */
1899
+ origins: z.array(OriginEntrySchema).max(100),
1900
+ })
1901
+ .strict();
1902
+ export const UpdatePublishableKeyRequestSchema = z
1903
+ .object({
1904
+ requestId: RequestIdSchema,
1905
+ origins: z.array(OriginEntrySchema).max(100),
1906
+ })
1907
+ .strict();
1908
+ // Successful answers of the Tenant and Admin APIs that had no schema of their own. With the
1909
+ // request schemas above they describe every body the Runtime sends (its OpenAPI document).
1910
+ /** `GET /v1/agents` with an application key: every definition, manifest included. */
1911
+ export const AgentDefinitionViewSchema = z
1912
+ .object({
1913
+ agentId: z.string(),
1914
+ manifest: z.record(z.string(), z.unknown()),
1915
+ manifestHash: z.string(),
1916
+ implementationVersion: z.string(),
1917
+ })
1918
+ .strict();
1919
+ export const ListAgentsResponseSchema = z
1920
+ .object({ agents: z.array(AgentDefinitionViewSchema) })
1921
+ .strict();
1922
+ /** `GET /v1/agents` with a subject token or publishable key: the allowed agents' names only. */
1923
+ export const PublicAgentSchema = z
1924
+ .object({
1925
+ agentId: z.string(),
1926
+ name: z.string().optional(),
1927
+ description: z.string().optional(),
1928
+ })
1929
+ .strict();
1930
+ export const ListPublicAgentsResponseSchema = z
1931
+ .object({ agents: z.array(PublicAgentSchema) })
1932
+ .strict();
1933
+ export const PutAgentResponseSchema = z
1934
+ .object({
1935
+ agentId: z.string(),
1936
+ manifestHash: z.string(),
1937
+ implementationVersion: z.string(),
1938
+ })
1939
+ .strict();
1940
+ export const SESSION_STATUSES = [
1941
+ "idle",
1942
+ "runnable",
1943
+ "running",
1944
+ "waiting",
1945
+ "paused",
1946
+ "uncertain",
1947
+ "completed",
1948
+ "failed",
1949
+ "cancelled",
1950
+ ];
1951
+ export const SessionSummarySchema = z
1952
+ .object({
1953
+ id: z.string(),
1954
+ agentId: z.string(),
1955
+ ownerUserId: z.string(),
1956
+ status: z.enum(SESSION_STATUSES),
1957
+ activeTurnId: z.string().nullable(),
1958
+ })
1959
+ .strict();
1960
+ export const ListSessionsResponseSchema = z
1961
+ .object({ sessions: z.array(SessionSummarySchema) })
1962
+ .strict();
1963
+ /** `PUT` and `GET /v1/sessions/:id`. */
1964
+ export const SessionViewSchema = z
1965
+ .object({
1966
+ id: z.string(),
1967
+ agentId: z.string(),
1968
+ ownerUserId: z.string(),
1969
+ manifestHash: z.string(),
1970
+ implementationVersion: z.string(),
1971
+ status: z.enum(SESSION_STATUSES),
1972
+ activeTurnId: z.string().nullable(),
1973
+ vaultIds: z.array(z.string()),
1974
+ credentialSelections: z.array(CredentialSelectionSchema),
1975
+ /** The session whose sandbox this one shares; `null` when it owns its own. */
1976
+ sandboxOwnerId: z.string().nullable(),
1977
+ /** The sandbox pinned when the session was opened, or `null`. */
1978
+ sandbox: z.record(z.string(), z.unknown()).nullable(),
1979
+ sandboxSource: z.enum(["default", "inline", "shared"]).optional(),
1980
+ mcpSnapshot: z.record(z.string(), z.unknown()).nullable(),
1981
+ mcpDiagnostics: z.array(z.record(z.string(), z.unknown())),
1982
+ /** What the session waits on: interactions, approvals, timers. */
1983
+ waits: z.unknown().optional(),
1984
+ error: z.string().optional(),
1985
+ /** Its Actions that are pending, being delivered or uncertain. */
1986
+ actions: z.array(ActionSchema),
1987
+ uncertainEffects: z.array(z
1988
+ .object({
1989
+ effectId: z.string(),
1990
+ turnId: z.string(),
1991
+ kind: z.string(),
1992
+ error: z.unknown(),
1993
+ })
1994
+ .strict()),
1995
+ })
1996
+ .strict();
1997
+ /** A sandbox tool call's answer (`POST …/sandbox/:tool`): its output, or why it failed. */
1998
+ export const SandboxToolOutcomeSchema = z.discriminatedUnion("kind", [
1999
+ z.object({ kind: z.literal("completed"), output: z.unknown() }).strict(),
2000
+ z
2001
+ .object({ kind: z.literal("failed"), code: z.string(), message: z.string() })
2002
+ .strict(),
2003
+ ]);
2004
+ export const ResetTenantResponseSchema = z.object({ ok: z.literal(true) }).strict();
2005
+ /** `GET /v1/tenant/models`: public provider and model names, no credentials. */
2006
+ export const HostModelCatalogSchema = z
2007
+ .object({
2008
+ providers: z.array(z
2009
+ .object({
2010
+ id: z.string(),
2011
+ name: z.string(),
2012
+ models: z.array(z.object({ id: z.string(), name: z.string() }).strict()),
2013
+ })
2014
+ .strict()),
2015
+ })
2016
+ .strict();
2017
+ export const HostModelProviderInfoSchema = z
2018
+ .object({
2019
+ id: z.string(),
2020
+ name: z.string(),
2021
+ model: z.string(),
2022
+ authType: z.enum(["api_key", "oauth"]),
2023
+ baseUrl: z.string().optional(),
2024
+ settings: CustomModelSettingsSchema.optional(),
2025
+ lastUpdated: z.string(),
2026
+ active: z.boolean(),
2027
+ })
2028
+ .strict();
2029
+ export const ListProvidersResponseSchema = z
2030
+ .object({ providers: z.array(HostModelProviderInfoSchema) })
2031
+ .strict();
2032
+ const SandboxResourcesLimitSchema = z
2033
+ .object({ cpus: z.number(), memoryMiB: z.number() })
2034
+ .strict();
2035
+ /** A Tenant's sandbox configuration with every default applied (sizes in MiB). */
2036
+ export const EffectiveSandboxConfigSchema = z
2037
+ .object({
2038
+ default: z.union([z.literal("none"), z.literal("virtual"), SandboxInlineRequestSchema]),
2039
+ limits: z
2040
+ .object({
2041
+ network: z.array(z.string()),
2042
+ resources: SandboxResourcesLimitSchema,
2043
+ defaultResources: SandboxResourcesLimitSchema,
2044
+ idle: z.string(),
2045
+ })
2046
+ .strict(),
2047
+ })
2048
+ .strict();
2049
+ const SandboxBackendNameSchema = z.enum(["virtual"]);
2050
+ const SandboxIsolationSchema = z.enum(["process", "container"]);
2051
+ /** `GET` and `PUT /v1/tenant/sandbox`: the backend chosen, and the configuration in force. */
2052
+ export const TenantSandboxViewSchema = z
2053
+ .object({
2054
+ preference: z.union([z.literal("auto"), SandboxBackendNameSchema]),
2055
+ backend: SandboxBackendNameSchema.nullable(),
2056
+ isolation: SandboxIsolationSchema.nullable(),
2057
+ reason: z.string(),
2058
+ probes: z.array(z
2059
+ .object({
2060
+ name: SandboxBackendNameSchema,
2061
+ available: z.boolean(),
2062
+ isolation: SandboxIsolationSchema,
2063
+ reason: z.string().optional(),
2064
+ version: z.string().optional(),
2065
+ })
2066
+ .strict()),
2067
+ defaultImage: z.string(),
2068
+ config: EffectiveSandboxConfigSchema,
2069
+ })
2070
+ .strict();
2071
+ export const ListVaultsResponseSchema = z.object({ vaults: z.array(VaultInfoSchema) }).strict();
2072
+ export const ListCredentialsResponseSchema = z
2073
+ .object({ credentials: z.array(CredentialInfoSchema) })
2074
+ .strict();
2075
+ /** A deleted vault or credential. */
2076
+ export const DeletedResponseSchema = z.object({ id: z.string() }).strict();
2077
+ export const AccessPolicyResponseSchema = z.object({ policy: AccessPolicySchema }).strict();
2078
+ export const ListPublishableKeysResponseSchema = z
2079
+ .object({ keys: z.array(PublishableKeySchema) })
2080
+ .strict();
2081
+ export const AdminTenantListSchema = z.array(AdminTenantSchema);
2082
+ export const HostShutdownResponseSchema = z
2083
+ .object({ status: z.literal("shutting_down") })
2084
+ .strict();
2085
+ /** The last frame of a session stream the Runtime ends: `event: nylorun.closed`. */
2086
+ export const StreamClosedFrameSchema = z
2087
+ .object({ reason: z.enum(["token_expired", "revoked"]) })
2088
+ .strict();
2089
+ /**
2090
+ * The `code` of an AG-UI `RUN_ERROR` the Runtime sends: a rejection's code, or `session_busy`
2091
+ * (another turn is running) or `runtime_error` (the Runtime failed). Never an HTTP body's code.
2092
+ */
2093
+ export const AgUiRunErrorCodeSchema = z.enum([
2094
+ ...ERROR_CODES,
2095
+ "session_busy",
2096
+ "runtime_error",
2097
+ ]);
2098
+ // --- Action endpoints: the Runtime delivers Actions over HTTP ------------------------------
2099
+ /** The JWT `typ` of a delivery token (RFC 8725 explicit typing). */
2100
+ export const DELIVERY_TOKEN_TYPE = "nylorun-delivery+jwt";
2101
+ /**
2102
+ * A delivery token lives no longer than a subject token: rotating signing keys revokes the
2103
+ * previous key once the longest token it may have signed has expired.
2104
+ */
2105
+ export const DELIVERY_TOKEN_MAX_TTL_SECONDS = TOKEN_TTL_MAX_SECONDS;
2106
+ /** Inline delivery timeouts, in milliseconds. The maximum keeps a token within its lifetime. */
2107
+ export const ENDPOINT_TIMEOUT_DEFAULT_MS = 60_000;
2108
+ export const ENDPOINT_TIMEOUT_MAX_MS = (DELIVERY_TOKEN_MAX_TTL_SECONDS - 60) * 1000;
2109
+ /** In-flight deliveries per endpoint when the registration does not say. */
2110
+ export const ENDPOINT_MAX_CONCURRENT_DEFAULT = 16;
2111
+ const isEndpointUrl = (value) => {
2112
+ try {
2113
+ const url = new URL(value);
2114
+ return ((url.protocol === "http:" || url.protocol === "https:") &&
2115
+ !url.username &&
2116
+ !url.password &&
2117
+ !url.hash);
2118
+ }
2119
+ catch {
2120
+ return false;
2121
+ }
2122
+ };
2123
+ const EndpointUrlSchema = z
2124
+ .string()
2125
+ .max(2048)
2126
+ .refine(isEndpointUrl, {
2127
+ message: "An endpoint URL is an http or https URL without credentials or a fragment",
2128
+ });
2129
+ /** One agent's or workflow's Action endpoint, as the application registers it. */
2130
+ export const EndpointRegistrationSchema = z
2131
+ .object({
2132
+ agentId: z.string().min(1),
2133
+ url: EndpointUrlSchema,
2134
+ implementationVersion: z.string().min(1),
2135
+ manifestHash: z.string().min(1).optional(),
2136
+ timeoutMs: z.number().int().min(1000).max(ENDPOINT_TIMEOUT_MAX_MS).optional(),
2137
+ maxConcurrent: z.number().int().min(1).max(256).optional(),
2138
+ })
2139
+ .strict();
2140
+ export const PutEndpointsRequestSchema = z
2141
+ .object({
2142
+ endpoints: z
2143
+ .array(EndpointRegistrationSchema)
2144
+ .min(1)
2145
+ .max(64)
2146
+ .refine((endpoints) => new Set(endpoints.map((e) => e.agentId)).size === endpoints.length, { message: "Endpoint registrations must be unique per agent" }),
2147
+ })
2148
+ .strict();
2149
+ /** What recent deliveries and the last ping say about an endpoint. */
2150
+ export const EndpointHealthSchema = z
2151
+ .object({
2152
+ lastDeliveryAt: z.string().optional(),
2153
+ lastSuccessAt: z.string().optional(),
2154
+ lastError: z.object({ code: z.string(), message: z.string() }).optional(),
2155
+ consecutiveFailures: z.number().int().nonnegative(),
2156
+ /** What the handler reported serving on the last ping. */
2157
+ served: z
2158
+ .object({
2159
+ implementationVersion: z.string(),
2160
+ manifestHash: z.string().optional(),
2161
+ })
2162
+ .strict()
2163
+ .optional(),
2164
+ })
2165
+ .strict();
2166
+ export const EndpointSchema = z
2167
+ .object({
2168
+ agentId: z.string(),
2169
+ url: z.string(),
2170
+ implementationVersion: z.string(),
2171
+ manifestHash: z.string().optional(),
2172
+ timeoutMs: z.number().int(),
2173
+ maxConcurrent: z.number().int(),
2174
+ health: EndpointHealthSchema,
2175
+ updatedAt: z.string(),
2176
+ })
2177
+ .strict();
2178
+ export const ListEndpointsResponseSchema = z
2179
+ .object({
2180
+ endpoints: z.array(EndpointSchema),
2181
+ })
2182
+ .strict();
2183
+ export const DeleteEndpointResponseSchema = z
2184
+ .object({ agentId: z.string(), deleted: z.literal(true) })
2185
+ .strict();
2186
+ /** The body the Runtime POSTs to an Action endpoint. */
2187
+ export const ActionDeliverySchema = z.discriminatedUnion("type", [
2188
+ z
2189
+ .object({
2190
+ type: z.literal("action"),
2191
+ action: ActionSchema,
2192
+ /** The Action's session has a sandbox, so `ctx.sandbox` is available. */
2193
+ sandbox: z.boolean(),
2194
+ })
2195
+ .strict(),
2196
+ z
2197
+ .object({
2198
+ type: z.literal("ping"),
2199
+ agentId: z.string().min(1),
2200
+ manifestHash: z.string().min(1).optional(),
2201
+ })
2202
+ .strict(),
2203
+ ]);
2204
+ /** An Action endpoint's answer to a ping. */
2205
+ export const EndpointPingResponseSchema = z.object({
2206
+ agentId: z.string(),
2207
+ implementationVersion: z.string(),
2208
+ manifestHash: z.string().optional(),
2209
+ });
2210
+ /** The answer to a background delivery's heartbeat: a fresh token and the new deadline. */
2211
+ export const DeliveryHeartbeatResponseSchema = z.object({
2212
+ token: z.string().min(1),
2213
+ deadlineAt: z.string(),
2214
+ });
2215
+ /**
2216
+ * The receipt of a background result (`POST /v1/actions/:id/result`): a session command's
2217
+ * receipt without `requestId`, since the result carries none. The same result again returns it.
2218
+ */
2219
+ export const ActionResultReceiptSchema = AcceptedResponseSchema.omit({ requestId: true });
2220
+ // --- Studio embedding (Studio design §8) ---------------------------------------------------
2221
+ /** A Tenant id as Studio's routes accept it. */
2222
+ const STUDIO_TENANT_ID = /^[A-Za-z0-9_-]{1,128}$/;
2223
+ /** `POST /_studio/login-tokens` body. No `tenant` mints a Host-wide token (the CLI's `{}`). */
2224
+ export const StudioLoginTokenRequestSchema = z
2225
+ .object({
2226
+ tenant: z.string().regex(STUDIO_TENANT_ID, "must be a Tenant id").optional(),
2227
+ subject: z
2228
+ .string()
2229
+ .refine(isSubject, "must be 1–200 visible ASCII characters")
2230
+ .optional(),
2231
+ })
2232
+ .strict();
2233
+ export const StudioLoginTokenResponseSchema = z.object({
2234
+ /** Single-use, valid for two minutes. */
2235
+ token: z.string().min(1),
2236
+ /** The cookie login URL; refused for a token limited to a Tenant. */
2237
+ url: z.string().min(1),
2238
+ expiresAt: z.string().min(1),
2239
+ tenant: z.string().nullable(),
2240
+ subject: z.string().nullable(),
2241
+ });
2242
+ /** `POST /_studio/sessions` body: the login token an embedder passed in `init`. */
2243
+ export const StudioSessionRequestSchema = z.object({ token: z.string().min(1) }).strict();
2244
+ export const StudioSessionResponseSchema = z.object({
2245
+ /** Bearer for every `/_studio/*` request; kept in memory only. */
2246
+ sessionToken: z.string().min(1),
2247
+ tenant: z.string().nullable(),
2248
+ subject: z.string().nullable(),
2249
+ expiresAt: z.string().min(1),
2250
+ });
2251
+ /** Message protocol versions this release speaks. */
2252
+ export const STUDIO_EMBED_PROTOCOLS = [1];
2253
+ export const STUDIO_EMBED_MESSAGE_TYPE = "nylorun.studio";
2254
+ const HEX_COLOR = z.string().regex(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/);
2255
+ /** The embedder's theme. Unknown keys are dropped, not rejected. */
2256
+ export const StudioThemeSchema = z.object({
2257
+ mode: z.enum(["light", "dark"]),
2258
+ accent: HEX_COLOR.optional(),
2259
+ background: HEX_COLOR.optional(),
2260
+ foreground: HEX_COLOR.optional(),
2261
+ });
2262
+ const EMBED_ROUTE = z
2263
+ .string()
2264
+ .max(2048)
2265
+ .regex(/^\/tenants\/[^/?#\s]+(?:\/[^?#\s]*)?$/, "must be a Studio route under /tenants/");
2266
+ const EXTERNAL_URL = z.string().refine((value) => {
2267
+ try {
2268
+ const url = new URL(value);
2269
+ return url.protocol === "https:" || url.protocol === "http:";
2270
+ }
2271
+ catch {
2272
+ return false;
2273
+ }
2274
+ }, "must be an http or https URL");
2275
+ function embed(kind, shape) {
2276
+ return z.object({
2277
+ type: z.literal(STUDIO_EMBED_MESSAGE_TYPE),
2278
+ protocol: z.number().int().positive(),
2279
+ kind: z.literal(kind),
2280
+ ...shape,
2281
+ });
2282
+ }
2283
+ /** Every message between an embedder and Studio (Studio design §8.8). */
2284
+ export const StudioEmbedMessageSchema = z.discriminatedUnion("kind", [
2285
+ embed("ready", {
2286
+ protocols: z.array(z.number().int().positive()).min(1),
2287
+ studioVersion: z.string(),
2288
+ }),
2289
+ embed("init", {
2290
+ token: z.string().min(1),
2291
+ theme: StudioThemeSchema.optional(),
2292
+ route: EMBED_ROUTE.optional(),
2293
+ }),
2294
+ embed("token.refresh", { token: z.string().min(1) }),
2295
+ embed("theme.changed", { theme: StudioThemeSchema }),
2296
+ embed("navigate", { route: EMBED_ROUTE }),
2297
+ embed("session", {
2298
+ tenant: z.string().nullable(),
2299
+ subject: z.string().nullable(),
2300
+ expiresAt: z.string(),
2301
+ }),
2302
+ embed("token.expiring", { expiresAt: z.string().nullable() }),
2303
+ embed("route.changed", { route: z.string() }),
2304
+ embed("open.external", { url: EXTERNAL_URL }),
2305
+ embed("open.babai", { sessionId: z.string().min(1) }),
2306
+ embed("error", { code: z.string().min(1), message: z.string() }),
2307
+ ]);
2308
+ /** Schemes that never name an embedder. */
2309
+ const NON_EMBEDDER_SCHEMES = new Set([
2310
+ "about",
2311
+ "blob",
2312
+ "data",
2313
+ "file",
2314
+ "filesystem",
2315
+ "javascript",
2316
+ "ws",
2317
+ "wss",
2318
+ ]);
2319
+ const CUSTOM_ORIGIN = /^([a-z][a-z0-9+.-]*):\/\/([a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::(\d{1,5}))?$/;
2320
+ /** True for one exact embedder origin: `https://…`, `http://…` or `<custom>://host[:port]`. */
2321
+ export function isFrameAncestor(value) {
2322
+ if (value.startsWith("http://") || value.startsWith("https://"))
2323
+ return isSerializedOrigin(value);
2324
+ const match = CUSTOM_ORIGIN.exec(value);
2325
+ if (!match)
2326
+ return false;
2327
+ if (NON_EMBEDDER_SCHEMES.has(match[1]))
2328
+ return false;
2329
+ return match[3] === undefined || Number(match[3]) <= 65535;
2330
+ }
2331
+ /**
2332
+ * Parses `NYLORUN_STUDIO_FRAME_ANCESTORS`: exact origins separated by whitespace. Wildcards,
2333
+ * keywords, scheme-only entries and paths are refused with the entry named. Empty gives `[]`.
2334
+ */
2335
+ export function parseFrameAncestors(value) {
2336
+ const entries = value.split(/\s+/).filter((entry) => entry !== "");
2337
+ for (const entry of entries)
2338
+ if (!isFrameAncestor(entry))
2339
+ 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.`);
2340
+ return [...new Set(entries)];
2341
+ }