operon-managed-agents 0.1.0-alpha.1 → 0.1.0-alpha.11

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
@@ -58,10 +58,13 @@ for await (const event of stream) {
58
58
  // stream.lastEventId is the cursor to continue from elsewhere.
59
59
  ```
60
60
 
61
+ `sessions.update(id, { title })` renames a session (`PATCH /v1/sessions/{id}`); the title is the
62
+ only field a client can change after creation, and it is durable before the call resolves.
63
+
61
64
  `run()` sends one input and resolves when the turn that took **that** delivery ends — not the
62
65
  first `turn.ended` in the replay, which on a session with history belongs to an older turn.
63
66
 
64
- The server accepts an `authorize(request, { action, sessionId })` hook. Configure it for any
67
+ The server accepts an `authorize(request, { action, sessionId, origin })` hook. Configure it for any
65
68
  networked deployment; it can verify credentials and enforce per-session ownership. The
66
69
  bundled in-memory idempotency store is atomic within one process and bounded by TTL/capacity;
67
70
  distributed deployments should provide a database-backed `ManagedDeliveryIdempotencyStore`.
@@ -101,3 +104,24 @@ await client.sessions.messages.create(
101
104
  { idempotencyKey: requestId },
102
105
  );
103
106
  ```
107
+
108
+ Whose words a delivery is, the caller says. The party holding a session's credential is its
109
+ user — the way a local session's stdin is — so by default `messages.create` delivers the
110
+ caller's own words and the model sees them bare, as a prompt. A caller relaying someone else's
111
+ words declares it:
112
+
113
+ ```ts
114
+ await client.sessions.messages.create(session.id, {
115
+ input: "deploy finished: 3 warnings",
116
+ origin: "external",
117
+ source: "ci",
118
+ actor: "deploy-bot",
119
+ });
120
+ ```
121
+
122
+ The model then sees the text inside an `<external-message>` envelope stamped as not from the
123
+ user — not an approval, not an answer to anything it asked. `source`, `actor` and `metadata`
124
+ describe the relay and are refused without the declaration. Declaring `external` lowers trust,
125
+ so it needs no permission of its own; the `authorize` hook receives `origin` on
126
+ `messages.create`, and a deployment that hands a credential to something that only relays (a
127
+ webhook bridge, a teammate agent) can refuse it anything else.
@@ -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 } 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;
@@ -48,8 +48,10 @@ export declare class ManagedSessionsClient {
48
48
  create(request: CreateManagedSessionRequest): Promise<ManagedSession>;
49
49
  list(): Promise<ListManagedSessionsResponse>;
50
50
  retrieve(sessionId: string): Promise<ManagedSession>;
51
+ /** Rename a session; the new title is durable before this resolves. */
52
+ update(sessionId: string, request: UpdateManagedSessionRequest): Promise<ManagedSession>;
51
53
  messages: {
52
- create: (sessionId: string, request: CreateManagedMessageRequest, options?: CreateManagedMessageOptions) => Promise<DeliveryReceiptResource>;
54
+ create: (sessionId: string, request: CreateManagedMessageRequest, options?: CreateManagedMessageOptions) => Promise<MessageReceiptResource>;
53
55
  };
54
56
  events: {
55
57
  list: (sessionId: string, options?: ListSessionEventsOptions) => Promise<ListSessionEventsResponse>;
@@ -129,6 +129,10 @@ export class ManagedSessionsClient {
129
129
  retrieve(sessionId) {
130
130
  return this.root.request(`/sessions/${encodeURIComponent(sessionId)}`);
131
131
  }
132
+ /** Rename a session; the new title is durable before this resolves. */
133
+ update(sessionId, request) {
134
+ return this.root.request(`/sessions/${encodeURIComponent(sessionId)}`, { method: "PATCH", body: request });
135
+ }
132
136
  messages = {
133
137
  create: (sessionId, request, options = {}) => this.root.request(`/sessions/${encodeURIComponent(sessionId)}/messages`, {
134
138
  method: "POST",
@@ -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 || (event.origin?.kind === "external" && event.origin.deliveryId === 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 && event.origin?.kind === "external" && event.origin.deliveryId === 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)
@@ -141,4 +142,12 @@ function textOf(content) {
141
142
  .map((part) => part.text);
142
143
  return parts.length === 0 ? undefined : parts.join("");
143
144
  }
145
+ /**
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.
149
+ */
150
+ function steerOf(origin) {
151
+ return origin !== undefined && "steerId" in origin ? origin.steerId : undefined;
152
+ }
144
153
  //# sourceMappingURL=run.js.map
@@ -27,23 +27,51 @@ export interface CreateManagedSessionRequest {
27
27
  readonly environment: EnvironmentRef | string;
28
28
  readonly metadata?: Readonly<Record<string, unknown>>;
29
29
  }
30
+ /** `PATCH /sessions/{id}`: rename a session. Only the title is client-writable after creation. */
31
+ export interface UpdateManagedSessionRequest {
32
+ readonly title: string;
33
+ }
30
34
  export interface ListManagedSessionsResponse {
31
35
  readonly data: readonly ManagedSession[];
32
36
  }
33
37
  export interface CreateManagedMessageRequest {
34
38
  readonly input: string;
39
+ /**
40
+ * Whose words these are.
41
+ *
42
+ * `user` (default): the caller's own. The party holding a session's credential is its user —
43
+ * the same way a local session's stdin is — so the model sees the text bare, as a prompt.
44
+ *
45
+ * `external`: another party's words the caller is relaying (a peer, a webhook, another
46
+ * agent). The model sees them inside an `<external-message>` envelope stamped as NOT from the
47
+ * user. Declaring this lowers trust, so it needs no extra permission; the server's `authorize`
48
+ * hook receives the value and can require it for a credential that only ever relays.
49
+ */
50
+ readonly origin?: "user" | "external";
51
+ /** `external` only: what relayed the words (default `"managed-api"`). */
35
52
  readonly source?: string;
53
+ /** `external` only: who said them. */
36
54
  readonly actor?: string;
55
+ /** `external` only: attributes rendered onto the envelope. */
37
56
  readonly metadata?: Readonly<Record<string, string | number | boolean | null>>;
38
- 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";
39
63
  }
40
- export interface DeliveryReceiptResource {
41
- 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;
42
72
  readonly sessionId: string;
43
73
  readonly acceptedAt: number;
44
- readonly status: "started" | "queued";
45
- readonly channel: "turn" | "steering" | "follow_up";
46
- readonly steerId?: string;
74
+ readonly channel: "steering" | "follow_up";
47
75
  }
48
76
  export interface ListSessionEventsResponse {
49
77
  /** Durable AgentEvents in store order. Store sequence remains inside the opaque page cursor;
@@ -1,10 +1,16 @@
1
1
  import { type IncomingMessage, type Server } from "node:http";
2
2
  import type { SessionService } from "./session-service.ts";
3
3
  import type { SessionWorker } from "./session-worker.ts";
4
- export type ManagedAuthorizationAction = "sessions.create" | "sessions.list" | "sessions.read" | "sessions.delete" | "messages.create" | "events.list" | "events.stream" | "sessions.cancel" | "interruptions.list" | "sessions.resume";
4
+ export type ManagedAuthorizationAction = "sessions.create" | "sessions.list" | "sessions.read" | "sessions.update" | "sessions.delete" | "messages.create" | "events.list" | "events.stream" | "sessions.cancel" | "interruptions.list" | "sessions.resume";
5
5
  export interface ManagedAuthorizationContext {
6
6
  readonly action: ManagedAuthorizationAction;
7
7
  readonly sessionId?: string;
8
+ /**
9
+ * `messages.create` only: whose words the caller says these are. `user` is the default and
10
+ * makes the caller this session's user; a deployment that hands a credential to something
11
+ * that only relays (a webhook bridge, a teammate agent) can refuse it anything but `external`.
12
+ */
13
+ readonly origin?: "user" | "external";
8
14
  }
9
15
  export type ManagedAuthorize = (request: IncomingMessage, context: ManagedAuthorizationContext) => boolean | void | Promise<boolean | void>;
10
16
  /**
@@ -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.
@@ -54,6 +55,11 @@ export function createManagedHttpServer(options) {
54
55
  await authorize(request, "sessions.read", sessionId);
55
56
  return sendJson(response, 200, await options.service.get(sessionId));
56
57
  }
58
+ if (method === "PATCH" && parts.length === 2) {
59
+ await authorize(request, "sessions.update", sessionId);
60
+ const body = await readJson(request, maxBodyBytes);
61
+ return sendJson(response, 200, await options.service.update(sessionId, body));
62
+ }
57
63
  if (method === "DELETE" && parts.length === 2) {
58
64
  await authorize(request, "sessions.delete", sessionId);
59
65
  await options.service.delete(sessionId);
@@ -62,8 +68,10 @@ export function createManagedHttpServer(options) {
62
68
  return;
63
69
  }
64
70
  if (method === "POST" && parts[2] === "messages" && parts.length === 3) {
65
- await authorize(request, "messages.create", sessionId);
71
+ // Body before authorization: the hook is told whose words the caller claims these are.
72
+ // Reading first costs an unauthenticated caller at most `maxBodyBytes` of parsing.
66
73
  const body = await readJson(request, maxBodyBytes);
74
+ await authorize(request, "messages.create", sessionId, body.origin === "external" ? "external" : "user");
67
75
  if (typeof body.input !== "string" || !body.input.trim()) {
68
76
  return sendJson(response, 400, apiError("invalid_request", "input must not be empty"));
69
77
  }
@@ -134,9 +142,7 @@ export function createManagedHttpServer(options) {
134
142
  }
135
143
  if (method === "POST" && parts[2] === "resume" && parts.length === 3) {
136
144
  await authorize(request, "sessions.resume", sessionId);
137
- const body = await readJson(request, maxBodyBytes);
138
- if (!isRecord(body.answers))
139
- return sendJson(response, 400, apiError("invalid_request", "answers must be an object"));
145
+ const body = parseRequest(ResumeSessionRequestSchema, await readJson(request, maxBodyBytes));
140
146
  const receipt = await options.service.answerInterruption(sessionId, body.answers);
141
147
  void options.worker?.drain(sessionId).catch(() => undefined);
142
148
  return sendJson(response, 202, receipt);
@@ -186,10 +192,11 @@ export function createManagedHttpServer(options) {
186
192
  response.write(": connected\n\n");
187
193
  manageStream(request, response, () => controller.abort());
188
194
  }
189
- async function authorize(request, action, sessionId) {
195
+ async function authorize(request, action, sessionId, origin) {
190
196
  const allowed = await options.authorize(request, {
191
197
  action,
192
198
  ...(sessionId !== undefined ? { sessionId } : {}),
199
+ ...(origin !== undefined ? { origin } : {}),
193
200
  });
194
201
  if (allowed === false)
195
202
  throw new ManagedForbiddenError();
@@ -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,8 +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 { InterruptAnswer, SessionStore } from "operon-agents";
16
- import type { ExternalOriginMetadataValue } from "operon-agents";
21
+ import { type InterruptAnswer, type SessionStore, type SteerMessage } from "operon-agents";
17
22
  /** Where processing stopped. Everything at or before it has been dealt with. */
18
23
  export declare const INBOX_CURSOR_KEY = "inbox:cursor";
19
24
  /**
@@ -24,7 +29,7 @@ export declare const INBOX_CURSOR_KEY = "inbox:cursor";
24
29
  export declare const CONTROL_RECORD_NAME = "managed.control";
25
30
  export type ControlCommand = {
26
31
  readonly kind: "cancel";
27
- /** Idempotency identity, the way `deliveryId` is for an input. */
32
+ /** Idempotency identity, the way `steerId` is for an input. */
28
33
  readonly commandId: string;
29
34
  readonly requestedAt: number;
30
35
  readonly actor?: string;
@@ -35,18 +40,11 @@ export type ControlCommand = {
35
40
  readonly answers: Readonly<Record<string, InterruptAnswer>>;
36
41
  readonly actor?: string;
37
42
  };
43
+ /** An accepted message: its `steer.queued` record, ready to be put back on a bus. */
38
44
  export interface InboxInput {
39
45
  readonly kind: "input";
40
46
  readonly sequence: string;
41
- readonly input: string;
42
- readonly origin: {
43
- readonly kind: "external";
44
- readonly source: string;
45
- readonly deliveryId: string;
46
- readonly actor?: string;
47
- readonly metadata?: Readonly<Record<string, ExternalOriginMetadataValue>>;
48
- };
49
- readonly mode: "auto" | "steer" | "follow_up";
47
+ readonly item: SteerMessage;
50
48
  }
51
49
  export interface InboxControl {
52
50
  readonly kind: "control";
@@ -54,7 +52,7 @@ export interface InboxControl {
54
52
  readonly command: ControlCommand;
55
53
  }
56
54
  export type InboxItem = InboxInput | InboxControl;
57
- /** 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`. */
58
56
  export declare function inboxItemId(item: InboxItem): string;
59
57
  export declare function readInboxCursor(store: SessionStore): Promise<string | undefined>;
60
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,4 +1,4 @@
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
3
  export interface AgentResolution<TContext = unknown> {
4
4
  readonly agent?: Agent<TContext>;
@@ -18,7 +18,7 @@ export interface EnvironmentResolution {
18
18
  /** Durable working directory recorded by the SessionRepository. */
19
19
  readonly workDir: string;
20
20
  /** Optional per-session execution backend. Lifecycle remains provider-owned. */
21
- readonly machine?: Machine | MachineFactory;
21
+ readonly environment?: Environment | EnvironmentFactory;
22
22
  }
23
23
  export interface ManagedEnvironmentRegistry {
24
24
  resolve(ref: EnvironmentRef): EnvironmentResolution | Promise<EnvironmentResolution>;
@@ -28,13 +28,13 @@ export declare class StaticEnvironmentRegistry implements ManagedEnvironmentRegi
28
28
  constructor(environments: Readonly<Record<string, EnvironmentResolution>>);
29
29
  resolve(ref: EnvironmentRef): EnvironmentResolution;
30
30
  }
31
- /** Convenience composition for a server that owns the Harness. Machine/sandbox lifecycle
31
+ /** Convenience composition for a server that owns the Harness. Environment/sandbox lifecycle
32
32
  * remains with the host; this merely makes that explicit at the managed-server boundary. */
33
33
  export interface ManagedHarnessOptions<TContext = unknown> {
34
34
  readonly harness: Harness<TContext>;
35
35
  readonly agents?: ManagedAgentRegistry<TContext>;
36
36
  readonly environments: ManagedEnvironmentRegistry;
37
37
  readonly defaultAgentId?: string;
38
- readonly machine?: Machine | MachineFactory;
38
+ readonly environment?: Environment | EnvironmentFactory;
39
39
  }
40
40
  //# 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
@@ -15,7 +15,7 @@
15
15
  * simple event-stream subscription ends up billing for compute.
16
16
  */
17
17
  import { type AgentEvent, type DeleteSessionOptions, type InterruptAnswer, type PendingRunInterrupt, type SessionRepository } from "operon-agents";
18
- import type { ControlReceiptResource, CreateManagedMessageRequest, CreateManagedSessionRequest, DeliveryReceiptResource, ManagedSession } from "../protocol/types.ts";
18
+ import type { ControlReceiptResource, CreateManagedMessageRequest, CreateManagedSessionRequest, ManagedSession, MessageReceiptResource, UpdateManagedSessionRequest } from "../protocol/types.ts";
19
19
  import type { SessionWork } from "./work.ts";
20
20
  import { type ManagedSessionMetadataStore } from "./metadata.ts";
21
21
  import type { ManagedEnvironmentRegistry } from "./registries.ts";
@@ -30,7 +30,7 @@ export interface SessionServiceOptions {
30
30
  * the same table the workers claim from.
31
31
  */
32
32
  readonly work: SessionWork;
33
- /** Resolves an environment to the durable `workDir` a session is created under. The machine
33
+ /** Resolves an environment to the durable `workDir` a session is created under. The environment
34
34
  * half of a resolution belongs to the worker; nothing here executes. */
35
35
  readonly environments: ManagedEnvironmentRegistry;
36
36
  readonly metadataStore?: ManagedSessionMetadataStore;
@@ -113,8 +113,15 @@ export declare class SessionService {
113
113
  * and tool configuration a worker holds, and doing it here would make creation depend on
114
114
  * execution being available.
115
115
  */
116
- create(input: CreateManagedSessionRequest): Promise<ManagedSession>;
116
+ create(request: CreateManagedSessionRequest): Promise<ManagedSession>;
117
117
  get(id: string): Promise<ManagedSession>;
118
+ /**
119
+ * Rename a session. The title lives in the session's own `meta` state, so the write goes
120
+ * through the store — the same path `create` takes — and reaches the repository catalog via
121
+ * the store's observer before this resolves. Like `interruptions`, it opens the store beside
122
+ * whoever may be running the session: `meta` is written by nobody during a turn.
123
+ */
124
+ update(id: string, request: UpdateManagedSessionRequest): Promise<ManagedSession>;
118
125
  list(): Promise<readonly ManagedSession[]>;
119
126
  listEvents(id: string, options: ListPersistedEventsOptions): Promise<PersistedEventPage>;
120
127
  /**
@@ -140,10 +147,13 @@ export declare class SessionService {
140
147
  * Accept an input and return a receipt. The write is awaited, so the receipt means the input
141
148
  * survives a crash — not merely that it reached a process.
142
149
  *
143
- * Acceptance is all this does. Whether the input steers a turn already in flight or starts a
144
- * fresh one is decided when a worker processes it, which can be an arbitrary moment later.
150
+ * Acceptance is all this does, and it is the same acceptance a local steer has: the record
151
+ * written here is the `steer.queued` a session's own bus would journal, built by the same
152
+ * function, so the worker that later opens the session puts it back on the bus unchanged.
153
+ * Whether it then steers a turn already in flight or wakes an idle session is decided when a
154
+ * worker processes it, which can be an arbitrary moment later.
145
155
  */
146
- appendEvent(id: string, request: CreateManagedMessageRequest, idempotencyKey?: string): Promise<DeliveryReceiptResource>;
156
+ appendEvent(id: string, input: CreateManagedMessageRequest, idempotencyKey?: string): Promise<MessageReceiptResource>;
147
157
  private acceptEvent;
148
158
  /**
149
159
  * Ask whoever is running this session to stop, or — if nobody is — discard what is waiting.
@@ -161,7 +171,7 @@ export declare class SessionService {
161
171
  * that dies mid-continuation leaves nothing for the client to resend: the next holder reads
162
172
  * the same record and continues from the last durable pause.
163
173
  */
164
- answerInterruption(id: string, answers: Readonly<Record<string, InterruptAnswer>>, options?: {
174
+ answerInterruption(id: string, input: Readonly<Record<string, InterruptAnswer>>, options?: {
165
175
  readonly actor?: string;
166
176
  }): Promise<ControlReceiptResource>;
167
177
  private appendControl;
@@ -14,8 +14,9 @@
14
14
  * by first reviving a runtime makes every read a potential sandbox wake-up, which is how a
15
15
  * simple event-stream subscription ends up billing for compute.
16
16
  */
17
- import { agentEventFromRecord, INTERRUPTION_STATE_KEY, newAgentEventId, flattenPendingInterrupts, parseInterruptionState, watchRecordsByPolling, SessionRepositoryConflictError, } from "operon-agents";
17
+ import { agentEventFromRecord, buildSteerMessage, INTERRUPTION_STATE_KEY, newAgentEventId, flattenPendingInterrupts, parseInterruptionState, steerQueuedRecord, watchRecordsByPolling, SessionRepositoryConflictError, } from "operon-agents";
18
18
  import { CONTROL_RECORD_NAME, hasUnprocessedInbox } from "./inbox.js";
19
+ import { CreateMessageRequestSchema, CreateSessionRequestSchema, InterruptAnswersSchema, UpdateSessionRequestSchema, parseRequest, } from "./request-schemas.js";
19
20
  import { MemoryManagedSessionMetadataStore, } from "./metadata.js";
20
21
  import { MemoryManagedDeliveryIdempotencyStore, } from "./idempotency.js";
21
22
  import { ManagedConflictError, ManagedInvalidRequestError, ManagedSessionNotFoundError } from "./errors.js";
@@ -78,10 +79,9 @@ export class SessionService {
78
79
  * and tool configuration a worker holds, and doing it here would make creation depend on
79
80
  * execution being available.
80
81
  */
81
- async create(input) {
82
- assertCreateSessionRequest(input);
83
- const agent = agentRef(input.agent);
84
- const environment = environmentRef(input.environment);
82
+ async create(request) {
83
+ const input = parseRequest(CreateSessionRequestSchema, request);
84
+ const { agent, environment } = input;
85
85
  const resolved = await this.environments.resolve(environment);
86
86
  const now = Date.now();
87
87
  const sessionId = input.id ?? managedSessionId();
@@ -130,6 +130,30 @@ export class SessionService {
130
130
  const summary = await this.summary(id);
131
131
  return this.toManagedSession(summary, metadata);
132
132
  }
133
+ /**
134
+ * Rename a session. The title lives in the session's own `meta` state, so the write goes
135
+ * through the store — the same path `create` takes — and reaches the repository catalog via
136
+ * the store's observer before this resolves. Like `interruptions`, it opens the store beside
137
+ * whoever may be running the session: `meta` is written by nobody during a turn.
138
+ */
139
+ async update(id, request) {
140
+ const input = parseRequest(UpdateSessionRequestSchema, request);
141
+ const metadata = await this.requireMetadata(id);
142
+ await this.summary(id);
143
+ const handle = await this.repository.open(id);
144
+ if (handle === undefined)
145
+ throw new ManagedSessionNotFoundError(id);
146
+ try {
147
+ const meta = await handle.store.getState("meta");
148
+ if (!isRecord(meta))
149
+ throw new Error(`session "${id}" has no meta state`);
150
+ await handle.store.putState("meta", { ...meta, title: input.title, updatedAt: Date.now() });
151
+ }
152
+ finally {
153
+ await handle.store.close?.();
154
+ }
155
+ return this.toManagedSession(await this.summary(id), metadata);
156
+ }
133
157
  async list() {
134
158
  const summaries = await this.repository.list(this.ownerKey !== undefined ? { ownerKey: this.ownerKey } : undefined);
135
159
  const metadataById = await this.metadata.getMany(summaries.map((summary) => summary.id));
@@ -335,11 +359,14 @@ export class SessionService {
335
359
  * Accept an input and return a receipt. The write is awaited, so the receipt means the input
336
360
  * survives a crash — not merely that it reached a process.
337
361
  *
338
- * Acceptance is all this does. Whether the input steers a turn already in flight or starts a
339
- * fresh one is decided when a worker processes it, which can be an arbitrary moment later.
362
+ * Acceptance is all this does, and it is the same acceptance a local steer has: the record
363
+ * written here is the `steer.queued` a session's own bus would journal, built by the same
364
+ * function, so the worker that later opens the session puts it back on the bus unchanged.
365
+ * Whether it then steers a turn already in flight or wakes an idle session is decided when a
366
+ * worker processes it, which can be an arbitrary moment later.
340
367
  */
341
- async appendEvent(id, request, idempotencyKey) {
342
- assertCreateMessageRequest(request);
368
+ async appendEvent(id, input, idempotencyKey) {
369
+ const request = parseRequest(CreateMessageRequestSchema, input);
343
370
  if (idempotencyKey !== undefined) {
344
371
  return this.idempotency.run(id, idempotencyKey, () => this.acceptEvent(id, request));
345
372
  }
@@ -352,36 +379,29 @@ export class SessionService {
352
379
  throw new ManagedConflictError(`session "${id}" is interrupted; resume it before delivering new work`);
353
380
  }
354
381
  const acceptedAt = Date.now();
355
- const deliveryId = managedDeliveryId();
356
- const mode = request.mode ?? "auto";
382
+ const channel = request.mode === "follow_up" ? "follow_up" : "steering";
383
+ // Whose words, not which transport: the caller is this session's user unless it says it is
384
+ // relaying someone else's. The bus files a user's words by kind — `user` steers, a
385
+ // `user_follow_up` queues behind the turn — and a relay by its declared channel.
386
+ const origin = request.origin === "external"
387
+ ? {
388
+ kind: "external",
389
+ source: request.source ?? "managed-api",
390
+ channel,
391
+ ...(request.actor !== undefined ? { actor: request.actor } : {}),
392
+ ...(request.metadata !== undefined ? { metadata: request.metadata } : {}),
393
+ }
394
+ : { kind: channel === "follow_up" ? "user_follow_up" : "user" };
395
+ const item = buildSteerMessage(request.input, origin, { now: () => acceptedAt });
357
396
  await this.work.append(id, {
358
- type: "inbox.received",
397
+ ...steerQueuedRecord(item, acceptedAt),
359
398
  // Assigned here because this writes through a plain repository handle, not through a
360
399
  // session's publishing store (which stamps one on the way past). Without it the record
361
400
  // is unprojectable — invisible to `listEvents` and to every client, whose reconnect
362
401
  // protocol dedupes on exactly this id.
363
402
  eventId: newAgentEventId(),
364
- time: acceptedAt,
365
- address: "main",
366
- input: request.input,
367
- origin: {
368
- kind: "external",
369
- source: request.source ?? "managed-api",
370
- deliveryId,
371
- ...(request.actor !== undefined ? { actor: request.actor } : {}),
372
- ...(request.metadata !== undefined
373
- ? { metadata: request.metadata }
374
- : {}),
375
- },
376
- mode,
377
403
  });
378
- return {
379
- deliveryId,
380
- sessionId: id,
381
- acceptedAt,
382
- status: "queued",
383
- channel: mode === "follow_up" ? "follow_up" : mode === "steer" ? "steering" : "turn",
384
- };
404
+ return { steerId: item.id, sessionId: id, acceptedAt, channel: item.channel };
385
405
  }
386
406
  /**
387
407
  * Ask whoever is running this session to stop, or — if nobody is — discard what is waiting.
@@ -404,7 +424,8 @@ export class SessionService {
404
424
  * that dies mid-continuation leaves nothing for the client to resend: the next holder reads
405
425
  * the same record and continues from the last durable pause.
406
426
  */
407
- async answerInterruption(id, answers, options = {}) {
427
+ async answerInterruption(id, input, options = {}) {
428
+ const answers = parseRequest(InterruptAnswersSchema, input);
408
429
  if ((await this.summary(id)).durableState !== "interrupted") {
409
430
  throw new ManagedConflictError(`session "${id}" has no interrupted run to resume`);
410
431
  }
@@ -478,65 +499,6 @@ export class SessionService {
478
499
  };
479
500
  }
480
501
  }
481
- function agentRef(value) {
482
- if (typeof value === "string") {
483
- if (!value.trim())
484
- throw new ManagedInvalidRequestError("agent id must not be empty");
485
- return { id: value };
486
- }
487
- if (!isRecord(value) || typeof value.id !== "string" || !value.id.trim()) {
488
- throw new ManagedInvalidRequestError("agent must be an id string or an object with a non-empty id");
489
- }
490
- if (value.version !== undefined && typeof value.version !== "string") {
491
- throw new ManagedInvalidRequestError("agent version must be a string");
492
- }
493
- return value;
494
- }
495
- function environmentRef(value) {
496
- if (typeof value === "string") {
497
- if (!value.trim())
498
- throw new ManagedInvalidRequestError("environment id must not be empty");
499
- return { id: value };
500
- }
501
- if (!isRecord(value) || typeof value.id !== "string" || !value.id.trim()) {
502
- throw new ManagedInvalidRequestError("environment must be an id string or an object with a non-empty id");
503
- }
504
- return value;
505
- }
506
- function assertCreateSessionRequest(input) {
507
- if (!isRecord(input))
508
- throw new ManagedInvalidRequestError("request body must be an object");
509
- if (input.id !== undefined && (typeof input.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(input.id))) {
510
- throw new ManagedInvalidRequestError("session id may contain only letters, digits, underscores and hyphens");
511
- }
512
- if (input.title !== undefined && typeof input.title !== "string") {
513
- throw new ManagedInvalidRequestError("title must be a string");
514
- }
515
- if (input.metadata !== undefined && !isRecord(input.metadata)) {
516
- throw new ManagedInvalidRequestError("metadata must be an object");
517
- }
518
- agentRef(input.agent);
519
- environmentRef(input.environment);
520
- }
521
- function assertCreateMessageRequest(input) {
522
- if (!isRecord(input))
523
- throw new ManagedInvalidRequestError("request body must be an object");
524
- if (typeof input.input !== "string" || !input.input.trim()) {
525
- throw new ManagedInvalidRequestError("input must not be empty");
526
- }
527
- if (input.source !== undefined && (typeof input.source !== "string" || !input.source.trim())) {
528
- throw new ManagedInvalidRequestError("source must be a non-empty string");
529
- }
530
- if (input.actor !== undefined && typeof input.actor !== "string") {
531
- throw new ManagedInvalidRequestError("actor must be a string");
532
- }
533
- if (input.metadata !== undefined && !isRecord(input.metadata)) {
534
- throw new ManagedInvalidRequestError("metadata must be an object");
535
- }
536
- if (input.mode !== undefined && input.mode !== "auto" && input.mode !== "steer" && input.mode !== "follow_up") {
537
- throw new ManagedInvalidRequestError("mode must be auto, steer or follow_up");
538
- }
539
- }
540
502
  function isRecord(value) {
541
503
  return typeof value === "object" && value !== null && !Array.isArray(value);
542
504
  }
@@ -545,11 +507,6 @@ function managedSessionId() {
545
507
  managedIdCounter += 1;
546
508
  return `ms_${Date.now().toString(36)}_${managedIdCounter.toString(36)}`;
547
509
  }
548
- let deliveryCounter = 0;
549
- function managedDeliveryId() {
550
- deliveryCounter += 1;
551
- return `delivery_${Date.now().toString(36)}_${deliveryCounter.toString(36)}`;
552
- }
553
510
  let commandCounter = 0;
554
511
  function managedCommandId() {
555
512
  commandCounter += 1;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The execution half: moves a session's inbox into its conversation, and runs it.
2
+ * The execution half: puts a session's accepted messages back on its bus, and runs it.
3
3
  *
4
4
  * A worker is not part of the API surface and does not look for work on its own terms. It
5
5
  * claims from the work table (`SessionWork`) — one row per session that has been appended to
@@ -116,14 +116,12 @@ export declare class SessionWorker<TContext = unknown> {
116
116
  private drainInbox;
117
117
  private openSession;
118
118
  /**
119
- * Hand inbox items to the session in log order, advancing the cursor as soon as each one is
120
- * in the conversation.
119
+ * Put inbox items back on the session's bus in log order, advancing the cursor as soon as
120
+ * each one is in the conversation.
121
121
  *
122
- * "In the conversation" is the `message.appended` that names the item's delivery — for a
123
- * steer, that is some step boundary of the running turn, which is why the cursor cannot
124
- * simply move on dispatch. For an input that STARTED a turn, the turn settling counts too:
125
- * a guardrail can refuse the input without ever journaling a message, and the input is no
126
- * less dealt with for it.
122
+ * "In the conversation" is the `message.appended` whose `origin.steerId` names the item — for
123
+ * a steer into a running turn, that is some step boundary of that turn, which is why the
124
+ * cursor cannot simply move on requeue. A resume is done when the run it continued settles.
127
125
  *
128
126
  * While a turn runs, the inbox is re-read on every wake — a nudge from this process, or a
129
127
  * heartbeat that came back `woken` — so a message steers the turn and a cancel stops it,
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The execution half: moves a session's inbox into its conversation, and runs it.
2
+ * The execution half: puts a session's accepted messages back on its bus, and runs it.
3
3
  *
4
4
  * A worker is not part of the API surface and does not look for work on its own terms. It
5
5
  * claims from the work table (`SessionWork`) — one row per session that has been appended to
@@ -226,7 +226,7 @@ export class SessionWorker {
226
226
  ]);
227
227
  const session = await this.harness.resumeSession(sessionId, {
228
228
  ...agentResolution.resumeOptions,
229
- ...(environmentResolution.machine !== undefined ? { machine: environmentResolution.machine } : {}),
229
+ ...(environmentResolution.environment !== undefined ? { environment: environmentResolution.environment } : {}),
230
230
  ...(agentResolution.agent !== undefined ? { agent: agentResolution.agent } : {}),
231
231
  eventPublication: "committed",
232
232
  });
@@ -237,14 +237,12 @@ export class SessionWorker {
237
237
  return session;
238
238
  }
239
239
  /**
240
- * Hand inbox items to the session in log order, advancing the cursor as soon as each one is
241
- * in the conversation.
240
+ * Put inbox items back on the session's bus in log order, advancing the cursor as soon as
241
+ * each one is in the conversation.
242
242
  *
243
- * "In the conversation" is the `message.appended` that names the item's delivery — for a
244
- * steer, that is some step boundary of the running turn, which is why the cursor cannot
245
- * simply move on dispatch. For an input that STARTED a turn, the turn settling counts too:
246
- * a guardrail can refuse the input without ever journaling a message, and the input is no
247
- * less dealt with for it.
243
+ * "In the conversation" is the `message.appended` whose `origin.steerId` names the item — for
244
+ * a steer into a running turn, that is some step boundary of that turn, which is why the
245
+ * cursor cannot simply move on requeue. A resume is done when the run it continued settles.
248
246
  *
249
247
  * While a turn runs, the inbox is re-read on every wake — a nudge from this process, or a
250
248
  * heartbeat that came back `woken` — so a message steers the turn and a cancel stops it,
@@ -257,20 +255,22 @@ export class SessionWorker {
257
255
  const unsubscribe = session.onEvent((event) => {
258
256
  if (event.type !== "message.appended")
259
257
  return;
260
- const origin = event.origin;
261
- if (origin?.kind !== "external")
258
+ // A message is in the conversation when its journal record carries the steer it came in
259
+ // as — whatever kind of origin it was filed under.
260
+ const steerId = event.origin !== undefined && "steerId" in event.origin ? event.origin.steerId : undefined;
261
+ if (steerId === undefined)
262
262
  return;
263
- consumed.add(origin.deliveryId);
263
+ consumed.add(steerId);
264
264
  // Persist the cursor now, not when the turn ends: a holder that dies in between must not
265
265
  // leave an input that IS in the conversation looking like one that is not.
266
266
  wake.raise();
267
267
  });
268
268
  try {
269
269
  let cursor = await readInboxCursor(store);
270
- // Dispatched, not yet in the conversation, in log order. The cursor advances across the
270
+ // Requeued, not yet in the conversation, in log order. The cursor advances across the
271
271
  // contiguous consumed prefix, so an item can never be skipped by a later one landing first.
272
272
  const outstanding = [];
273
- let completion;
273
+ let resuming;
274
274
  const advance = async () => {
275
275
  let moved = false;
276
276
  while (outstanding.length > 0 && consumed.has(inboxItemId(outstanding[0]))) {
@@ -285,9 +285,9 @@ export class SessionWorker {
285
285
  break;
286
286
  wake.take();
287
287
  const items = [...await readInbox(store, cursor, new Set(outstanding.map((item) => item.sequence)))];
288
- // A cancel discards everything that precedes it: the turn in flight, inputs dispatched
289
- // to it but not yet taken, and inputs in this batch that never got dispatched. "Stop"
290
- // means stop, not "stop, then carry on with what was queued".
288
+ // A cancel discards everything that precedes it: the turn in flight, inputs requeued
289
+ // but not yet taken, and inputs in this batch that never got requeued. "Stop" means
290
+ // stop, not "stop, then carry on with what was queued".
291
291
  const lastCancel = findLastIndex(items, (item) => item.kind === "control" && item.command.kind === "cancel");
292
292
  if (lastCancel !== -1) {
293
293
  for (const item of outstanding)
@@ -296,17 +296,15 @@ export class SessionWorker {
296
296
  outstanding.push(item);
297
297
  consumed.add(inboxItemId(item));
298
298
  }
299
- if (completion !== undefined) {
300
- session.cancel();
301
- await completion;
302
- }
299
+ session.cancel();
300
+ await session.whenIdle();
303
301
  await advance();
304
302
  return true;
305
303
  }
306
304
  // Paused for an answer: inputs ahead of the resume that answers it are the ones the
307
305
  // paused turn already took (the service accepts no new input while interrupted), so
308
306
  // they are done, not dispatchable. Without a resume there is nothing to do but wait.
309
- if (session.status.state === "interrupted" && completion === undefined) {
307
+ if (session.status.state === "interrupted" && resuming === undefined) {
310
308
  const resumeAt = items.findIndex((item) => item.kind === "control" && item.command.kind === "resume");
311
309
  if (resumeAt === -1)
312
310
  break;
@@ -320,42 +318,32 @@ export class SessionWorker {
320
318
  if (halted())
321
319
  break;
322
320
  outstanding.push(item);
323
- const id = inboxItemId(item);
324
321
  if (item.kind === "input") {
325
- const receipt = session.dispatchAccepted(item.input, {
326
- kind: "external",
327
- source: item.origin.source,
328
- deliveryId: item.origin.deliveryId,
329
- channel: item.mode === "follow_up" ? "follow_up" : "steering",
330
- ...(item.origin.actor !== undefined ? { actor: item.origin.actor } : {}),
331
- ...(item.origin.metadata !== undefined ? { metadata: item.origin.metadata } : {}),
332
- });
333
- if (receipt.completion !== undefined) {
334
- // Resolved: the turn ran to some end (answered, refused by a guardrail, paused)
335
- // and the input is dealt with even if no message ever named it. Rejected: the
336
- // turn failed; if the message got in, `message.appended` already said so, and if
337
- // it did not, the input is still after the cursor for the next drain.
338
- completion = receipt.completion.then(() => { consumed.add(id); }, () => undefined);
339
- }
322
+ // Its `steer.queued` record exists — that is how it got here. Back on the bus, which
323
+ // steers a running turn or wakes an idle session, exactly as a live enqueue would.
324
+ session.requeue(item.item);
340
325
  }
341
326
  else if (item.command.kind === "resume") {
342
- completion = session.resume({ ...item.command.answers }).then(() => { consumed.add(id); }, () => { consumed.add(id); });
327
+ const id = inboxItemId(item);
328
+ // Settled either way: a resume that failed is not going to succeed by being re-read.
329
+ resuming = session.resume({ ...item.command.answers }).then(() => { consumed.add(id); }, () => { consumed.add(id); });
343
330
  }
344
331
  }
345
- if (completion !== undefined) {
346
- // A turn is running. Sleep until it ends or something new arrives, whichever first.
347
- const settled = await Promise.race([
348
- completion.then(() => "done"),
349
- wake.wait().then(() => "woken"),
350
- ]);
351
- if (settled === "done")
352
- completion = undefined;
332
+ // Sleep until the session is idle or something new arrives, whichever first. `whenIdle`
333
+ // counts the run a requeue above just woke.
334
+ const settled = await Promise.race([
335
+ session.whenIdle().then(() => "idle"),
336
+ wake.wait().then(() => "woken"),
337
+ ]);
338
+ if (settled === "idle") {
339
+ await resuming;
340
+ resuming = undefined;
353
341
  }
354
342
  await advance();
355
- // Nothing running and nothing new: done. Anything still outstanding was dispatched to a
356
- // turn that ended without taking it; it is still after the cursor, and the next run —
357
- // the next append, or the next claim — dispatches it again on a fresh object.
358
- if (completion === undefined && items.length === 0)
343
+ // Idle and nothing new: done. Anything still outstanding was requeued to a run that
344
+ // ended without taking it; it is still after the cursor, and the next run — the next
345
+ // append, or the next claim — requeues it again on a fresh object.
346
+ if (settled === "idle" && items.length === 0)
359
347
  break;
360
348
  }
361
349
  }
@@ -11,8 +11,8 @@
11
11
  * - `claim` takes the lease on one woken (or abandoned) session. Taking it IS the claim; there
12
12
  * is no separate "dispatched" state that could disagree with "held".
13
13
  * - `renew` is the holder's heartbeat, and carries the only signal a holder gets from other
14
- * nodes: whether anything was appended since it last looked. A cancel reaches the machine
15
- * running the turn this way — no address for that machine is needed anywhere.
14
+ * nodes: whether anything was appended since it last looked. A cancel reaches the environment
15
+ * running the turn this way — no address for that environment is needed anywhere.
16
16
  *
17
17
  * A worker that dies leaves its row held past its TTL. The next `claim` takes such a row like
18
18
  * any other: an abandoned session is work, whether or not anything new was appended to it.
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "operon-managed-agents",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.11",
4
4
  "description": "Managed server and TypeScript client for operon-agents.",
5
5
  "type": "module",
6
+ "engines": {
7
+ "node": ">=22"
8
+ },
6
9
  "license": "MIT",
7
10
  "repository": {
8
11
  "type": "git",
@@ -40,12 +43,12 @@
40
43
  "README.md"
41
44
  ],
42
45
  "dependencies": {
43
- "operon-agents": "0.1.0-alpha.1"
46
+ "zod": "^4.0.0",
47
+ "operon-agents": "0.1.0-alpha.11"
44
48
  },
45
49
  "devDependencies": {
46
50
  "@earendil-works/pi-ai": "0.84.1",
47
- "zod": "^4.0.0",
48
- "operon-agents-core": "0.1.0-alpha.1"
51
+ "operon-agents-core": "0.1.0-alpha.11"
49
52
  },
50
53
  "scripts": {
51
54
  "clean": "rm -rf dist *.tsbuildinfo",