@amalgm/agents 0.2.1 → 0.2.2

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 (56) hide show
  1. package/PURPOSE.md +25 -24
  2. package/README.md +21 -47
  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 +9 -71
  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/docs/SHELL_INTEGRATION.md +29 -0
  32. package/examples/basic.ts +8 -22
  33. package/package.json +2 -2
  34. package/skills/amalgm-agents/SKILL.md +231 -20
  35. package/skills/amalgm-agents/agents/openai.yaml +2 -2
  36. package/dist/cli/session-commands.d.ts +0 -4
  37. package/dist/cli/session-commands.js +0 -54
  38. package/dist/drivers.d.ts +0 -4
  39. package/dist/drivers.js +0 -25
  40. package/dist/event-store.d.ts +0 -13
  41. package/dist/event-store.js +0 -50
  42. package/dist/http/session-routes.d.ts +0 -2
  43. package/dist/http/session-routes.js +0 -67
  44. package/dist/http/stream.d.ts +0 -3
  45. package/dist/http/stream.js +0 -30
  46. package/dist/mcp/session-tools.d.ts +0 -3
  47. package/dist/mcp/session-tools.js +0 -81
  48. package/dist/messages.d.ts +0 -3
  49. package/dist/messages.js +0 -56
  50. package/dist/runtime.d.ts +0 -29
  51. package/dist/runtime.js +0 -176
  52. package/dist/session-store.d.ts +0 -15
  53. package/dist/session-store.js +0 -83
  54. package/dist/turn-store.d.ts +0 -31
  55. package/dist/turn-store.js +0 -164
  56. package/docs/DRIVERS.md +0 -72
