@amalgm/agents 0.1.3 → 0.2.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 (55) hide show
  1. package/PURPOSE.md +25 -24
  2. package/README.md +19 -46
  3. package/dist/agents.d.ts +4 -26
  4. package/dist/agents.js +4 -87
  5. package/dist/bin/mcp.js +1 -1
  6. package/dist/cli/help.d.ts +1 -1
  7. package/dist/cli/help.js +2 -13
  8. package/dist/cli/open.d.ts +1 -1
  9. package/dist/cli/open.js +1 -5
  10. package/dist/cli/run.js +3 -8
  11. package/dist/errors.d.ts +1 -1
  12. package/dist/errors.js +0 -2
  13. package/dist/http/server.js +1 -7
  14. package/dist/index.d.ts +0 -2
  15. package/dist/index.js +0 -2
  16. package/dist/mcp/agent-tools.js +1 -1
  17. package/dist/mcp/tools.js +1 -2
  18. package/dist/rows.d.ts +1 -4
  19. package/dist/rows.js +0 -39
  20. package/dist/schema.js +53 -101
  21. package/dist/types.d.ts +0 -106
  22. package/docs/ARCHITECTURE.md +21 -33
  23. package/docs/CLI.md +3 -43
  24. package/docs/DATA_MODEL.md +7 -46
  25. package/docs/DEFINITIONS.md +4 -4
  26. package/docs/ENGINE_INTEGRATION.md +22 -67
  27. package/docs/MCP.md +3 -19
  28. package/docs/REST.md +14 -97
  29. package/docs/SDK.md +12 -61
  30. package/docs/SECURITY.md +6 -35
  31. package/examples/basic.ts +8 -22
  32. package/package.json +2 -2
  33. package/skills/amalgm-agents/SKILL.md +3 -12
  34. package/skills/amalgm-agents/agents/openai.yaml +2 -2
  35. package/dist/cli/session-commands.d.ts +0 -4
  36. package/dist/cli/session-commands.js +0 -54
  37. package/dist/drivers.d.ts +0 -4
  38. package/dist/drivers.js +0 -25
  39. package/dist/event-store.d.ts +0 -13
  40. package/dist/event-store.js +0 -50
  41. package/dist/http/session-routes.d.ts +0 -2
  42. package/dist/http/session-routes.js +0 -67
  43. package/dist/http/stream.d.ts +0 -3
  44. package/dist/http/stream.js +0 -30
  45. package/dist/mcp/session-tools.d.ts +0 -3
  46. package/dist/mcp/session-tools.js +0 -81
  47. package/dist/messages.d.ts +0 -3
  48. package/dist/messages.js +0 -56
  49. package/dist/runtime.d.ts +0 -29
  50. package/dist/runtime.js +0 -176
  51. package/dist/session-store.d.ts +0 -15
  52. package/dist/session-store.js +0 -83
  53. package/dist/turn-store.d.ts +0 -31
  54. package/dist/turn-store.js +0 -164
  55. package/docs/DRIVERS.md +0 -72
