operon-managed-agents 0.1.0-alpha.2 → 0.1.0-alpha.21
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 +57 -1
- package/dist/client/client.d.ts +4 -2
- package/dist/client/client.js +4 -0
- package/dist/client/run.d.ts +1 -1
- package/dist/client/run.js +14 -5
- package/dist/protocol/types.d.ts +34 -6
- package/dist/server/http-server.d.ts +7 -1
- package/dist/server/http-server.js +12 -5
- package/dist/server/idempotency.d.ts +5 -5
- package/dist/server/inbox.d.ts +14 -16
- package/dist/server/inbox.js +26 -5
- package/dist/server/registries.d.ts +22 -6
- package/dist/server/request-schemas.d.ts +164 -0
- package/dist/server/request-schemas.js +86 -0
- package/dist/server/session-service.d.ts +17 -7
- package/dist/server/session-service.js +60 -99
- package/dist/server/session-worker.d.ts +19 -8
- package/dist/server/session-worker.js +116 -54
- package/dist/server/work.d.ts +2 -2
- package/package.json +5 -5
|
@@ -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,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(
|
|
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
|
|
144
|
-
*
|
|
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,
|
|
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,
|
|
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,13 +79,16 @@ 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);
|
|
85
|
-
const resolved = await this.environments.resolve(environment);
|
|
86
|
-
const now = Date.now();
|
|
82
|
+
async create(request) {
|
|
83
|
+
const input = parseRequest(CreateSessionRequestSchema, request);
|
|
84
|
+
const { agent, environment } = input;
|
|
87
85
|
const sessionId = input.id ?? managedSessionId();
|
|
86
|
+
const resolved = await this.environments.resolve(environment, {
|
|
87
|
+
sessionId,
|
|
88
|
+
...(this.ownerKey !== undefined ? { ownerKey: this.ownerKey } : {}),
|
|
89
|
+
...(input.metadata !== undefined ? { metadata: input.metadata } : {}),
|
|
90
|
+
});
|
|
91
|
+
const now = Date.now();
|
|
88
92
|
// Metadata is the write-ahead identity record: after the repository commits, a crash must
|
|
89
93
|
// never leave a durable session the managed layer cannot resolve on restart.
|
|
90
94
|
const claimed = await this.metadata.create({
|
|
@@ -130,6 +134,30 @@ export class SessionService {
|
|
|
130
134
|
const summary = await this.summary(id);
|
|
131
135
|
return this.toManagedSession(summary, metadata);
|
|
132
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* Rename a session. The title lives in the session's own `meta` state, so the write goes
|
|
139
|
+
* through the store — the same path `create` takes — and reaches the repository catalog via
|
|
140
|
+
* the store's observer before this resolves. Like `interruptions`, it opens the store beside
|
|
141
|
+
* whoever may be running the session: `meta` is written by nobody during a turn.
|
|
142
|
+
*/
|
|
143
|
+
async update(id, request) {
|
|
144
|
+
const input = parseRequest(UpdateSessionRequestSchema, request);
|
|
145
|
+
const metadata = await this.requireMetadata(id);
|
|
146
|
+
await this.summary(id);
|
|
147
|
+
const handle = await this.repository.open(id);
|
|
148
|
+
if (handle === undefined)
|
|
149
|
+
throw new ManagedSessionNotFoundError(id);
|
|
150
|
+
try {
|
|
151
|
+
const meta = await handle.store.getState("meta");
|
|
152
|
+
if (!isRecord(meta))
|
|
153
|
+
throw new Error(`session "${id}" has no meta state`);
|
|
154
|
+
await handle.store.putState("meta", { ...meta, title: input.title, updatedAt: Date.now() });
|
|
155
|
+
}
|
|
156
|
+
finally {
|
|
157
|
+
await handle.store.close?.();
|
|
158
|
+
}
|
|
159
|
+
return this.toManagedSession(await this.summary(id), metadata);
|
|
160
|
+
}
|
|
133
161
|
async list() {
|
|
134
162
|
const summaries = await this.repository.list(this.ownerKey !== undefined ? { ownerKey: this.ownerKey } : undefined);
|
|
135
163
|
const metadataById = await this.metadata.getMany(summaries.map((summary) => summary.id));
|
|
@@ -335,11 +363,14 @@ export class SessionService {
|
|
|
335
363
|
* Accept an input and return a receipt. The write is awaited, so the receipt means the input
|
|
336
364
|
* survives a crash — not merely that it reached a process.
|
|
337
365
|
*
|
|
338
|
-
* Acceptance is all this does
|
|
339
|
-
*
|
|
366
|
+
* Acceptance is all this does, and it is the same acceptance a local steer has: the record
|
|
367
|
+
* written here is the `steer.queued` a session's own bus would journal, built by the same
|
|
368
|
+
* function, so the worker that later opens the session puts it back on the bus unchanged.
|
|
369
|
+
* Whether it then steers a turn already in flight or wakes an idle session is decided when a
|
|
370
|
+
* worker processes it, which can be an arbitrary moment later.
|
|
340
371
|
*/
|
|
341
|
-
async appendEvent(id,
|
|
342
|
-
|
|
372
|
+
async appendEvent(id, input, idempotencyKey) {
|
|
373
|
+
const request = parseRequest(CreateMessageRequestSchema, input);
|
|
343
374
|
if (idempotencyKey !== undefined) {
|
|
344
375
|
return this.idempotency.run(id, idempotencyKey, () => this.acceptEvent(id, request));
|
|
345
376
|
}
|
|
@@ -352,36 +383,29 @@ export class SessionService {
|
|
|
352
383
|
throw new ManagedConflictError(`session "${id}" is interrupted; resume it before delivering new work`);
|
|
353
384
|
}
|
|
354
385
|
const acceptedAt = Date.now();
|
|
355
|
-
const
|
|
356
|
-
|
|
386
|
+
const channel = request.mode === "follow_up" ? "follow_up" : "steering";
|
|
387
|
+
// Whose words, not which transport: the caller is this session's user unless it says it is
|
|
388
|
+
// relaying someone else's. The bus files a user's words by kind — `user` steers, a
|
|
389
|
+
// `user_follow_up` queues behind the turn — and a relay by its declared channel.
|
|
390
|
+
const origin = request.origin === "external"
|
|
391
|
+
? {
|
|
392
|
+
kind: "external",
|
|
393
|
+
source: request.source ?? "managed-api",
|
|
394
|
+
channel,
|
|
395
|
+
...(request.actor !== undefined ? { actor: request.actor } : {}),
|
|
396
|
+
...(request.metadata !== undefined ? { metadata: request.metadata } : {}),
|
|
397
|
+
}
|
|
398
|
+
: { kind: channel === "follow_up" ? "user_follow_up" : "user" };
|
|
399
|
+
const item = buildSteerMessage(request.input, origin, { now: () => acceptedAt });
|
|
357
400
|
await this.work.append(id, {
|
|
358
|
-
|
|
401
|
+
...steerQueuedRecord(item, acceptedAt),
|
|
359
402
|
// Assigned here because this writes through a plain repository handle, not through a
|
|
360
403
|
// session's publishing store (which stamps one on the way past). Without it the record
|
|
361
404
|
// is unprojectable — invisible to `listEvents` and to every client, whose reconnect
|
|
362
405
|
// protocol dedupes on exactly this id.
|
|
363
406
|
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
407
|
});
|
|
378
|
-
return {
|
|
379
|
-
deliveryId,
|
|
380
|
-
sessionId: id,
|
|
381
|
-
acceptedAt,
|
|
382
|
-
status: "queued",
|
|
383
|
-
channel: mode === "follow_up" ? "follow_up" : mode === "steer" ? "steering" : "turn",
|
|
384
|
-
};
|
|
408
|
+
return { steerId: item.id, sessionId: id, acceptedAt, channel: item.channel };
|
|
385
409
|
}
|
|
386
410
|
/**
|
|
387
411
|
* Ask whoever is running this session to stop, or — if nobody is — discard what is waiting.
|
|
@@ -404,7 +428,8 @@ export class SessionService {
|
|
|
404
428
|
* that dies mid-continuation leaves nothing for the client to resend: the next holder reads
|
|
405
429
|
* the same record and continues from the last durable pause.
|
|
406
430
|
*/
|
|
407
|
-
async answerInterruption(id,
|
|
431
|
+
async answerInterruption(id, input, options = {}) {
|
|
432
|
+
const answers = parseRequest(InterruptAnswersSchema, input);
|
|
408
433
|
if ((await this.summary(id)).durableState !== "interrupted") {
|
|
409
434
|
throw new ManagedConflictError(`session "${id}" has no interrupted run to resume`);
|
|
410
435
|
}
|
|
@@ -478,65 +503,6 @@ export class SessionService {
|
|
|
478
503
|
};
|
|
479
504
|
}
|
|
480
505
|
}
|
|
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
506
|
function isRecord(value) {
|
|
541
507
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
542
508
|
}
|
|
@@ -545,11 +511,6 @@ function managedSessionId() {
|
|
|
545
511
|
managedIdCounter += 1;
|
|
546
512
|
return `ms_${Date.now().toString(36)}_${managedIdCounter.toString(36)}`;
|
|
547
513
|
}
|
|
548
|
-
let deliveryCounter = 0;
|
|
549
|
-
function managedDeliveryId() {
|
|
550
|
-
deliveryCounter += 1;
|
|
551
|
-
return `delivery_${Date.now().toString(36)}_${deliveryCounter.toString(36)}`;
|
|
552
|
-
}
|
|
553
514
|
let commandCounter = 0;
|
|
554
515
|
function managedCommandId() {
|
|
555
516
|
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
|
|
@@ -75,6 +75,14 @@ export interface SessionWorkerOptions<TContext = unknown> {
|
|
|
75
75
|
* to that session wakes it again. Default: `console.error`.
|
|
76
76
|
*/
|
|
77
77
|
readonly onError?: (error: unknown, sessionId: string) => void;
|
|
78
|
+
/**
|
|
79
|
+
* Who this worker's sessions belong to. `"multi-tenant"` (the default) refuses what would leak
|
|
80
|
+
* across tenants or run outside the sandbox: an environment not from the registry, a harness
|
|
81
|
+
* holding process-wide MCP connections or an OAuth service, MCP over stdio, a token read from
|
|
82
|
+
* the process environment. `"single-tenant"` lifts all of that for a self-hosted, one-owner
|
|
83
|
+
* deployment, and says so once at construction. See docs/server-profile.md.
|
|
84
|
+
*/
|
|
85
|
+
readonly profile?: "multi-tenant" | "single-tenant";
|
|
78
86
|
}
|
|
79
87
|
export declare class SessionWorker<TContext = unknown> {
|
|
80
88
|
private readonly harness;
|
|
@@ -88,6 +96,9 @@ export declare class SessionWorker<TContext = unknown> {
|
|
|
88
96
|
private readonly concurrency;
|
|
89
97
|
private readonly broadcaster;
|
|
90
98
|
private readonly onError;
|
|
99
|
+
private readonly multiTenant;
|
|
100
|
+
/** The harness check, run once and remembered — a misconfigured harness fails every open alike. */
|
|
101
|
+
private harnessChecked;
|
|
91
102
|
private readonly running;
|
|
92
103
|
/** Runs the claim loop started, counted synchronously so the cap is exact; nudges are not. */
|
|
93
104
|
private claimed;
|
|
@@ -95,6 +106,8 @@ export declare class SessionWorker<TContext = unknown> {
|
|
|
95
106
|
private stopping;
|
|
96
107
|
private interruptPause;
|
|
97
108
|
constructor(options: SessionWorkerOptions<TContext>);
|
|
109
|
+
/** Multi-tenant only: the harness must not carry what every session on the process would share. */
|
|
110
|
+
private checkHarness;
|
|
98
111
|
/** Begin claiming. Without this a worker only runs what it is nudged about in-process. */
|
|
99
112
|
start(): void;
|
|
100
113
|
/**
|
|
@@ -116,14 +129,12 @@ export declare class SessionWorker<TContext = unknown> {
|
|
|
116
129
|
private drainInbox;
|
|
117
130
|
private openSession;
|
|
118
131
|
/**
|
|
119
|
-
*
|
|
120
|
-
* in the conversation.
|
|
132
|
+
* Put inbox items back on the session's bus in log order, advancing the cursor as soon as
|
|
133
|
+
* each one is in the conversation.
|
|
121
134
|
*
|
|
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.
|
|
135
|
+
* "In the conversation" is the `message.appended` whose `origin.steerId` names the item — for
|
|
136
|
+
* a steer into a running turn, that is some step boundary of that turn, which is why the
|
|
137
|
+
* cursor cannot simply move on requeue. A resume is done when the run it continued settles.
|
|
127
138
|
*
|
|
128
139
|
* While a turn runs, the inbox is re-read on every wake — a nudge from this process, or a
|
|
129
140
|
* heartbeat that came back `woken` — so a message steers the turn and a cancel stops it,
|