operon-managed-agents 0.1.0-alpha.3 → 0.1.0-alpha.30

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/README.md CHANGED
@@ -125,3 +125,35 @@ describe the relay and are refused without the declaration. Declaring `external`
125
125
  so it needs no permission of its own; the `authorize` hook receives `origin` on
126
126
  `messages.create`, and a deployment that hands a credential to something that only relays (a
127
127
  webhook bridge, a teammate agent) can refuse it anything else.
128
+
129
+ A worker serves many tenants by default, and refuses what would leak between them or run outside
130
+ the sandbox: a session whose environment does not come from the environment registry, a harness
131
+ holding process-wide MCP connections or an OAuth service, MCP over stdio, and a token read from
132
+ the process environment. A self-hosted, one-owner deployment says so —
133
+ `new SessionWorker({ profile: "single-tenant", … })` — and the worker logs that it did.
134
+
135
+ What a host decides per tenant goes through the registries, which are told whose session they
136
+ resolve for: `resolve(ref, { sessionId, ownerKey, metadata })`. `ownerKey` is stamped by the
137
+ service and trustworthy; `metadata` came from the client. Per-user MCP credentials — a vault —
138
+ are a provider the agent registry hands out, asked on every connect:
139
+
140
+ ```ts
141
+ const agents: ManagedAgentRegistry = {
142
+ resolve: (_ref, { ownerKey }) => ({
143
+ resumeOptions: {
144
+ mcpServers: { linear: { transport: "http", url: "https://mcp.linear.app/mcp" } },
145
+ mcpCredentials: {
146
+ credentialsFor: async ({ url }) => {
147
+ const token = await vault.tokenFor(ownerKey!, url); // the host's store, refresh, lock
148
+ return token === undefined ? undefined : { headers: { Authorization: `Bearer ${token}` } };
149
+ },
150
+ invalidate: ({ url }) => vault.refresh(ownerKey!, url), // on a 401; the connect retries once
151
+ },
152
+ },
153
+ }),
154
+ };
155
+ ```
156
+
157
+ The engine never stores, refreshes or logs a credential, and since the MCP client runs in the
158
+ worker, a credential never enters the sandbox. The rules and their reasons are in
159
+ `docs/server-profile.md`.
@@ -1,6 +1,6 @@
1
1
  import type { AgentEvent, InterruptAnswer } from "operon-agents";
2
2
  import { type SseFrame } from "../protocol/sse.ts";
