operon-managed-agents 0.1.0-alpha.6 → 0.1.0-alpha.9
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/dist/client/client.d.ts +2 -2
- package/dist/client/run.d.ts +1 -1
- package/dist/client/run.js +11 -12
- package/dist/protocol/types.d.ts +15 -6
- package/dist/server/http-server.js +2 -3
- package/dist/server/idempotency.d.ts +5 -5
- package/dist/server/inbox.d.ts +14 -10
- package/dist/server/inbox.js +26 -5
- package/dist/server/registries.d.ts +4 -4
- package/dist/server/request-schemas.d.ts +164 -0
- package/dist/server/request-schemas.js +86 -0
- package/dist/server/session-service.d.ts +11 -8
- package/dist/server/session-service.js +32 -117
- package/dist/server/session-worker.d.ts +6 -8
- package/dist/server/session-worker.js +39 -58
- package/dist/server/work.d.ts +2 -2
- package/package.json +4 -4
package/dist/client/client.d.ts
CHANGED
|
@@ -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,
|
|
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<
|
|
54
|
+
create: (sessionId: string, request: CreateManagedMessageRequest, options?: CreateManagedMessageOptions) => Promise<MessageReceiptResource>;
|
|
55
55
|
};
|
|
56
56
|
events: {
|
|
57
57
|
list: (sessionId: string, options?: ListSessionEventsOptions) => Promise<ListSessionEventsResponse>;
|
package/dist/client/run.d.ts
CHANGED
|
@@ -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
|
|
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.
|
package/dist/client/run.js
CHANGED
|
@@ -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 {
|
|
36
|
-
// Trap 2: which turn is ours. Unknown until
|
|
37
|
-
//
|
|
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 ||
|
|
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 &&
|
|
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
|
|
146
|
-
*
|
|
147
|
-
*
|
|
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
|
|
150
|
-
return origin
|
|
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
|
package/dist/protocol/types.d.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
60
|
-
|
|
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
|
|
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
|
-
*
|
|
2
|
+
* Message idempotency.
|
|
3
3
|
*
|
|
4
|
-
* A client that retries a message after a timeout must not have 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 {
|
|
8
|
+
import type { MessageReceiptResource } from "../protocol/types.ts";
|
|
9
9
|
export interface ManagedDeliveryIdempotencyStore {
|
|
10
|
-
run(sessionId: string, key: string, operation: () => Promise<
|
|
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<
|
|
20
|
+
run(sessionId: string, key: string, operation: () => Promise<MessageReceiptResource>): Promise<MessageReceiptResource>;
|
|
21
21
|
private pruneExpired;
|
|
22
22
|
private makeRoom;
|
|
23
23
|
}
|
package/dist/server/inbox.d.ts
CHANGED
|
@@ -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 `
|
|
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
|
|
7
|
-
* Queues, pending marks and wake-up signals are indexes over this read, never 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.
|
|
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
|
|
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 `
|
|
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
|
|
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: `
|
|
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`. */
|
package/dist/server/inbox.js
CHANGED
|
@@ -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: `
|
|
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.
|
|
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
|
-
|
|
40
|
-
|
|
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,
|
|
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
|
|
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.
|
|
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
|
|
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,
|
|
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
|
|
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,7 +113,7 @@ 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(
|
|
116
|
+
create(request: CreateManagedSessionRequest): Promise<ManagedSession>;
|
|
117
117
|
get(id: string): Promise<ManagedSession>;
|
|
118
118
|
/**
|
|
119
119
|
* Rename a session. The title lives in the session's own `meta` state, so the write goes
|
|
@@ -121,7 +121,7 @@ export declare class SessionService {
|
|
|
121
121
|
* the store's observer before this resolves. Like `interruptions`, it opens the store beside
|
|
122
122
|
* whoever may be running the session: `meta` is written by nobody during a turn.
|
|
123
123
|
*/
|
|
124
|
-
update(id: string,
|
|
124
|
+
update(id: string, request: UpdateManagedSessionRequest): Promise<ManagedSession>;
|
|
125
125
|
list(): Promise<readonly ManagedSession[]>;
|
|
126
126
|
listEvents(id: string, options: ListPersistedEventsOptions): Promise<PersistedEventPage>;
|
|
127
127
|
/**
|
|
@@ -147,10 +147,13 @@ export declare class SessionService {
|
|
|
147
147
|
* Accept an input and return a receipt. The write is awaited, so the receipt means the input
|
|
148
148
|
* survives a crash — not merely that it reached a process.
|
|
149
149
|
*
|
|
150
|
-
* Acceptance is all this does
|
|
151
|
-
*
|
|
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.
|
|
152
155
|
*/
|
|
153
|
-
appendEvent(id: string,
|
|
156
|
+
appendEvent(id: string, input: CreateManagedMessageRequest, idempotencyKey?: string): Promise<MessageReceiptResource>;
|
|
154
157
|
private acceptEvent;
|
|
155
158
|
/**
|
|
156
159
|
* Ask whoever is running this session to stop, or — if nobody is — discard what is waiting.
|
|
@@ -168,7 +171,7 @@ export declare class SessionService {
|
|
|
168
171
|
* that dies mid-continuation leaves nothing for the client to resend: the next holder reads
|
|
169
172
|
* the same record and continues from the last durable pause.
|
|
170
173
|
*/
|
|
171
|
-
answerInterruption(id: string,
|
|
174
|
+
answerInterruption(id: string, input: Readonly<Record<string, InterruptAnswer>>, options?: {
|
|
172
175
|
readonly actor?: string;
|
|
173
176
|
}): Promise<ControlReceiptResource>;
|
|
174
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(
|
|
82
|
-
|
|
83
|
-
const 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();
|
|
@@ -136,8 +136,8 @@ export class SessionService {
|
|
|
136
136
|
* the store's observer before this resolves. Like `interruptions`, it opens the store beside
|
|
137
137
|
* whoever may be running the session: `meta` is written by nobody during a turn.
|
|
138
138
|
*/
|
|
139
|
-
async update(id,
|
|
140
|
-
|
|
139
|
+
async update(id, request) {
|
|
140
|
+
const input = parseRequest(UpdateSessionRequestSchema, request);
|
|
141
141
|
const metadata = await this.requireMetadata(id);
|
|
142
142
|
await this.summary(id);
|
|
143
143
|
const handle = await this.repository.open(id);
|
|
@@ -359,11 +359,14 @@ export class SessionService {
|
|
|
359
359
|
* Accept an input and return a receipt. The write is awaited, so the receipt means the input
|
|
360
360
|
* survives a crash — not merely that it reached a process.
|
|
361
361
|
*
|
|
362
|
-
* Acceptance is all this does
|
|
363
|
-
*
|
|
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.
|
|
364
367
|
*/
|
|
365
|
-
async appendEvent(id,
|
|
366
|
-
|
|
368
|
+
async appendEvent(id, input, idempotencyKey) {
|
|
369
|
+
const request = parseRequest(CreateMessageRequestSchema, input);
|
|
367
370
|
if (idempotencyKey !== undefined) {
|
|
368
371
|
return this.idempotency.run(id, idempotencyKey, () => this.acceptEvent(id, request));
|
|
369
372
|
}
|
|
@@ -376,41 +379,29 @@ export class SessionService {
|
|
|
376
379
|
throw new ManagedConflictError(`session "${id}" is interrupted; resume it before delivering new work`);
|
|
377
380
|
}
|
|
378
381
|
const acceptedAt = Date.now();
|
|
379
|
-
const
|
|
380
|
-
|
|
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 });
|
|
381
396
|
await this.work.append(id, {
|
|
382
|
-
|
|
397
|
+
...steerQueuedRecord(item, acceptedAt),
|
|
383
398
|
// Assigned here because this writes through a plain repository handle, not through a
|
|
384
399
|
// session's publishing store (which stamps one on the way past). Without it the record
|
|
385
400
|
// is unprojectable — invisible to `listEvents` and to every client, whose reconnect
|
|
386
401
|
// protocol dedupes on exactly this id.
|
|
387
402
|
eventId: newAgentEventId(),
|
|
388
|
-
time: acceptedAt,
|
|
389
|
-
address: "main",
|
|
390
|
-
input: request.input,
|
|
391
|
-
// Whose words, not which transport: the caller is this session's user unless it says it is
|
|
392
|
-
// relaying someone else's. `mode` is the record's own field, so the origin never carries
|
|
393
|
-
// `user_follow_up` — the worker files a `user` delivery by mode when it dispatches.
|
|
394
|
-
origin: request.origin === "external"
|
|
395
|
-
? {
|
|
396
|
-
kind: "external",
|
|
397
|
-
source: request.source ?? "managed-api",
|
|
398
|
-
deliveryId,
|
|
399
|
-
...(request.actor !== undefined ? { actor: request.actor } : {}),
|
|
400
|
-
...(request.metadata !== undefined
|
|
401
|
-
? { metadata: request.metadata }
|
|
402
|
-
: {}),
|
|
403
|
-
}
|
|
404
|
-
: { kind: "user", deliveryId },
|
|
405
|
-
mode,
|
|
406
403
|
});
|
|
407
|
-
return {
|
|
408
|
-
deliveryId,
|
|
409
|
-
sessionId: id,
|
|
410
|
-
acceptedAt,
|
|
411
|
-
status: "queued",
|
|
412
|
-
channel: mode === "follow_up" ? "follow_up" : mode === "steer" ? "steering" : "turn",
|
|
413
|
-
};
|
|
404
|
+
return { steerId: item.id, sessionId: id, acceptedAt, channel: item.channel };
|
|
414
405
|
}
|
|
415
406
|
/**
|
|
416
407
|
* Ask whoever is running this session to stop, or — if nobody is — discard what is waiting.
|
|
@@ -433,7 +424,8 @@ export class SessionService {
|
|
|
433
424
|
* that dies mid-continuation leaves nothing for the client to resend: the next holder reads
|
|
434
425
|
* the same record and continues from the last durable pause.
|
|
435
426
|
*/
|
|
436
|
-
async answerInterruption(id,
|
|
427
|
+
async answerInterruption(id, input, options = {}) {
|
|
428
|
+
const answers = parseRequest(InterruptAnswersSchema, input);
|
|
437
429
|
if ((await this.summary(id)).durableState !== "interrupted") {
|
|
438
430
|
throw new ManagedConflictError(`session "${id}" has no interrupted run to resume`);
|
|
439
431
|
}
|
|
@@ -507,78 +499,6 @@ export class SessionService {
|
|
|
507
499
|
};
|
|
508
500
|
}
|
|
509
501
|
}
|
|
510
|
-
function agentRef(value) {
|
|
511
|
-
if (typeof value === "string") {
|
|
512
|
-
if (!value.trim())
|
|
513
|
-
throw new ManagedInvalidRequestError("agent id must not be empty");
|
|
514
|
-
return { id: value };
|
|
515
|
-
}
|
|
516
|
-
if (!isRecord(value) || typeof value.id !== "string" || !value.id.trim()) {
|
|
517
|
-
throw new ManagedInvalidRequestError("agent must be an id string or an object with a non-empty id");
|
|
518
|
-
}
|
|
519
|
-
if (value.version !== undefined && typeof value.version !== "string") {
|
|
520
|
-
throw new ManagedInvalidRequestError("agent version must be a string");
|
|
521
|
-
}
|
|
522
|
-
return value;
|
|
523
|
-
}
|
|
524
|
-
function environmentRef(value) {
|
|
525
|
-
if (typeof value === "string") {
|
|
526
|
-
if (!value.trim())
|
|
527
|
-
throw new ManagedInvalidRequestError("environment id must not be empty");
|
|
528
|
-
return { id: value };
|
|
529
|
-
}
|
|
530
|
-
if (!isRecord(value) || typeof value.id !== "string" || !value.id.trim()) {
|
|
531
|
-
throw new ManagedInvalidRequestError("environment must be an id string or an object with a non-empty id");
|
|
532
|
-
}
|
|
533
|
-
return value;
|
|
534
|
-
}
|
|
535
|
-
function assertCreateSessionRequest(input) {
|
|
536
|
-
if (!isRecord(input))
|
|
537
|
-
throw new ManagedInvalidRequestError("request body must be an object");
|
|
538
|
-
if (input.id !== undefined && (typeof input.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(input.id))) {
|
|
539
|
-
throw new ManagedInvalidRequestError("session id may contain only letters, digits, underscores and hyphens");
|
|
540
|
-
}
|
|
541
|
-
if (input.title !== undefined && typeof input.title !== "string") {
|
|
542
|
-
throw new ManagedInvalidRequestError("title must be a string");
|
|
543
|
-
}
|
|
544
|
-
if (input.metadata !== undefined && !isRecord(input.metadata)) {
|
|
545
|
-
throw new ManagedInvalidRequestError("metadata must be an object");
|
|
546
|
-
}
|
|
547
|
-
agentRef(input.agent);
|
|
548
|
-
environmentRef(input.environment);
|
|
549
|
-
}
|
|
550
|
-
function assertUpdateSessionRequest(input) {
|
|
551
|
-
if (!isRecord(input))
|
|
552
|
-
throw new ManagedInvalidRequestError("request body must be an object");
|
|
553
|
-
if (typeof input.title !== "string" || !input.title.trim()) {
|
|
554
|
-
throw new ManagedInvalidRequestError("title must be a non-empty string");
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
function assertCreateMessageRequest(input) {
|
|
558
|
-
if (!isRecord(input))
|
|
559
|
-
throw new ManagedInvalidRequestError("request body must be an object");
|
|
560
|
-
if (typeof input.input !== "string" || !input.input.trim()) {
|
|
561
|
-
throw new ManagedInvalidRequestError("input must not be empty");
|
|
562
|
-
}
|
|
563
|
-
if (input.origin !== undefined && input.origin !== "user" && input.origin !== "external") {
|
|
564
|
-
throw new ManagedInvalidRequestError("origin must be user or external");
|
|
565
|
-
}
|
|
566
|
-
if (input.origin !== "external" && (input.source !== undefined || input.actor !== undefined || input.metadata !== undefined)) {
|
|
567
|
-
throw new ManagedInvalidRequestError('source, actor and metadata describe a relayed delivery; set origin: "external"');
|
|
568
|
-
}
|
|
569
|
-
if (input.source !== undefined && (typeof input.source !== "string" || !input.source.trim())) {
|
|
570
|
-
throw new ManagedInvalidRequestError("source must be a non-empty string");
|
|
571
|
-
}
|
|
572
|
-
if (input.actor !== undefined && typeof input.actor !== "string") {
|
|
573
|
-
throw new ManagedInvalidRequestError("actor must be a string");
|
|
574
|
-
}
|
|
575
|
-
if (input.metadata !== undefined && !isRecord(input.metadata)) {
|
|
576
|
-
throw new ManagedInvalidRequestError("metadata must be an object");
|
|
577
|
-
}
|
|
578
|
-
if (input.mode !== undefined && input.mode !== "auto" && input.mode !== "steer" && input.mode !== "follow_up") {
|
|
579
|
-
throw new ManagedInvalidRequestError("mode must be auto, steer or follow_up");
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
502
|
function isRecord(value) {
|
|
583
503
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
584
504
|
}
|
|
@@ -587,11 +507,6 @@ function managedSessionId() {
|
|
|
587
507
|
managedIdCounter += 1;
|
|
588
508
|
return `ms_${Date.now().toString(36)}_${managedIdCounter.toString(36)}`;
|
|
589
509
|
}
|
|
590
|
-
let deliveryCounter = 0;
|
|
591
|
-
function managedDeliveryId() {
|
|
592
|
-
deliveryCounter += 1;
|
|
593
|
-
return `delivery_${Date.now().toString(36)}_${deliveryCounter.toString(36)}`;
|
|
594
|
-
}
|
|
595
510
|
let commandCounter = 0;
|
|
596
511
|
function managedCommandId() {
|
|
597
512
|
commandCounter += 1;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The execution half:
|
|
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
|
-
*
|
|
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`
|
|
123
|
-
* steer, that is some step boundary of
|
|
124
|
-
* simply move on
|
|
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:
|
|
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.
|
|
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
|
-
*
|
|
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`
|
|
244
|
-
* steer, that is some step boundary of
|
|
245
|
-
* simply move on
|
|
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,25 +255,22 @@ export class SessionWorker {
|
|
|
257
255
|
const unsubscribe = session.onEvent((event) => {
|
|
258
256
|
if (event.type !== "message.appended")
|
|
259
257
|
return;
|
|
260
|
-
|
|
261
|
-
//
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
? origin.deliveryId
|
|
265
|
-
: undefined;
|
|
266
|
-
if (deliveryId === undefined)
|
|
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)
|
|
267
262
|
return;
|
|
268
|
-
consumed.add(
|
|
263
|
+
consumed.add(steerId);
|
|
269
264
|
// Persist the cursor now, not when the turn ends: a holder that dies in between must not
|
|
270
265
|
// leave an input that IS in the conversation looking like one that is not.
|
|
271
266
|
wake.raise();
|
|
272
267
|
});
|
|
273
268
|
try {
|
|
274
269
|
let cursor = await readInboxCursor(store);
|
|
275
|
-
//
|
|
270
|
+
// Requeued, not yet in the conversation, in log order. The cursor advances across the
|
|
276
271
|
// contiguous consumed prefix, so an item can never be skipped by a later one landing first.
|
|
277
272
|
const outstanding = [];
|
|
278
|
-
let
|
|
273
|
+
let resuming;
|
|
279
274
|
const advance = async () => {
|
|
280
275
|
let moved = false;
|
|
281
276
|
while (outstanding.length > 0 && consumed.has(inboxItemId(outstanding[0]))) {
|
|
@@ -290,9 +285,9 @@ export class SessionWorker {
|
|
|
290
285
|
break;
|
|
291
286
|
wake.take();
|
|
292
287
|
const items = [...await readInbox(store, cursor, new Set(outstanding.map((item) => item.sequence)))];
|
|
293
|
-
// A cancel discards everything that precedes it: the turn in flight, inputs
|
|
294
|
-
//
|
|
295
|
-
//
|
|
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".
|
|
296
291
|
const lastCancel = findLastIndex(items, (item) => item.kind === "control" && item.command.kind === "cancel");
|
|
297
292
|
if (lastCancel !== -1) {
|
|
298
293
|
for (const item of outstanding)
|
|
@@ -301,17 +296,15 @@ export class SessionWorker {
|
|
|
301
296
|
outstanding.push(item);
|
|
302
297
|
consumed.add(inboxItemId(item));
|
|
303
298
|
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
await completion;
|
|
307
|
-
}
|
|
299
|
+
session.cancel();
|
|
300
|
+
await session.whenIdle();
|
|
308
301
|
await advance();
|
|
309
302
|
return true;
|
|
310
303
|
}
|
|
311
304
|
// Paused for an answer: inputs ahead of the resume that answers it are the ones the
|
|
312
305
|
// paused turn already took (the service accepts no new input while interrupted), so
|
|
313
306
|
// they are done, not dispatchable. Without a resume there is nothing to do but wait.
|
|
314
|
-
if (session.status.state === "interrupted" &&
|
|
307
|
+
if (session.status.state === "interrupted" && resuming === undefined) {
|
|
315
308
|
const resumeAt = items.findIndex((item) => item.kind === "control" && item.command.kind === "resume");
|
|
316
309
|
if (resumeAt === -1)
|
|
317
310
|
break;
|
|
@@ -325,44 +318,32 @@ export class SessionWorker {
|
|
|
325
318
|
if (halted())
|
|
326
319
|
break;
|
|
327
320
|
outstanding.push(item);
|
|
328
|
-
const id = inboxItemId(item);
|
|
329
321
|
if (item.kind === "input") {
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
source: item.origin.source,
|
|
334
|
-
deliveryId: item.origin.deliveryId,
|
|
335
|
-
channel: item.mode === "follow_up" ? "follow_up" : "steering",
|
|
336
|
-
...(item.origin.actor !== undefined ? { actor: item.origin.actor } : {}),
|
|
337
|
-
...(item.origin.metadata !== undefined ? { metadata: item.origin.metadata } : {}),
|
|
338
|
-
}
|
|
339
|
-
: { kind: item.mode === "follow_up" ? "user_follow_up" : "user", deliveryId: item.origin.deliveryId });
|
|
340
|
-
if (receipt.completion !== undefined) {
|
|
341
|
-
// Resolved: the turn ran to some end (answered, refused by a guardrail, paused)
|
|
342
|
-
// and the input is dealt with even if no message ever named it. Rejected: the
|
|
343
|
-
// turn failed; if the message got in, `message.appended` already said so, and if
|
|
344
|
-
// it did not, the input is still after the cursor for the next drain.
|
|
345
|
-
completion = receipt.completion.then(() => { consumed.add(id); }, () => undefined);
|
|
346
|
-
}
|
|
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);
|
|
347
325
|
}
|
|
348
326
|
else if (item.command.kind === "resume") {
|
|
349
|
-
|
|
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); });
|
|
350
330
|
}
|
|
351
331
|
}
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
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;
|
|
360
341
|
}
|
|
361
342
|
await advance();
|
|
362
|
-
//
|
|
363
|
-
//
|
|
364
|
-
//
|
|
365
|
-
if (
|
|
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)
|
|
366
347
|
break;
|
|
367
348
|
}
|
|
368
349
|
}
|
package/dist/server/work.d.ts
CHANGED
|
@@ -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
|
|
15
|
-
* running the turn this way — no address for that
|
|
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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "operon-managed-agents",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.9",
|
|
4
4
|
"description": "Managed server and TypeScript client for operon-agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -43,12 +43,12 @@
|
|
|
43
43
|
"README.md"
|
|
44
44
|
],
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"
|
|
46
|
+
"zod": "^4.0.0",
|
|
47
|
+
"operon-agents": "0.1.0-alpha.9"
|
|
47
48
|
},
|
|
48
49
|
"devDependencies": {
|
|
49
50
|
"@earendil-works/pi-ai": "0.84.1",
|
|
50
|
-
"
|
|
51
|
-
"operon-agents-core": "0.1.0-alpha.6"
|
|
51
|
+
"operon-agents-core": "0.1.0-alpha.9"
|
|
52
52
|
},
|
|
53
53
|
"scripts": {
|
|
54
54
|
"clean": "rm -rf dist *.tsbuildinfo",
|