package/dist/drivers.d.ts DELETED
@@ -1,4 +0,0 @@
1
- import type { AgentDriver } from './types.js';
2
- export declare function defineDriver(driver: AgentDriver): AgentDriver;
3
- export declare function loadDriverModules(specifiers: string[]): Promise<AgentDriver[]>;
4
- export declare function driverSpecifiers(value?: string): string[];
package/dist/drivers.js DELETED
@@ -1,25 +0,0 @@
1
- import path from 'node:path';
2
- import { pathToFileURL } from 'node:url';
3
- import { AgentError } from './errors.js';
4
- export function defineDriver(driver) {
5
- if (!driver || typeof driver.id !== 'string' || typeof driver.run !== 'function') {
6
- throw new AgentError('invalid_input', 'Agent drivers require id and run.');
7
- }
8
- return driver;
9
- }
10
- export async function loadDriverModules(specifiers) {
11
- const drivers = [];
12
- for (const specifier of specifiers) {
13
- const target = specifier.startsWith('.') || specifier.startsWith('/')
14
- ? pathToFileURL(path.resolve(specifier)).href
15
- : specifier;
16
- const loaded = await import(target);
17
- const value = loaded.default ?? loaded.driver ?? loaded;
18
- const driver = typeof value === 'function' ? await value() : value;
19
- drivers.push(defineDriver(driver));
20
- }
21
- return drivers;
22
- }
23
- export function driverSpecifiers(value = process.env.AMALGM_AGENT_DRIVERS || '') {
24
- return value.split(',').map((item) => item.trim()).filter(Boolean);
25
- }
@@ -1,13 +0,0 @@
1
- import type Database from 'better-sqlite3';
2
- import type { EventListener, JsonObject, SessionEvent } from './types.js';
3
- export declare class EventStore {
4
- private readonly database;
5
- private readonly now;
6
- private readonly listener;
7
- constructor(database: Database.Database, now: () => string, listener: EventListener);
8
- append(sessionId: string, turnId: string | null, type: string, data: JsonObject): SessionEvent;
9
- write(sessionId: string, turnId: string | null, type: string, data: JsonObject): SessionEvent;
10
- announce(event: SessionEvent): void;
11
- list(sessionId: string, after?: number, limit?: number): SessionEvent[];
12
- forTurn(turnId: string): SessionEvent[];
13
- }
@@ -1,50 +0,0 @@
1
- import { AgentError } from './errors.js';
2
- import { newId } from './ids.js';
3
- import { eventFromRow } from './rows.js';
4
- export class EventStore {
5
- database;
6
- now;
7
- listener;
8
- constructor(database, now, listener) {
9
- this.database = database;
10
- this.now = now;
11
- this.listener = listener;
12
- }
13
- append(sessionId, turnId, type, data) {
14
- let event;
15
- this.database.transaction(() => {
16
- event = this.write(sessionId, turnId, type, data);
17
- this.database.prepare('UPDATE sessions SET updated_at = ? WHERE id = ?').run(this.now(), sessionId);
18
- })();
19
- if (!event)
20
- throw new AgentError('internal', 'Event transaction produced no event.');
21
- this.announce(event);
22
- return event;
23
- }
24
- write(sessionId, turnId, type, data) {
25
- const sequence = Number(this.database.prepare(`
26
- SELECT COALESCE(MAX(sequence), 0) + 1 AS value FROM session_events WHERE session_id = ?
27
- `).get(sessionId).value);
28
- const id = newId('event');
29
- const createdAt = this.now();
30
- this.database.prepare(`
31
- INSERT INTO session_events (id, session_id, turn_id, sequence, type, data_json, created_at)
32
- VALUES (?, ?, ?, ?, ?, ?, ?)
33
- `).run(id, sessionId, turnId, sequence, type, JSON.stringify(data), createdAt);
34
- return { id, sessionId, turnId, sequence, type, data, createdAt };
35
- }
36
- announce(event) {
37
- this.listener(event);
38
- }
39
- list(sessionId, after = 0, limit = 200) {
40
- const cursor = Number.isFinite(after) ? Math.max(0, Math.floor(after)) : 0;
41
- const bounded = Number.isFinite(limit) ? Math.max(1, Math.min(1000, Math.floor(limit))) : 200;
42
- return this.database.prepare(`
43
- SELECT * FROM session_events WHERE session_id = ? AND sequence > ? ORDER BY sequence ASC LIMIT ?
44
- `).all(sessionId, cursor, bounded).map(eventFromRow);
45
- }
46
- forTurn(turnId) {
47
- return this.database.prepare('SELECT * FROM session_events WHERE turn_id = ? ORDER BY sequence ASC')
48
- .all(turnId).map(eventFromRow);
49
- }
50
- }
@@ -1,2 +0,0 @@
1
- import type { RouteContext } from '../http-types.js';
2
- export declare function routeSessions(context: RouteContext): Promise<boolean>;
@@ -1,67 +0,0 @@
1
- import { AgentError } from '../errors.js';
2
- export async function routeSessions(context) {
3
- const [resource, id, child] = context.path;
4
- if (resource !== 'sessions')
5
- return false;
6
- if (!id && context.method === 'GET') {
7
- const agentId = context.url.searchParams.get('agent_id') || undefined;
8
- const archived = context.url.searchParams.get('include_archived') === 'true';
9
- context.json(200, { sessions: context.agents.listSessions(agentId, archived) });
10
- return true;
11
- }
12
- if (!id && context.method === 'POST') {
13
- const body = await context.body();
14
- if (typeof body.agentId !== 'string')
15
- throw new AgentError('invalid_input', 'agentId is required.');
16
- context.json(201, { session: context.agents.startSession({
17
- agentId: body.agentId,
18
- ...(typeof body.revisionId === 'string' ? { revisionId: body.revisionId } : {}),
19
- ...(typeof body.sessionId === 'string' ? { sessionId: body.sessionId } : {}),
20
- ...(body.metadata ? { metadata: body.metadata } : {}),
21
- }) });
22
- return true;
23
- }
24
- if (!id)
25
- throw new AgentError('not_found', 'Route not found.');
26
- if (!child && context.method === 'GET') {
27
- const session = context.agents.getSession(id);
28
- if (!session)
29
- throw new AgentError('not_found', `Session not found: ${id}`);
30
- context.json(200, { session });
31
- return true;
32
- }
33
- if (!child && context.method === 'DELETE') {
34
- context.json(200, { session: context.agents.archiveSession(id) });
35
- return true;
36
- }
37
- if (child === 'events' && context.method === 'GET') {
38
- const after = Number(context.url.searchParams.get('after') || 0);
39
- const limit = Number(context.url.searchParams.get('limit') || 200);
40
- context.json(200, { events: context.agents.listEvents(id, after, limit) });
41
- return true;
42
- }
43
- if (child === 'turns' && context.method === 'GET') {
44
- context.json(200, { turns: context.agents.listTurns(id) });
45
- return true;
46
- }
47
- if (child === 'cancel' && context.method === 'POST') {
48
- context.json(202, { turn: context.agents.cancelSession(id) });
49
- return true;
50
- }
51
- if (child === 'messages' && context.method === 'POST') {
52
- const body = await context.body();
53
- if (body.message === undefined)
54
- throw new AgentError('invalid_input', 'message is required.');
55
- const enqueued = context.agents.enqueue(id, {
56
- message: body.message,
57
- ...(typeof body.idempotencyKey === 'string' ? { idempotencyKey: body.idempotencyKey } : {}),
58
- });
59
- if (body.wait === false) {
60
- context.json(202, { turn: enqueued.turn, duplicate: enqueued.duplicate });
61
- return true;
62
- }
63
- context.json(200, { turn: await enqueued.completion, duplicate: enqueued.duplicate });
64
- return true;
65
- }
66
- return false;
67
- }
@@ -1,3 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from 'node:http';
2
- import type { Agents } from '../agents.js';
3
- export declare function streamEvents(agents: Agents, sessionId: string, request: IncomingMessage, response: ServerResponse, after?: number): void;
@@ -1,30 +0,0 @@
1
- import { AgentError } from '../errors.js';
2
- export function streamEvents(agents, sessionId, request, response, after = 0) {
3
- if (!agents.getSession(sessionId))
4
- throw new AgentError('not_found', `Session not found: ${sessionId}`);
5
- response.writeHead(200, {
6
- 'content-type': 'text/event-stream',
7
- 'cache-control': 'no-cache, no-transform',
8
- connection: 'keep-alive',
9
- });
10
- response.flushHeaders();
11
- let last = after;
12
- const write = (event) => {
13
- if (event.sequence <= last || response.destroyed)
14
- return;
15
- last = event.sequence;
16
- response.write(`id: ${event.sequence}\nevent: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
17
- };
18
- for (const event of agents.listEvents(sessionId, after, 1000))
19
- write(event);
20
- const unsubscribe = agents.subscribe(sessionId, write);
21
- const heartbeat = setInterval(() => {
22
- if (!response.destroyed)
23
- response.write(': heartbeat\n\n');
24
- }, 15_000);
25
- heartbeat.unref();
26
- request.once('close', () => {
27
- clearInterval(heartbeat);
28
- unsubscribe();
29
- });
30
- }
@@ -1,3 +0,0 @@
1
- import type { Agents } from '../agents.js';
2
- import type { McpTool } from './types.js';
3
- export declare function sessionTools(agents: Agents): McpTool[];
@@ -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
- }