3
- import type { CancelManagedSessionResponse, CreateManagedMessageRequest, CreateManagedSessionRequest, DeliveryReceiptResource, InterruptionsResponse, ListSessionEventsOptions, ListSessionEventsResponse, ListManagedSessionsResponse, ManagedSession, ResumeManagedSessionResponse, StreamSessionEventsOptions, UpdateManagedSessionRequest } from "../protocol/types.ts";
3
+ import type { CancelManagedSessionResponse, CreateManagedMessageRequest, CreateManagedSessionRequest, MessageReceiptResource, InterruptionsResponse, ListSessionEventsOptions, ListSessionEventsResponse, ListManagedSessionsResponse, ManagedSession, ResumeManagedSessionResponse, StreamSessionEventsOptions, UpdateManagedSessionRequest } from "../protocol/types.ts";
4
4
  export interface ManagedAgentsClientOptions {
5
5
  readonly baseUrl: string;
6
6
  readonly apiKey?: string;
@@ -51,7 +51,7 @@ export declare class ManagedSessionsClient {
51
51
  /** Rename a session; the new title is durable before this resolves. */
52
52
  update(sessionId: string, request: UpdateManagedSessionRequest): Promise<ManagedSession>;
53
53
  messages: {
54
- create: (sessionId: string, request: CreateManagedMessageRequest, options?: CreateManagedMessageOptions) => Promise<DeliveryReceiptResource>;
54
+ create: (sessionId: string, request: CreateManagedMessageRequest, options?: CreateManagedMessageOptions) => Promise<MessageReceiptResource>;
55
55
  };
56
56
  events: {
57
57
  list: (sessionId: string, options?: ListSessionEventsOptions) => Promise<ListSessionEventsResponse>;
@@ -10,7 +10,7 @@
10
10
  * the replay — and the ordering is still the only way to be sure of seeing it live.
11
11
  * 2. The stream begins with history. On a session that has run before, the first `turn.ended`
12
12
  * to arrive is an OLD one; ending on it returns the previous answer for the new question.
13
- * Nothing counts until the turn that took our delivery is known, and only that turn's end
13
+ * Nothing counts until the turn that took our message is known, and only that turn's end
14
14
  * is an ending.
15
15
  * 3. Idle is transient. A session goes idle between parallel tool executions and while waiting
16
16
  * for an answer from you; breaking on the first idle ends the loop mid-conversation.
@@ -32,9 +32,10 @@ export async function run(client, sessionId, input, options = {}) {
32
32
  // Trap 1: open first, then send. Reversing these can drop everything in between.
33
33
  const stream = await client.sessions.events.stream(sessionId, { signal: controller.signal });
34
34
  iterator = stream[Symbol.asyncIterator]();
35
- const { deliveryId } = await client.sessions.messages.create(sessionId, request);
36
- // Trap 2: which turn is ours. Unknown until the delivery shows up — as the origin of a
37
- // fresh `turn.started`, or as a `message.appended` inside a turn already running (a steer).
35
+ const { steerId } = await client.sessions.messages.create(sessionId, request);
36
+ // Trap 2: which turn is ours. Unknown until our message shows up — as a `message.appended`
37
+ // carrying our steer id, either inside a turn already running (a steer) or just ahead of the
38
+ // turn that was woken to take it.
38
39
  let currentTurn;
39
40
  let ourTurn;
40
41
  // After answering a pause, the continuation is ours whatever id it runs under.
@@ -60,14 +61,14 @@ export async function run(client, sessionId, input, options = {}) {
60
61
  continue;
61
62
  if (event.type === "turn.started") {
62
63
  currentTurn = event.turnId;
63
- if (claimNextTurn || deliveryOf(event.origin) === deliveryId) {
64
+ if (claimNextTurn || steerOf(event.origin) === steerId) {
64
65
  ourTurn = event.turnId;
65
66
  claimNextTurn = false;
66
67
  }
67
68
  continue;
68
69
  }
69
70
  if (event.type === "message.appended") {
70
- if (ourTurn === undefined && deliveryOf(event.origin) === deliveryId) {
71
+ if (ourTurn === undefined && steerOf(event.origin) === steerId) {
71
72
  // Inside a turn: a steer, and that turn is ours. Between turns: the prompt was
72
73
  // journaled ahead of its turn, so the next one to start is ours.
73
74
  if (currentTurn !== undefined)
@@ -142,13 +143,11 @@ function textOf(content) {
142
143
  return parts.length === 0 ? undefined : parts.join("");
143
144
  }
144
145
  /**
145
- * The delivery a journaled prompt — or the turn it started — came in as, on whichever origin it
146
- * was filed under: `user` for the caller's own words, `external` for a relayed party's. Undefined
147
- * for everything else in the user role (reminders, compaction summaries): those answer no delivery.
146
+ * The steer a journaled prompt — or the turn it started — came in as: `origin.steerId`, whatever
147
+ * kind the origin is. Undefined for a message that never went through the bus (a reminder, a
148
+ * compaction summary): those answer no message of ours.
148
149
  */
149
- function deliveryOf(origin) {
150
- return origin?.kind === "user" || origin?.kind === "user_follow_up" || origin?.kind === "external"
151
- ? origin.deliveryId
152
- : undefined;
150
+ function steerOf(origin) {
151
+ return origin !== undefined && "steerId" in origin ? origin.steerId : undefined;
153
152
  }
154
153
  //# sourceMappingURL=run.js.map
@@ -54,15 +54,24 @@ export interface CreateManagedMessageRequest {
54
54
  readonly actor?: string;
55
55
  /** `external` only: attributes rendered onto the envelope. */
56
56
  readonly metadata?: Readonly<Record<string, string | number | boolean | null>>;
57
- readonly mode?: "auto" | "steer" | "follow_up";
57
+ /**
58
+ * Which queue the message is filed into (default `steer`). `steer`: taken at the running
59
+ * turn's next step boundary, or — with nothing running — as the next turn's prompt.
60
+ * `follow_up`: a prompt of its own, queued behind the turn in flight.
61
+ */
62
+ readonly mode?: "steer" | "follow_up";
58
63
  }
59
- export interface DeliveryReceiptResource {
60
- readonly deliveryId: string;
64
+ /**
65
+ * The receipt for an accepted message. It means the message's `steer.queued` record is durable
66
+ * — a worker will take it — not that a turn has started: whoever holds the session decides that
67
+ * later. `steerId` is the message's identity from here on: on the `steer.queued` event, and as
68
+ * `origin.steerId` of the `message.appended` that shows the model saw it.
69
+ */
70
+ export interface MessageReceiptResource {
71
+ readonly steerId: string;
61
72
  readonly sessionId: string;
62
73
  readonly acceptedAt: number;
63
- readonly status: "started" | "queued";
64
- readonly channel: "turn" | "steering" | "follow_up";
65
- readonly steerId?: string;
74
+ readonly channel: "steering" | "follow_up";
66
75
  }
67
76
  export interface ListSessionEventsResponse {
68
77
  /** Durable AgentEvents in store order. Store sequence remains inside the opaque page cursor;
@@ -1,5 +1,6 @@
1
1
  import { createServer } from "node:http";
2
2
  import { isDurableAgentEvent } from "operon-agents";
3
+ import { ResumeSessionRequestSchema, parseRequest } from "./request-schemas.js";
3
4
  import { ManagedForbiddenError, ManagedInvalidRequestError, ManagedServerError, } from "./errors.js";
4
5
  /**
5
6
  * Authorize every request. For local demos and tests only.
@@ -141,9 +142,7 @@ export function createManagedHttpServer(options) {
141
142
  }
142
143
  if (method === "POST" && parts[2] === "resume" && parts.length === 3) {
143
144
  await authorize(request, "sessions.resume", sessionId);
144
- const body = await readJson(request, maxBodyBytes);
145
- if (!isRecord(body.answers))
146
- return sendJson(response, 400, apiError("invalid_request", "answers must be an object"));
145
+ const body = parseRequest(ResumeSessionRequestSchema, await readJson(request, maxBodyBytes));
147
146
  const receipt = await options.service.answerInterruption(sessionId, body.answers);
148
147
  void options.worker?.drain(sessionId).catch(() => undefined);
149
148
  return sendJson(response, 202, receipt);
@@ -1,13 +1,13 @@
1
1
  /**
2
- * Delivery idempotency.
2
+ * Message idempotency.
3
3
  *
4
- * A client that retries a message after a timeout must not have it delivered twice, and it
4
+ * A client that retries a message after a timeout must not have it accepted twice, and it
5
5
  * cannot tell from a failed request whether the first attempt landed. Keyed by
6
6
  * `(sessionId, key)`: the same key on a different session is a different delivery.
7
7
  */
8
- import type { DeliveryReceiptResource } from "../protocol/types.ts";
8
+ import type { MessageReceiptResource } from "../protocol/types.ts";
9
9
  export interface ManagedDeliveryIdempotencyStore {
10
- run(sessionId: string, key: string, operation: () => Promise<DeliveryReceiptResource>): Promise<DeliveryReceiptResource>;
10
+ run(sessionId: string, key: string, operation: () => Promise<MessageReceiptResource>): Promise<MessageReceiptResource>;
11
11
  }
12
12
  export declare class MemoryManagedDeliveryIdempotencyStore implements ManagedDeliveryIdempotencyStore {
13
13
  private readonly entries;
@@ -17,7 +17,7 @@ export declare class MemoryManagedDeliveryIdempotencyStore implements ManagedDel
17
17
  readonly ttlMs?: number;
18
18
  readonly maxEntries?: number;
19
19
  });
20
- run(sessionId: string, key: string, operation: () => Promise<DeliveryReceiptResource>): Promise<DeliveryReceiptResource>;
20
+ run(sessionId: string, key: string, operation: () => Promise<MessageReceiptResource>): Promise<MessageReceiptResource>;
21
21
  private pruneExpired;
22
22
  private makeRoom;
23
23
  }
@@ -1,10 +1,16 @@
1
1
  /**
2
2
  * The inbox: what a session has been asked to do that no turn has dealt with yet.
3
3
  *
4
- * It is not a table. It is a READ of the session log — every `inbox.received` and every
4
+ * It is not a table. It is a READ of the session log — every `steer.queued` record and every
5
5
  * control record after the worker's cursor — which is what makes it impossible to lose: the
6
- * log is the only thing a delivery writes, so there is no second place for the two to disagree.
7
- * Queues, pending marks and wake-up signals are indexes over this read, never the truth of it.
6
+ * log is the only thing an accepted message writes, so there is no second place for the two to
7
+ * disagree. Queues, pending marks and wake-up signals are indexes over this read, never the
8
+ * truth of it.
9
+ *
10
+ * The input records are the framework's own: a message accepted over the API is journaled
11
+ * exactly as one steered into a local session is (`steerQueuedRecord`), and a worker puts it
12
+ * back on a session's bus unchanged (`HarnessSession.requeue`). Only the control commands are
13
+ * this layer's vocabulary, and they ride the log as `custom` records.
8
14
  *
9
15
  * Shared by the two things that need the same answer to "is there work here?": the worker (to
10
16
  * do it) and the service (to tell a watching client nobody is doing it). One definition, so
@@ -12,7 +18,7 @@
12
18
  * read — set by the same write that creates an item, cleared by a holder about to read — never
13
19
  * the truth of it.
14
20
  */
15
- import type { InboxOrigin, InterruptAnswer, SessionStore } from "operon-agents";
21
+ import { type InterruptAnswer, type SessionStore, type SteerMessage } from "operon-agents";
16
22
  /** Where processing stopped. Everything at or before it has been dealt with. */
17
23
  export declare const INBOX_CURSOR_KEY = "inbox:cursor";
18
24
  /**
@@ -23,7 +29,7 @@ export declare const INBOX_CURSOR_KEY = "inbox:cursor";
23
29
  export declare const CONTROL_RECORD_NAME = "managed.control";
24
30
  export type ControlCommand = {
25
31
  readonly kind: "cancel";
26
- /** Idempotency identity, the way `deliveryId` is for an input. */
32
+ /** Idempotency identity, the way `steerId` is for an input. */
27
33
  readonly commandId: string;
28
34
  readonly requestedAt: number;
29
35
  readonly actor?: string;
@@ -34,13 +40,11 @@ export type ControlCommand = {
34
40
  readonly answers: Readonly<Record<string, InterruptAnswer>>;
35
41
  readonly actor?: string;
36
42
  };
43
+ /** An accepted message: its `steer.queued` record, ready to be put back on a bus. */
37
44
  export interface InboxInput {
38
45
  readonly kind: "input";
39
46
  readonly sequence: string;
40
- readonly input: string;
41
- /** Whose words: the session's user (`user`) or a relayed party (`external`). */
42
- readonly origin: InboxOrigin;
43
- readonly mode: "auto" | "steer" | "follow_up";
47
+ readonly item: SteerMessage;
44
48
  }
45
49
  export interface InboxControl {
46
50
  readonly kind: "control";
@@ -48,7 +52,7 @@ export interface InboxControl {
48
52
  readonly command: ControlCommand;
49
53
  }
50
54
  export type InboxItem = InboxInput | InboxControl;
51
- /** The identity an item is tracked by once dispatched: `deliveryId` or `commandId`. */
55
+ /** The identity an item is tracked by once dispatched: `steerId` or `commandId`. */
52
56
  export declare function inboxItemId(item: InboxItem): string;
53
57
  export declare function readInboxCursor(store: SessionStore): Promise<string | undefined>;
54
58
  /** Inbox records after `cursor`, in log order, excluding sequences in `exclude`. */
@@ -1,3 +1,24 @@
1
+ /**
2
+ * The inbox: what a session has been asked to do that no turn has dealt with yet.
3
+ *
4
+ * It is not a table. It is a READ of the session log — every `steer.queued` record and every
5
+ * control record after the worker's cursor — which is what makes it impossible to lose: the
6
+ * log is the only thing an accepted message writes, so there is no second place for the two to
7
+ * disagree. Queues, pending marks and wake-up signals are indexes over this read, never the
8
+ * truth of it.
9
+ *
10
+ * The input records are the framework's own: a message accepted over the API is journaled
11
+ * exactly as one steered into a local session is (`steerQueuedRecord`), and a worker puts it
12
+ * back on a session's bus unchanged (`HarnessSession.requeue`). Only the control commands are
13
+ * this layer's vocabulary, and they ride the log as `custom` records.
14
+ *
15
+ * Shared by the two things that need the same answer to "is there work here?": the worker (to
16
+ * do it) and the service (to tell a watching client nobody is doing it). One definition, so
17
+ * they can never disagree on what counts. The work table's `woken` flag is an index over this
18
+ * read — set by the same write that creates an item, cleared by a holder about to read — never
19
+ * the truth of it.
20
+ */
21
+ import { steerMessageFromRecord } from "operon-agents";
1
22
  /** Where processing stopped. Everything at or before it has been dealt with. */
2
23
  export const INBOX_CURSOR_KEY = "inbox:cursor";
3
24
  /**
@@ -6,9 +27,9 @@ export const INBOX_CURSOR_KEY = "inbox:cursor";
6
27
  * extension point the framework left for exactly that.
7
28
  */
8
29
  export const CONTROL_RECORD_NAME = "managed.control";
9
- /** The identity an item is tracked by once dispatched: `deliveryId` or `commandId`. */
30
+ /** The identity an item is tracked by once dispatched: `steerId` or `commandId`. */
10
31
  export function inboxItemId(item) {
11
- return item.kind === "input" ? item.origin.deliveryId : item.command.commandId;
32
+ return item.kind === "input" ? item.item.id : item.command.commandId;
12
33
  }
13
34
  export async function readInboxCursor(store) {
14
35
  const raw = await store.getState(INBOX_CURSOR_KEY);
@@ -36,9 +57,9 @@ export async function hasUnprocessedInbox(store) {
36
57
  return (await readInbox(store, await readInboxCursor(store))).length > 0;
37
58
  }
38
59
  function inboxItemFromRecord(sequence, record) {
39
- if (record.type === "inbox.received") {
40
- return { kind: "input", sequence, input: record.input, origin: record.origin, mode: record.mode };
41
- }
60
+ const steer = steerMessageFromRecord(record);
61
+ if (steer !== undefined)
62
+ return { kind: "input", sequence, item: steer };
42
63
  if (record.type === "custom" && record.name === CONTROL_RECORD_NAME) {
43
64
  const command = parseControlCommand(record.data);
44
65
  return command === undefined ? undefined : { kind: "control", sequence, command };
@@ -1,12 +1,28 @@
1
- import type { Agent, CreateSessionOptions, Harness, Machine, MachineFactory, ResumeSessionOptions } from "operon-agents";
1
+ import type { Agent, CreateSessionOptions, Harness, Environment, EnvironmentFactory, ResumeSessionOptions } from "operon-agents";
2
2
  import type { AgentRef, EnvironmentRef } from "../protocol/types.ts";
3
+ /**
4
+ * Which session a registry is resolving for. Handed to both registries by the service at create
5
+ * and by the worker on every open, so a host can choose per session — per tenant — the agent,
6
+ * the environment and the credentials (`resumeOptions.mcpCredentials`) it runs with.
7
+ */
8
+ export interface ManagedSessionContext {
9
+ readonly sessionId: string;
10
+ /** Stamped by `SessionService({ ownerKey })` at create. Trusted: no client can set it. */
11
+ readonly ownerKey?: string;
12
+ /**
13
+ * The create request's `metadata`. Untrusted: a client wrote it. A host that acts on it (a
14
+ * vault id, a repository) must check it against `ownerKey`, or a client names another
15
+ * tenant's.
16
+ */
17
+ readonly metadata?: Readonly<Record<string, unknown>>;
18
+ }
3
19
  export interface AgentResolution<TContext = unknown> {
4
20
  readonly agent?: Agent<TContext>;
5
21
  readonly createOptions?: Omit<CreateSessionOptions<TContext>, "id" | "title" | "workDir" | "agent">;
6
22
  readonly resumeOptions?: Omit<ResumeSessionOptions<TContext>, "agent">;
7
23
  }
8
24
  export interface ManagedAgentRegistry<TContext = unknown> {
9
- resolve(ref: AgentRef): AgentResolution<TContext> | Promise<AgentResolution<TContext>>;
25
+ resolve(ref: AgentRef, session: ManagedSessionContext): AgentResolution<TContext> | Promise<AgentResolution<TContext>>;
10
26
  }
11
27
  /** Let managed sessions use the Harness's configured default Agent. */
12
28
  export declare class DefaultAgentRegistry<TContext = unknown> implements ManagedAgentRegistry<TContext> {
@@ -18,23 +34,23 @@ export interface EnvironmentResolution {
18
34
  /** Durable working directory recorded by the SessionRepository. */
19
35
  readonly workDir: string;
20
36
  /** Optional per-session execution backend. Lifecycle remains provider-owned. */
21
- readonly machine?: Machine | MachineFactory;
37
+ readonly environment?: Environment | EnvironmentFactory;
22
38
  }
23
39
  export interface ManagedEnvironmentRegistry {
24
- resolve(ref: EnvironmentRef): EnvironmentResolution | Promise<EnvironmentResolution>;
40
+ resolve(ref: EnvironmentRef, session: ManagedSessionContext): EnvironmentResolution | Promise<EnvironmentResolution>;
25
41
  }
26
42
  export declare class StaticEnvironmentRegistry implements ManagedEnvironmentRegistry {
27
43
  private readonly environments;
28
44
  constructor(environments: Readonly<Record<string, EnvironmentResolution>>);
29
45
  resolve(ref: EnvironmentRef): EnvironmentResolution;
30
46
  }
31
- /** Convenience composition for a server that owns the Harness. Machine/sandbox lifecycle
47
+ /** Convenience composition for a server that owns the Harness. Environment/sandbox lifecycle
32
48
  * remains with the host; this merely makes that explicit at the managed-server boundary. */
33
49
  export interface ManagedHarnessOptions<TContext = unknown> {
34
50
  readonly harness: Harness<TContext>;
35
51
  readonly agents?: ManagedAgentRegistry<TContext>;
36
52
  readonly environments: ManagedEnvironmentRegistry;
37
53
  readonly defaultAgentId?: string;
38
- readonly machine?: Machine | MachineFactory;
54
+ readonly environment?: Environment | EnvironmentFactory;
39
55
  }
40
56
  //# sourceMappingURL=registries.d.ts.map
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Wire-side validation for what the managed API accepts. The `protocol/types.ts` interfaces are
3
+ * what a client compiles against; these schemas are what the server holds a request body to
4
+ * before it touches the store. They are kept together so a field added to one shows up as a
5
+ * type error in the other (see the `satisfies` checks at the bottom).
6
+ *
7
+ * Bodies arrive as `unknown` from JSON: every rule about them lives here, and nowhere else,
8
+ * so a rejected request always names the field that failed.
9
+ */
10
+ import { z } from "zod";
11
+ import type { InterruptAnswer } from "operon-agents";
12
+ import type { AgentRef, CreateManagedMessageRequest, CreateManagedSessionRequest, EnvironmentRef, ResumeManagedSessionRequest, UpdateManagedSessionRequest } from "../protocol/types.ts";
13
+ /** `AgentRef | string` on the wire, always an `AgentRef` once parsed. */
14
+ export declare const AgentRefSchema: z.ZodUnion<readonly [z.ZodPipe<z.ZodString, z.ZodTransform<AgentRef, string>>, z.ZodObject<{
15
+ id: z.ZodString;
16
+ version: z.ZodOptional<z.ZodString>;
17
+ }, z.core.$strip>]>;
18
+ /** `EnvironmentRef | string` on the wire, always an `EnvironmentRef` once parsed. */
19
+ export declare const EnvironmentRefSchema: z.ZodUnion<readonly [z.ZodPipe<z.ZodString, z.ZodTransform<EnvironmentRef, string>>, z.ZodObject<{
20
+ id: z.ZodString;
21
+ }, z.core.$strip>]>;
22
+ export declare const CreateSessionRequestSchema: z.ZodObject<{
23
+ id: z.ZodOptional<z.ZodString>;
24
+ title: z.ZodOptional<z.ZodString>;
25
+ agent: z.ZodUnion<readonly [z.ZodPipe<z.ZodString, z.ZodTransform<AgentRef, string>>, z.ZodObject<{
26
+ id: z.ZodString;
27
+ version: z.ZodOptional<z.ZodString>;
28
+ }, z.core.$strip>]>;
29
+ environment: z.ZodUnion<readonly [z.ZodPipe<z.ZodString, z.ZodTransform<EnvironmentRef, string>>, z.ZodObject<{
30
+ id: z.ZodString;
31
+ }, z.core.$strip>]>;
32
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
33
+ }, z.core.$strip>;
34
+ export declare const UpdateSessionRequestSchema: z.ZodObject<{
35
+ title: z.ZodString;
36
+ }, z.core.$strip>;
37
+ export declare const CreateMessageRequestSchema: z.ZodObject<{
38
+ input: z.ZodString;
39
+ origin: z.ZodOptional<z.ZodEnum<{
40
+ user: "user";
41
+ external: "external";
42
+ }>>;
43
+ source: z.ZodOptional<z.ZodString>;
44
+ actor: z.ZodOptional<z.ZodString>;
45
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>>>;
46
+ mode: z.ZodOptional<z.ZodEnum<{
47
+ steer: "steer";
48
+ follow_up: "follow_up";
49
+ }>>;
50
+ }, z.core.$strip>;
51
+ /**
52
+ * One answer per pending interrupt. A bare `ApprovalResponse` (no `kind`) is accepted the way
53
+ * `HarnessSession.resume` accepts it, and normalised to the tagged form before it is journaled.
54
+ */
55
+ export declare const InterruptAnswerSchema: z.ZodUnion<readonly [z.ZodObject<{
56
+ decision: z.ZodEnum<{
57
+ approved: "approved";
58
+ rejected: "rejected";
59
+ cancelled: "cancelled";
60
+ }>;
61
+ scope: z.ZodOptional<z.ZodLiteral<"session">>;
62
+ feedback: z.ZodOptional<z.ZodString>;
63
+ kind: z.ZodLiteral<"approval">;
64
+ }, z.core.$strip>, z.ZodObject<{
65
+ kind: z.ZodLiteral<"input">;
66
+ data: z.ZodUnknown;
67
+ }, z.core.$strip>, z.ZodPipe<z.ZodObject<{
68
+ decision: z.ZodEnum<{
69
+ approved: "approved";
70
+ rejected: "rejected";
71
+ cancelled: "cancelled";
72
+ }>;
73
+ scope: z.ZodOptional<z.ZodLiteral<"session">>;
74
+ feedback: z.ZodOptional<z.ZodString>;
75
+ kind: z.ZodOptional<z.ZodUndefined>;
76
+ }, z.core.$strip>, z.ZodTransform<({
77
+ readonly kind: "approval";
78
+ } & import("operon-agents-core").ApprovalResponse) | {
79
+ readonly kind: "input";
80
+ readonly data: unknown;
81
+ }, {
82
+ decision: "approved" | "rejected" | "cancelled";
83
+ scope?: "session" | undefined;
84
+ feedback?: string | undefined;
85
+ kind?: undefined;
86
+ }>>]>;
87
+ export declare const InterruptAnswersSchema: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodObject<{
88
+ decision: z.ZodEnum<{
89
+ approved: "approved";
90
+ rejected: "rejected";
91
+ cancelled: "cancelled";
92
+ }>;
93
+ scope: z.ZodOptional<z.ZodLiteral<"session">>;
94
+ feedback: z.ZodOptional<z.ZodString>;
95
+ kind: z.ZodLiteral<"approval">;
96
+ }, z.core.$strip>, z.ZodObject<{
97
+ kind: z.ZodLiteral<"input">;
98
+ data: z.ZodUnknown;
99
+ }, z.core.$strip>, z.ZodPipe<z.ZodObject<{
100
+ decision: z.ZodEnum<{
101
+ approved: "approved";
102
+ rejected: "rejected";
103
+ cancelled: "cancelled";
104
+ }>;
105
+ scope: z.ZodOptional<z.ZodLiteral<"session">>;
106
+ feedback: z.ZodOptional<z.ZodString>;
107
+ kind: z.ZodOptional<z.ZodUndefined>;
108
+ }, z.core.$strip>, z.ZodTransform<({
109
+ readonly kind: "approval";
110
+ } & import("operon-agents-core").ApprovalResponse) | {
111
+ readonly kind: "input";
112
+ readonly data: unknown;
113
+ }, {
114
+ decision: "approved" | "rejected" | "cancelled";
115
+ scope?: "session" | undefined;
116
+ feedback?: string | undefined;
117
+ kind?: undefined;
118
+ }>>]>>;
119
+ export declare const ResumeSessionRequestSchema: z.ZodObject<{
120
+ answers: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodObject<{
121
+ decision: z.ZodEnum<{
122
+ approved: "approved";
123
+ rejected: "rejected";
124
+ cancelled: "cancelled";
125
+ }>;
126
+ scope: z.ZodOptional<z.ZodLiteral<"session">>;
127
+ feedback: z.ZodOptional<z.ZodString>;
128
+ kind: z.ZodLiteral<"approval">;
129
+ }, z.core.$strip>, z.ZodObject<{
130
+ kind: z.ZodLiteral<"input">;
131
+ data: z.ZodUnknown;
132
+ }, z.core.$strip>, z.ZodPipe<z.ZodObject<{
133
+ decision: z.ZodEnum<{
134
+ approved: "approved";
135
+ rejected: "rejected";
136
+ cancelled: "cancelled";
137
+ }>;
138
+ scope: z.ZodOptional<z.ZodLiteral<"session">>;
139
+ feedback: z.ZodOptional<z.ZodString>;
140
+ kind: z.ZodOptional<z.ZodUndefined>;
141
+ }, z.core.$strip>, z.ZodTransform<({
142
+ readonly kind: "approval";
143
+ } & import("operon-agents-core").ApprovalResponse) | {
144
+ readonly kind: "input";
145
+ readonly data: unknown;
146
+ }, {
147
+ decision: "approved" | "rejected" | "cancelled";
148
+ scope?: "session" | undefined;
149
+ feedback?: string | undefined;
150
+ kind?: undefined;
151
+ }>>]>>;
152
+ }, z.core.$strip>;
153
+ /** Parse a request body, turning schema issues into a 400 that names the offending field. */
154
+ export declare function parseRequest<S extends z.ZodType>(schema: S, input: unknown): z.output<S>;
155
+ type Assert<T extends true> = T;
156
+ type Extends<A, B> = A extends B ? true : false;
157
+ export type _CreateSessionInput = Assert<Extends<CreateManagedSessionRequest, z.input<typeof CreateSessionRequestSchema>>>;
158
+ export type _UpdateSessionInput = Assert<Extends<UpdateManagedSessionRequest, z.input<typeof UpdateSessionRequestSchema>>>;
159
+ export type _CreateMessageInput = Assert<Extends<CreateManagedMessageRequest, z.input<typeof CreateMessageRequestSchema>>>;
160
+ export type _CreateMessageOutput = Assert<Extends<z.output<typeof CreateMessageRequestSchema>, CreateManagedMessageRequest>>;
161
+ export type _ResumeInput = Assert<Extends<ResumeManagedSessionRequest, z.input<typeof ResumeSessionRequestSchema>>>;
162
+ export type _InterruptAnswerOutput = Assert<Extends<z.output<typeof InterruptAnswerSchema>, InterruptAnswer>>;
163
+ export {};
164
+ //# sourceMappingURL=request-schemas.d.ts.map
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Wire-side validation for what the managed API accepts. The `protocol/types.ts` interfaces are
3
+ * what a client compiles against; these schemas are what the server holds a request body to
4
+ * before it touches the store. They are kept together so a field added to one shows up as a
5
+ * type error in the other (see the `satisfies` checks at the bottom).
6
+ *
7
+ * Bodies arrive as `unknown` from JSON: every rule about them lives here, and nowhere else,
8
+ * so a rejected request always names the field that failed.
9
+ */
10
+ import { z } from "zod";
11
+ import { ManagedInvalidRequestError } from "./errors.js";
12
+ const nonBlank = (what) => z.string().refine((value) => value.trim().length > 0, `${what} must not be empty`);
13
+ /** `AgentRef | string` on the wire, always an `AgentRef` once parsed. */
14
+ export const AgentRefSchema = z.union([
15
+ nonBlank("agent id").transform((id) => ({ id })),
16
+ z.object({ id: nonBlank("agent id"), version: z.string().optional() }),
17
+ ], { error: "agent must be an id string or an object with a non-empty id" });
18
+ /** `EnvironmentRef | string` on the wire, always an `EnvironmentRef` once parsed. */
19
+ export const EnvironmentRefSchema = z.union([
20
+ nonBlank("environment id").transform((id) => ({ id })),
21
+ z.object({ id: nonBlank("environment id") }),
22
+ ], { error: "environment must be an id string or an object with a non-empty id" });
23
+ export const CreateSessionRequestSchema = z.object({
24
+ id: z.string().regex(/^[A-Za-z0-9_-]+$/, "session id may contain only letters, digits, underscores and hyphens").optional(),
25
+ title: z.string().optional(),
26
+ agent: AgentRefSchema,
27
+ environment: EnvironmentRefSchema,
28
+ metadata: z.record(z.string(), z.unknown()).optional(),
29
+ });
30
+ export const UpdateSessionRequestSchema = z.object({
31
+ title: nonBlank("title"),
32
+ });
33
+ const ExternalMetadataValueSchema = z.union([z.string(), z.number(), z.boolean(), z.null()], {
34
+ error: "metadata values must be strings, numbers, booleans or null",
35
+ });
36
+ export const CreateMessageRequestSchema = z.object({
37
+ input: nonBlank("input"),
38
+ origin: z.enum(["user", "external"]).optional(),
39
+ source: nonBlank("source").optional(),
40
+ actor: z.string().optional(),
41
+ metadata: z.record(z.string(), ExternalMetadataValueSchema).optional(),
42
+ mode: z.enum(["steer", "follow_up"]).optional(),
43
+ }).check((ctx) => {
44
+ const { origin, source, actor, metadata } = ctx.value;
45
+ if (origin !== "external" && (source !== undefined || actor !== undefined || metadata !== undefined)) {
46
+ ctx.issues.push({
47
+ code: "custom",
48
+ input: ctx.value,
49
+ message: 'source, actor and metadata describe a relayed delivery; set origin: "external"',
50
+ });
51
+ }
52
+ });
53
+ const ApprovalResponseShape = {
54
+ decision: z.enum(["approved", "rejected", "cancelled"]),
55
+ scope: z.literal("session").optional(),
56
+ feedback: z.string().optional(),
57
+ };
58
+ /**
59
+ * One answer per pending interrupt. A bare `ApprovalResponse` (no `kind`) is accepted the way
60
+ * `HarnessSession.resume` accepts it, and normalised to the tagged form before it is journaled.
61
+ */
62
+ export const InterruptAnswerSchema = z.union([
63
+ z.object({ kind: z.literal("approval"), ...ApprovalResponseShape }),
64
+ z.object({ kind: z.literal("input"), data: z.unknown() }),
65
+ z.object({ kind: z.undefined().optional(), ...ApprovalResponseShape }).transform(({ kind: _kind, ...response }) => ({ kind: "approval", ...response })),
66
+ ], { error: 'an answer is { kind: "approval", decision } or { kind: "input", data }' });
67
+ export const InterruptAnswersSchema = z.record(z.string(), InterruptAnswerSchema);
68
+ export const ResumeSessionRequestSchema = z.object({
69
+ answers: InterruptAnswersSchema,
70
+ });
71
+ /** Parse a request body, turning schema issues into a 400 that names the offending field. */
72
+ export function parseRequest(schema, input) {
73
+ const result = schema.safeParse(input);
74
+ if (result.success)
75
+ return result.data;
76
+ throw new ManagedInvalidRequestError(describeIssues(result.error.issues));
77
+ }
78
+ function describeIssues(issues) {
79
+ return issues
80
+ .map((issue) => {
81
+ const path = issue.path.map(String).join(".");
82
+ return path.length > 0 ? `${path}: ${issue.message}` : issue.message;
83
+ })
84
+ .join("; ");
85
+ }
86
+ //# sourceMappingURL=request-schemas.js.map