operon-managed-agents 0.1.0-alpha.0
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/LICENSE +55 -0
- package/README.md +103 -0
- package/dist/client/client.d.ts +80 -0
- package/dist/client/client.js +232 -0
- package/dist/client/errors.d.ts +7 -0
- package/dist/client/errors.js +21 -0
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +4 -0
- package/dist/client/run.d.ts +71 -0
- package/dist/client/run.js +144 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/protocol/index.d.ts +3 -0
- package/dist/protocol/index.js +3 -0
- package/dist/protocol/sse.d.ts +7 -0
- package/dist/protocol/sse.js +53 -0
- package/dist/protocol/types.d.ts +102 -0
- package/dist/protocol/types.js +2 -0
- package/dist/server/broadcast.d.ts +105 -0
- package/dist/server/broadcast.js +130 -0
- package/dist/server/errors.d.ts +23 -0
- package/dist/server/errors.js +43 -0
- package/dist/server/http-server.d.ts +54 -0
- package/dist/server/http-server.js +325 -0
- package/dist/server/idempotency.d.ts +24 -0
- package/dist/server/idempotency.js +52 -0
- package/dist/server/inbox.d.ts +64 -0
- package/dist/server/inbox.js +71 -0
- package/dist/server/index.d.ts +14 -0
- package/dist/server/index.js +14 -0
- package/dist/server/metadata-pg.d.ts +31 -0
- package/dist/server/metadata-pg.js +64 -0
- package/dist/server/metadata.d.ts +38 -0
- package/dist/server/metadata.js +107 -0
- package/dist/server/registries.d.ts +40 -0
- package/dist/server/registries.js +26 -0
- package/dist/server/session-service.d.ts +181 -0
- package/dist/server/session-service.js +658 -0
- package/dist/server/session-worker.d.ts +136 -0
- package/dist/server/session-worker.js +428 -0
- package/dist/server/work-memory.d.ts +27 -0
- package/dist/server/work-memory.js +85 -0
- package/dist/server/work-pg.d.ts +46 -0
- package/dist/server/work-pg.js +122 -0
- package/dist/server/work.d.ts +49 -0
- package/dist/server/work.js +2 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yingjie Qiao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
-------------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
THIRD-PARTY LICENSES
|
|
27
|
+
|
|
28
|
+
Portions of this software were adapted from kimi-code, which is distributed
|
|
29
|
+
under the MIT License. Its copyright and permission notice is reproduced below.
|
|
30
|
+
|
|
31
|
+
-------------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
kimi-code
|
|
34
|
+
|
|
35
|
+
MIT License
|
|
36
|
+
|
|
37
|
+
Copyright (c) 2026 Moonshot AI
|
|
38
|
+
|
|
39
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
40
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
41
|
+
in the Software without restriction, including without limitation the rights
|
|
42
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
43
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
44
|
+
furnished to do so, subject to the following conditions:
|
|
45
|
+
|
|
46
|
+
The above copyright notice and this permission notice shall be included in all
|
|
47
|
+
copies or substantial portions of the Software.
|
|
48
|
+
|
|
49
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
50
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
51
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
52
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
53
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
54
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
55
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# operon-managed-agents
|
|
2
|
+
|
|
3
|
+
Managed HTTP/SSE server and TypeScript client for `operon-agents`. One package contains
|
|
4
|
+
three public surfaces:
|
|
5
|
+
|
|
6
|
+
- `operon-managed-agents/protocol` — wire/resource types and SSE codec
|
|
7
|
+
- `operon-managed-agents/server` — Session host, registries and HTTP server
|
|
8
|
+
- `operon-managed-agents/client` — typed client SDK
|
|
9
|
+
|
|
10
|
+
The wire contract deliberately separates writes from observation. `messages.create()`
|
|
11
|
+
returns an acceptance receipt immediately; `events.stream()` is a session-scoped stream
|
|
12
|
+
that survives individual turns and therefore carries background completion and idle-wake
|
|
13
|
+
events too.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
const session = await client.sessions.create({
|
|
17
|
+
agent: "default",
|
|
18
|
+
environment: "workspace",
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const stream = await client.sessions.events.stream(session.id);
|
|
22
|
+
await client.sessions.messages.create(session.id, { input: "inspect this repository" });
|
|
23
|
+
|
|
24
|
+
for await (const event of stream) console.log(event);
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The external observation API has two deliberately separate operations:
|
|
28
|
+
|
|
29
|
+
- `sessions.events.list()` pages persisted history as `AgentEvent[]`; `nextPage` is opaque.
|
|
30
|
+
- `sessions.events.stream()` is a pure live `AsyncIterable<AgentEvent>` with no synthetic first event.
|
|
31
|
+
|
|
32
|
+
Every event has a stable `eventId`. Durable events keep that same identity in `list()` and
|
|
33
|
+
`stream()`, so a reconnecting client can open the stream first, page history second, and
|
|
34
|
+
deduplicate the overlap without a loss window. Low-frequency lifecycle events needed to
|
|
35
|
+
rebuild state (`agent.*`, `turn.*`, pauses, messages and workflow journal progress) are
|
|
36
|
+
persisted before publication in managed sessions. High-frequency deltas and progress are
|
|
37
|
+
live-only: a client that joins midway reconstructs the committed structural state from
|
|
38
|
+
`list()` and continues transient rendering from `stream()`.
|
|
39
|
+
|
|
40
|
+
`SessionProjection` remains the standard reducer from `AgentEvent` to state-shaped UI data.
|
|
41
|
+
It is not exposed as a separate managed snapshot endpoint: fold the stream into a projection.
|
|
42
|
+
|
|
43
|
+
The stream replays the session's durable history first and then follows live, so one
|
|
44
|
+
subscription is the whole story. It carries a durable cursor — the SSE `id:` is stamped only
|
|
45
|
+
on events the log can find again, never on a token delta — and the client reconnects on a
|
|
46
|
+
dropped connection by itself, resuming after the last durable event it delivered and filtering
|
|
47
|
+
the overlap by `eventId`. Pass `after` to start from a cursor you kept, or `reconnect: false`
|
|
48
|
+
to see drops yourself.
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
const stream = await client.sessions.events.stream(session.id);
|
|
52
|
+
const projection = new SessionProjection(session.id);
|
|
53
|
+
|
|
54
|
+
for await (const event of stream) {
|
|
55
|
+
projection.apply(event);
|
|
56
|
+
render(projection.snapshot());
|
|
57
|
+
}
|
|
58
|
+
// stream.lastEventId is the cursor to continue from elsewhere.
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`run()` sends one input and resolves when the turn that took **that** delivery ends — not the
|
|
62
|
+
first `turn.ended` in the replay, which on a session with history belongs to an older turn.
|
|
63
|
+
|
|
64
|
+
The server accepts an `authorize(request, { action, sessionId })` hook. Configure it for any
|
|
65
|
+
networked deployment; it can verify credentials and enforce per-session ownership. The
|
|
66
|
+
bundled in-memory idempotency store is atomic within one process and bounded by TTL/capacity;
|
|
67
|
+
distributed deployments should provide a database-backed `ManagedDeliveryIdempotencyStore`.
|
|
68
|
+
|
|
69
|
+
The service and the workers share one **work table** (`SessionWork`): one row per session that
|
|
70
|
+
has been appended to or is being run. `work.append` writes an input to the session's log and
|
|
71
|
+
wakes its row as one step — in Postgres, one transaction — and a worker's claim loop
|
|
72
|
+
(`worker.start()`) takes woken rows, one indexed statement per ask (`FOR UPDATE SKIP LOCKED`).
|
|
73
|
+
Taking the row *is* the lease: one runtime owner per session, with a fencing token, and no
|
|
74
|
+
dispatcher anywhere. Workers only make outbound calls; nothing needs to know which node holds
|
|
75
|
+
a session.
|
|
76
|
+
|
|
77
|
+
Cancel and resume are journaled commands written the same way. The holder learns of them from
|
|
78
|
+
its heartbeat — every lease renew reports whether anything was appended since the last one —
|
|
79
|
+
so a command accepted on any node reaches the turn running on any other within one renew
|
|
80
|
+
interval (2s by default). With no holder, the next claim reads them first.
|
|
81
|
+
|
|
82
|
+
An input is processed once it is in the conversation: the worker's cursor advances when the
|
|
83
|
+
session's record holds the message, not when the turn that took it finishes. A turn that fails
|
|
84
|
+
or dies halfway leaves the history intact up to where it stopped, and the next message
|
|
85
|
+
continues from there; nothing is re-run and nothing runs twice. A worker that dies leaves its
|
|
86
|
+
row held past the TTL; the claim loop takes such a row like any other, closes the turn it left
|
|
87
|
+
open (`turn.ended`, reason `failed`) and broadcasts the close, so a client waiting on it learns
|
|
88
|
+
within a TTL rather than whenever the next message happens to arrive.
|
|
89
|
+
|
|
90
|
+
In one process, `MemorySessionWork` — the service and the worker must share the instance.
|
|
91
|
+
Across nodes, `PgSessionWork` over the same Postgres the log lives in (run
|
|
92
|
+
`sessionWorkTableDDL()` once); no queue, no broker, no other component. An accepted input is
|
|
93
|
+
durable and woken before its 202; the in-process nudge after it is latency, not correctness.
|
|
94
|
+
|
|
95
|
+
Pass an idempotency key when an HTTP retry must not inject the same user message twice:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
await client.sessions.messages.create(
|
|
99
|
+
session.id,
|
|
100
|
+
{ input: "continue" },
|
|
101
|
+
{ idempotencyKey: requestId },
|
|
102
|
+
);
|
|
103
|
+
```
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { AgentEvent, InterruptAnswer } from "operon-agents";
|
|
2
|
+
import { type SseFrame } from "../protocol/sse.ts";
|
|
3
|
+
import type { CancelManagedSessionResponse, CreateManagedMessageRequest, CreateManagedSessionRequest, DeliveryReceiptResource, InterruptionsResponse, ListSessionEventsOptions, ListSessionEventsResponse, ListManagedSessionsResponse, ManagedSession, ResumeManagedSessionResponse, StreamSessionEventsOptions } from "../protocol/types.ts";
|
|
4
|
+
export interface ManagedAgentsClientOptions {
|
|
5
|
+
readonly baseUrl: string;
|
|
6
|
+
readonly apiKey?: string;
|
|
7
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
8
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
9
|
+
}
|
|
10
|
+
export interface CreateManagedMessageOptions {
|
|
11
|
+
readonly idempotencyKey?: string;
|
|
12
|
+
}
|
|
13
|
+
/** Opens one SSE connection, resuming after `after` when given. */
|
|
14
|
+
type StreamConnector = (after: string | undefined) => Promise<AsyncIterator<SseFrame>>;
|
|
15
|
+
/**
|
|
16
|
+
* A session's events as one continuous iterable, across however many connections it takes.
|
|
17
|
+
*
|
|
18
|
+
* A dropped connection is not the end of the session, so by default it is not the end of the
|
|
19
|
+
* iteration either: the stream reopens after the last durable event it delivered and filters
|
|
20
|
+
* out what the overlap repeats. The cursor is the SSE `id:` the server stamps on durable events
|
|
21
|
+
* only, so resuming never points at a live-only event (a token delta) that the log cannot find.
|
|
22
|
+
*/
|
|
23
|
+
export declare class ManagedSessionEventStream implements AsyncIterable<AgentEvent> {
|
|
24
|
+
private readonly connect;
|
|
25
|
+
private readonly reconnect;
|
|
26
|
+
private readonly signal;
|
|
27
|
+
private frames;
|
|
28
|
+
private consumed;
|
|
29
|
+
private cursor;
|
|
30
|
+
private readonly delivered;
|
|
31
|
+
private attempts;
|
|
32
|
+
constructor(connect: StreamConnector, first: AsyncIterator<SseFrame>, options: {
|
|
33
|
+
readonly after?: string;
|
|
34
|
+
readonly reconnect?: boolean;
|
|
35
|
+
readonly signal?: AbortSignal;
|
|
36
|
+
});
|
|
37
|
+
/** The last resume cursor this stream delivered — pass it as `after` to continue elsewhere. */
|
|
38
|
+
get lastEventId(): string | undefined;
|
|
39
|
+
[Symbol.asyncIterator](): AsyncIterator<AgentEvent>;
|
|
40
|
+
private next;
|
|
41
|
+
/** Reconnect after a drop. False when reconnecting is off or the caller has aborted. */
|
|
42
|
+
private reopen;
|
|
43
|
+
private remember;
|
|
44
|
+
}
|
|
45
|
+
export declare class ManagedSessionsClient {
|
|
46
|
+
private readonly root;
|
|
47
|
+
constructor(root: ManagedAgentsClient);
|
|
48
|
+
create(request: CreateManagedSessionRequest): Promise<ManagedSession>;
|
|
49
|
+
list(): Promise<ListManagedSessionsResponse>;
|
|
50
|
+
retrieve(sessionId: string): Promise<ManagedSession>;
|
|
51
|
+
messages: {
|
|
52
|
+
create: (sessionId: string, request: CreateManagedMessageRequest, options?: CreateManagedMessageOptions) => Promise<DeliveryReceiptResource>;
|
|
53
|
+
};
|
|
54
|
+
events: {
|
|
55
|
+
list: (sessionId: string, options?: ListSessionEventsOptions) => Promise<ListSessionEventsResponse>;
|
|
56
|
+
stream: (sessionId: string, options?: StreamSessionEventsOptions) => Promise<ManagedSessionEventStream>;
|
|
57
|
+
};
|
|
58
|
+
cancel(sessionId: string): Promise<CancelManagedSessionResponse>;
|
|
59
|
+
delete(sessionId: string): Promise<void>;
|
|
60
|
+
interruptions(sessionId: string): Promise<InterruptionsResponse>;
|
|
61
|
+
resume(sessionId: string, answers: Readonly<Record<string, InterruptAnswer>>): Promise<ResumeManagedSessionResponse>;
|
|
62
|
+
}
|
|
63
|
+
interface RequestOptions {
|
|
64
|
+
readonly method?: string;
|
|
65
|
+
readonly body?: unknown;
|
|
66
|
+
readonly signal?: AbortSignal;
|
|
67
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
68
|
+
}
|
|
69
|
+
export declare class ManagedAgentsClient {
|
|
70
|
+
readonly sessions: ManagedSessionsClient;
|
|
71
|
+
private readonly baseUrl;
|
|
72
|
+
private readonly fetchImpl;
|
|
73
|
+
private readonly defaultHeaders;
|
|
74
|
+
constructor(options: ManagedAgentsClientOptions);
|
|
75
|
+
request<T>(path: string, options?: RequestOptions): Promise<T>;
|
|
76
|
+
requestVoid(path: string, options?: RequestOptions): Promise<void>;
|
|
77
|
+
raw(path: string, options?: RequestOptions): Promise<Response>;
|
|
78
|
+
}
|
|
79
|
+
export {};
|
|
80
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { parseSse } from "../protocol/sse.js";
|
|
2
|
+
import { ManagedApiClientError, throwApiError } from "./errors.js";
|
|
3
|
+
/** How many delivered event ids to remember for filtering a reconnect's overlap. */
|
|
4
|
+
const DEDUPE_WINDOW = 2048;
|
|
5
|
+
const RECONNECT_BACKOFF_MS = [250, 500, 1000, 2000, 5000];
|
|
6
|
+
/**
|
|
7
|
+
* A session's events as one continuous iterable, across however many connections it takes.
|
|
8
|
+
*
|
|
9
|
+
* A dropped connection is not the end of the session, so by default it is not the end of the
|
|
10
|
+
* iteration either: the stream reopens after the last durable event it delivered and filters
|
|
11
|
+
* out what the overlap repeats. The cursor is the SSE `id:` the server stamps on durable events
|
|
12
|
+
* only, so resuming never points at a live-only event (a token delta) that the log cannot find.
|
|
13
|
+
*/
|
|
14
|
+
export class ManagedSessionEventStream {
|
|
15
|
+
connect;
|
|
16
|
+
reconnect;
|
|
17
|
+
signal;
|
|
18
|
+
frames;
|
|
19
|
+
consumed = false;
|
|
20
|
+
cursor;
|
|
21
|
+
delivered = new Set();
|
|
22
|
+
attempts = 0;
|
|
23
|
+
constructor(connect, first, options) {
|
|
24
|
+
this.connect = connect;
|
|
25
|
+
this.frames = first;
|
|
26
|
+
this.cursor = options.after;
|
|
27
|
+
this.reconnect = options.reconnect ?? true;
|
|
28
|
+
this.signal = options.signal;
|
|
29
|
+
}
|
|
30
|
+
/** The last resume cursor this stream delivered — pass it as `after` to continue elsewhere. */
|
|
31
|
+
get lastEventId() {
|
|
32
|
+
return this.cursor;
|
|
33
|
+
}
|
|
34
|
+
[Symbol.asyncIterator]() {
|
|
35
|
+
if (this.consumed)
|
|
36
|
+
throw new Error("managed session event stream can only be consumed once");
|
|
37
|
+
this.consumed = true;
|
|
38
|
+
return {
|
|
39
|
+
next: () => this.next(),
|
|
40
|
+
return: async () => {
|
|
41
|
+
await this.frames?.return?.(undefined);
|
|
42
|
+
this.frames = undefined;
|
|
43
|
+
return { done: true, value: undefined };
|
|
44
|
+
},
|
|
45
|
+
throw: async (error) => {
|
|
46
|
+
if (this.frames?.throw !== undefined)
|
|
47
|
+
await this.frames.throw(error);
|
|
48
|
+
else
|
|
49
|
+
await this.frames?.return?.(undefined);
|
|
50
|
+
this.frames = undefined;
|
|
51
|
+
throw error;
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
async next() {
|
|
56
|
+
for (;;) {
|
|
57
|
+
if (this.frames === undefined)
|
|
58
|
+
return { done: true, value: undefined };
|
|
59
|
+
let result;
|
|
60
|
+
try {
|
|
61
|
+
result = await this.frames.next();
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (!(await this.reopen()))
|
|
65
|
+
throw error;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (result.done) {
|
|
69
|
+
if (!(await this.reopen()))
|
|
70
|
+
return { done: true, value: undefined };
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
this.attempts = 0;
|
|
74
|
+
const frame = result.value;
|
|
75
|
+
if (frame.event !== "session.event")
|
|
76
|
+
continue;
|
|
77
|
+
const event = frame.data;
|
|
78
|
+
if (this.delivered.has(event.eventId))
|
|
79
|
+
continue;
|
|
80
|
+
this.remember(event.eventId);
|
|
81
|
+
if (frame.id !== undefined)
|
|
82
|
+
this.cursor = frame.id;
|
|
83
|
+
return { done: false, value: event };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** Reconnect after a drop. False when reconnecting is off or the caller has aborted. */
|
|
87
|
+
async reopen() {
|
|
88
|
+
this.frames = undefined;
|
|
89
|
+
const aborted = () => this.signal?.aborted === true;
|
|
90
|
+
if (!this.reconnect || aborted())
|
|
91
|
+
return false;
|
|
92
|
+
const delay = RECONNECT_BACKOFF_MS[Math.min(this.attempts, RECONNECT_BACKOFF_MS.length - 1)];
|
|
93
|
+
this.attempts += 1;
|
|
94
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
95
|
+
if (aborted())
|
|
96
|
+
return false;
|
|
97
|
+
try {
|
|
98
|
+
this.frames = await this.connect(this.cursor);
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
// A definite answer — gone, forbidden, malformed — will not change by asking again.
|
|
103
|
+
if (error instanceof ManagedApiClientError && error.status < 500)
|
|
104
|
+
throw error;
|
|
105
|
+
// The server is still away: try again after the next backoff step, not forever at once.
|
|
106
|
+
return this.reopen();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
remember(eventId) {
|
|
110
|
+
this.delivered.add(eventId);
|
|
111
|
+
if (this.delivered.size > DEDUPE_WINDOW) {
|
|
112
|
+
const oldest = this.delivered.values().next().value;
|
|
113
|
+
if (oldest !== undefined)
|
|
114
|
+
this.delivered.delete(oldest);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
export class ManagedSessionsClient {
|
|
119
|
+
root;
|
|
120
|
+
constructor(root) {
|
|
121
|
+
this.root = root;
|
|
122
|
+
}
|
|
123
|
+
create(request) {
|
|
124
|
+
return this.root.request("/sessions", { method: "POST", body: request });
|
|
125
|
+
}
|
|
126
|
+
list() {
|
|
127
|
+
return this.root.request("/sessions");
|
|
128
|
+
}
|
|
129
|
+
retrieve(sessionId) {
|
|
130
|
+
return this.root.request(`/sessions/${encodeURIComponent(sessionId)}`);
|
|
131
|
+
}
|
|
132
|
+
messages = {
|
|
133
|
+
create: (sessionId, request, options = {}) => this.root.request(`/sessions/${encodeURIComponent(sessionId)}/messages`, {
|
|
134
|
+
method: "POST",
|
|
135
|
+
body: request,
|
|
136
|
+
...(options.idempotencyKey !== undefined
|
|
137
|
+
? { headers: { "idempotency-key": options.idempotencyKey } }
|
|
138
|
+
: {}),
|
|
139
|
+
}),
|
|
140
|
+
};
|
|
141
|
+
events = {
|
|
142
|
+
list: (sessionId, options = {}) => {
|
|
143
|
+
const query = new URLSearchParams();
|
|
144
|
+
if (options.limit !== undefined)
|
|
145
|
+
query.set("limit", String(options.limit));
|
|
146
|
+
if (options.page !== undefined)
|
|
147
|
+
query.set("page", options.page);
|
|
148
|
+
if (options.order !== undefined)
|
|
149
|
+
query.set("order", options.order);
|
|
150
|
+
if (options.address !== undefined)
|
|
151
|
+
query.set("address", options.address);
|
|
152
|
+
const suffix = query.size === 0 ? "" : `?${query.toString()}`;
|
|
153
|
+
return this.root.request(`/sessions/${encodeURIComponent(sessionId)}/events${suffix}`);
|
|
154
|
+
},
|
|
155
|
+
stream: async (sessionId, options = {}) => {
|
|
156
|
+
const connect = async (after) => {
|
|
157
|
+
const query = new URLSearchParams();
|
|
158
|
+
if (options.address !== undefined)
|
|
159
|
+
query.set("address", options.address);
|
|
160
|
+
const suffix = query.size === 0 ? "" : `?${query.toString()}`;
|
|
161
|
+
const response = await this.root.raw(`/sessions/${encodeURIComponent(sessionId)}/events/stream${suffix}`, {
|
|
162
|
+
signal: options.signal,
|
|
163
|
+
headers: {
|
|
164
|
+
accept: "text/event-stream",
|
|
165
|
+
...(after !== undefined ? { "last-event-id": after } : {}),
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
if (!response.ok)
|
|
169
|
+
return throwApiError(response);
|
|
170
|
+
if (response.body === null)
|
|
171
|
+
throw new Error("event stream response has no body");
|
|
172
|
+
return parseSse(response.body)[Symbol.asyncIterator]();
|
|
173
|
+
};
|
|
174
|
+
return new ManagedSessionEventStream(connect, await connect(options.after), {
|
|
175
|
+
...(options.after !== undefined ? { after: options.after } : {}),
|
|
176
|
+
...(options.reconnect !== undefined ? { reconnect: options.reconnect } : {}),
|
|
177
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
178
|
+
});
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
cancel(sessionId) {
|
|
182
|
+
return this.root.request(`/sessions/${encodeURIComponent(sessionId)}/cancel`, { method: "POST" });
|
|
183
|
+
}
|
|
184
|
+
delete(sessionId) {
|
|
185
|
+
return this.root.requestVoid(`/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" });
|
|
186
|
+
}
|
|
187
|
+
interruptions(sessionId) {
|
|
188
|
+
return this.root.request(`/sessions/${encodeURIComponent(sessionId)}/interruptions`);
|
|
189
|
+
}
|
|
190
|
+
resume(sessionId, answers) {
|
|
191
|
+
return this.root.request(`/sessions/${encodeURIComponent(sessionId)}/resume`, { method: "POST", body: { answers } });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
export class ManagedAgentsClient {
|
|
195
|
+
sessions;
|
|
196
|
+
baseUrl;
|
|
197
|
+
fetchImpl;
|
|
198
|
+
defaultHeaders;
|
|
199
|
+
constructor(options) {
|
|
200
|
+
this.baseUrl = options.baseUrl.replace(/\/+$/, "");
|
|
201
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
|
202
|
+
this.defaultHeaders = {
|
|
203
|
+
...options.headers,
|
|
204
|
+
...(options.apiKey !== undefined ? { authorization: `Bearer ${options.apiKey}` } : {}),
|
|
205
|
+
};
|
|
206
|
+
this.sessions = new ManagedSessionsClient(this);
|
|
207
|
+
}
|
|
208
|
+
async request(path, options = {}) {
|
|
209
|
+
const response = await this.raw(path, options);
|
|
210
|
+
if (!response.ok)
|
|
211
|
+
return throwApiError(response);
|
|
212
|
+
return await response.json();
|
|
213
|
+
}
|
|
214
|
+
async requestVoid(path, options = {}) {
|
|
215
|
+
const response = await this.raw(path, options);
|
|
216
|
+
if (!response.ok)
|
|
217
|
+
return throwApiError(response);
|
|
218
|
+
}
|
|
219
|
+
raw(path, options = {}) {
|
|
220
|
+
return this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
221
|
+
method: options.method ?? "GET",
|
|
222
|
+
headers: {
|
|
223
|
+
...this.defaultHeaders,
|
|
224
|
+
...options.headers,
|
|
225
|
+
...(options.body !== undefined ? { "content-type": "application/json" } : {}),
|
|
226
|
+
},
|
|
227
|
+
...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}),
|
|
228
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare class ManagedApiClientError extends Error {
|
|
2
|
+
readonly status: number;
|
|
3
|
+
readonly code?: string;
|
|
4
|
+
constructor(message: string, status: number, code?: string);
|
|
5
|
+
}
|
|
6
|
+
export declare function throwApiError(response: Response): Promise<never>;
|
|
7
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export class ManagedApiClientError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
code;
|
|
4
|
+
constructor(message, status, code) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "ManagedApiClientError";
|
|
7
|
+
this.status = status;
|
|
8
|
+
this.code = code;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export async function throwApiError(response) {
|
|
12
|
+
let body;
|
|
13
|
+
try {
|
|
14
|
+
body = await response.json();
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// Fall through to HTTP status text.
|
|
18
|
+
}
|
|
19
|
+
throw new ManagedApiClientError(body?.error.message ?? `${response.status} ${response.statusText}`, response.status, body?.error.code);
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `run()` — send an input and wait for the agent to be done with it.
|
|
3
|
+
*
|
|
4
|
+
* The protocol underneath is asynchronous and cannot be otherwise: a turn outlives any request,
|
|
5
|
+
* survives the client disconnecting, and can be started by something that is not a client at all.
|
|
6
|
+
* But "send this and tell me when it's finished" is what most callers actually want, and writing
|
|
7
|
+
* that loop correctly is harder than it looks. The traps, in the order people hit them:
|
|
8
|
+
*
|
|
9
|
+
* 1. The stream must be opened BEFORE the input is sent, or what happens in between is only in
|
|
10
|
+
* the replay — and the ordering is still the only way to be sure of seeing it live.
|
|
11
|
+
* 2. The stream begins with history. On a session that has run before, the first `turn.ended`
|
|
12
|
+
* to arrive is an OLD one; ending on it returns the previous answer for the new question.
|
|
13
|
+
* Nothing counts until the turn that took our delivery is known, and only that turn's end
|
|
14
|
+
* is an ending.
|
|
15
|
+
* 3. Idle is transient. A session goes idle between parallel tool executions and while waiting
|
|
16
|
+
* for an answer from you; breaking on the first idle ends the loop mid-conversation.
|
|
17
|
+
* 4. A pause that needs an answer is not an ending. Treating it as one leaves the agent waiting
|
|
18
|
+
* forever for a reply nobody will send.
|
|
19
|
+
* 5. Waiting forever is also wrong. Without a handler the correct move is to fail loudly, not
|
|
20
|
+
* to hang — a caller that cannot answer approvals should learn that immediately.
|
|
21
|
+
*
|
|
22
|
+
* Anthropic's Managed Agents documentation devotes a section to warning about the same loop
|
|
23
|
+
* ("Do not break on session.status_idle alone"). A hazard that needs its own documentation
|
|
24
|
+
* section is one the library should absorb.
|
|
25
|
+
*/
|
|
26
|
+
import type { AgentEvent } from "operon-agents";
|
|
27
|
+
import type { ManagedAgentsClient } from "./client.ts";
|
|
28
|
+
import type { CreateManagedMessageRequest, ManagedSession } from "../protocol/types.ts";
|
|
29
|
+
/** A pause the agent cannot get past without an answer from the caller. */
|
|
30
|
+
export interface RunInterruptRequest {
|
|
31
|
+
readonly sessionId: string;
|
|
32
|
+
/** The pending approvals / tool-input requests, as reported by the session. */
|
|
33
|
+
readonly pending: readonly unknown[];
|
|
34
|
+
}
|
|
35
|
+
export interface RunOptions {
|
|
36
|
+
/**
|
|
37
|
+
* Answer a durable interruption so the run can continue. Receives the pending requests and
|
|
38
|
+
* returns the answers keyed the way `sessions.resume` expects.
|
|
39
|
+
*
|
|
40
|
+
* Omitting it is a statement that this caller never expects to be asked. If the agent does ask,
|
|
41
|
+
* `run` rejects rather than waiting — a hang here is indistinguishable from a slow model, and
|
|
42
|
+
* would be diagnosed hours later.
|
|
43
|
+
*/
|
|
44
|
+
readonly onInterrupt?: (request: RunInterruptRequest) => Promise<Record<string, unknown>>;
|
|
45
|
+
/** Observe events as they arrive. Purely informational; `run` handles control flow. */
|
|
46
|
+
readonly onEvent?: (event: AgentEvent) => void;
|
|
47
|
+
readonly signal?: AbortSignal;
|
|
48
|
+
/** Give up after this long with no terminal state. Off by default. */
|
|
49
|
+
readonly timeoutMs?: number;
|
|
50
|
+
}
|
|
51
|
+
export interface RunResult {
|
|
52
|
+
readonly sessionId: string;
|
|
53
|
+
/** Every event seen while running, in arrival order. */
|
|
54
|
+
readonly events: readonly AgentEvent[];
|
|
55
|
+
/** The last assistant text, when the run produced any. */
|
|
56
|
+
readonly output?: string;
|
|
57
|
+
/** How many interruptions were answered along the way. */
|
|
58
|
+
readonly interruptionsAnswered: number;
|
|
59
|
+
readonly session: ManagedSession;
|
|
60
|
+
}
|
|
61
|
+
export declare class RunInterruptedError extends Error {
|
|
62
|
+
readonly sessionId: string;
|
|
63
|
+
readonly pending: readonly unknown[];
|
|
64
|
+
constructor(sessionId: string, pending: readonly unknown[]);
|
|
65
|
+
}
|
|
66
|
+
export declare class RunTimeoutError extends Error {
|
|
67
|
+
readonly sessionId: string;
|
|
68
|
+
constructor(sessionId: string, timeoutMs: number);
|
|
69
|
+
}
|
|
70
|
+
export declare function run(client: ManagedAgentsClient, sessionId: string, input: CreateManagedMessageRequest | string, options?: RunOptions): Promise<RunResult>;
|
|
71
|
+
//# sourceMappingURL=run.d.ts.map
|