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.
Files changed (47) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +103 -0
  3. package/dist/client/client.d.ts +80 -0
  4. package/dist/client/client.js +232 -0
  5. package/dist/client/errors.d.ts +7 -0
  6. package/dist/client/errors.js +21 -0
  7. package/dist/client/index.d.ts +4 -0
  8. package/dist/client/index.js +4 -0
  9. package/dist/client/run.d.ts +71 -0
  10. package/dist/client/run.js +144 -0
  11. package/dist/index.d.ts +4 -0
  12. package/dist/index.js +4 -0
  13. package/dist/protocol/index.d.ts +3 -0
  14. package/dist/protocol/index.js +3 -0
  15. package/dist/protocol/sse.d.ts +7 -0
  16. package/dist/protocol/sse.js +53 -0
  17. package/dist/protocol/types.d.ts +102 -0
  18. package/dist/protocol/types.js +2 -0
  19. package/dist/server/broadcast.d.ts +105 -0
  20. package/dist/server/broadcast.js +130 -0
  21. package/dist/server/errors.d.ts +23 -0
  22. package/dist/server/errors.js +43 -0
  23. package/dist/server/http-server.d.ts +54 -0
  24. package/dist/server/http-server.js +325 -0
  25. package/dist/server/idempotency.d.ts +24 -0
  26. package/dist/server/idempotency.js +52 -0
  27. package/dist/server/inbox.d.ts +64 -0
  28. package/dist/server/inbox.js +71 -0
  29. package/dist/server/index.d.ts +14 -0
  30. package/dist/server/index.js +14 -0
  31. package/dist/server/metadata-pg.d.ts +31 -0
  32. package/dist/server/metadata-pg.js +64 -0
  33. package/dist/server/metadata.d.ts +38 -0
  34. package/dist/server/metadata.js +107 -0
  35. package/dist/server/registries.d.ts +40 -0
  36. package/dist/server/registries.js +26 -0
  37. package/dist/server/session-service.d.ts +181 -0
  38. package/dist/server/session-service.js +658 -0
  39. package/dist/server/session-worker.d.ts +136 -0
  40. package/dist/server/session-worker.js +428 -0
  41. package/dist/server/work-memory.d.ts +27 -0
  42. package/dist/server/work-memory.js +85 -0
  43. package/dist/server/work-pg.d.ts +46 -0
  44. package/dist/server/work-pg.js +122 -0
  45. package/dist/server/work.d.ts +49 -0
  46. package/dist/server/work.js +2 -0
  47. package/package.json +56 -0
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The work table in Postgres. See `work.ts` for what the table means; this file is the
3
+ * statements.
4
+ *
5
+ * Every operation is ONE statement, and the conditions in their WHERE clauses are the whole
6
+ * mechanism: `claim` and `acquire` only touch a row whose lease is absent or expired, `renew`
7
+ * and `release` only a row this holder still owns at this fence. `FOR UPDATE SKIP LOCKED` is
8
+ * what lets any number of workers claim at once without handing two of them the same session
9
+ * and without making them wait for each other.
10
+ *
11
+ * ## Why a table and not a queue
12
+ *
13
+ * An agent turn runs for minutes, must be exclusive, and can be cancelled from outside while it
14
+ * runs. A queue hands a message to a consumer; it has no notion of "the consumer is still on
15
+ * it" or "tell that consumer something". The lease does both: it IS the claim, and its heartbeat
16
+ * is the channel back to the holder. Postgres already holds the log, so this costs no second
17
+ * system and no second source of truth — the wake and the record it announces are one commit.
18
+ */
19
+ import type { AgentRecord, PgExecutor, PgSessionRepository } from "operon-agents";
20
+ import type { SessionWork, WorkLease } from "./work.ts";
21
+ export interface PgSessionWorkOptions {
22
+ readonly pool: PgExecutor;
23
+ /** The repository the log lives in — `append` joins its write and the wake in one transaction. */
24
+ readonly repository: PgSessionRepository;
25
+ /** Identifies this holder in the table. Use something a restart changes — a pod name plus a
26
+ * boot id — so a restarted node does not look like its old self. */
27
+ readonly ownerId: string;
28
+ readonly table?: string;
29
+ readonly ttlMs?: number;
30
+ }
31
+ /** DDL for the work table. Idempotent; run it once per deployment, before any worker starts. */
32
+ export declare function sessionWorkTableDDL(table?: string): string;
33
+ export declare class PgSessionWork implements SessionWork {
34
+ private readonly pool;
35
+ private readonly repository;
36
+ private readonly ownerId;
37
+ private readonly table;
38
+ private readonly ttlMs;
39
+ constructor(options: PgSessionWorkOptions);
40
+ append(sessionId: string, record: AgentRecord): Promise<void>;
41
+ claim(): Promise<WorkLease | undefined>;
42
+ acquire(sessionId: string): Promise<WorkLease | undefined>;
43
+ peek(sessionId: string): Promise<boolean>;
44
+ private lease;
45
+ }
46
+ //# sourceMappingURL=work-pg.d.ts.map
@@ -0,0 +1,122 @@
1
+ const DEFAULT_TTL_MS = 30_000;
2
+ /** DDL for the work table. Idempotent; run it once per deployment, before any worker starts. */
3
+ export function sessionWorkTableDDL(table = "session_work") {
4
+ return `
5
+ CREATE TABLE IF NOT EXISTS ${table} (
6
+ session_id TEXT PRIMARY KEY,
7
+ woken BOOLEAN NOT NULL DEFAULT false,
8
+ lease_owner TEXT,
9
+ lease_until TIMESTAMPTZ,
10
+ fence BIGINT NOT NULL DEFAULT 0
11
+ );
12
+ ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS woken BOOLEAN NOT NULL DEFAULT false;
13
+ ALTER TABLE ${table} DROP COLUMN IF EXISTS pending_since;
14
+ -- Partial: only rows a claim could take are indexed, so a claim costs a range read over the
15
+ -- backlog and the sessions currently running — never over every session that ever existed.
16
+ CREATE INDEX IF NOT EXISTS ${table}_claim_idx
17
+ ON ${table} (lease_until)
18
+ WHERE woken OR lease_owner IS NOT NULL;
19
+ `;
20
+ }
21
+ export class PgSessionWork {
22
+ pool;
23
+ repository;
24
+ ownerId;
25
+ table;
26
+ ttlMs;
27
+ constructor(options) {
28
+ this.pool = options.pool;
29
+ this.repository = options.repository;
30
+ this.ownerId = options.ownerId;
31
+ this.table = options.table ?? "session_work";
32
+ this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
33
+ }
34
+ async append(sessionId, record) {
35
+ await this.repository.transaction(async (tx) => {
36
+ await tx.store(sessionId).appendRecord(record);
37
+ await tx.exec.query(`INSERT INTO ${this.table} (session_id, woken) VALUES ($1, true)
38
+ ON CONFLICT (session_id) DO UPDATE SET woken = true`, [sessionId]);
39
+ });
40
+ }
41
+ async claim() {
42
+ // Woken and unheld, or held past its TTL by a holder that never released: both are work.
43
+ // The subquery picks one such row and locks it; `SKIP LOCKED` steps over rows another
44
+ // claim is taking at this moment instead of waiting for it.
45
+ const { rows } = await this.pool.query(`UPDATE ${this.table}
46
+ SET lease_owner = $1, lease_until = now() + make_interval(secs => $2),
47
+ fence = fence + 1, woken = false
48
+ WHERE session_id = (
49
+ SELECT session_id FROM ${this.table}
50
+ WHERE (woken OR lease_owner IS NOT NULL)
51
+ AND (lease_until IS NULL OR lease_until < now())
52
+ ORDER BY lease_until NULLS FIRST
53
+ LIMIT 1
54
+ FOR UPDATE SKIP LOCKED)
55
+ RETURNING session_id, fence`, [this.ownerId, this.ttlMs / 1000]);
56
+ const row = rows[0];
57
+ return row === undefined ? undefined : this.lease(String(row.session_id), Number(row.fence));
58
+ }
59
+ async acquire(sessionId) {
60
+ // Insert the row if absent, take it if free or expired. The WHERE on the DO UPDATE is the
61
+ // compare-and-set: a live lease held elsewhere leaves the row untouched and returns nothing.
62
+ const { rows } = await this.pool.query(`INSERT INTO ${this.table} (session_id, lease_owner, lease_until, fence, woken)
63
+ VALUES ($1, $2, now() + make_interval(secs => $3), 1, false)
64
+ ON CONFLICT (session_id) DO UPDATE
65
+ SET lease_owner = EXCLUDED.lease_owner,
66
+ lease_until = EXCLUDED.lease_until,
67
+ fence = ${this.table}.fence + 1,
68
+ woken = false
69
+ WHERE ${this.table}.lease_until IS NULL OR ${this.table}.lease_until < now()
70
+ RETURNING fence`, [sessionId, this.ownerId, this.ttlMs / 1000]);
71
+ const fence = rows[0]?.fence;
72
+ return fence === undefined ? undefined : this.lease(sessionId, Number(fence));
73
+ }
74
+ async peek(sessionId) {
75
+ const { rows } = await this.pool.query(`SELECT 1 FROM ${this.table} WHERE session_id = $1 AND lease_until IS NOT NULL AND lease_until > now()`, [sessionId]);
76
+ return rows.length > 0;
77
+ }
78
+ lease(sessionId, fence) {
79
+ const controller = new AbortController();
80
+ let gone = false;
81
+ const lose = () => {
82
+ if (gone)
83
+ return;
84
+ gone = true;
85
+ controller.abort();
86
+ };
87
+ return {
88
+ sessionId,
89
+ fence,
90
+ signal: controller.signal,
91
+ renew: async () => {
92
+ if (gone)
93
+ return "lost";
94
+ // Owner AND fence: a node that reclaimed and released this row must not let the old
95
+ // holder extend a lease that has moved on. The self-join locks the row first and reads
96
+ // `woken` before clearing it, so a wake committed at this very moment either shows up
97
+ // here or lands after our clear — never under it.
98
+ const { rows } = await this.pool.query(`UPDATE ${this.table} AS w
99
+ SET lease_until = now() + make_interval(secs => $3), woken = false
100
+ FROM (SELECT session_id, woken FROM ${this.table} WHERE session_id = $1 FOR UPDATE) AS before
101
+ WHERE w.session_id = before.session_id AND w.lease_owner = $2 AND w.fence = $4
102
+ RETURNING before.woken AS woken`, [sessionId, this.ownerId, this.ttlMs / 1000, fence]);
103
+ const row = rows[0];
104
+ if (row === undefined) {
105
+ lose();
106
+ return "lost";
107
+ }
108
+ return row.woken === true ? "woken" : "quiet";
109
+ },
110
+ release: async () => {
111
+ if (gone)
112
+ return;
113
+ lose();
114
+ // Only our own hold, at our fence: if the row moved on, it is someone else's now.
115
+ // `woken` is left alone — a wake that arrived since our last look is the next claim's.
116
+ await this.pool.query(`UPDATE ${this.table} SET lease_owner = NULL, lease_until = NULL
117
+ WHERE session_id = $1 AND lease_owner = $2 AND fence = $3`, [sessionId, this.ownerId, fence]);
118
+ },
119
+ };
120
+ }
121
+ }
122
+ //# sourceMappingURL=work-pg.js.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The work table: which sessions have something to do, and who is doing it.
3
+ *
4
+ * One row per session that has been appended to or is being run. A row says two things — "new
5
+ * inbox since a holder last looked" (`woken`) and "who holds the lease" — and every operation
6
+ * here is one atomic step over that row, which is what makes this both the queue and the lock:
7
+ *
8
+ * - `append` puts a record in the session's log AND wakes the row, in one transaction where
9
+ * the backing has them. There is no moment where the log has an input the table does not
10
+ * know about, so nothing ever has to scan the log to find forgotten work.
11
+ * - `claim` takes the lease on one woken (or abandoned) session. Taking it IS the claim; there
12
+ * is no separate "dispatched" state that could disagree with "held".
13
+ * - `renew` is the holder's heartbeat, and carries the only signal a holder gets from other
14
+ * nodes: whether anything was appended since it last looked. A cancel reaches the machine
15
+ * running the turn this way — no address for that machine is needed anywhere.
16
+ *
17
+ * A worker that dies leaves its row held past its TTL. The next `claim` takes such a row like
18
+ * any other: an abandoned session is work, whether or not anything new was appended to it.
19
+ */
20
+ import type { AgentRecord } from "operon-agents";
21
+ export interface WorkLease {
22
+ readonly sessionId: string;
23
+ /** Monotonic fencing token, bumped on every take of this row. */
24
+ readonly fence: number;
25
+ /** Aborts when the lease is lost or released. Treat it as a cancel. */
26
+ readonly signal: AbortSignal;
27
+ /**
28
+ * Heartbeat. `"woken"`: something was appended since the last renew (or the claim) — read the
29
+ * inbox. `"quiet"`: still held, nothing new. `"lost"`: gone — taken over, or expired — and the
30
+ * signal has been aborted.
31
+ */
32
+ renew(): Promise<"woken" | "quiet" | "lost">;
33
+ /** Give the row back. Idempotent. A wake that arrived meanwhile stays on the row. */
34
+ release(): Promise<void>;
35
+ }
36
+ export interface SessionWork {
37
+ /** Put `record` in the session's log and the session in line for a worker — one durable step. */
38
+ append(sessionId: string, record: AgentRecord): Promise<void>;
39
+ /**
40
+ * Lease the next session that is woken, or whose holder let its lease lapse. Undefined when
41
+ * there is none. Concurrent callers never receive the same session.
42
+ */
43
+ claim(): Promise<WorkLease | undefined>;
44
+ /** Lease this one session, or undefined while a live lease is held elsewhere. */
45
+ acquire(sessionId: string): Promise<WorkLease | undefined>;
46
+ /** Advisory: is a live lease held right now? Stale the instant it returns — never gate on it. */
47
+ peek(sessionId: string): Promise<boolean>;
48
+ }
49
+ //# sourceMappingURL=work.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=work.js.map
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "operon-managed-agents",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Managed server and TypeScript client for operon-agents.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/nickqiaoo/operon-agents.git",
10
+ "directory": "packages/managed-agents"
11
+ },
12
+ "homepage": "https://github.com/nickqiaoo/operon-agents/tree/main/packages/managed-agents#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/nickqiaoo/operon-agents/issues"
15
+ },
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ },
23
+ "./protocol": {
24
+ "types": "./dist/protocol/index.d.ts",
25
+ "import": "./dist/protocol/index.js"
26
+ },
27
+ "./server": {
28
+ "types": "./dist/server/index.d.ts",
29
+ "import": "./dist/server/index.js"
30
+ },
31
+ "./client": {
32
+ "types": "./dist/client/index.d.ts",
33
+ "import": "./dist/client/index.js"
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "!dist/**/*.map",
40
+ "README.md"
41
+ ],
42
+ "dependencies": {
43
+ "operon-agents": "0.1.0-alpha.0"
44
+ },
45
+ "devDependencies": {
46
+ "@earendil-works/pi-ai": "0.84.1",
47
+ "zod": "^4.0.0",
48
+ "operon-agents-core": "0.1.0-alpha.0"
49
+ },
50
+ "scripts": {
51
+ "clean": "rm -rf dist *.tsbuildinfo",
52
+ "build": "pnpm --filter operon-agents build && tsc -p tsconfig.build.json",
53
+ "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.test.json",
54
+ "test": "for f in test/e2e*.ts; do echo \"\\n▶ $f\"; node --experimental-strip-types --no-warnings \"$f\" || exit 1; done"
55
+ }
56
+ }