@nylorun/core 0.9.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # @nylorun/core
2
2
 
3
+ ## 0.10.0-beta
4
+
5
+ ### Major Changes
6
+
7
+ - 5ca1923: **Clients for one Tenant per installation: a stack per project, nothing selects a Tenant.** Upgrade these with the Runtime; they speak protocol 5. Existing stacks are left as they are: see MIGRATION.md.
8
+
9
+ - **Breaking (`nylorun`): one stack per project.** `nylorun start` in a project creates the project's stack (named after the project directory, or `--name`; Host root `~/.nylorun/stacks/<name>/`, Compose project `nylorun-<name>`, its own free ports and volumes), waits for its Runtime to create the stack's Tenant, writes the Project link (`.nylorun/link.json` format 2: `stack`, `hostUrl`, `hostId`, `tenantId`) and `.nylorun/credentials.json` (the key of the derived principal `project`, derived from the stack's admin key), and seeds the model provider from the project's `.env`. `nylorun ls` lists the machine's stacks and `nylorun delete <name>` removes one with its volumes and Host root. `nylorun status` shows the stack's Tenant; `nylorun studio` opens it. The old single stack under `~/.nylorun` is never touched: `start` notes it, and `nylorun legacy stop|delete` handles it. Every stack command takes `--name <stack>` (or `NYLORUN_STACK`, or the Project link's stack); `start --no-link` starts a stack without linking the directory; `nylorun reset` resets the selected stack only. The runtime container's healthcheck is now `/health`, so a Tenant that cannot open is reported by `start` from the Admin status at once instead of after a 300 s wait. `NYLORUN_HOME` still overrides the Host root. Stacks start and stop only when you say so.
10
+ - **Breaking (`@nylorun/cli`): no Tenant commands.** `nylo tenant create|use|list|current|delete` are removed; `nylo status`, `nylo reset` and `nylo endpoints` replace `nylo tenant status|reset|endpoints` on the linked installation. `nylo env` prints `NYLORUN_RUNTIME_URL` and `NYLORUN_SERVER_KEY` only. `nylo` no longer writes Project links.
11
+ - **Breaking (`@nylorun/agents`): no Tenant to name.** The `tenant` option (`createClient`, `Transport`, `resolveConnection`, `createActionHandler({ runtime })`, `JwksCache`) and `NYLORUN_TENANT` are gone, and no request sends `Nylorun-Tenant`; a connection is a URL and a key. A Project link of format 0 or 1 is refused with `connection_missing`, naming `npx nylorun start`. `verifyDeliveryToken`'s `tenantId` is optional: without it any Tenant issuer is accepted, since the installation's keys bind it. `TENANT_HEADER` is no longer re-exported.
12
+ - **Breaking (`@nylorun/admin`): status only.** `createTenant`, `listTenants`, `getTenant` and `deleteTenant` are removed; `status().tenant` names the Host's Tenant, and `deriveTenantKey` / `deriveStudioToken` derive its keys. Local Host resolution reads the stack's Host root (`stack` option, `NYLORUN_STACK`, or the Project link's `stack`); `NYLORUN_HOME` and `home` still override it. `stackHostRoot(name)` is exported.
13
+ - **Breaking (`@nylorun/studio`): Studio serves its installation's Tenant.** The Tenant picker, list and create are gone, with `/_studio/tenants`; `/` opens `/tenants/<id>`. The `/tenants/:tenant` routes and the login token's `tenant` claim stay for embedders and must name that Tenant. The proxy sends no `Nylorun-Tenant`.
14
+ - **`@nylorun/create-agent`:** the next steps are `npx nylorun start`, then `npm run dev`.
15
+ - `@nylorun/core`: `ProjectLinkFileSchema` accepts format 2 with `stack`, and `tenantId` is optional; `ERROR_CODES` loses `tenant_conflict` and `active_work`.
16
+
17
+ - 5ca1923: **One Tenant per installation: a database per Tenant, protocol 5.** A Runtime serves exactly one Tenant, the one its Postgres database holds. Two Tenants are two installations.
18
+
19
+ - **Breaking: fresh start.** The Tenant's state is in the fixed schema `nylorun` of its own database and its record in `nylorun_streams`, keyed by session (no `tenant_id`). A database written by an earlier Runtime (`tenant_<id>` schemas, or a record keyed by Tenant) is refused: the Host stays up but not ready, and `/v1/admin/status` names the cause `database-layout-old`. Point the Runtime at a new database (with the local stack, a new stack); the old one is never changed.
20
+ - **The Host creates its Tenant** on first start, in the migration transaction: `NYLORUN_TENANT_ID` (default a new id), `NYLORUN_TENANT_NAME` (default `default`), the Studio principal and the derived principals of `NYLORUN_DERIVED_PRINCIPALS` (comma-separated, default `project`), whose keys the admin key derives (`deriveTenantKey`). Later starts open the same Tenant and add derived principals configured since.
21
+ - **Breaking: no Tenant catalog.** `/v1/admin/tenants` and `/v1/admin/tenants/{tenantId}` are gone (404). `AdminStatus.tenants[]` is replaced by `AdminStatus.tenant` (`id`, `name`, `state: open | unavailable`, `envelope`, and `cause` when it could not be opened). `CreateTenantRequestSchema`, `AdminTenantSchema`, `AdminTenantStatusSchema`, `AdminTenantListSchema` and `QuarantineSchema` leave `@nylorun/core`; `HostTenantSchema` and `TenantCauseSchema` replace them. `@nylorun/admin`'s `listTenants`, `getTenant`, `deleteTenant` and `createTenant` are removed (see below).
22
+ - **Readiness instead of quarantine.** A Tenant that cannot be opened (`schema-too-new`, `kek-missing`, `migration-failed`, `envelope-invalid`, `database-layout-old`, …) fails `/ready` (check `tenant`, which replaces `discovery`) and is reported with its repair in `/v1/admin/status` and the log; every Tenant request gets the opaque 404. A failure outside it (Postgres unreachable) is retried.
23
+ - **Protocol 5.** `PROTOCOL_VERSION = 5`; the Host serves protocols 4 and 5 for one release. Clients no longer require `runtime-tenants`; the Host still advertises it. No request needs `Nylorun-Tenant`: a request without it reaches the Host's Tenant, and one naming another Tenant (or a malformed one), or a publishable key of another Tenant, gets the opaque 404. The OpenAPI documents drop the header parameter and the Admin Tenant routes.
24
+ - **Paths.** The Tenant directory is `<Host root>/tenant/` (was `tenants/<id>/`); `trash/` and the SQLite move to it are gone. The gates service serves its database's Tenant, and its `Nylorun-Tenant` header is optional (when sent, it must name that Tenant).
25
+ - **Breaking: `startEphemeralRuntime` needs a database; the in-memory Session Store is removed.** `StartEphemeralRuntimeOptions.database` is required: a Postgres URL, for which the Runtime opens a pool and ends it on `close()`, or a pool the caller ends. It creates its Tenant in that database through the same bootstrap as a Host, or serves the Tenant the database already holds; the data stays after `close()`, so give each test Tenant a database of its own. Durable Streams and scheduling stay in process. See `MIGRATION.md`.
26
+
27
+ ### Minor Changes
28
+
29
+ - fed780d: **Hard caps on model spend.** A Tenant can cap what its model calls use, per turn, per agent per UTC day or month, or for the whole Tenant per day or month, in USD, tokens or both. Before each call the model gate checks the scope's recorded spend, plus its calls in flight, against the cap. Once a cap is reached the call fails with the new `budget_exhausted` code, which is never retried, and the turn fails with `model.budget_exhausted`. A runaway loop stops there, at most one call over its cap.
30
+
31
+ - `PUT /v1/tenant/budgets` replaces the budgets and `GET /v1/tenant/budgets` reads them. Both need the application key or `tenant:settings`.
32
+ - `@nylorun/core` adds `budget_exhausted` to `ModelFailureCode` and `MODEL_FAILURE_CODES`, plus `ModelBudgetSchema`, `PutModelBudgetsRequestSchema` and `ModelBudgetsSchema`. Code that switches over failure codes exhaustively needs the new case.
33
+ - Custom endpoints are priced at $0, so only a token limit stops them.
34
+ - Budgets survive a `sessions` reset. A reset of scope `all` clears them.
35
+
36
+ - fed780d: **Every model call is recorded in the Tenant's usage ledger.** The model gate writes one row per call that answers: the session, turn and agent, the provider and model, the tokens (input, output, cached, cache write, reasoning) and pi-ai's price in USD. Custom endpoints count as $0. A call the gateway ran twice after a restart is recorded twice and flagged as a duplicate, since the provider billed both.
37
+
38
+ - `GET /v1/tenant/usage?scope=tenant|agent|turn&id=&period=day|month|total` totals the ledger. It needs the application key or `tenant:settings`, like the other Tenant settings.
39
+ - `@nylorun/core/contracts` adds `ModelUsageScopeSchema`, `ModelUsageQuerySchema` and `ModelUsageTotalsSchema`.
40
+ - The ledger survives a `sessions` reset. A reset of scope `all` clears it.
41
+ - The gateway and the runtime must run the same build, as before.
42
+
43
+ - 7f4c3f1: **One history: a session's transcript is folded from its record.** The own loop's model-facing transcript is no longer stored on the session row, where up to three copies of it lived (`state`, `turnStartState` and the checkpoint). After each segment that keeps its state, the Runtime records the change as an internal `transcript.updated` event: the new entries, or a snapshot after compaction. Each segment folds the transcript back from the record, and a cancelled or failed turn's entries are undone, as before.
44
+
45
+ - **Internal events.** `transcript.updated` is in the event catalog with `visibility: "internal"`. SSE, history, AG-UI and A2A never serve it. Served events can therefore skip the seq numbers internal events hold; cursors resume as before. `TranscriptUpdatedPayloadSchema` is exported from `@nylorun/core/contracts`, and catalog entries may declare `visibility`.
46
+ - **No checkpoints table.** Every settle used to write a copy of the session's checkpoint to a `checkpoints` table that nothing read; it is gone. The checkpoint a session resumes from stays on the session row.
47
+ - **Storage.** A long session's row no longer grows with its transcript (a 10-turn, 300-step session on a 16k window: under 16 KB instead of up to 196 KB).
48
+
3
49
  ## 0.9.0-beta
4
50
 
5
51
  ### Major Changes
@@ -1,14 +1,20 @@
1
1
  export { hashManifest } from "./utils/hash.js";
2
- export declare const PROTOCOL_VERSION = 4;
3
- export declare const PROTOCOL_FEATURES: readonly ["runtime-tenants", "admin-status", "studio-principal", "action-endpoints"];
2
+ /**
3
+ * Protocol 5: a Host serves one Tenant, and nothing in a request selects it. Clients send no
4
+ * `Nylorun-Tenant`; the Host still accepts protocol 4 (and the header) for one release.
5
+ */
6
+ export declare const PROTOCOL_VERSION = 5;
7
+ /** What a client of this protocol requires of a Host. */
8
+ export declare const PROTOCOL_FEATURES: readonly ["admin-status", "studio-principal", "action-endpoints"];
4
9
  export type ProtocolFeature = (typeof PROTOCOL_FEATURES)[number];
5
10
  /**
6
11
  * Host features no client requires: a client that uses one checks the Host's `/health`
7
12
  * for it first. `tenant-fixture-model`: `PUT /v1/tenant/config/seed` accepts
8
13
  * `fixtureModel: true` (the Tenant's model calls use the Runtime's fixture model).
9
14
  * `transcript-events`: the log carries `message.assistant` and `tool.completed`, and
10
- * tool `action.*` events carry `callId` and `invocationId`. `derived-principals`:
11
- * `POST /v1/admin/tenants` accepts `derivedPrincipals`. `subject-headers`: an application
15
+ * tool `action.*` events carry `callId` and `invocationId`. `derived-principals`: the Host
16
+ * registers the derived principals it is configured with (`NYLORUN_DERIVED_PRINCIPALS`,
17
+ * default `project`) on its Tenant, whose keys the admin key derives. `subject-headers`: an application
12
18
  * principal may act for a subject with `Nylorun-Subject` and `Nylorun-Scopes`, and the Runtime
13
19
  * enforces the scopes and the subject's ownership of sessions and vaults.
14
20
  * `subject-tokens`: `POST /v1/tokens` mints ES256 subject tokens for the roles of the Tenant's
@@ -31,21 +37,29 @@ export interface ProtocolRange {
31
37
  max: number;
32
38
  features: readonly string[];
33
39
  }
40
+ /**
41
+ * What this Host serves. `runtime-tenants` (protocol 4 clients require it) is still advertised
42
+ * for the compatibility window; protocol 5 clients no longer require it.
43
+ */
34
44
  export declare const HOST_PROTOCOL: ProtocolRange;
35
45
  export declare const DEFINITION_SCHEMA_VERSION = 2;
46
+ /**
47
+ * The Tenant a protocol 4 client names on every request. Protocol 5 clients send none: the
48
+ * Host serves one Tenant, and answers a header naming another with the opaque 404.
49
+ */
36
50
  export declare const TENANT_HEADER = "Nylorun-Tenant";
37
51
  export declare const PROTOCOL_HEADER = "Nylorun-Protocol";
38
52
  /** The subject an application principal acts for (Host feature `subject-headers`). */
39
53
  export declare const SUBJECT_HEADER = "Nylorun-Subject";
40
54
  /** The space-separated scopes of that subject; required with `Nylorun-Subject`. */
41
55
  export declare const SCOPES_HEADER = "Nylorun-Scopes";
42
- /** A publishable key: names the Tenant and the client app (Host feature `browser-access`). */
56
+ /** A publishable key: names the client app, and its Tenant (Host feature `browser-access`). */
43
57
  export declare const PUBLISHABLE_KEY_HEADER = "Nylorun-Key";
44
58
  /** The delivery token on a request the Runtime sends to an Action endpoint. */
45
59
  export declare const SIGNATURE_HEADER = "Nylorun-Signature";
46
60
  /** Set to `1` on an Action endpoint's response whose body is a tagged `ActionOutcome`. */
47
61
  export declare const OUTCOME_HEADER = "Nylorun-Outcome";
48
- export declare const ERROR_CODES: readonly ["not_found", "protocol_unsupported", "host_rejected", "origin_rejected", "unsupported_media_type", "tenant_conflict", "active_work", "connection_missing", "incompatible_host", "subject_invalid", "scope_required", "token_expired", "limit_exceeded",
62
+ export declare const ERROR_CODES: readonly ["not_found", "protocol_unsupported", "host_rejected", "origin_rejected", "unsupported_media_type", "connection_missing", "incompatible_host", "subject_invalid", "scope_required", "token_expired", "limit_exceeded",
49
63
  /** A request the Runtime refuses for a reason the message gives. */
50
64
  "request_rejected",
51
65
  /** A request the Host could not read: headers, body or query. */
@@ -1,7 +1,11 @@
1
1
  export { hashManifest } from "./utils/hash.js";
2
- export const PROTOCOL_VERSION = 4;
2
+ /**
3
+ * Protocol 5: a Host serves one Tenant, and nothing in a request selects it. Clients send no
4
+ * `Nylorun-Tenant`; the Host still accepts protocol 4 (and the header) for one release.
5
+ */
6
+ export const PROTOCOL_VERSION = 5;
7
+ /** What a client of this protocol requires of a Host. */
3
8
  export const PROTOCOL_FEATURES = [
4
- "runtime-tenants",
5
9
  "admin-status",
6
10
  "studio-principal",
7
11
  "action-endpoints",
@@ -11,8 +15,9 @@ export const PROTOCOL_FEATURES = [
11
15
  * for it first. `tenant-fixture-model`: `PUT /v1/tenant/config/seed` accepts
12
16
  * `fixtureModel: true` (the Tenant's model calls use the Runtime's fixture model).
13
17
  * `transcript-events`: the log carries `message.assistant` and `tool.completed`, and
14
- * tool `action.*` events carry `callId` and `invocationId`. `derived-principals`:
15
- * `POST /v1/admin/tenants` accepts `derivedPrincipals`. `subject-headers`: an application
18
+ * tool `action.*` events carry `callId` and `invocationId`. `derived-principals`: the Host
19
+ * registers the derived principals it is configured with (`NYLORUN_DERIVED_PRINCIPALS`,
20
+ * default `project`) on its Tenant, whose keys the admin key derives. `subject-headers`: an application
16
21
  * principal may act for a subject with `Nylorun-Subject` and `Nylorun-Scopes`, and the Runtime
17
22
  * enforces the scopes and the subject's ownership of sessions and vaults.
18
23
  * `subject-tokens`: `POST /v1/tokens` mints ES256 subject tokens for the roles of the Tenant's
@@ -39,19 +44,27 @@ export const OPTIONAL_HOST_FEATURES = [
39
44
  "a2a-endpoint",
40
45
  "action-endpoints",
41
46
  ];
47
+ /**
48
+ * What this Host serves. `runtime-tenants` (protocol 4 clients require it) is still advertised
49
+ * for the compatibility window; protocol 5 clients no longer require it.
50
+ */
42
51
  export const HOST_PROTOCOL = {
43
52
  min: 4,
44
- max: 4,
45
- features: [...PROTOCOL_FEATURES, ...OPTIONAL_HOST_FEATURES],
53
+ max: 5,
54
+ features: ["runtime-tenants", ...PROTOCOL_FEATURES, ...OPTIONAL_HOST_FEATURES],
46
55
  };
47
56
  export const DEFINITION_SCHEMA_VERSION = 2;
57
+ /**
58
+ * The Tenant a protocol 4 client names on every request. Protocol 5 clients send none: the
59
+ * Host serves one Tenant, and answers a header naming another with the opaque 404.
60
+ */
48
61
  export const TENANT_HEADER = "Nylorun-Tenant";
49
62
  export const PROTOCOL_HEADER = "Nylorun-Protocol";
50
63
  /** The subject an application principal acts for (Host feature `subject-headers`). */
51
64
  export const SUBJECT_HEADER = "Nylorun-Subject";
52
65
  /** The space-separated scopes of that subject; required with `Nylorun-Subject`. */
53
66
  export const SCOPES_HEADER = "Nylorun-Scopes";
54
- /** A publishable key: names the Tenant and the client app (Host feature `browser-access`). */
67
+ /** A publishable key: names the client app, and its Tenant (Host feature `browser-access`). */
55
68
  export const PUBLISHABLE_KEY_HEADER = "Nylorun-Key";
56
69
  /** The delivery token on a request the Runtime sends to an Action endpoint. */
57
70
  export const SIGNATURE_HEADER = "Nylorun-Signature";
@@ -63,8 +76,6 @@ export const ERROR_CODES = [
63
76
  "host_rejected",
64
77
  "origin_rejected",
65
78
  "unsupported_media_type",
66
- "tenant_conflict",
67
- "active_work",
68
79
  "connection_missing",
69
80
  "incompatible_host",
70
81
  "subject_invalid",
@@ -517,7 +517,6 @@ export type AcceptedResponse = z.infer<typeof AcceptedResponseSchema>;
517
517
  export declare const RejectedResponseSchema: z.ZodObject<{
518
518
  status: z.ZodLiteral<"rejected">;
519
519
  code: z.ZodEnum<{
520
- active_work: "active_work";
521
520
  connection_missing: "connection_missing";
522
521
  host_rejected: "host_rejected";
523
522
  incompatible_host: "incompatible_host";
@@ -531,7 +530,6 @@ export declare const RejectedResponseSchema: z.ZodObject<{
531
530
  scope_required: "scope_required";
532
531
  subject_invalid: "subject_invalid";
533
532
  subject_required: "subject_required";
534
- tenant_conflict: "tenant_conflict";
535
533
  token_expired: "token_expired";
536
534
  unsupported_media_type: "unsupported_media_type";
537
535
  }>;
@@ -1107,9 +1105,24 @@ export declare const LoopDecidedPayloadSchema: z.ZodObject<{
1107
1105
  }>;
1108
1106
  patched: z.ZodBoolean;
1109
1107
  }, z.core.$loose>;
1108
+ /**
1109
+ * `transcript.updated` (internal; blueprint P0.3): the own loop's model-facing transcript after a
1110
+ * settled segment, as an edit of the previous one: keep its first `keep` entries, then append
1111
+ * `entries`; the result has `length` entries. `keep` is 0 for a snapshot (after compaction, or
1112
+ * for a session written before transcripts were recorded). Large edits are split into
1113
+ * consecutive events, each appending to the last. Entries are the engine's `TranscriptEntry`
1114
+ * values, checked by the Runtime when it folds them. Never served to clients.
1115
+ */
1116
+ export declare const TranscriptUpdatedPayloadSchema: z.ZodObject<{
1117
+ keep: z.ZodNumber;
1118
+ entries: z.ZodArray<z.ZodUnknown>;
1119
+ length: z.ZodNumber;
1120
+ }, z.core.$loose>;
1110
1121
  /**
1111
1122
  * The event catalog (Durable Streams §9.5): every session event type, its payload schema, its
1112
- * payload schema version and who writes it. A type not listed here cannot be written.
1123
+ * payload schema version and who writes it. A type not listed here cannot be written. A type
1124
+ * with `visibility: "internal"` is recorded and folded by the Runtime but never served to
1125
+ * clients (SSE, history, AG-UI and A2A skip it).
1113
1126
  *
1114
1127
  * Evolution: new types and new optional payload fields are additive (clients ignore types
1115
1128
  * they do not know, and payloads pass unknown fields through). A breaking payload change is a
@@ -1457,6 +1470,16 @@ export declare const EVENT_CATALOG: {
1457
1470
  readonly source: "api";
1458
1471
  readonly version: 1;
1459
1472
  };
1473
+ readonly "transcript.updated": {
1474
+ readonly payload: z.ZodObject<{
1475
+ keep: z.ZodNumber;
1476
+ entries: z.ZodArray<z.ZodUnknown>;
1477
+ length: z.ZodNumber;
1478
+ }, z.core.$loose>;
1479
+ readonly source: "loop";
1480
+ readonly version: 1;
1481
+ readonly visibility: "internal";
1482
+ };
1460
1483
  };
1461
1484
  export type EventType = keyof typeof EVENT_CATALOG;
1462
1485
  export declare const EVENT_TYPES: readonly EventType[];
@@ -1477,7 +1500,7 @@ type EventSchemaOf<T extends EventType> = z.ZodObject<typeof eventEnvelope & {
1477
1500
  /** One schema per event type, keyed by type (the OpenAPI components). */
1478
1501
  export declare const EVENT_SCHEMAS: { [T in EventType]: EventSchemaOf<T>; };
1479
1502
  /** A session event of a known type, discriminated on `type`. */
1480
- export declare const SessionEventSchema: z.ZodDiscriminatedUnion<[EventSchemaOf<"action.completed" | "action.delivered" | "action.delivery_failed" | "action.pending" | "action.uncertain" | "command.approve" | "command.message" | "command.respond" | "context.compacted" | "delegation.completed" | "delegation.started" | "effect.uncertain" | "loop.decided" | "loop.iteration" | "loop.verified" | "message.assistant" | "model.failed" | "node.agent" | "node.started" | "sandbox.exec" | "sandbox.state" | "tool.completed" | "turn.cancelled" | "turn.completed" | "turn.failed" | "turn.paused">, ...EventSchemaOf<"action.completed" | "action.delivered" | "action.delivery_failed" | "action.pending" | "action.uncertain" | "command.approve" | "command.message" | "command.respond" | "context.compacted" | "delegation.completed" | "delegation.started" | "effect.uncertain" | "loop.decided" | "loop.iteration" | "loop.verified" | "message.assistant" | "model.failed" | "node.agent" | "node.started" | "sandbox.exec" | "sandbox.state" | "tool.completed" | "turn.cancelled" | "turn.completed" | "turn.failed" | "turn.paused">[]], "type">;
1503
+ export declare const SessionEventSchema: z.ZodDiscriminatedUnion<[EventSchemaOf<"action.completed" | "action.delivered" | "action.delivery_failed" | "action.pending" | "action.uncertain" | "command.approve" | "command.message" | "command.respond" | "context.compacted" | "delegation.completed" | "delegation.started" | "effect.uncertain" | "loop.decided" | "loop.iteration" | "loop.verified" | "message.assistant" | "model.failed" | "node.agent" | "node.started" | "sandbox.exec" | "sandbox.state" | "tool.completed" | "transcript.updated" | "turn.cancelled" | "turn.completed" | "turn.failed" | "turn.paused">, ...EventSchemaOf<"action.completed" | "action.delivered" | "action.delivery_failed" | "action.pending" | "action.uncertain" | "command.approve" | "command.message" | "command.respond" | "context.compacted" | "delegation.completed" | "delegation.started" | "effect.uncertain" | "loop.decided" | "loop.iteration" | "loop.verified" | "message.assistant" | "model.failed" | "node.agent" | "node.started" | "sandbox.exec" | "sandbox.state" | "tool.completed" | "transcript.updated" | "turn.cancelled" | "turn.completed" | "turn.failed" | "turn.paused">[]], "type">;
1481
1504
  export type SessionEvent = {
1482
1505
  [T in EventType]: z.infer<EventSchemaOf<T>>;
1483
1506
  }[EventType];
@@ -1492,7 +1515,7 @@ export type SessionEventOf<T extends EventType> = Extract<SessionEvent, {
1492
1515
  */
1493
1516
  export declare function parseSessionEvent(value: unknown): SessionEvent | LiveEvent;
1494
1517
  export declare const SessionItemsResponseSchema: z.ZodObject<{
1495
- items: z.ZodArray<z.ZodDiscriminatedUnion<[EventSchemaOf<"action.completed" | "action.delivered" | "action.delivery_failed" | "action.pending" | "action.uncertain" | "command.approve" | "command.message" | "command.respond" | "context.compacted" | "delegation.completed" | "delegation.started" | "effect.uncertain" | "loop.decided" | "loop.iteration" | "loop.verified" | "message.assistant" | "model.failed" | "node.agent" | "node.started" | "sandbox.exec" | "sandbox.state" | "tool.completed" | "turn.cancelled" | "turn.completed" | "turn.failed" | "turn.paused">, ...EventSchemaOf<"action.completed" | "action.delivered" | "action.delivery_failed" | "action.pending" | "action.uncertain" | "command.approve" | "command.message" | "command.respond" | "context.compacted" | "delegation.completed" | "delegation.started" | "effect.uncertain" | "loop.decided" | "loop.iteration" | "loop.verified" | "message.assistant" | "model.failed" | "node.agent" | "node.started" | "sandbox.exec" | "sandbox.state" | "tool.completed" | "turn.cancelled" | "turn.completed" | "turn.failed" | "turn.paused">[]], "type">>;
1518
+ items: z.ZodArray<z.ZodDiscriminatedUnion<[EventSchemaOf<"action.completed" | "action.delivered" | "action.delivery_failed" | "action.pending" | "action.uncertain" | "command.approve" | "command.message" | "command.respond" | "context.compacted" | "delegation.completed" | "delegation.started" | "effect.uncertain" | "loop.decided" | "loop.iteration" | "loop.verified" | "message.assistant" | "model.failed" | "node.agent" | "node.started" | "sandbox.exec" | "sandbox.state" | "tool.completed" | "transcript.updated" | "turn.cancelled" | "turn.completed" | "turn.failed" | "turn.paused">, ...EventSchemaOf<"action.completed" | "action.delivered" | "action.delivery_failed" | "action.pending" | "action.uncertain" | "command.approve" | "command.message" | "command.respond" | "context.compacted" | "delegation.completed" | "delegation.started" | "effect.uncertain" | "loop.decided" | "loop.iteration" | "loop.verified" | "message.assistant" | "model.failed" | "node.agent" | "node.started" | "sandbox.exec" | "sandbox.state" | "tool.completed" | "transcript.updated" | "turn.cancelled" | "turn.completed" | "turn.failed" | "turn.paused">[]], "type">>;
1496
1519
  cursor: z.ZodNullable<z.ZodString>;
1497
1520
  }, z.core.$strip>;
1498
1521
  export type SessionItemsResponse = {
@@ -1548,38 +1571,16 @@ export declare const TenantEnvelopeSchema: z.ZodObject<{
1548
1571
  schemaVersion: z.ZodNumber;
1549
1572
  }, z.core.$strict>;
1550
1573
  export type TenantEnvelope = z.infer<typeof TenantEnvelopeSchema>;
1551
- export declare const CreateTenantRequestSchema: z.ZodObject<{
1552
- tenantId: z.ZodString;
1553
- name: z.ZodString;
1554
- principalId: z.ZodString;
1555
- credentialHash: z.ZodString;
1556
- idempotencyKey: z.ZodString;
1557
- studioCredentialHash: z.ZodOptional<z.ZodString>;
1558
- derivedPrincipals: z.ZodOptional<z.ZodArray<z.ZodObject<{
1559
- id: z.ZodString;
1560
- credentialHash: z.ZodString;
1561
- }, z.core.$strict>>>;
1562
- }, z.core.$strict>;
1563
- export type CreateTenantRequest = z.infer<typeof CreateTenantRequestSchema>;
1564
- export declare const AdminTenantSchema: z.ZodObject<{
1565
- id: z.ZodString;
1566
- name: z.ZodNullable<z.ZodString>;
1567
- state: z.ZodEnum<{
1568
- open: "open";
1569
- quarantined: "quarantined";
1570
- }>;
1571
- envelope: z.ZodNullable<z.ZodObject<{
1572
- id: z.ZodString;
1573
- name: z.ZodString;
1574
- createdAt: z.ZodString;
1575
- updatedAt: z.ZodString;
1576
- schemaVersion: z.ZodNumber;
1577
- }, z.core.$strict>>;
1578
- }, z.core.$strict>;
1579
- export type AdminTenant = z.infer<typeof AdminTenantSchema>;
1580
- export declare const QuarantineSchema: z.ZodObject<{
1574
+ /**
1575
+ * Why a Host's Tenant is not open (`HostTenant.cause`): it could not be opened, and the Host
1576
+ * fails readiness until the cause is repaired and the Host restarted. `database-layout-old`:
1577
+ * the database was written by a Runtime from before one Tenant per installation; this release
1578
+ * starts fresh on a new database.
1579
+ */
1580
+ export declare const TenantCauseSchema: z.ZodObject<{
1581
1581
  code: z.ZodEnum<{
1582
1582
  corrupt: "corrupt";
1583
+ "database-layout-old": "database-layout-old";
1583
1584
  "envelope-invalid": "envelope-invalid";
1584
1585
  "kek-missing": "kek-missing";
1585
1586
  "migration-failed": "migration-failed";
@@ -1590,13 +1591,17 @@ export declare const QuarantineSchema: z.ZodObject<{
1590
1591
  message: z.ZodString;
1591
1592
  repair: z.ZodString;
1592
1593
  }, z.core.$strict>;
1593
- export type QuarantineInfo = z.infer<typeof QuarantineSchema>;
1594
- export declare const AdminTenantStatusSchema: z.ZodObject<{
1595
- id: z.ZodString;
1594
+ export type TenantCause = z.infer<typeof TenantCauseSchema>;
1595
+ /**
1596
+ * The Host's one Tenant, as `/v1/admin/status` reports it. `unavailable` while it opens, when
1597
+ * opening it failed (`cause`), or when it is closing.
1598
+ */
1599
+ export declare const HostTenantSchema: z.ZodObject<{
1600
+ id: z.ZodNullable<z.ZodString>;
1596
1601
  name: z.ZodNullable<z.ZodString>;
1597
1602
  state: z.ZodEnum<{
1598
1603
  open: "open";
1599
- quarantined: "quarantined";
1604
+ unavailable: "unavailable";
1600
1605
  }>;
1601
1606
  envelope: z.ZodNullable<z.ZodObject<{
1602
1607
  id: z.ZodString;
@@ -1605,9 +1610,10 @@ export declare const AdminTenantStatusSchema: z.ZodObject<{
1605
1610
  updatedAt: z.ZodString;
1606
1611
  schemaVersion: z.ZodNumber;
1607
1612
  }, z.core.$strict>>;
1608
- quarantine: z.ZodOptional<z.ZodObject<{
1613
+ cause: z.ZodOptional<z.ZodObject<{
1609
1614
  code: z.ZodEnum<{
1610
1615
  corrupt: "corrupt";
1616
+ "database-layout-old": "database-layout-old";
1611
1617
  "envelope-invalid": "envelope-invalid";
1612
1618
  "kek-missing": "kek-missing";
1613
1619
  "migration-failed": "migration-failed";
@@ -1619,7 +1625,7 @@ export declare const AdminTenantStatusSchema: z.ZodObject<{
1619
1625
  repair: z.ZodString;
1620
1626
  }, z.core.$strict>>;
1621
1627
  }, z.core.$strict>;
1622
- export type AdminTenantStatus = z.infer<typeof AdminTenantStatusSchema>;
1628
+ export type HostTenant = z.infer<typeof HostTenantSchema>;
1623
1629
  /** A stream relay's state (Durable Streams §7). */
1624
1630
  export declare const StreamRelayStatusSchema: z.ZodObject<{
1625
1631
  active: z.ZodBoolean;
@@ -1657,12 +1663,12 @@ export declare const AdminHostStatusSchema: z.ZodObject<{
1657
1663
  max: z.ZodNumber;
1658
1664
  features: z.ZodArray<z.ZodString>;
1659
1665
  }, z.core.$strict>;
1660
- tenants: z.ZodArray<z.ZodObject<{
1661
- id: z.ZodString;
1666
+ tenant: z.ZodObject<{
1667
+ id: z.ZodNullable<z.ZodString>;
1662
1668
  name: z.ZodNullable<z.ZodString>;
1663
1669
  state: z.ZodEnum<{
1664
1670
  open: "open";
1665
- quarantined: "quarantined";
1671
+ unavailable: "unavailable";
1666
1672
  }>;
1667
1673
  envelope: z.ZodNullable<z.ZodObject<{
1668
1674
  id: z.ZodString;
@@ -1671,7 +1677,21 @@ export declare const AdminHostStatusSchema: z.ZodObject<{
1671
1677
  updatedAt: z.ZodString;
1672
1678
  schemaVersion: z.ZodNumber;
1673
1679
  }, z.core.$strict>>;
1674
- }, z.core.$strict>>;
1680
+ cause: z.ZodOptional<z.ZodObject<{
1681
+ code: z.ZodEnum<{
1682
+ corrupt: "corrupt";
1683
+ "database-layout-old": "database-layout-old";
1684
+ "envelope-invalid": "envelope-invalid";
1685
+ "kek-missing": "kek-missing";
1686
+ "migration-failed": "migration-failed";
1687
+ "open-failed": "open-failed";
1688
+ "open-timeout": "open-timeout";
1689
+ "schema-too-new": "schema-too-new";
1690
+ }>;
1691
+ message: z.ZodString;
1692
+ repair: z.ZodString;
1693
+ }, z.core.$strict>>;
1694
+ }, z.core.$strict>;
1675
1695
  aggregate: z.ZodObject<{
1676
1696
  runningSessions: z.ZodNumber;
1677
1697
  inFlightDeliveries: z.ZodNumber;
@@ -1698,12 +1718,12 @@ export declare const AdminStatusSchema: z.ZodObject<{
1698
1718
  max: z.ZodNumber;
1699
1719
  features: z.ZodArray<z.ZodString>;
1700
1720
  }, z.core.$strict>;
1701
- tenants: z.ZodArray<z.ZodObject<{
1702
- id: z.ZodString;
1721
+ tenant: z.ZodObject<{
1722
+ id: z.ZodNullable<z.ZodString>;
1703
1723
  name: z.ZodNullable<z.ZodString>;
1704
1724
  state: z.ZodEnum<{
1705
1725
  open: "open";
1706
- quarantined: "quarantined";
1726
+ unavailable: "unavailable";
1707
1727
  }>;
1708
1728
  envelope: z.ZodNullable<z.ZodObject<{
1709
1729
  id: z.ZodString;
@@ -1712,7 +1732,21 @@ export declare const AdminStatusSchema: z.ZodObject<{
1712
1732
  updatedAt: z.ZodString;
1713
1733
  schemaVersion: z.ZodNumber;
1714
1734
  }, z.core.$strict>>;
1715
- }, z.core.$strict>>;
1735
+ cause: z.ZodOptional<z.ZodObject<{
1736
+ code: z.ZodEnum<{
1737
+ corrupt: "corrupt";
1738
+ "database-layout-old": "database-layout-old";
1739
+ "envelope-invalid": "envelope-invalid";
1740
+ "kek-missing": "kek-missing";
1741
+ "migration-failed": "migration-failed";
1742
+ "open-failed": "open-failed";
1743
+ "open-timeout": "open-timeout";
1744
+ "schema-too-new": "schema-too-new";
1745
+ }>;
1746
+ message: z.ZodString;
1747
+ repair: z.ZodString;
1748
+ }, z.core.$strict>>;
1749
+ }, z.core.$strict>;
1716
1750
  aggregate: z.ZodObject<{
1717
1751
  runningSessions: z.ZodNumber;
1718
1752
  inFlightDeliveries: z.ZodNumber;
@@ -1735,11 +1769,18 @@ export declare const AdminStatusSchema: z.ZodObject<{
1735
1769
  }, z.core.$strict>>;
1736
1770
  }, z.core.$strict>;
1737
1771
  export type AdminStatus = z.infer<typeof AdminStatusSchema>;
1772
+ /**
1773
+ * `.nylorun/link.json`: the installation a Project uses. Format 2 (one Tenant per
1774
+ * installation) names the local `stack` that `nylorun start` created or attached; `tenantId`
1775
+ * is information only, since nothing in a request selects a Tenant. Formats 0 and 1 named a
1776
+ * Tenant on a multi-Tenant Host of an older Runtime.
1777
+ */
1738
1778
  export declare const ProjectLinkFileSchema: z.ZodObject<{
1739
- format: z.ZodDefault<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<1>]>>;
1779
+ format: z.ZodDefault<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodLiteral<2>]>>;
1780
+ stack: z.ZodOptional<z.ZodString>;
1740
1781
  hostUrl: z.ZodString;
1741
1782
  hostId: z.ZodString;
1742
- tenantId: z.ZodString;
1783
+ tenantId: z.ZodOptional<z.ZodString>;
1743
1784
  }, z.core.$loose>;
1744
1785
  export type ProjectLinkFile = z.infer<typeof ProjectLinkFileSchema>;
1745
1786
  export declare const ProjectCredentialsFileSchema: z.ZodObject<{
@@ -2600,6 +2641,103 @@ export declare const TenantSandboxViewSchema: z.ZodObject<{
2600
2641
  }, z.core.$strict>;
2601
2642
  }, z.core.$strict>;
2602
2643
  export type TenantSandboxView = z.infer<typeof TenantSandboxViewSchema>;
2644
+ /** What a usage total or a budget covers: the whole Tenant, one agent, or one turn. */
2645
+ export declare const ModelUsageScopeSchema: z.ZodEnum<{
2646
+ agent: "agent";
2647
+ tenant: "tenant";
2648
+ turn: "turn";
2649
+ }>;
2650
+ export type ModelUsageScope = z.infer<typeof ModelUsageScopeSchema>;
2651
+ /** `GET /v1/tenant/usage`: which rows of the model usage ledger to total. */
2652
+ export declare const ModelUsageQuerySchema: z.ZodObject<{
2653
+ scope: z.ZodDefault<z.ZodEnum<{
2654
+ agent: "agent";
2655
+ tenant: "tenant";
2656
+ turn: "turn";
2657
+ }>>;
2658
+ id: z.ZodOptional<z.ZodString>;
2659
+ period: z.ZodDefault<z.ZodEnum<{
2660
+ day: "day";
2661
+ month: "month";
2662
+ total: "total";
2663
+ }>>;
2664
+ }, z.core.$strict>;
2665
+ export type ModelUsageQuery = z.infer<typeof ModelUsageQuerySchema>;
2666
+ /** The model calls the ledger recorded for one scope and period, and what they cost. */
2667
+ export declare const ModelUsageTotalsSchema: z.ZodObject<{
2668
+ scope: z.ZodEnum<{
2669
+ agent: "agent";
2670
+ tenant: "tenant";
2671
+ turn: "turn";
2672
+ }>;
2673
+ id: z.ZodOptional<z.ZodString>;
2674
+ period: z.ZodEnum<{
2675
+ day: "day";
2676
+ month: "month";
2677
+ total: "total";
2678
+ }>;
2679
+ since: z.ZodOptional<z.ZodString>;
2680
+ calls: z.ZodNumber;
2681
+ tokens: z.ZodNumber;
2682
+ costUsd: z.ZodNumber;
2683
+ }, z.core.$strict>;
2684
+ export type ModelUsageTotals = z.infer<typeof ModelUsageTotalsSchema>;
2685
+ /**
2686
+ * A hard cap on model spend. Before each call the model gate checks the scope's spend (and its
2687
+ * calls in flight) against the cap; once it is reached the call fails with `budget_exhausted`
2688
+ * and the turn with `model.budget_exhausted`.
2689
+ */
2690
+ export declare const ModelBudgetSchema: z.ZodObject<{
2691
+ scope: z.ZodEnum<{
2692
+ agent: "agent";
2693
+ tenant: "tenant";
2694
+ turn: "turn";
2695
+ }>;
2696
+ id: z.ZodOptional<z.ZodString>;
2697
+ period: z.ZodOptional<z.ZodEnum<{
2698
+ day: "day";
2699
+ month: "month";
2700
+ }>>;
2701
+ limitUsd: z.ZodOptional<z.ZodNumber>;
2702
+ limitTokens: z.ZodOptional<z.ZodNumber>;
2703
+ }, z.core.$strict>;
2704
+ export type ModelBudget = z.infer<typeof ModelBudgetSchema>;
2705
+ /** `PUT /v1/tenant/budgets`: replaces every budget. An empty list removes them all. */
2706
+ export declare const PutModelBudgetsRequestSchema: z.ZodObject<{
2707
+ requestId: z.ZodOptional<z.ZodString>;
2708
+ budgets: z.ZodArray<z.ZodObject<{
2709
+ scope: z.ZodEnum<{
2710
+ agent: "agent";
2711
+ tenant: "tenant";
2712
+ turn: "turn";
2713
+ }>;
2714
+ id: z.ZodOptional<z.ZodString>;
2715
+ period: z.ZodOptional<z.ZodEnum<{
2716
+ day: "day";
2717
+ month: "month";
2718
+ }>>;
2719
+ limitUsd: z.ZodOptional<z.ZodNumber>;
2720
+ limitTokens: z.ZodOptional<z.ZodNumber>;
2721
+ }, z.core.$strict>>;
2722
+ }, z.core.$strict>;
2723
+ export type PutModelBudgetsRequest = z.infer<typeof PutModelBudgetsRequestSchema>;
2724
+ export declare const ModelBudgetsSchema: z.ZodObject<{
2725
+ budgets: z.ZodArray<z.ZodObject<{
2726
+ scope: z.ZodEnum<{
2727
+ agent: "agent";
2728
+ tenant: "tenant";
2729
+ turn: "turn";
2730
+ }>;
2731
+ id: z.ZodOptional<z.ZodString>;
2732
+ period: z.ZodOptional<z.ZodEnum<{
2733
+ day: "day";
2734
+ month: "month";
2735
+ }>>;
2736
+ limitUsd: z.ZodOptional<z.ZodNumber>;
2737
+ limitTokens: z.ZodOptional<z.ZodNumber>;
2738
+ }, z.core.$strict>>;
2739
+ }, z.core.$strict>;
2740
+ export type ModelBudgets = z.infer<typeof ModelBudgetsSchema>;
2603
2741
  export declare const ListVaultsResponseSchema: z.ZodObject<{
2604
2742
  vaults: z.ZodArray<z.ZodObject<{
2605
2743
  id: z.ZodString;
@@ -2669,21 +2807,6 @@ export declare const ListPublishableKeysResponseSchema: z.ZodObject<{
2669
2807
  }, z.core.$strict>>;
2670
2808
  }, z.core.$strict>;
2671
2809
  export type ListPublishableKeysResponse = z.infer<typeof ListPublishableKeysResponseSchema>;
2672
- export declare const AdminTenantListSchema: z.ZodArray<z.ZodObject<{
2673
- id: z.ZodString;
2674
- name: z.ZodNullable<z.ZodString>;
2675
- state: z.ZodEnum<{
2676
- open: "open";
2677
- quarantined: "quarantined";
2678
- }>;
2679
- envelope: z.ZodNullable<z.ZodObject<{
2680
- id: z.ZodString;
2681
- name: z.ZodString;
2682
- createdAt: z.ZodString;
2683
- updatedAt: z.ZodString;
2684
- schemaVersion: z.ZodNumber;
2685
- }, z.core.$strict>>;
2686
- }, z.core.$strict>>;
2687
2810
  export declare const HostShutdownResponseSchema: z.ZodObject<{
2688
2811
  status: z.ZodLiteral<"shutting_down">;
2689
2812
  }, z.core.$strict>;
@@ -2700,7 +2823,6 @@ export type StreamClosedFrame = z.infer<typeof StreamClosedFrameSchema>;
2700
2823
  * (another turn is running) or `runtime_error` (the Runtime failed). Never an HTTP body's code.
2701
2824
  */
2702
2825
  export declare const AgUiRunErrorCodeSchema: z.ZodEnum<{
2703
- active_work: "active_work";
2704
2826
  connection_missing: "connection_missing";
2705
2827
  host_rejected: "host_rejected";
2706
2828
  incompatible_host: "incompatible_host";
@@ -2716,7 +2838,6 @@ export declare const AgUiRunErrorCodeSchema: z.ZodEnum<{
2716
2838
  session_busy: "session_busy";
2717
2839
  subject_invalid: "subject_invalid";
2718
2840
  subject_required: "subject_required";
2719
- tenant_conflict: "tenant_conflict";
2720
2841
  token_expired: "token_expired";
2721
2842
  unsupported_media_type: "unsupported_media_type";
2722
2843
  }>;
package/dist/contracts.js CHANGED
@@ -5,7 +5,6 @@ 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);
@@ -1239,9 +1238,26 @@ export const LoopDecidedPayloadSchema = z
1239
1238
  patched: z.boolean(),
1240
1239
  })
1241
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();
1242
1256
  /**
1243
1257
  * 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.
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).
1245
1261
  *
1246
1262
  * Evolution: new types and new optional payload fields are additive (clients ignore types
1247
1263
  * they do not know, and payloads pass unknown fields through). A breaking payload change is a
@@ -1278,6 +1294,12 @@ export const EVENT_CATALOG = {
1278
1294
  "loop.iteration": { payload: LoopIterationPayloadSchema, source: "loop", version: 1 },
1279
1295
  "loop.verified": { payload: LoopVerifiedPayloadSchema, source: "api", version: 1 },
1280
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
+ },
1281
1303
  };
1282
1304
  export const EVENT_TYPES = Object.keys(EVENT_CATALOG);
1283
1305
  export function isEventType(type) {
@@ -1357,71 +1379,13 @@ export const TenantEnvelopeSchema = z
1357
1379
  schemaVersion: z.number().int(),
1358
1380
  })
1359
1381
  .strict();
1360
- export const CreateTenantRequestSchema = z
1361
- .object({
1362
- tenantId: z.string().min(1),
1363
- name: z.string().min(1),
1364
- /** `studio` is reserved for the derived Studio principal. */
1365
- principalId: z
1366
- .string()
1367
- .min(1)
1368
- .refine((id) => id !== "studio", "principalId `studio` is reserved"),
1369
- credentialHash: z.string().regex(/^[0-9a-f]{64}$/),
1370
- idempotencyKey: IdempotencyKeySchema,
1371
- /** SHA-256 of the derived Studio key; registers principal `studio` (feature `studio-principal`). */
1372
- studioCredentialHash: z
1373
- .string()
1374
- .regex(/^[0-9a-f]{64}$/)
1375
- .optional(),
1376
- /**
1377
- * SHA-256 of each derived principal's key (feature `derived-principals`): application
1378
- * principals whose keys the admin key derives, so their clients store no key.
1379
- */
1380
- derivedPrincipals: z
1381
- .array(z
1382
- .object({
1383
- id: z
1384
- .string()
1385
- .regex(DERIVED_PRINCIPAL_ID_PATTERN)
1386
- .refine((id) => id !== "studio", "principal id `studio` is reserved"),
1387
- credentialHash: z.string().regex(/^[0-9a-f]{64}$/),
1388
- })
1389
- .strict())
1390
- .max(16)
1391
- .optional(),
1392
- })
1393
- .strict()
1394
- .superRefine((body, ctx) => {
1395
- const ids = new Set([body.principalId]);
1396
- const hashes = new Set([body.credentialHash]);
1397
- if (body.studioCredentialHash)
1398
- hashes.add(body.studioCredentialHash);
1399
- for (const [index, principal] of (body.derivedPrincipals ?? []).entries()) {
1400
- if (ids.has(principal.id))
1401
- ctx.addIssue({
1402
- code: "custom",
1403
- path: ["derivedPrincipals", index, "id"],
1404
- message: `Principal id ${principal.id} is used twice`,
1405
- });
1406
- if (hashes.has(principal.credentialHash))
1407
- ctx.addIssue({
1408
- code: "custom",
1409
- path: ["derivedPrincipals", index, "credentialHash"],
1410
- message: "Every principal needs its own credential",
1411
- });
1412
- ids.add(principal.id);
1413
- hashes.add(principal.credentialHash);
1414
- }
1415
- });
1416
- export const AdminTenantSchema = z
1417
- .object({
1418
- id: z.string().min(1),
1419
- name: z.string().nullable(),
1420
- state: z.enum(["open", "quarantined"]),
1421
- envelope: TenantEnvelopeSchema.nullable(),
1422
- })
1423
- .strict();
1424
- 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
1425
1389
  .object({
1426
1390
  code: z.enum([
1427
1391
  "kek-missing",
@@ -1431,14 +1395,26 @@ export const QuarantineSchema = z
1431
1395
  "envelope-invalid",
1432
1396
  "open-timeout",
1433
1397
  "open-failed",
1398
+ "database-layout-old",
1434
1399
  ]),
1435
1400
  message: z.string(),
1436
1401
  repair: z.string(),
1437
1402
  })
1438
1403
  .strict();
1439
- export const AdminTenantStatusSchema = AdminTenantSchema.extend({
1440
- quarantine: QuarantineSchema.optional(),
1441
- });
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();
1442
1418
  /** A stream relay's state (Durable Streams §7). */
1443
1419
  export const StreamRelayStatusSchema = z
1444
1420
  .object({
@@ -1460,7 +1436,7 @@ export const StreamRelayStatusSchema = z
1460
1436
  export const HostAggregateSchema = z
1461
1437
  .object({
1462
1438
  runningSessions: z.number().int().nonnegative(),
1463
- /** Deliveries to Action endpoints in flight on this Host's open Tenants. */
1439
+ /** Deliveries to Action endpoints in flight on this Host. */
1464
1440
  inFlightDeliveries: z.number().int().nonnegative(),
1465
1441
  pendingActions: z.number().int().nonnegative(),
1466
1442
  uncertainEffects: z.number().int().nonnegative(),
@@ -1475,7 +1451,7 @@ export const AdminHostStatusSchema = z
1475
1451
  pid: z.number().int(),
1476
1452
  version: z.string().min(1),
1477
1453
  protocol: ProtocolRangeSchema,
1478
- tenants: z.array(AdminTenantSchema),
1454
+ tenant: HostTenantSchema,
1479
1455
  aggregate: HostAggregateSchema,
1480
1456
  })
1481
1457
  .strict();
@@ -1485,7 +1461,8 @@ export const AdminStatusSchema = z
1485
1461
  service: z.string().min(1),
1486
1462
  version: z.string().min(1),
1487
1463
  protocol: ProtocolRangeSchema,
1488
- tenants: z.array(AdminTenantSchema),
1464
+ /** The Tenant this installation serves. */
1465
+ tenant: HostTenantSchema,
1489
1466
  aggregate: HostAggregateSchema,
1490
1467
  host: z
1491
1468
  .object({
@@ -1497,12 +1474,20 @@ export const AdminStatusSchema = z
1497
1474
  .optional(),
1498
1475
  })
1499
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
+ */
1500
1483
  export const ProjectLinkFileSchema = z
1501
1484
  .object({
1502
- 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(),
1503
1488
  hostUrl: z.string().min(1),
1504
1489
  hostId: z.string().min(1),
1505
- tenantId: z.string().min(1),
1490
+ tenantId: z.string().min(1).optional(),
1506
1491
  })
1507
1492
  .passthrough();
1508
1493
  export const ProjectCredentialsFileSchema = z
@@ -1625,7 +1610,7 @@ export const SeedTenantConfigRequestSchema = z
1625
1610
  model: seedModelSchema.optional(),
1626
1611
  /**
1627
1612
  * The Tenant's model calls use the Runtime's deterministic fixture model instead of its
1628
- * 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
1629
1614
  * as Tenant setting `model.fixture`. Host feature `tenant-fixture-model`.
1630
1615
  */
1631
1616
  fixtureModel: z.literal(true).optional(),
@@ -2068,6 +2053,75 @@ export const TenantSandboxViewSchema = z
2068
2053
  config: EffectiveSandboxConfigSchema,
2069
2054
  })
2070
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();
2071
2125
  export const ListVaultsResponseSchema = z.object({ vaults: z.array(VaultInfoSchema) }).strict();
2072
2126
  export const ListCredentialsResponseSchema = z
2073
2127
  .object({ credentials: z.array(CredentialInfoSchema) })
@@ -2078,7 +2132,6 @@ export const AccessPolicyResponseSchema = z.object({ policy: AccessPolicySchema
2078
2132
  export const ListPublishableKeysResponseSchema = z
2079
2133
  .object({ keys: z.array(PublishableKeySchema) })
2080
2134
  .strict();
2081
- export const AdminTenantListSchema = z.array(AdminTenantSchema);
2082
2135
  export const HostShutdownResponseSchema = z
2083
2136
  .object({ status: z.literal("shutting_down") })
2084
2137
  .strict();
@@ -8,6 +8,7 @@ export const MODEL_FAILURE_CODES = Object.freeze([
8
8
  "auth",
9
9
  "invalid_request",
10
10
  "invalid_output",
11
+ "budget_exhausted",
11
12
  ]);
12
13
  /** True for a model adapter's failure outcome (`{ kind: "failed", code, message, retryable }`). */
13
14
  export function isModelFailureOutcome(value) {
@@ -49,7 +49,9 @@ export interface ModelCandidate {
49
49
  readonly evidence?: ModelEvidence;
50
50
  }
51
51
  /** Why a model call failed in a known way (Model Calls §6.1). */
52
- export type ModelFailureCode = "context_overflow" | "rate_limited" | "overloaded" | "timeout" | "transient" | "content_policy" | "auth" | "invalid_request" | "invalid_output";
52
+ export type ModelFailureCode = "context_overflow" | "rate_limited" | "overloaded" | "timeout" | "transient" | "content_policy" | "auth" | "invalid_request" | "invalid_output"
53
+ /** A model budget's cap is reached (`PUT /v1/tenant/budgets`); never retried. */
54
+ | "budget_exhausted";
53
55
  /**
54
56
  * A model call that failed in a known way. It is a completed outcome, not a lost one:
55
57
  * the engine fails the step with `model.<code>` instead of treating the call as uncertain.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nylorun/core",
3
- "version": "0.9.0-beta",
3
+ "version": "0.10.0-beta",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Shared agent definitions and wire contracts",