@clearideas/agent-runtime-server 0.0.0-stage → 0.9.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/dist/kv.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import type { KeyValueStoreConfig } from "./config.js";
2
+ export interface KeyValueStore {
3
+ get(namespace: string, key: string): Promise<string | undefined>;
4
+ set(namespace: string, key: string, value: string, ttlMs: number): Promise<void>;
5
+ delete(namespace: string, key: string): Promise<void>;
6
+ /**
7
+ * Remove and return up to `limit` expired entries of a namespace. Used for
8
+ * queues whose expiry triggers work, such as run retention.
9
+ */
10
+ takeExpired(namespace: string, limit: number): Promise<Array<{
11
+ key: string;
12
+ value: string;
13
+ }>>;
14
+ close?(): void | Promise<void>;
15
+ }
16
+ /**
17
+ * A bounded in-process store. Expired entries are removed when read or
18
+ * taken; the least recently used entries are evicted above `maxEntries`.
19
+ */
20
+ export declare class MemoryKeyValueStore implements KeyValueStore {
21
+ #private;
22
+ constructor(options?: {
23
+ maxEntries?: number;
24
+ now?: () => number;
25
+ });
26
+ get(namespace: string, key: string): Promise<string | undefined>;
27
+ set(namespace: string, key: string, value: string, ttlMs: number): Promise<void>;
28
+ delete(namespace: string, key: string): Promise<void>;
29
+ takeExpired(namespace: string, limit: number): Promise<Array<{
30
+ key: string;
31
+ value: string;
32
+ }>>;
33
+ }
34
+ /** A durable single-node store in one SQLite file (owner-only permissions). */
35
+ export declare class SqliteKeyValueStore implements KeyValueStore {
36
+ #private;
37
+ private constructor();
38
+ static open(filename: string, options?: {
39
+ now?: () => number;
40
+ }): Promise<SqliteKeyValueStore>;
41
+ get(namespace: string, key: string): Promise<string | undefined>;
42
+ set(namespace: string, key: string, value: string, ttlMs: number): Promise<void>;
43
+ delete(namespace: string, key: string): Promise<void>;
44
+ takeExpired(namespace: string, limit: number): Promise<Array<{
45
+ key: string;
46
+ value: string;
47
+ }>>;
48
+ close(): void;
49
+ }
50
+ /** Open a configured store. */
51
+ export declare const openKeyValueStore: (config: KeyValueStoreConfig) => Promise<KeyValueStore>;
package/dist/kv.js ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Key-value stores for server state: the conversation ledger, the media
3
+ * index, and the retention queue. Values are strings (JSON) and every entry
4
+ * has a time to live.
5
+ */
6
+ import { chmodSync, mkdirSync } from "node:fs";
7
+ import path from "node:path";
8
+ /**
9
+ * A bounded in-process store. Expired entries are removed when read or
10
+ * taken; the least recently used entries are evicted above `maxEntries`.
11
+ */
12
+ export class MemoryKeyValueStore {
13
+ #entries = new Map();
14
+ #maxEntries;
15
+ #now;
16
+ constructor(options = {}) {
17
+ this.#maxEntries = options.maxEntries ?? 100_000;
18
+ this.#now = options.now ?? Date.now;
19
+ }
20
+ async get(namespace, key) {
21
+ const id = `${namespace}\u0000${key}`;
22
+ const entry = this.#entries.get(id);
23
+ if (!entry)
24
+ return undefined;
25
+ if (entry.expiresAt <= this.#now()) {
26
+ this.#entries.delete(id);
27
+ return undefined;
28
+ }
29
+ // Refresh recency.
30
+ this.#entries.delete(id);
31
+ this.#entries.set(id, entry);
32
+ return entry.value;
33
+ }
34
+ async set(namespace, key, value, ttlMs) {
35
+ const id = `${namespace}\u0000${key}`;
36
+ this.#entries.delete(id);
37
+ this.#entries.set(id, { value, expiresAt: this.#now() + ttlMs });
38
+ while (this.#entries.size > this.#maxEntries) {
39
+ const oldest = this.#entries.keys().next().value;
40
+ if (oldest === undefined)
41
+ break;
42
+ this.#entries.delete(oldest);
43
+ }
44
+ }
45
+ async delete(namespace, key) {
46
+ this.#entries.delete(`${namespace}\u0000${key}`);
47
+ }
48
+ async takeExpired(namespace, limit) {
49
+ const now = this.#now();
50
+ const prefix = `${namespace}\u0000`;
51
+ const taken = [];
52
+ for (const [id, entry] of this.#entries) {
53
+ if (taken.length >= limit)
54
+ break;
55
+ if (!id.startsWith(prefix) || entry.expiresAt > now)
56
+ continue;
57
+ this.#entries.delete(id);
58
+ taken.push({ key: id.slice(prefix.length), value: entry.value });
59
+ }
60
+ return taken;
61
+ }
62
+ }
63
+ /** A durable single-node store in one SQLite file (owner-only permissions). */
64
+ export class SqliteKeyValueStore {
65
+ #database;
66
+ #now;
67
+ constructor(database, now) {
68
+ this.#database = database;
69
+ this.#now = now;
70
+ this.#database.exec(`
71
+ PRAGMA busy_timeout = 5000;
72
+ CREATE TABLE IF NOT EXISTS agent_runtime_server_kv (
73
+ namespace TEXT NOT NULL,
74
+ key TEXT NOT NULL,
75
+ value TEXT NOT NULL,
76
+ expires_at INTEGER NOT NULL,
77
+ PRIMARY KEY (namespace, key)
78
+ );
79
+ CREATE INDEX IF NOT EXISTS agent_runtime_server_kv_expiry
80
+ ON agent_runtime_server_kv(namespace, expires_at);
81
+ `);
82
+ }
83
+ static async open(filename, options = {}) {
84
+ // node:sqlite is loaded only when a SQLite store is configured.
85
+ const { DatabaseSync } = await import("node:sqlite");
86
+ let database;
87
+ if (filename === ":memory:") {
88
+ database = new DatabaseSync(filename);
89
+ }
90
+ else {
91
+ const resolved = path.resolve(filename);
92
+ mkdirSync(path.dirname(resolved), { recursive: true });
93
+ database = new DatabaseSync(resolved);
94
+ chmodSync(resolved, 0o600);
95
+ database.exec("PRAGMA journal_mode = WAL;");
96
+ }
97
+ return new SqliteKeyValueStore(database, options.now ?? Date.now);
98
+ }
99
+ async get(namespace, key) {
100
+ const row = this.#database
101
+ .prepare("SELECT value FROM agent_runtime_server_kv WHERE namespace = ? AND key = ? AND expires_at > ?")
102
+ .get(namespace, key, this.#now());
103
+ return row?.value;
104
+ }
105
+ async set(namespace, key, value, ttlMs) {
106
+ this.#database
107
+ .prepare(`INSERT INTO agent_runtime_server_kv (namespace, key, value, expires_at)
108
+ VALUES (?, ?, ?, ?)
109
+ ON CONFLICT (namespace, key) DO UPDATE
110
+ SET value = excluded.value, expires_at = excluded.expires_at`)
111
+ .run(namespace, key, value, this.#now() + ttlMs);
112
+ }
113
+ async delete(namespace, key) {
114
+ this.#database
115
+ .prepare("DELETE FROM agent_runtime_server_kv WHERE namespace = ? AND key = ?")
116
+ .run(namespace, key);
117
+ }
118
+ async takeExpired(namespace, limit) {
119
+ this.#database.exec("BEGIN IMMEDIATE");
120
+ try {
121
+ const rows = this.#database
122
+ .prepare(`SELECT key, value FROM agent_runtime_server_kv
123
+ WHERE namespace = ? AND expires_at <= ?
124
+ ORDER BY expires_at LIMIT ?`)
125
+ .all(namespace, this.#now(), limit);
126
+ const remove = this.#database.prepare("DELETE FROM agent_runtime_server_kv WHERE namespace = ? AND key = ?");
127
+ for (const row of rows)
128
+ remove.run(namespace, row.key);
129
+ this.#database.exec("COMMIT");
130
+ return rows.map((row) => ({ key: row.key, value: row.value }));
131
+ }
132
+ catch (error) {
133
+ this.#database.exec("ROLLBACK");
134
+ throw error;
135
+ }
136
+ }
137
+ close() {
138
+ this.#database.close();
139
+ }
140
+ }
141
+ /** Open a configured store. */
142
+ export const openKeyValueStore = async (config) => config.driver === "sqlite"
143
+ ? SqliteKeyValueStore.open(config.path)
144
+ : new MemoryKeyValueStore({ maxEntries: config.maxEntries });
@@ -0,0 +1,59 @@
1
+ import type { ConversationMessage, MessagesSignature } from "@clearideas/agent-runtime-contracts";
2
+ import type { KeyValueStore } from "./kv.js";
3
+ export type LedgerMatch = "exact" | "user-turns";
4
+ type ProjectedPart = {
5
+ text: string;
6
+ } | {
7
+ json: unknown;
8
+ } | {
9
+ media: "image" | "file";
10
+ source: string;
11
+ };
12
+ interface ProjectedMessage {
13
+ role: "user" | "assistant";
14
+ parts: ProjectedPart[];
15
+ }
16
+ /**
17
+ * The client-visible form of a conversation: roles, normalized text, and
18
+ * media by content. With `user-turns`, assistant text is ignored, so a
19
+ * client that rewrites replies still matches.
20
+ */
21
+ export declare const projectConversation: (messages: readonly ConversationMessage[], match: LedgerMatch) => ProjectedMessage[];
22
+ export declare const ledgerKey: (input: {
23
+ scope: string;
24
+ model: string;
25
+ match: LedgerMatch;
26
+ messages: readonly ConversationMessage[];
27
+ }) => string;
28
+ export interface LedgerEntry {
29
+ /** The runtime's output history: what the next turn continues from. */
30
+ history: ConversationMessage[];
31
+ signature?: MessagesSignature;
32
+ scope: string;
33
+ runId: string;
34
+ model: string;
35
+ manifestHash: string;
36
+ createdAt: string;
37
+ }
38
+ export declare class ConversationLedger {
39
+ #private;
40
+ constructor(store: KeyValueStore, options: {
41
+ ttlMs: number;
42
+ match: LedgerMatch;
43
+ });
44
+ /** Remove a bounded batch of expired entries, including unread histories. */
45
+ sweepExpired(limit?: number): Promise<number>;
46
+ get match(): LedgerMatch;
47
+ /** The runtime history issued for this client-visible conversation, if any. */
48
+ lookup(input: {
49
+ scope: string;
50
+ model: string;
51
+ messages: readonly ConversationMessage[];
52
+ }): Promise<LedgerEntry | undefined>;
53
+ /** Record the history issued after the client-visible conversation `messages`. */
54
+ record(input: {
55
+ messages: readonly ConversationMessage[];
56
+ entry: LedgerEntry;
57
+ }): Promise<void>;
58
+ }
59
+ export {};
package/dist/ledger.js ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The conversation ledger maps what a chat client sends back to the history
3
+ * the runtime issued, so a returning conversation continues from the
4
+ * runtime's own signed, compacted history instead of the client's copy.
5
+ *
6
+ * Keys are content addresses of the client-visible conversation; values are
7
+ * the runtime's output history. A client that resends exactly what it was
8
+ * shown finds its entry. A client that changed anything does not, and is
9
+ * handled by the operator's `onUnrecognized` policy.
10
+ */
11
+ import { createHash } from "node:crypto";
12
+ import { canonicalJson } from "@clearideas/agent-runtime-core";
13
+ const LEDGER_NAMESPACE = "ledger:v1";
14
+ const normalizeText = (text) => text.replace(/\r\n?/gu, "\n").replace(/[ \t\n]+$/u, "");
15
+ const projectPart = (part) => {
16
+ switch (part.type) {
17
+ case "text": {
18
+ const text = normalizeText(part.text);
19
+ return text ? { text } : undefined;
20
+ }
21
+ case "json":
22
+ return { json: part.value };
23
+ case "image":
24
+ case "file":
25
+ return {
26
+ media: part.type,
27
+ source: part.artifact?.sha256
28
+ ? `sha256:${part.artifact.sha256}`
29
+ : part.url
30
+ ? `url:${part.url}`
31
+ : `ref:${part.artifact?.id ?? ""}`,
32
+ };
33
+ }
34
+ };
35
+ /**
36
+ * The client-visible form of a conversation: roles, normalized text, and
37
+ * media by content. With `user-turns`, assistant text is ignored, so a
38
+ * client that rewrites replies still matches.
39
+ */
40
+ export const projectConversation = (messages, match) => messages.map((message) => ({
41
+ role: message.role,
42
+ parts: match === "user-turns" && message.role === "assistant"
43
+ ? []
44
+ : message.content.flatMap((part) => {
45
+ const projected = projectPart(part);
46
+ return projected ? [projected] : [];
47
+ }),
48
+ }));
49
+ export const ledgerKey = (input) => createHash("sha256")
50
+ .update(canonicalJson({
51
+ version: 1,
52
+ scope: input.scope,
53
+ model: input.model,
54
+ match: input.match,
55
+ conversation: projectConversation(input.messages, input.match),
56
+ }))
57
+ .digest("hex");
58
+ export class ConversationLedger {
59
+ #store;
60
+ #ttlMs;
61
+ #match;
62
+ constructor(store, options) {
63
+ this.#store = store;
64
+ this.#ttlMs = options.ttlMs;
65
+ this.#match = options.match;
66
+ }
67
+ /** Remove a bounded batch of expired entries, including unread histories. */
68
+ async sweepExpired(limit = 1_000) {
69
+ return (await this.#store.takeExpired(LEDGER_NAMESPACE, limit)).length;
70
+ }
71
+ get match() {
72
+ return this.#match;
73
+ }
74
+ /** The runtime history issued for this client-visible conversation, if any. */
75
+ async lookup(input) {
76
+ const value = await this.#store.get(LEDGER_NAMESPACE, ledgerKey({ ...input, match: this.#match }));
77
+ if (!value)
78
+ return undefined;
79
+ const entry = JSON.parse(value);
80
+ // Defence in depth: the scope is part of the key, and must also match.
81
+ return entry.scope === input.scope && entry.model === input.model
82
+ ? entry
83
+ : undefined;
84
+ }
85
+ /** Record the history issued after the client-visible conversation `messages`. */
86
+ async record(input) {
87
+ await this.#store.set(LEDGER_NAMESPACE, ledgerKey({
88
+ scope: input.entry.scope,
89
+ model: input.entry.model,
90
+ match: this.#match,
91
+ messages: input.messages,
92
+ }), JSON.stringify(input.entry), this.#ttlMs);
93
+ }
94
+ }
@@ -0,0 +1,37 @@
1
+ import type { ArtifactRef, ConversationContentPart } from "@clearideas/agent-runtime-contracts";
2
+ import type { ArtifactStore } from "@clearideas/agent-runtime-core";
3
+ import type { KeyValueStore } from "./kv.js";
4
+ export interface MediaPolicy {
5
+ /** Largest decoded inline part, in bytes. */
6
+ maxInlineBytes: number;
7
+ urls: "reject" | "allow";
8
+ /** Origins such as https://images.example.com that `allow` admits. */
9
+ allowOrigins: readonly string[];
10
+ /** How long an index entry lives after its last use. */
11
+ ttlMs: number;
12
+ }
13
+ interface DecodedDataUrl {
14
+ mediaType: string;
15
+ bytes: Buffer;
16
+ }
17
+ export declare const parseDataUrl: (value: string) => DecodedDataUrl | undefined;
18
+ export declare class MediaIngestor {
19
+ #private;
20
+ constructor(index: KeyValueStore, policy: MediaPolicy);
21
+ /** Remove a bounded batch of expired entries, including unread histories. */
22
+ sweepExpired(limit?: number): Promise<number>;
23
+ /** A message part for an image or file given as a data URL or a URL. */
24
+ part(input: {
25
+ kind: "image" | "file";
26
+ source: string;
27
+ name?: string;
28
+ scope: string;
29
+ artifacts: ArtifactStore;
30
+ }): Promise<ConversationContentPart>;
31
+ /**
32
+ * The runtime's `authorizeArtifact`: accept exactly the references this
33
+ * server minted for the scope. Every other reference is refused.
34
+ */
35
+ authorize(ref: ArtifactRef, scope: string | undefined): Promise<boolean>;
36
+ }
37
+ export {};
package/dist/media.js ADDED
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Media from chat requests. Inline images and files are stored once per
3
+ * scope, addressed by content: the same bytes always map to the same
4
+ * artifact reference, so media a client resends every turn is stored once.
5
+ * The runtime receives references, never bytes, and accepts only the
6
+ * references this server minted for the request's scope.
7
+ */
8
+ import { createHash } from "node:crypto";
9
+ import { invalidRequest, ServerError } from "./errors.js";
10
+ const MEDIA_NAMESPACE = "media:v1";
11
+ const EXTENSIONS = {
12
+ "image/png": "png",
13
+ "image/jpeg": "jpg",
14
+ "image/gif": "gif",
15
+ "image/webp": "webp",
16
+ "application/pdf": "pdf",
17
+ };
18
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/u;
19
+ export const parseDataUrl = (value) => {
20
+ const match = /^data:([^;,]+)((?:;[^;,]+)*),(.*)$/su.exec(value);
21
+ if (!match)
22
+ return undefined;
23
+ const parameters = match[2].split(";").filter(Boolean);
24
+ if (!parameters.includes("base64")) {
25
+ throw invalidRequest("Inline media must be a base64 data URL.", "messages");
26
+ }
27
+ const payload = match[3].replace(/\s+/gu, "");
28
+ if (!BASE64.test(payload) || payload.length % 4 === 1) {
29
+ throw invalidRequest("Inline media is not valid base64.", "messages");
30
+ }
31
+ return {
32
+ mediaType: match[1].trim().toLowerCase(),
33
+ bytes: Buffer.from(payload, "base64"),
34
+ };
35
+ };
36
+ const indexKey = (scope, sha256, mediaType) => `${scope}\u0000content\u0000${sha256}\u0000${mediaType}`;
37
+ const mintKey = (scope, id) => `${scope}\u0000minted\u0000${id}`;
38
+ export class MediaIngestor {
39
+ #index;
40
+ #policy;
41
+ constructor(index, policy) {
42
+ this.#index = index;
43
+ this.#policy = policy;
44
+ }
45
+ /** Remove a bounded batch of expired entries, including unread histories. */
46
+ async sweepExpired(limit = 1_000) {
47
+ return (await this.#index.takeExpired(MEDIA_NAMESPACE, limit)).length;
48
+ }
49
+ /** A message part for an image or file given as a data URL or a URL. */
50
+ async part(input) {
51
+ const decoded = parseDataUrl(input.source);
52
+ if (decoded) {
53
+ const artifact = await this.#ingest({ ...input, decoded });
54
+ return input.kind === "image"
55
+ ? { type: "image", artifact }
56
+ : {
57
+ type: "file",
58
+ artifact,
59
+ ...(input.name ? { name: input.name } : {}),
60
+ };
61
+ }
62
+ this.#checkUrl(input.source);
63
+ return input.kind === "image"
64
+ ? { type: "image", url: input.source }
65
+ : {
66
+ type: "file",
67
+ url: input.source,
68
+ ...(input.name ? { name: input.name } : {}),
69
+ };
70
+ }
71
+ #checkUrl(source) {
72
+ let url;
73
+ try {
74
+ url = new URL(source);
75
+ }
76
+ catch {
77
+ throw invalidRequest("Media must be a data URL or an https URL.", "messages");
78
+ }
79
+ const allowed = this.#policy.urls === "allow" &&
80
+ (url.protocol === "https:" || url.protocol === "http:") &&
81
+ this.#policy.allowOrigins.some((origin) => new URL(origin).origin === url.origin);
82
+ if (!allowed) {
83
+ throw invalidRequest("Media URLs are not accepted by this server. Send the image or file inline as a base64 data URL.", "messages");
84
+ }
85
+ }
86
+ async #ingest(input) {
87
+ const { bytes, mediaType } = input.decoded;
88
+ if (bytes.byteLength > this.#policy.maxInlineBytes) {
89
+ throw new ServerError(413, "context_length_exceeded", `Inline media is ${bytes.byteLength} bytes, exceeding the limit of ${this.#policy.maxInlineBytes}.`, { type: "invalid_request_error", param: "messages" });
90
+ }
91
+ if (input.kind === "image" && !mediaType.startsWith("image/")) {
92
+ throw invalidRequest(`An image part must carry an image media type, not ${mediaType}.`, "messages");
93
+ }
94
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
95
+ const key = indexKey(input.scope, sha256, mediaType);
96
+ const existing = await this.#index.get(MEDIA_NAMESPACE, key);
97
+ if (existing) {
98
+ const ref = JSON.parse(existing);
99
+ await this.#remember(input.scope, key, ref);
100
+ return ref;
101
+ }
102
+ const extension = EXTENSIONS[mediaType];
103
+ const name = input.name ??
104
+ `${input.kind}-${sha256.slice(0, 12)}${extension ? `.${extension}` : ""}`;
105
+ const stored = await input.artifacts.put({
106
+ name,
107
+ mediaType,
108
+ data: new Uint8Array(bytes),
109
+ metadata: { source: "chat-request" },
110
+ });
111
+ // History media must carry sha256; stores that omit it get ours, which
112
+ // matches the stored bytes.
113
+ const ref = { ...stored, sha256: stored.sha256 ?? sha256 };
114
+ await this.#remember(input.scope, key, ref);
115
+ return ref;
116
+ }
117
+ /** Record (or refresh) a minted reference under its content and its id. */
118
+ async #remember(scope, key, ref) {
119
+ const value = JSON.stringify(ref);
120
+ await this.#index.set(MEDIA_NAMESPACE, key, value, this.#policy.ttlMs);
121
+ await this.#index.set(MEDIA_NAMESPACE, mintKey(scope, ref.id), value, this.#policy.ttlMs);
122
+ }
123
+ /**
124
+ * The runtime's `authorizeArtifact`: accept exactly the references this
125
+ * server minted for the scope. Every other reference is refused.
126
+ */
127
+ async authorize(ref, scope) {
128
+ if (!scope)
129
+ return false;
130
+ const minted = await this.#index.get(MEDIA_NAMESPACE, mintKey(scope, ref.id));
131
+ if (!minted)
132
+ return false;
133
+ const known = JSON.parse(minted);
134
+ return known.sha256 === ref.sha256 && known.mediaType === ref.mediaType;
135
+ }
136
+ }