@@ -1,81 +0,0 @@
1
- import { AgentError } from '../errors.js';
2
- import { objectSchema, toolResult } from './helpers.js';
3
- const string = { type: 'string' };
4
- function text(input, ...keys) {
5
- for (const key of keys) {
6
- if (typeof input[key] === 'string' && input[key])
7
- return input[key];
8
- }
9
- return undefined;
10
- }
11
- function resolveAgentId(agents, requested) {
12
- const normalized = requested.toLowerCase();
13
- const matches = agents.listAgents().filter(({ id, definition }) => {
14
- return id.toLowerCase() === normalized || definition.name.toLowerCase() === normalized;
15
- });
16
- if (matches.length === 1)
17
- return matches[0].id;
18
- if (matches.length > 1)
19
- throw new AgentError('conflict', `Agent name is ambiguous: ${requested}`);
20
- throw new AgentError('not_found', `Agent not found: ${requested}`);
21
- }
22
- export function sessionTools(agents) {
23
- return [
24
- {
25
- name: 'agents_get_conversation',
26
- description: 'Read one durable agent session, including its turns and ordered events.',
27
- inputSchema: objectSchema({ conversation_id: string, session_id: string, after: { type: 'number' } }),
28
- handler(input) {
29
- const id = text(input, 'conversation_id', 'session_id');
30
- if (!id)
31
- throw new AgentError('invalid_input', 'conversation_id is required.');
32
- return toolResult({
33
- conversation_id: id,
34
- session: agents.getSession(id),
35
- turns: agents.listTurns(id),
36
- events: agents.listEvents(id, Number(input.after || 0)),
37
- });
38
- },
39
- },
40
- {
41
- name: 'talk_to_agent',
42
- description: 'Start or continue a durable agent session. Agents sessions are not Chat conversations.',
43
- inputSchema: objectSchema({
44
- agent: string,
45
- agent_id: string,
46
- conversation_id: string,
47
- session_id: string,
48
- description: string,
49
- prompt: string,
50
- message: { type: ['string', 'object'] },
51
- idempotency_key: string,
52
- run_in_background: { type: 'boolean' },
53
- }),
54
- async handler(input) {
55
- const requestedAgent = text(input, 'agent', 'agent_id');
56
- if (!requestedAgent)
57
- throw new AgentError('invalid_input', 'agent is required.');
58
- const agentId = resolveAgentId(agents, requestedAgent);
59
- const message = input.message ?? input.prompt;
60
- if (message === undefined)
61
- throw new AgentError('invalid_input', 'prompt or message is required.');
62
- const sessionId = text(input, 'conversation_id', 'session_id');
63
- const idempotencyKey = text(input, 'idempotency_key');
64
- const call = agents.talk(agentId, {
65
- message: message,
66
- ...(sessionId ? { sessionId } : {}),
67
- ...(idempotencyKey ? { idempotencyKey } : {}),
68
- });
69
- const base = {
70
- conversation_id: call.session.id,
71
- session: call.session,
72
- turn: call.turn,
73
- duplicate: call.duplicate,
74
- };
75
- if (input.run_in_background === true)
76
- return toolResult(base);
77
- return toolResult({ ...base, turn: await call.completion });
78
- },
79
- },
80
- ];
81
- }
@@ -1,3 +0,0 @@
1
- import type { AgentMessage } from './types.js';
2
- export declare function normalizeMessage(value: string | AgentMessage, role?: AgentMessage['role']): AgentMessage;
3
- export declare function messageText(message: AgentMessage): string;
package/dist/messages.js DELETED
@@ -1,56 +0,0 @@
1
- import { AgentError } from './errors.js';
2
- import { isObject } from './json.js';
3
- function normalizePart(value) {
4
- if (!isObject(value))
5
- throw new AgentError('invalid_input', 'message parts must be objects.');
6
- if (value.type === 'text') {
7
- if (typeof value.text !== 'string' || !value.text) {
8
- throw new AgentError('invalid_input', 'text parts require non-empty text.');
9
- }
10
- return { type: 'text', text: value.text };
11
- }
12
- if (value.type === 'reference') {
13
- if (typeof value.uri !== 'string' || !value.uri.trim()) {
14
- throw new AgentError('invalid_input', 'reference parts require uri.');
15
- }
16
- return {
17
- type: 'reference',
18
- uri: value.uri.trim(),
19
- name: typeof value.name === 'string' && value.name.trim() ? value.name.trim() : null,
20
- mediaType: typeof value.mediaType === 'string' && value.mediaType.trim()
21
- ? value.mediaType.trim()
22
- : null,
23
- };
24
- }
25
- if (value.type === 'data') {
26
- if (typeof value.name !== 'string' || !value.name.trim() || value.data === undefined) {
27
- throw new AgentError('invalid_input', 'data parts require name and data.');
28
- }
29
- return {
30
- type: 'data',
31
- name: value.name.trim(),
32
- data: JSON.parse(JSON.stringify(value.data)),
33
- };
34
- }
35
- throw new AgentError('invalid_input', `Unsupported message part: ${String(value.type)}`);
36
- }
37
- export function normalizeMessage(value, role = 'user') {
38
- if (typeof value === 'string') {
39
- if (!value)
40
- throw new AgentError('invalid_input', 'message must not be empty.');
41
- return { role, parts: [{ type: 'text', text: value }] };
42
- }
43
- if (!isObject(value) || !Array.isArray(value.parts) || value.parts.length === 0) {
44
- throw new AgentError('invalid_input', 'message requires at least one part.');
45
- }
46
- const validRoles = new Set(['user', 'assistant', 'system']);
47
- if (!validRoles.has(value.role))
48
- throw new AgentError('invalid_input', 'message role is invalid.');
49
- return { role: value.role, parts: value.parts.map(normalizePart) };
50
- }
51
- export function messageText(message) {
52
- return message.parts
53
- .filter((part) => part.type === 'text')
54
- .map((part) => part.text)
55
- .join('');
56
- }
package/dist/runtime.d.ts DELETED
@@ -1,29 +0,0 @@
1
- import type { AgentStore } from './agent-store.js';
2
- import type { EventStore } from './event-store.js';
3
- import type { SessionStore } from './session-store.js';
4
- import type { TurnStore } from './turn-store.js';
5
- import type { AgentDriver, AgentTurn, EnqueuedTurn, SendInput } from './types.js';
6
- export interface RuntimeLimits {
7
- maxInputBytes: number;
8
- maxEventBytes: number;
9
- turnTimeoutMs: number;
10
- }
11
- export declare class AgentRuntime {
12
- private readonly agents;
13
- private readonly sessions;
14
- private readonly turns;
15
- private readonly events;
16
- private readonly limits;
17
- private readonly drivers;
18
- private readonly active;
19
- constructor(agents: AgentStore, sessions: SessionStore, turns: TurnStore, events: EventStore, limits: RuntimeLimits, drivers?: AgentDriver[]);
20
- register(driver: AgentDriver): void;
21
- driverIds(): string[];
22
- enqueue(sessionId: string, input: SendInput): EnqueuedTurn;
23
- send(sessionId: string, input: SendInput): Promise<AgentTurn>;
24
- cancel(sessionId: string): AgentTurn;
25
- shutdown(): Promise<void>;
26
- private execute;
27
- private emit;
28
- private normalizeResult;
29
- }
package/dist/runtime.js DELETED
@@ -1,176 +0,0 @@
1
- import { AgentError, asAgentError } from './errors.js';
2
- import { assertByteLimit, isObject } from './json.js';
3
- import { normalizeMessage } from './messages.js';
4
- export class AgentRuntime {
5
- agents;
6
- sessions;
7
- turns;
8
- events;
9
- limits;
10
- drivers = new Map();
11
- active = new Map();
12
- constructor(agents, sessions, turns, events, limits, drivers = []) {
13
- this.agents = agents;
14
- this.sessions = sessions;
15
- this.turns = turns;
16
- this.events = events;
17
- this.limits = limits;
18
- for (const driver of drivers)
19
- this.register(driver);
20
- }
21
- register(driver) {
22
- if (!driver || typeof driver.id !== 'string' || typeof driver.run !== 'function') {
23
- throw new AgentError('invalid_input', 'Agent drivers require id and run.');
24
- }
25
- if (this.drivers.has(driver.id)) {
26
- throw new AgentError('conflict', `Agent driver already registered: ${driver.id}`);
27
- }
28
- this.drivers.set(driver.id, driver);
29
- }
30
- driverIds() {
31
- return [...this.drivers.keys()].sort();
32
- }
33
- enqueue(sessionId, input) {
34
- const message = normalizeMessage(input.message, 'user');
35
- assertByteLimit(message, this.limits.maxInputBytes, 'message');
36
- const reserved = this.turns.reserve(sessionId, message, input.idempotencyKey);
37
- if (reserved.duplicate) {
38
- const running = this.active.get(reserved.turn.id);
39
- return {
40
- turn: reserved.turn,
41
- completion: running?.completion || Promise.resolve(reserved.turn),
42
- duplicate: true,
43
- };
44
- }
45
- const controller = new AbortController();
46
- const completion = this.execute(reserved.turn, controller);
47
- this.active.set(reserved.turn.id, { controller, completion });
48
- void completion.then(() => this.active.delete(reserved.turn.id), () => this.active.delete(reserved.turn.id));
49
- return { turn: reserved.turn, completion, duplicate: false };
50
- }
51
- async send(sessionId, input) {
52
- return this.enqueue(sessionId, input).completion;
53
- }
54
- cancel(sessionId) {
55
- const turn = this.turns.active(sessionId);
56
- if (!turn)
57
- throw new AgentError('conflict', 'Session has no active turn.');
58
- const execution = this.active.get(turn.id);
59
- if (!execution)
60
- throw new AgentError('conflict', 'Active turn is not owned by this process.');
61
- const cancelling = this.turns.requestCancellation(turn.id);
62
- execution.controller.abort(new AgentError('cancelled', 'Turn cancelled by caller.'));
63
- return cancelling;
64
- }
65
- async shutdown() {
66
- const executions = [...this.active.entries()];
67
- for (const [turnId, execution] of executions) {
68
- const turn = this.turns.get(turnId);
69
- if (turn && (turn.status === 'queued' || turn.status === 'running')) {
70
- this.turns.requestCancellation(turnId);
71
- }
72
- execution.controller.abort(new Error('Agents service shutting down.'));
73
- }
74
- await Promise.allSettled(executions.map(([, execution]) => execution.completion));
75
- }
76
- async execute(turn, controller) {
77
- const session = this.sessions.require(turn.sessionId);
78
- const revision = this.agents.revision(session.agentId, session.agentRevisionId);
79
- const driver = this.drivers.get(revision.definition.driver.id);
80
- if (!driver) {
81
- return this.turns.fail(turn.id, failure('driver_unavailable', `Agent driver is not registered: ${revision.definition.driver.id}`));
82
- }
83
- this.turns.markRunning(turn.id);
84
- let timedOut = false;
85
- const timer = this.limits.turnTimeoutMs > 0
86
- ? setTimeout(() => {
87
- timedOut = true;
88
- controller.abort(new Error('Turn timed out.'));
89
- }, this.limits.turnTimeoutMs)
90
- : null;
91
- timer?.unref();
92
- try {
93
- const result = await driver.run({
94
- agent: revision,
95
- session,
96
- turn: this.turns.require(turn.id),
97
- history: this.turns.history(session.id, turn.id),
98
- input: turn.input,
99
- driverSessionId: session.driverSessionId,
100
- }, {
101
- signal: controller.signal,
102
- emit: (event) => this.emit(session.id, turn.id, event),
103
- });
104
- if (controller.signal.aborted) {
105
- if (this.turns.require(turn.id).status === 'cancelling')
106
- return this.turns.cancel(turn.id);
107
- return this.turns.fail(turn.id, failure('turn_timeout', 'Turn timed out.'));
108
- }
109
- const normalized = this.normalizeResult(result);
110
- if (normalized.message) {
111
- const data = {
112
- message: normalized.message,
113
- };
114
- assertByteLimit(data, this.limits.maxEventBytes, 'driver result message');
115
- this.events.append(session.id, turn.id, 'message', data);
116
- }
117
- if (normalized.driverSessionId) {
118
- this.sessions.setDriverSession(session.id, normalized.driverSessionId);
119
- }
120
- const storedResult = {
121
- metadata: normalized.metadata || {},
122
- ...(normalized.driverSessionId ? { driverSessionId: normalized.driverSessionId } : {}),
123
- };
124
- assertByteLimit(storedResult, this.limits.maxEventBytes, 'driver result');
125
- return this.turns.complete(turn.id, storedResult);
126
- }
127
- catch (error) {
128
- const current = this.turns.require(turn.id);
129
- if (current.status === 'cancelling')
130
- return this.turns.cancel(turn.id);
131
- const normalized = asAgentError(error);
132
- return this.turns.fail(turn.id, failure(timedOut ? 'turn_timeout' : normalized.code === 'internal' ? 'driver_error' : normalized.code, normalized.message, normalized.details));
133
- }
134
- finally {
135
- if (timer)
136
- clearTimeout(timer);
137
- }
138
- }
139
- emit(sessionId, turnId, event) {
140
- if (!event || typeof event.type !== 'string' || !event.type.trim() || !isObject(event.data)) {
141
- throw new AgentError('invalid_input', 'Driver events require type and object data.');
142
- }
143
- if (/^(session|turn)\./.test(event.type)) {
144
- throw new AgentError('invalid_input', 'Driver events cannot use reserved session.* or turn.* types.');
145
- }
146
- assertByteLimit(event.data, this.limits.maxEventBytes, 'driver event');
147
- if (event.type === 'message' && event.data.message) {
148
- const message = normalizeMessage(event.data.message, 'assistant');
149
- if (message.role !== 'assistant') {
150
- throw new AgentError('invalid_input', 'Driver message events must have assistant role.');
151
- }
152
- return this.events.append(sessionId, turnId, 'message', { message: message });
153
- }
154
- return this.events.append(sessionId, turnId, event.type.trim(), event.data);
155
- }
156
- normalizeResult(result) {
157
- if (!result)
158
- return {};
159
- const normalized = {};
160
- if (result.message) {
161
- normalized.message = normalizeMessage(result.message, 'assistant');
162
- if (normalized.message.role !== 'assistant') {
163
- throw new AgentError('invalid_input', 'Driver result messages must have assistant role.');
164
- }
165
- }
166
- if (typeof result.driverSessionId === 'string' && result.driverSessionId.trim()) {
167
- normalized.driverSessionId = result.driverSessionId.trim();
168
- }
169
- if (result.metadata && isObject(result.metadata))
170
- normalized.metadata = result.metadata;
171
- return normalized;
172
- }
173
- }
174
- function failure(code, message, details = {}) {
175
- return { code, message, details };
176
- }
@@ -1,15 +0,0 @@
1
- import type Database from 'better-sqlite3';
2
- import type { AgentRevision, AgentSession, JsonObject } from './types.js';
3
- import type { EventStore } from './event-store.js';
4
- export declare class SessionStore {
5
- private readonly database;
6
- private readonly events;
7
- private readonly now;
8
- constructor(database: Database.Database, events: EventStore, now: () => string);
9
- create(revision: AgentRevision, sessionId?: string, metadata?: JsonObject): AgentSession;
10
- get(id: string): AgentSession | null;
11
- require(id: string): AgentSession;
12
- list(agentId?: string, includeArchived?: boolean): AgentSession[];
13
- archive(id: string, hasActiveTurn: boolean): AgentSession;
14
- setDriverSession(id: string, driverSessionId: string): void;
15
- }
@@ -1,83 +0,0 @@
1
- import { AgentError } from './errors.js';
2
- import { newId, optionalId, requireId } from './ids.js';
3
- import { assertJsonObject } from './json.js';
4
- import { sessionFromRow } from './rows.js';
5
- export class SessionStore {
6
- database;
7
- events;
8
- now;
9
- constructor(database, events, now) {
10
- this.database = database;
11
- this.events = events;
12
- this.now = now;
13
- }
14
- create(revision, sessionId, metadata = {}) {
15
- const id = optionalId(sessionId, 'session id') || newId('session');
16
- if (this.get(id))
17
- throw new AgentError('conflict', `Session id already exists: ${id}`);
18
- const timestamp = this.now();
19
- const storedMetadata = assertJsonObject(metadata, 'metadata');
20
- let event;
21
- this.database.transaction(() => {
22
- this.database.prepare(`
23
- INSERT INTO sessions
24
- (id, agent_id, agent_revision_id, agent_revision_number, status, metadata_json, created_at, updated_at)
25
- VALUES (?, ?, ?, ?, 'active', ?, ?, ?)
26
- `).run(id, revision.agentId, revision.id, revision.number, JSON.stringify(storedMetadata), timestamp, timestamp);
27
- event = this.events.write(id, null, 'session.started', {
28
- agentId: revision.agentId,
29
- agentRevisionId: revision.id,
30
- agentRevision: revision.number,
31
- });
32
- })();
33
- if (event)
34
- this.events.announce(event);
35
- return this.require(id);
36
- }
37
- get(id) {
38
- const clean = requireId(id, 'session id');
39
- const row = this.database.prepare('SELECT * FROM sessions WHERE id = ?').get(clean);
40
- return row ? sessionFromRow(row) : null;
41
- }
42
- require(id) {
43
- const session = this.get(id);
44
- if (!session)
45
- throw new AgentError('not_found', `Session not found: ${id}`);
46
- return session;
47
- }
48
- list(agentId, includeArchived = false) {
49
- const filters = [];
50
- const values = [];
51
- if (agentId) {
52
- filters.push('agent_id = ?');
53
- values.push(requireId(agentId, 'agent id'));
54
- }
55
- if (!includeArchived)
56
- filters.push("status = 'active'");
57
- const where = filters.length ? ` WHERE ${filters.join(' AND ')}` : '';
58
- return this.database.prepare(`SELECT * FROM sessions${where} ORDER BY updated_at DESC`).all(...values)
59
- .map(sessionFromRow);
60
- }
61
- archive(id, hasActiveTurn) {
62
- const session = this.require(id);
63
- if (hasActiveTurn)
64
- throw new AgentError('conflict', 'Cannot archive a session with an active turn.');
65
- if (session.status === 'archived')
66
- return session;
67
- const timestamp = this.now();
68
- let event;
69
- this.database.transaction(() => {
70
- this.database.prepare(`
71
- UPDATE sessions SET status = 'archived', archived_at = ?, updated_at = ? WHERE id = ?
72
- `).run(timestamp, timestamp, session.id);
73
- event = this.events.write(session.id, null, 'session.archived', {});
74
- })();
75
- if (event)
76
- this.events.announce(event);
77
- return this.require(session.id);
78
- }
79
- setDriverSession(id, driverSessionId) {
80
- this.database.prepare('UPDATE sessions SET driver_session_id = ?, updated_at = ? WHERE id = ?')
81
- .run(driverSessionId, this.now(), requireId(id, 'session id'));
82
- }
83
- }
@@ -1,31 +0,0 @@
1
- import type Database from 'better-sqlite3';
2
- import type { EventStore } from './event-store.js';
3
- import type { SessionStore } from './session-store.js';
4
- import type { AgentFailure, AgentMessage, AgentTurn, JsonObject } from './types.js';
5
- export declare class TurnStore {
6
- private readonly database;
7
- private readonly sessions;
8
- private readonly events;
9
- private readonly now;
10
- constructor(database: Database.Database, sessions: SessionStore, events: EventStore, now: () => string);
11
- reserve(sessionId: string, input: AgentMessage, key?: string): {
12
- turn: AgentTurn;
13
- duplicate: boolean;
14
- };
15
- markRunning(id: string): AgentTurn;
16
- requestCancellation(id: string): AgentTurn;
17
- complete(id: string, result: JsonObject): AgentTurn;
18
- fail(id: string, failure: AgentFailure): AgentTurn;
19
- cancel(id: string): AgentTurn;
20
- interrupt(id: string, failure: AgentFailure): AgentTurn;
21
- get(id: string): AgentTurn | null;
22
- require(id: string): AgentTurn;
23
- list(sessionId: string): AgentTurn[];
24
- active(sessionId: string): AgentTurn | null;
25
- history(sessionId: string, beforeTurnId?: string): AgentMessage[];
26
- recoverInterrupted(): number;
27
- private byKey;
28
- private transition;
29
- private terminal;
30
- private touch;
31
- }
@@ -1,164 +0,0 @@
1
- import { AgentError } from './errors.js';
2
- import { newId, optionalKey, randomKey, requireId } from './ids.js';
3
- import { isObject } from './json.js';
4
- import { turnFromRow } from './rows.js';
5
- const ACTIVE_SQL = `status IN ('queued', 'running', 'cancelling')`;
6
- const TERMINAL = new Set(['completed', 'failed', 'cancelled', 'interrupted']);
7
- export class TurnStore {
8
- database;
9
- sessions;
10
- events;
11
- now;
12
- constructor(database, sessions, events, now) {
13
- this.database = database;
14
- this.sessions = sessions;
15
- this.events = events;
16
- this.now = now;
17
- }
18
- reserve(sessionId, input, key) {
19
- const session = this.sessions.require(sessionId);
20
- if (session.status !== 'active')
21
- throw new AgentError('conflict', 'Session is archived.');
22
- const idempotencyKey = optionalKey(key) || randomKey('turn-key');
23
- const existing = this.byKey(session.id, idempotencyKey);
24
- if (existing)
25
- return { turn: existing, duplicate: true };
26
- if (this.active(session.id))
27
- throw new AgentError('conflict', 'Session already has an active turn.');
28
- const id = newId('turn');
29
- const timestamp = this.now();
30
- let event;
31
- try {
32
- this.database.transaction(() => {
33
- this.database.prepare(`
34
- INSERT INTO turns (id, session_id, idempotency_key, status, input_json, created_at)
35
- VALUES (?, ?, ?, 'queued', ?, ?)
36
- `).run(id, session.id, idempotencyKey, JSON.stringify(input), timestamp);
37
- event = this.events.write(session.id, id, 'turn.input', { message: input });
38
- this.touch(session.id, timestamp);
39
- })();
40
- }
41
- catch (error) {
42
- const racedDuplicate = this.byKey(session.id, idempotencyKey);
43
- if (racedDuplicate)
44
- return { turn: racedDuplicate, duplicate: true };
45
- if (isUniqueConstraint(error)) {
46
- throw new AgentError('conflict', 'Session already has an active turn.');
47
- }
48
- throw error;
49
- }
50
- if (event)
51
- this.events.announce(event);
52
- return { turn: this.require(id), duplicate: false };
53
- }
54
- markRunning(id) {
55
- return this.transition(id, 'running', 'turn.running', true);
56
- }
57
- requestCancellation(id) {
58
- return this.transition(id, 'cancelling', 'turn.cancelling');
59
- }
60
- complete(id, result) {
61
- return this.terminal(id, 'completed', result, null, 'turn.completed');
62
- }
63
- fail(id, failure) {
64
- return this.terminal(id, 'failed', null, failure, 'turn.failed');
65
- }
66
- cancel(id) {
67
- return this.terminal(id, 'cancelled', null, null, 'turn.cancelled');
68
- }
69
- interrupt(id, failure) {
70
- return this.terminal(id, 'interrupted', null, failure, 'turn.interrupted');
71
- }
72
- get(id) {
73
- const row = this.database.prepare('SELECT * FROM turns WHERE id = ?').get(requireId(id, 'turn id'));
74
- return row ? turnFromRow(row) : null;
75
- }
76
- require(id) {
77
- const turn = this.get(id);
78
- if (!turn)
79
- throw new AgentError('not_found', `Turn not found: ${id}`);
80
- return turn;
81
- }
82
- list(sessionId) {
83
- this.sessions.require(sessionId);
84
- return this.database.prepare('SELECT * FROM turns WHERE session_id = ? ORDER BY created_at ASC')
85
- .all(sessionId).map(turnFromRow);
86
- }
87
- active(sessionId) {
88
- const row = this.database.prepare(`
89
- SELECT * FROM turns WHERE session_id = ? AND ${ACTIVE_SQL} ORDER BY created_at DESC LIMIT 1
90
- `).get(sessionId);
91
- return row ? turnFromRow(row) : null;
92
- }
93
- history(sessionId, beforeTurnId) {
94
- const messages = [];
95
- for (const turn of this.list(sessionId)) {
96
- if (turn.id === beforeTurnId)
97
- break;
98
- messages.push(turn.input);
99
- for (const event of this.events.forTurn(turn.id)) {
100
- const message = isObject(event.data.message) ? event.data.message : null;
101
- if (event.type === 'message' && message)
102
- messages.push(message);
103
- }
104
- }
105
- return messages;
106
- }
107
- recoverInterrupted() {
108
- const rows = this.database.prepare(`SELECT * FROM turns WHERE ${ACTIVE_SQL}`).all();
109
- for (const row of rows) {
110
- this.interrupt(turnFromRow(row).id, {
111
- code: 'process_restarted',
112
- message: 'The owning process restarted before the driver settled.',
113
- details: {},
114
- });
115
- }
116
- return rows.length;
117
- }
118
- byKey(sessionId, key) {
119
- const row = this.database.prepare('SELECT * FROM turns WHERE session_id = ? AND idempotency_key = ?')
120
- .get(sessionId, key);
121
- return row ? turnFromRow(row) : null;
122
- }
123
- transition(id, status, type, started = false) {
124
- const turn = this.require(id);
125
- const timestamp = this.now();
126
- let event;
127
- this.database.transaction(() => {
128
- this.database.prepare(`UPDATE turns SET status = ?, started_at = COALESCE(started_at, ?) WHERE id = ?`)
129
- .run(status, started ? timestamp : turn.startedAt, turn.id);
130
- event = this.events.write(turn.sessionId, turn.id, type, {});
131
- this.touch(turn.sessionId, timestamp);
132
- })();
133
- if (event)
134
- this.events.announce(event);
135
- return this.require(turn.id);
136
- }
137
- terminal(id, status, result, error, type) {
138
- const turn = this.require(id);
139
- if (TERMINAL.has(turn.status))
140
- return turn;
141
- const timestamp = this.now();
142
- let event;
143
- this.database.transaction(() => {
144
- this.database.prepare(`
145
- UPDATE turns SET status = ?, result_json = ?, error_json = ?, completed_at = ? WHERE id = ?
146
- `).run(status, result && JSON.stringify(result), error && JSON.stringify(error), timestamp, turn.id);
147
- const data = error ? { error: error } : {};
148
- event = this.events.write(turn.sessionId, turn.id, type, data);
149
- this.touch(turn.sessionId, timestamp);
150
- })();
151
- if (event)
152
- this.events.announce(event);
153
- return this.require(turn.id);
154
- }
155
- touch(sessionId, timestamp) {
156
- this.database.prepare('UPDATE sessions SET updated_at = ? WHERE id = ?').run(timestamp, sessionId);
157
- }
158
- }
159
- function isUniqueConstraint(error) {
160
- return Boolean(error
161
- && typeof error === 'object'
162
- && 'code' in error
163
- && String(error.code).startsWith('SQLITE_CONSTRAINT'));
164
- }