@kernl-sdk/libsql 0.1.36 → 0.1.39
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/.turbo/turbo-build.log +5 -4
- package/CHANGELOG.md +20 -0
- package/README.md +225 -0
- package/dist/__tests__/constraints.test.d.ts +2 -0
- package/dist/__tests__/constraints.test.d.ts.map +1 -0
- package/dist/__tests__/constraints.test.js +97 -0
- package/dist/__tests__/helpers.d.ts +36 -0
- package/dist/__tests__/helpers.d.ts.map +1 -0
- package/dist/__tests__/helpers.js +80 -0
- package/dist/__tests__/memory.create-get.test.d.ts +2 -0
- package/dist/__tests__/memory.create-get.test.d.ts.map +1 -0
- package/dist/__tests__/memory.create-get.test.js +8 -0
- package/dist/__tests__/memory.delete.test.d.ts +2 -0
- package/dist/__tests__/memory.delete.test.d.ts.map +1 -0
- package/dist/__tests__/memory.delete.test.js +6 -0
- package/dist/__tests__/memory.list.test.d.ts +2 -0
- package/dist/__tests__/memory.list.test.d.ts.map +1 -0
- package/dist/__tests__/memory.list.test.js +8 -0
- package/dist/__tests__/memory.update.test.d.ts +2 -0
- package/dist/__tests__/memory.update.test.d.ts.map +1 -0
- package/dist/__tests__/memory.update.test.js +8 -0
- package/dist/__tests__/migrations.test.d.ts +2 -0
- package/dist/__tests__/migrations.test.d.ts.map +1 -0
- package/dist/__tests__/migrations.test.js +68 -0
- package/dist/__tests__/row-codecs.test.d.ts +2 -0
- package/dist/__tests__/row-codecs.test.d.ts.map +1 -0
- package/dist/__tests__/row-codecs.test.js +175 -0
- package/dist/__tests__/sql-utils.test.d.ts +2 -0
- package/dist/__tests__/sql-utils.test.d.ts.map +1 -0
- package/dist/__tests__/sql-utils.test.js +45 -0
- package/dist/__tests__/storage.init.test.d.ts +2 -0
- package/dist/__tests__/storage.init.test.d.ts.map +1 -0
- package/dist/__tests__/storage.init.test.js +63 -0
- package/dist/__tests__/thread.lifecycle.test.d.ts +2 -0
- package/dist/__tests__/thread.lifecycle.test.d.ts.map +1 -0
- package/dist/__tests__/thread.lifecycle.test.js +172 -0
- package/dist/__tests__/transaction.test.d.ts +2 -0
- package/dist/__tests__/transaction.test.d.ts.map +1 -0
- package/dist/__tests__/transaction.test.js +16 -0
- package/dist/__tests__/utils.test.d.ts +2 -0
- package/dist/__tests__/utils.test.d.ts.map +1 -0
- package/dist/__tests__/utils.test.js +31 -0
- package/dist/client.d.ts +46 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +46 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/memory/__tests__/create-get.test.d.ts +2 -0
- package/dist/memory/__tests__/create-get.test.d.ts.map +1 -0
- package/dist/memory/__tests__/create-get.test.js +126 -0
- package/dist/memory/__tests__/delete.test.d.ts +2 -0
- package/dist/memory/__tests__/delete.test.d.ts.map +1 -0
- package/dist/memory/__tests__/delete.test.js +96 -0
- package/dist/memory/__tests__/list.test.d.ts +2 -0
- package/dist/memory/__tests__/list.test.d.ts.map +1 -0
- package/dist/memory/__tests__/list.test.js +168 -0
- package/dist/memory/__tests__/sql.test.d.ts +2 -0
- package/dist/memory/__tests__/sql.test.d.ts.map +1 -0
- package/dist/memory/__tests__/sql.test.js +159 -0
- package/dist/memory/__tests__/update.test.d.ts +2 -0
- package/dist/memory/__tests__/update.test.d.ts.map +1 -0
- package/dist/memory/__tests__/update.test.js +113 -0
- package/dist/memory/row.d.ts +11 -0
- package/dist/memory/row.d.ts.map +1 -0
- package/dist/memory/row.js +29 -0
- package/dist/memory/sql.d.ts +34 -0
- package/dist/memory/sql.d.ts.map +1 -0
- package/dist/memory/sql.js +109 -0
- package/dist/memory/store.d.ts +41 -0
- package/dist/memory/store.d.ts.map +1 -0
- package/dist/memory/store.js +132 -0
- package/dist/migrations.d.ts +32 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +157 -0
- package/dist/sql.d.ts +28 -0
- package/dist/sql.d.ts.map +1 -0
- package/dist/sql.js +22 -0
- package/dist/storage.d.ts +75 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +123 -0
- package/dist/thread/__tests__/append.test.d.ts +2 -0
- package/dist/thread/__tests__/append.test.d.ts.map +1 -0
- package/dist/thread/__tests__/append.test.js +141 -0
- package/dist/thread/__tests__/history.test.d.ts +2 -0
- package/dist/thread/__tests__/history.test.d.ts.map +1 -0
- package/dist/thread/__tests__/history.test.js +146 -0
- package/dist/thread/__tests__/sql.test.d.ts +2 -0
- package/dist/thread/__tests__/sql.test.d.ts.map +1 -0
- package/dist/thread/__tests__/sql.test.js +129 -0
- package/dist/thread/__tests__/store.test.d.ts +2 -0
- package/dist/thread/__tests__/store.test.d.ts.map +1 -0
- package/dist/thread/__tests__/store.test.js +170 -0
- package/dist/thread/row.d.ts +19 -0
- package/dist/thread/row.d.ts.map +1 -0
- package/dist/thread/row.js +65 -0
- package/dist/thread/sql.d.ts +33 -0
- package/dist/thread/sql.d.ts.map +1 -0
- package/dist/thread/sql.js +112 -0
- package/dist/thread/store.d.ts +67 -0
- package/dist/thread/store.d.ts.map +1 -0
- package/dist/thread/store.js +282 -0
- package/dist/utils.d.ts +10 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +21 -0
- package/package.json +15 -11
- package/src/__tests__/constraints.test.ts +123 -0
- package/src/__tests__/helpers.ts +98 -0
- package/src/__tests__/migrations.test.ts +114 -0
- package/src/__tests__/row-codecs.test.ts +201 -0
- package/src/__tests__/sql-utils.test.ts +52 -0
- package/src/__tests__/storage.init.test.ts +92 -0
- package/src/__tests__/thread.lifecycle.test.ts +234 -0
- package/src/__tests__/transaction.test.ts +25 -0
- package/src/__tests__/utils.test.ts +38 -0
- package/src/client.ts +71 -0
- package/src/index.ts +10 -0
- package/src/memory/__tests__/create-get.test.ts +161 -0
- package/src/memory/__tests__/delete.test.ts +124 -0
- package/src/memory/__tests__/list.test.ts +198 -0
- package/src/memory/__tests__/sql.test.ts +186 -0
- package/src/memory/__tests__/update.test.ts +148 -0
- package/src/memory/row.ts +36 -0
- package/src/memory/sql.ts +142 -0
- package/src/memory/store.ts +173 -0
- package/src/migrations.ts +206 -0
- package/src/sql.ts +35 -0
- package/src/storage.ts +170 -0
- package/src/thread/__tests__/append.test.ts +201 -0
- package/src/thread/__tests__/history.test.ts +198 -0
- package/src/thread/__tests__/sql.test.ts +154 -0
- package/src/thread/__tests__/store.test.ts +219 -0
- package/src/thread/row.ts +77 -0
- package/src/thread/sql.ts +153 -0
- package/src/thread/store.ts +381 -0
- package/src/utils.ts +20 -0
- package/LICENSE +0 -201
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thread SQL conversion codecs for LibSQL.
|
|
3
|
+
*
|
|
4
|
+
* Uses ? placeholders instead of PostgreSQL's $1, $2, etc.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { ThreadFilter, ThreadUpdate, SortOrder } from "kernl";
|
|
8
|
+
import type { Codec } from "@kernl-sdk/shared/lib";
|
|
9
|
+
|
|
10
|
+
import { type SQLClause, expandarray } from "../sql";
|
|
11
|
+
|
|
12
|
+
export interface WhereInput {
|
|
13
|
+
filter?: ThreadFilter;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Encode ThreadFilter to SQL WHERE clause with ? placeholders.
|
|
18
|
+
*/
|
|
19
|
+
export const SQL_WHERE: Codec<WhereInput, SQLClause> = {
|
|
20
|
+
encode({ filter }) {
|
|
21
|
+
if (!filter) {
|
|
22
|
+
return { sql: "", params: [] };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const conditions: string[] = [];
|
|
26
|
+
const params: unknown[] = [];
|
|
27
|
+
|
|
28
|
+
if (filter.namespace !== undefined) {
|
|
29
|
+
conditions.push(`namespace = ?`);
|
|
30
|
+
params.push(filter.namespace);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (filter.state !== undefined) {
|
|
34
|
+
if (Array.isArray(filter.state)) {
|
|
35
|
+
const { placeholders, params: stateParams } = expandarray(filter.state);
|
|
36
|
+
conditions.push(`state IN (${placeholders})`);
|
|
37
|
+
params.push(...stateParams);
|
|
38
|
+
} else {
|
|
39
|
+
conditions.push(`state = ?`);
|
|
40
|
+
params.push(filter.state);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (filter.agentId !== undefined) {
|
|
45
|
+
conditions.push(`agent_id = ?`);
|
|
46
|
+
params.push(filter.agentId);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (filter.parentTaskId !== undefined) {
|
|
50
|
+
conditions.push(`parent_task_id = ?`);
|
|
51
|
+
params.push(filter.parentTaskId);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (filter.createdAfter !== undefined) {
|
|
55
|
+
conditions.push(`created_at > ?`);
|
|
56
|
+
params.push(filter.createdAfter.getTime());
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (filter.createdBefore !== undefined) {
|
|
60
|
+
conditions.push(`created_at < ?`);
|
|
61
|
+
params.push(filter.createdBefore.getTime());
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
sql: conditions.length > 0 ? conditions.join(" AND ") : "",
|
|
66
|
+
params,
|
|
67
|
+
};
|
|
68
|
+
},
|
|
69
|
+
|
|
70
|
+
decode() {
|
|
71
|
+
throw new Error("SQL_WHERE.decode not implemented");
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export interface OrderInput {
|
|
76
|
+
order?: {
|
|
77
|
+
createdAt?: SortOrder;
|
|
78
|
+
updatedAt?: SortOrder;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Encode order options to SQL ORDER BY clause.
|
|
84
|
+
*/
|
|
85
|
+
export const SQL_ORDER: Codec<OrderInput, string> = {
|
|
86
|
+
encode({ order }) {
|
|
87
|
+
const clauses: string[] = [];
|
|
88
|
+
|
|
89
|
+
if (order?.createdAt) {
|
|
90
|
+
clauses.push(`created_at ${order.createdAt.toUpperCase()}`);
|
|
91
|
+
}
|
|
92
|
+
if (order?.updatedAt) {
|
|
93
|
+
clauses.push(`updated_at ${order.updatedAt.toUpperCase()}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (clauses.length === 0) {
|
|
97
|
+
return "created_at DESC";
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return clauses.join(", ");
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
decode() {
|
|
104
|
+
throw new Error("SQL_ORDER.decode not implemented");
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
export interface UpdateInput {
|
|
109
|
+
patch: ThreadUpdate;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Encode ThreadUpdate to SQL SET clause with ? placeholders.
|
|
114
|
+
*/
|
|
115
|
+
export const SQL_UPDATE: Codec<UpdateInput, SQLClause> = {
|
|
116
|
+
encode({ patch }) {
|
|
117
|
+
const sets: string[] = [];
|
|
118
|
+
const params: unknown[] = [];
|
|
119
|
+
|
|
120
|
+
if (patch.tick !== undefined) {
|
|
121
|
+
sets.push(`tick = ?`);
|
|
122
|
+
params.push(patch.tick);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (patch.state !== undefined) {
|
|
126
|
+
sets.push(`state = ?`);
|
|
127
|
+
params.push(patch.state);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (patch.context !== undefined) {
|
|
131
|
+
sets.push(`context = ?`);
|
|
132
|
+
params.push(JSON.stringify(patch.context.context));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (patch.metadata !== undefined) {
|
|
136
|
+
sets.push(`metadata = ?`);
|
|
137
|
+
params.push(patch.metadata ? JSON.stringify(patch.metadata) : null);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// always update updated_at
|
|
141
|
+
sets.push(`updated_at = ?`);
|
|
142
|
+
params.push(Date.now());
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
sql: sets.join(", "),
|
|
146
|
+
params,
|
|
147
|
+
};
|
|
148
|
+
},
|
|
149
|
+
|
|
150
|
+
decode() {
|
|
151
|
+
throw new Error("SQL_UPDATE.decode not implemented");
|
|
152
|
+
},
|
|
153
|
+
};
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LibSQL Thread store implementation.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import assert from "assert";
|
|
6
|
+
import type { Client, InValue } from "@libsql/client";
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
Agent,
|
|
10
|
+
Context,
|
|
11
|
+
type IAgentRegistry,
|
|
12
|
+
type IModelRegistry,
|
|
13
|
+
type ThreadStore,
|
|
14
|
+
type NewThread,
|
|
15
|
+
type ThreadUpdate,
|
|
16
|
+
type ThreadInclude,
|
|
17
|
+
type ThreadListOptions,
|
|
18
|
+
type ThreadHistoryOptions,
|
|
19
|
+
} from "kernl";
|
|
20
|
+
import { Thread, type ThreadEvent } from "kernl/internal";
|
|
21
|
+
import {
|
|
22
|
+
KERNL_SCHEMA_NAME,
|
|
23
|
+
NewThreadCodec,
|
|
24
|
+
ThreadEventRecordCodec,
|
|
25
|
+
type ThreadRecord,
|
|
26
|
+
} from "@kernl-sdk/storage";
|
|
27
|
+
|
|
28
|
+
import { SQL_WHERE, SQL_ORDER, SQL_UPDATE } from "./sql";
|
|
29
|
+
import {
|
|
30
|
+
RowToThreadRecord,
|
|
31
|
+
RowToEventRecord,
|
|
32
|
+
RowToEventRecordDirect,
|
|
33
|
+
} from "./row";
|
|
34
|
+
import { expandarray } from "../sql";
|
|
35
|
+
|
|
36
|
+
// SQLite doesn't support schemas, so we use table name prefix
|
|
37
|
+
const THREADS_TABLE = `${KERNL_SCHEMA_NAME}_threads`;
|
|
38
|
+
const THREAD_EVENTS_TABLE = `${KERNL_SCHEMA_NAME}_thread_events`;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* LibSQL Thread store implementation.
|
|
42
|
+
*
|
|
43
|
+
* All async methods call `ensureInit()` before database operations
|
|
44
|
+
* to ensure schema/tables exist.
|
|
45
|
+
*/
|
|
46
|
+
export class LibSQLThreadStore implements ThreadStore {
|
|
47
|
+
private db: Client;
|
|
48
|
+
private registries: { agents: IAgentRegistry; models: IModelRegistry } | null;
|
|
49
|
+
private ensureInit: () => Promise<void>;
|
|
50
|
+
|
|
51
|
+
constructor(db: Client, ensureInit: () => Promise<void>) {
|
|
52
|
+
this.db = db;
|
|
53
|
+
this.ensureInit = ensureInit;
|
|
54
|
+
this.registries = null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Bind runtime registries for hydrating Thread instances.
|
|
59
|
+
*/
|
|
60
|
+
bind(registries: { agents: IAgentRegistry; models: IModelRegistry }): void {
|
|
61
|
+
this.registries = registries;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Get a thread by id.
|
|
66
|
+
*/
|
|
67
|
+
async get(tid: string, include?: ThreadInclude): Promise<Thread | null> {
|
|
68
|
+
await this.ensureInit();
|
|
69
|
+
|
|
70
|
+
// JOIN with thread_events if include.history
|
|
71
|
+
if (include?.history) {
|
|
72
|
+
const opts =
|
|
73
|
+
typeof include.history === "object" ? include.history : undefined;
|
|
74
|
+
|
|
75
|
+
const params: InValue[] = [tid];
|
|
76
|
+
let eventFilter = "";
|
|
77
|
+
|
|
78
|
+
if (opts?.after !== undefined) {
|
|
79
|
+
eventFilter += ` AND e.seq > ?`;
|
|
80
|
+
params.push(opts.after);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (opts?.kinds && opts.kinds.length > 0) {
|
|
84
|
+
const { placeholders, params: kindParams } = expandarray(opts.kinds);
|
|
85
|
+
eventFilter += ` AND e.kind IN (${placeholders})`;
|
|
86
|
+
params.push(...(kindParams as InValue[]));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const order = opts?.order ?? "asc";
|
|
90
|
+
const limit = opts?.limit ? ` LIMIT ${opts.limit}` : "";
|
|
91
|
+
|
|
92
|
+
const query = `
|
|
93
|
+
SELECT
|
|
94
|
+
t.*,
|
|
95
|
+
e.id as event_id,
|
|
96
|
+
e.tid as event_tid,
|
|
97
|
+
e.seq,
|
|
98
|
+
e.kind as event_kind,
|
|
99
|
+
e.timestamp,
|
|
100
|
+
e.data,
|
|
101
|
+
e.metadata as event_metadata
|
|
102
|
+
FROM ${THREADS_TABLE} t
|
|
103
|
+
LEFT JOIN ${THREAD_EVENTS_TABLE} e ON t.id = e.tid${eventFilter}
|
|
104
|
+
WHERE t.id = ?
|
|
105
|
+
ORDER BY e.seq ${order.toUpperCase()}
|
|
106
|
+
${limit}
|
|
107
|
+
`;
|
|
108
|
+
|
|
109
|
+
// Move tid to end of params (WHERE t.id = ?)
|
|
110
|
+
const finalParams = [...params.slice(1), tid];
|
|
111
|
+
|
|
112
|
+
const result = await this.db.execute({ sql: query, args: finalParams });
|
|
113
|
+
|
|
114
|
+
if (result.rows.length === 0) {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// first row has thread data (all rows have same thread data)
|
|
119
|
+
const record = RowToThreadRecord.encode(result.rows[0]);
|
|
120
|
+
|
|
121
|
+
// collect events from all rows (skip rows where event_id is null)
|
|
122
|
+
const events: ThreadEvent[] = result.rows
|
|
123
|
+
.filter((row) => row.event_id !== null)
|
|
124
|
+
.map((row) =>
|
|
125
|
+
ThreadEventRecordCodec.decode(RowToEventRecord.encode(row)),
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
try {
|
|
129
|
+
return this.hydrate({ record, events });
|
|
130
|
+
} catch {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// simple query without events
|
|
136
|
+
const result = await this.db.execute({
|
|
137
|
+
sql: `SELECT * FROM ${THREADS_TABLE} WHERE id = ?`,
|
|
138
|
+
args: [tid],
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
if (result.rows.length === 0) {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
try {
|
|
146
|
+
return this.hydrate({ record: RowToThreadRecord.encode(result.rows[0]) });
|
|
147
|
+
} catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* List threads matching the filter.
|
|
154
|
+
*/
|
|
155
|
+
async list(options?: ThreadListOptions): Promise<Thread[]> {
|
|
156
|
+
await this.ensureInit();
|
|
157
|
+
|
|
158
|
+
const { sql: where, params } = SQL_WHERE.encode({
|
|
159
|
+
filter: options?.filter,
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
let query = `SELECT * FROM ${THREADS_TABLE}`;
|
|
163
|
+
|
|
164
|
+
if (where) query += ` WHERE ${where}`;
|
|
165
|
+
query += ` ORDER BY ${SQL_ORDER.encode({ order: options?.order })}`;
|
|
166
|
+
|
|
167
|
+
const args = [...params] as InValue[];
|
|
168
|
+
|
|
169
|
+
if (options?.limit) {
|
|
170
|
+
query += ` LIMIT ?`;
|
|
171
|
+
args.push(options.limit);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (options?.offset) {
|
|
175
|
+
query += ` OFFSET ?`;
|
|
176
|
+
args.push(options.offset);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const result = await this.db.execute({ sql: query, args });
|
|
180
|
+
|
|
181
|
+
return result.rows
|
|
182
|
+
.map((row) => {
|
|
183
|
+
try {
|
|
184
|
+
return this.hydrate({ record: RowToThreadRecord.encode(row) });
|
|
185
|
+
} catch {
|
|
186
|
+
// Skip threads with non-existent agent/model (graceful degradation)
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
})
|
|
190
|
+
.filter((thread) => thread !== null);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Insert a new thread into the store.
|
|
195
|
+
*/
|
|
196
|
+
async insert(thread: NewThread): Promise<Thread> {
|
|
197
|
+
await this.ensureInit();
|
|
198
|
+
|
|
199
|
+
const record = NewThreadCodec.encode(thread);
|
|
200
|
+
|
|
201
|
+
const result = await this.db.execute({
|
|
202
|
+
sql: `INSERT INTO ${THREADS_TABLE}
|
|
203
|
+
(id, namespace, agent_id, model, context, tick, state, parent_task_id, metadata, created_at, updated_at)
|
|
204
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
205
|
+
RETURNING *`,
|
|
206
|
+
args: [
|
|
207
|
+
record.id,
|
|
208
|
+
record.namespace,
|
|
209
|
+
record.agent_id,
|
|
210
|
+
record.model,
|
|
211
|
+
JSON.stringify(record.context),
|
|
212
|
+
record.tick,
|
|
213
|
+
record.state,
|
|
214
|
+
record.parent_task_id,
|
|
215
|
+
record.metadata ? JSON.stringify(record.metadata) : null,
|
|
216
|
+
record.created_at,
|
|
217
|
+
record.updated_at,
|
|
218
|
+
],
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
return this.hydrate({ record: RowToThreadRecord.encode(result.rows[0]) });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Update thread runtime state.
|
|
226
|
+
*/
|
|
227
|
+
async update(tid: string, patch: ThreadUpdate): Promise<Thread> {
|
|
228
|
+
await this.ensureInit();
|
|
229
|
+
|
|
230
|
+
const { sql: updates, params } = SQL_UPDATE.encode({ patch });
|
|
231
|
+
const args = [...params, tid] as InValue[];
|
|
232
|
+
|
|
233
|
+
const result = await this.db.execute({
|
|
234
|
+
sql: `UPDATE ${THREADS_TABLE}
|
|
235
|
+
SET ${updates}
|
|
236
|
+
WHERE id = ?
|
|
237
|
+
RETURNING *`,
|
|
238
|
+
args,
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
return this.hydrate({ record: RowToThreadRecord.encode(result.rows[0]) });
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Delete a thread and cascade to thread_events.
|
|
246
|
+
*/
|
|
247
|
+
async delete(tid: string): Promise<void> {
|
|
248
|
+
await this.ensureInit();
|
|
249
|
+
await this.db.execute({
|
|
250
|
+
sql: `DELETE FROM ${THREADS_TABLE} WHERE id = ?`,
|
|
251
|
+
args: [tid],
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Get the event history for a thread.
|
|
257
|
+
*/
|
|
258
|
+
async history(
|
|
259
|
+
tid: string,
|
|
260
|
+
opts?: ThreadHistoryOptions,
|
|
261
|
+
): Promise<ThreadEvent[]> {
|
|
262
|
+
await this.ensureInit();
|
|
263
|
+
|
|
264
|
+
let query = `SELECT * FROM ${THREAD_EVENTS_TABLE} WHERE tid = ?`;
|
|
265
|
+
const args: InValue[] = [tid];
|
|
266
|
+
|
|
267
|
+
// - filter:seq -
|
|
268
|
+
if (opts?.after !== undefined) {
|
|
269
|
+
query += ` AND seq > ?`;
|
|
270
|
+
args.push(opts.after);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// - filter:kind -
|
|
274
|
+
if (opts?.kinds && opts.kinds.length > 0) {
|
|
275
|
+
const { placeholders, params: kindParams } = expandarray(opts.kinds);
|
|
276
|
+
query += ` AND kind IN (${placeholders})`;
|
|
277
|
+
args.push(...(kindParams as InValue[]));
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// - order -
|
|
281
|
+
const order = opts?.order ?? "asc";
|
|
282
|
+
query += ` ORDER BY seq ${order.toUpperCase()}`;
|
|
283
|
+
|
|
284
|
+
// - limit -
|
|
285
|
+
if (opts?.limit !== undefined) {
|
|
286
|
+
query += ` LIMIT ?`;
|
|
287
|
+
args.push(opts.limit);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const result = await this.db.execute({ sql: query, args });
|
|
291
|
+
|
|
292
|
+
return result.rows.map((row) =>
|
|
293
|
+
ThreadEventRecordCodec.decode(RowToEventRecordDirect.encode(row)),
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Append events to the thread history.
|
|
299
|
+
*
|
|
300
|
+
* Semantics:
|
|
301
|
+
* - Guaranteed per-thread ordering via monotonically increasing `seq`
|
|
302
|
+
* - Idempotent on `(tid, event.id)`: duplicate ids MUST NOT create duplicate rows
|
|
303
|
+
* - Events maintain insertion order
|
|
304
|
+
*/
|
|
305
|
+
async append(events: ThreadEvent[]): Promise<void> {
|
|
306
|
+
if (events.length === 0) return;
|
|
307
|
+
await this.ensureInit();
|
|
308
|
+
|
|
309
|
+
const records = events.map((e) => ThreadEventRecordCodec.encode(e));
|
|
310
|
+
|
|
311
|
+
const placeholders: string[] = [];
|
|
312
|
+
const values: InValue[] = [];
|
|
313
|
+
|
|
314
|
+
for (const record of records) {
|
|
315
|
+
placeholders.push(`(?, ?, ?, ?, ?, ?, ?)`);
|
|
316
|
+
values.push(
|
|
317
|
+
record.id,
|
|
318
|
+
record.tid,
|
|
319
|
+
record.seq,
|
|
320
|
+
record.kind,
|
|
321
|
+
record.timestamp,
|
|
322
|
+
record.data ? JSON.stringify(record.data) : null,
|
|
323
|
+
record.metadata ? JSON.stringify(record.metadata) : null,
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// insert with ON CONFLICT DO NOTHING for idempotency
|
|
328
|
+
await this.db.execute({
|
|
329
|
+
sql: `INSERT INTO ${THREAD_EVENTS_TABLE}
|
|
330
|
+
(id, tid, seq, kind, timestamp, data, metadata)
|
|
331
|
+
VALUES ${placeholders.join(", ")}
|
|
332
|
+
ON CONFLICT (tid, id) DO NOTHING`,
|
|
333
|
+
args: values,
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Hydrate a Thread instance from a database record.
|
|
339
|
+
*/
|
|
340
|
+
hydrate(thread: { record: ThreadRecord; events?: ThreadEvent[] }): Thread {
|
|
341
|
+
assert(
|
|
342
|
+
this.registries,
|
|
343
|
+
"registries should be bound to storage in Kernl constructor",
|
|
344
|
+
);
|
|
345
|
+
|
|
346
|
+
const { record, events = [] } = thread;
|
|
347
|
+
|
|
348
|
+
const agent = this.registries.agents.get(record.agent_id);
|
|
349
|
+
const model = this.registries.models.get(record.model);
|
|
350
|
+
|
|
351
|
+
if (!agent || !model) {
|
|
352
|
+
throw new Error(
|
|
353
|
+
`Thread ${record.id} references non-existent agent/model (agent: ${record.agent_id}, model: ${record.model})`,
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// safety: threads only exist for llm agents
|
|
358
|
+
if (agent.kind !== "llm") {
|
|
359
|
+
throw new Error(
|
|
360
|
+
`Thread ${record.id} references non-llm agent ${record.agent_id} (kind: ${agent.kind})`,
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return new Thread({
|
|
365
|
+
agent: agent as Agent,
|
|
366
|
+
history: events,
|
|
367
|
+
context: new Context(record.namespace, record.context),
|
|
368
|
+
model,
|
|
369
|
+
task: null, // TODO: load from TaskStore when it exists
|
|
370
|
+
tid: record.id,
|
|
371
|
+
namespace: record.namespace,
|
|
372
|
+
tick: record.tick,
|
|
373
|
+
state: record.state,
|
|
374
|
+
metadata: record.metadata,
|
|
375
|
+
createdAt: new Date(Number(record.created_at)),
|
|
376
|
+
updatedAt: new Date(Number(record.updated_at)),
|
|
377
|
+
storage: this, // pass storage reference so resumed thread can persist
|
|
378
|
+
persisted: true,
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
}
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared utilities for LibSQL storage.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Parse a JSON string from SQLite into an object.
|
|
7
|
+
*
|
|
8
|
+
* SQLite stores JSON as TEXT, so we need to parse it back.
|
|
9
|
+
*/
|
|
10
|
+
export function parsejson<T>(value: unknown): T | null {
|
|
11
|
+
if (value === null || value === undefined) return null;
|
|
12
|
+
if (typeof value === "string") {
|
|
13
|
+
try {
|
|
14
|
+
return JSON.parse(value) as T;
|
|
15
|
+
} catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return value as T;
|
|
20
|
+
}
|