@axiom-lattice/local-stores 5.2.4 → 5.4.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/.turbo/turbo-build.log +10 -10
- package/CHANGELOG.md +54 -0
- package/dist/index.d.mts +25 -3
- package/dist/index.d.ts +25 -3
- package/dist/index.js +245 -54
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +196 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
- package/src/__tests__/LocalOpenAuditStore.test.ts +43 -0
- package/src/__tests__/LocalSessionStore.test.ts +53 -0
- package/src/__tests__/LocalThreadMessageQueueStore.monitor.test.ts +31 -0
- package/src/__tests__/LocalThreadStore.monitor.test.ts +29 -0
- package/src/index.ts +1 -0
- package/src/stores/LocalAssistantStore.ts +1 -1
- package/src/stores/LocalOpenAuditStore.ts +30 -1
- package/src/stores/LocalSessionStore.ts +169 -0
- package/src/stores/LocalThreadMessageQueueStore.ts +3 -2
- package/src/stores/LocalThreadStore.ts +47 -4
- package/src/stores/LocalUserStore.ts +10 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@axiom-lattice/local-stores",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.4.0",
|
|
4
4
|
"description": "Local SQLite-based stores for Axiom Lattice framework",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -25,8 +25,8 @@
|
|
|
25
25
|
"@types/sql.js": "^1.4.11",
|
|
26
26
|
"sql.js": "^1.14.1",
|
|
27
27
|
"uuid": "^14.0.1",
|
|
28
|
-
"@axiom-lattice/core": "13.0
|
|
29
|
-
"@axiom-lattice/protocols": "7.
|
|
28
|
+
"@axiom-lattice/core": "13.2.0",
|
|
29
|
+
"@axiom-lattice/protocols": "7.8.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"@types/jest": "^29.5.14",
|
|
@@ -114,3 +114,46 @@ describe("LocalOpenAuditStore.query", () => {
|
|
|
114
114
|
expect(limited).toHaveLength(1);
|
|
115
115
|
});
|
|
116
116
|
});
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
describe("LocalOpenAuditStore.get and filters", () => {
|
|
120
|
+
let store: LocalOpenAuditStore;
|
|
121
|
+
let db: DatabaseWrapper;
|
|
122
|
+
|
|
123
|
+
beforeEach(async () => {
|
|
124
|
+
db = await initDatabase({ dbPath: nextDbPath() });
|
|
125
|
+
store = new LocalOpenAuditStore(db);
|
|
126
|
+
await store.append({
|
|
127
|
+
tenantId: "t1",
|
|
128
|
+
credentialId: "k1",
|
|
129
|
+
credentialKind: "api_key",
|
|
130
|
+
projectId: "p1",
|
|
131
|
+
domain: "sandbox",
|
|
132
|
+
action: "shell_exec",
|
|
133
|
+
args: {},
|
|
134
|
+
status: "cancelled",
|
|
135
|
+
durationMs: 1,
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
afterEach(() => closeDatabase());
|
|
140
|
+
|
|
141
|
+
it("gets a record by tenant and id and rejects another tenant", async () => {
|
|
142
|
+
const [row] = await store.query({ tenantId: "t1" });
|
|
143
|
+
expect(await store.get("t1", row.id)).toMatchObject({
|
|
144
|
+
id: row.id,
|
|
145
|
+
status: "cancelled",
|
|
146
|
+
});
|
|
147
|
+
expect(await store.get("t2", row.id)).toBeNull();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("filters by project, action and cancelled status", async () => {
|
|
151
|
+
const rows = await store.query({
|
|
152
|
+
tenantId: "t1",
|
|
153
|
+
projectId: "p1",
|
|
154
|
+
action: "shell_exec",
|
|
155
|
+
status: "cancelled",
|
|
156
|
+
});
|
|
157
|
+
expect(rows).toHaveLength(1);
|
|
158
|
+
});
|
|
159
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from "@jest/globals";
|
|
2
|
+
import { existsSync, unlinkSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { closeDatabase, initDatabase } from "../database";
|
|
6
|
+
import { LocalSessionStore } from "../stores/LocalSessionStore";
|
|
7
|
+
import type { SessionRecord } from "@axiom-lattice/protocols";
|
|
8
|
+
|
|
9
|
+
const dbPath = path.join(tmpdir(), `lt-session-${Date.now()}.db`);
|
|
10
|
+
const now = new Date("2026-01-01T00:00:00Z");
|
|
11
|
+
|
|
12
|
+
function record(overrides: Partial<SessionRecord> = {}): SessionRecord {
|
|
13
|
+
return {
|
|
14
|
+
id: "s1",
|
|
15
|
+
familyId: "f1",
|
|
16
|
+
userId: "u1",
|
|
17
|
+
authEpoch: "e1",
|
|
18
|
+
refreshTokenHash: "h1",
|
|
19
|
+
createdAt: now,
|
|
20
|
+
lastUsedAt: now,
|
|
21
|
+
idleExpiresAt: new Date(now.getTime() + 1000),
|
|
22
|
+
absoluteExpiresAt: new Date(now.getTime() + 2000),
|
|
23
|
+
providerId: "local",
|
|
24
|
+
...overrides,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
afterEach(() => {
|
|
29
|
+
closeDatabase();
|
|
30
|
+
if (existsSync(dbPath)) unlinkSync(dbPath);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe("LocalSessionStore", () => {
|
|
34
|
+
it("rotates and revokes a family", async () => {
|
|
35
|
+
const store = new LocalSessionStore(await initDatabase({ dbPath }));
|
|
36
|
+
await store.create(record());
|
|
37
|
+
expect(await store.findByRefreshTokenHash("h1")).toMatchObject({ id: "s1" });
|
|
38
|
+
|
|
39
|
+
await store.rotate("s1", record({ id: "s2", refreshTokenHash: "h2", createdAt: new Date(now.getTime() + 10) }));
|
|
40
|
+
expect(await store.findByRefreshTokenHash("h1")).toMatchObject({ replacedBy: "s2" });
|
|
41
|
+
expect(await store.findByFamilyId("f1")).toMatchObject({ id: "s2" });
|
|
42
|
+
|
|
43
|
+
await store.revokeFamily("f1", "logout");
|
|
44
|
+
expect((await store.findByFamilyId("f1"))?.revokedAt).toBeInstanceOf(Date);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("round-trips the user auth epoch", async () => {
|
|
48
|
+
const store = new LocalSessionStore(await initDatabase({ dbPath }));
|
|
49
|
+
await store.create(record({ authEpoch: "epoch-1" }));
|
|
50
|
+
const row = await store.findByFamilyId("f1");
|
|
51
|
+
expect(row?.authEpoch).toBe("epoch-1");
|
|
52
|
+
});
|
|
53
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
import { tmpdir } from "os";
|
|
3
|
+
import { closeDatabase, initDatabase } from "../database";
|
|
4
|
+
import { LocalThreadMessageQueueStore } from "../stores/LocalThreadMessageQueueStore";
|
|
5
|
+
|
|
6
|
+
describe("LocalThreadMessageQueueStore tenant filter", () => {
|
|
7
|
+
it("filters pending threads by tenant when asked", async () => {
|
|
8
|
+
const dbPath = path.join(
|
|
9
|
+
tmpdir(),
|
|
10
|
+
`lt-queue-monitor-${Date.now()}-${Math.random().toString(36).slice(2)}.db`,
|
|
11
|
+
);
|
|
12
|
+
const db = await initDatabase({ dbPath });
|
|
13
|
+
const store = new LocalThreadMessageQueueStore(db);
|
|
14
|
+
await store.addMessage({
|
|
15
|
+
threadId: "thread-a",
|
|
16
|
+
tenantId: "tenant-a",
|
|
17
|
+
assistantId: "agent-1",
|
|
18
|
+
content: "a",
|
|
19
|
+
});
|
|
20
|
+
await store.addMessage({
|
|
21
|
+
threadId: "thread-b",
|
|
22
|
+
tenantId: "tenant-b",
|
|
23
|
+
assistantId: "agent-1",
|
|
24
|
+
content: "b",
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const rows = await store.getThreadsWithPendingMessages("tenant-a");
|
|
28
|
+
expect(rows.map((row) => row.threadId)).toEqual(["thread-a"]);
|
|
29
|
+
closeDatabase();
|
|
30
|
+
});
|
|
31
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
import { tmpdir } from "os";
|
|
3
|
+
import { closeDatabase, initDatabase } from "../database";
|
|
4
|
+
import { LocalThreadStore } from "../stores/LocalThreadStore";
|
|
5
|
+
|
|
6
|
+
describe("LocalThreadStore.listThreadsByTenant", () => {
|
|
7
|
+
it("lists the tenant's threads with kind filtering", async () => {
|
|
8
|
+
const dbPath = path.join(
|
|
9
|
+
tmpdir(),
|
|
10
|
+
`lt-threads-monitor-${Date.now()}-${Math.random().toString(36).slice(2)}.db`,
|
|
11
|
+
);
|
|
12
|
+
const db = await initDatabase({ dbPath });
|
|
13
|
+
const store = new LocalThreadStore(db);
|
|
14
|
+
await store.createThread("tenant-1", "agent-1", "t-chat", { metadata: {} });
|
|
15
|
+
await store.createThread("tenant-1", "agent-1", "t-room", {
|
|
16
|
+
metadata: { source: "project_room", kind: "room_presence" },
|
|
17
|
+
});
|
|
18
|
+
await store.createThread("tenant-2", "agent-1", "t-other", { metadata: {} });
|
|
19
|
+
|
|
20
|
+
const all = await store.listThreadsByTenant("tenant-1");
|
|
21
|
+
expect(all.total).toBe(2);
|
|
22
|
+
const rooms = await store.listThreadsByTenant("tenant-1", {
|
|
23
|
+
kind: "room_presence",
|
|
24
|
+
});
|
|
25
|
+
expect(rooms.records).toHaveLength(1);
|
|
26
|
+
expect(rooms.records[0].id).toBe("t-room");
|
|
27
|
+
closeDatabase();
|
|
28
|
+
});
|
|
29
|
+
});
|
package/src/index.ts
CHANGED
|
@@ -38,6 +38,7 @@ export { LocalProjectBotMembershipStore, ProjectBotMembershipIdConflictError } f
|
|
|
38
38
|
export { LocalProjectRoomMessageStore, ProjectRoomMessageIdConflictError, DuplicateProjectRoomMessageIdempotencyKeyError } from "./stores/LocalProjectRoomMessageStore";
|
|
39
39
|
export { LocalProjectRoomReadStateStore } from "./stores/LocalProjectRoomReadStateStore";
|
|
40
40
|
export { LocalUserStore } from "./stores/LocalUserStore";
|
|
41
|
+
export { LocalSessionStore } from "./stores/LocalSessionStore";
|
|
41
42
|
export { LocalTenantStore } from "./stores/LocalTenantStore";
|
|
42
43
|
export { LocalUserTenantLinkStore } from "./stores/LocalUserTenantLinkStore";
|
|
43
44
|
export { LocalUserExternalIdentityStore } from "./stores/LocalUserExternalIdentityStore";
|
|
@@ -146,7 +146,7 @@ export class LocalAssistantStore implements AssistantStore {
|
|
|
146
146
|
|
|
147
147
|
async getByOwner(tenantId: string, userId: string): Promise<Assistant | null> {
|
|
148
148
|
const row = this.db.prepare(
|
|
149
|
-
`SELECT * FROM lt_assistants WHERE tenant_id = ? AND owner_user_id = ? LIMIT 1`,
|
|
149
|
+
`SELECT * FROM lt_assistants WHERE tenant_id = ? AND owner_user_id = ? ORDER BY created_at ASC LIMIT 1`,
|
|
150
150
|
).get(tenantId, userId) as unknown as AssistantRow | undefined;
|
|
151
151
|
return row ? mapRowToAssistant(row) : null;
|
|
152
152
|
}
|
|
@@ -37,6 +37,27 @@ export class LocalOpenAuditStore implements OpenAuditStore {
|
|
|
37
37
|
ensureTable(db, DDL);
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
async get(tenantId: string, id: string): Promise<OpenAuditRecord | null> {
|
|
41
|
+
const row = this.db
|
|
42
|
+
.prepare("SELECT * FROM lt_open_audit WHERE tenant_id = ? AND id = ?")
|
|
43
|
+
.get(tenantId, id) as Record<string, unknown> | undefined;
|
|
44
|
+
if (!row) return null;
|
|
45
|
+
return {
|
|
46
|
+
id: row.id as string,
|
|
47
|
+
tenantId: row.tenant_id as string,
|
|
48
|
+
credentialId: row.credential_id as string,
|
|
49
|
+
credentialKind: row.credential_kind as OpenAuditRecord["credentialKind"],
|
|
50
|
+
projectId: row.project_id as string,
|
|
51
|
+
domain: row.domain as string,
|
|
52
|
+
action: row.action as string,
|
|
53
|
+
args: row.args ? JSON.parse(row.args as string) : undefined,
|
|
54
|
+
status: row.status as OpenAuditRecord["status"],
|
|
55
|
+
errorCode: (row.error_code as string) ?? undefined,
|
|
56
|
+
durationMs: row.duration_ms as number,
|
|
57
|
+
createdAt: parseISO(row.created_at as string),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
40
61
|
async query(params: OpenAuditQuery): Promise<OpenAuditRecord[]> {
|
|
41
62
|
const clauses = ["tenant_id = ?"];
|
|
42
63
|
const values: unknown[] = [params.tenantId];
|
|
@@ -44,10 +65,18 @@ export class LocalOpenAuditStore implements OpenAuditStore {
|
|
|
44
65
|
clauses.push("credential_id = ?");
|
|
45
66
|
values.push(params.credentialId);
|
|
46
67
|
}
|
|
68
|
+
if (params.projectId) {
|
|
69
|
+
clauses.push("project_id = ?");
|
|
70
|
+
values.push(params.projectId);
|
|
71
|
+
}
|
|
47
72
|
if (params.domain) {
|
|
48
73
|
clauses.push("domain = ?");
|
|
49
74
|
values.push(params.domain);
|
|
50
75
|
}
|
|
76
|
+
if (params.action) {
|
|
77
|
+
clauses.push("action = ?");
|
|
78
|
+
values.push(params.action);
|
|
79
|
+
}
|
|
51
80
|
if (params.status) {
|
|
52
81
|
clauses.push("status = ?");
|
|
53
82
|
values.push(params.status);
|
|
@@ -78,7 +107,7 @@ export class LocalOpenAuditStore implements OpenAuditStore {
|
|
|
78
107
|
domain: row.domain as string,
|
|
79
108
|
action: row.action as string,
|
|
80
109
|
args: row.args ? JSON.parse(row.args as string) : undefined,
|
|
81
|
-
status: row.status as "
|
|
110
|
+
status: row.status as OpenAuditRecord["status"],
|
|
82
111
|
errorCode: (row.error_code as string) ?? undefined,
|
|
83
112
|
durationMs: row.duration_ms as number,
|
|
84
113
|
createdAt: parseISO(row.created_at as string),
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local SQLite implementation of SessionStore.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { SessionRecord, SessionStore } from "@axiom-lattice/protocols";
|
|
6
|
+
import { DatabaseWrapper, ensureTable, nowISO, parseISO } from "../database";
|
|
7
|
+
|
|
8
|
+
const DDL = `
|
|
9
|
+
CREATE TABLE IF NOT EXISTS lt_sessions (
|
|
10
|
+
id TEXT PRIMARY KEY,
|
|
11
|
+
family_id TEXT NOT NULL,
|
|
12
|
+
user_id TEXT NOT NULL,
|
|
13
|
+
tenant_id TEXT,
|
|
14
|
+
auth_epoch TEXT NOT NULL DEFAULT '',
|
|
15
|
+
refresh_token_hash TEXT NOT NULL UNIQUE,
|
|
16
|
+
created_at TEXT NOT NULL,
|
|
17
|
+
last_used_at TEXT NOT NULL,
|
|
18
|
+
idle_expires_at TEXT NOT NULL,
|
|
19
|
+
absolute_expires_at TEXT NOT NULL,
|
|
20
|
+
revoked_at TEXT,
|
|
21
|
+
replaced_by TEXT,
|
|
22
|
+
ip TEXT,
|
|
23
|
+
user_agent TEXT,
|
|
24
|
+
provider_id TEXT NOT NULL,
|
|
25
|
+
idp_refresh_token_enc TEXT,
|
|
26
|
+
idp_refresh_expires_at TEXT
|
|
27
|
+
);
|
|
28
|
+
CREATE INDEX IF NOT EXISTS idx_lt_sessions_family ON lt_sessions(family_id);
|
|
29
|
+
CREATE INDEX IF NOT EXISTS idx_lt_sessions_user ON lt_sessions(user_id);
|
|
30
|
+
`;
|
|
31
|
+
|
|
32
|
+
interface SessionRow {
|
|
33
|
+
id: string;
|
|
34
|
+
family_id: string;
|
|
35
|
+
user_id: string;
|
|
36
|
+
tenant_id: string | null;
|
|
37
|
+
auth_epoch: string;
|
|
38
|
+
refresh_token_hash: string;
|
|
39
|
+
created_at: string;
|
|
40
|
+
last_used_at: string;
|
|
41
|
+
idle_expires_at: string;
|
|
42
|
+
absolute_expires_at: string;
|
|
43
|
+
revoked_at: string | null;
|
|
44
|
+
replaced_by: string | null;
|
|
45
|
+
ip: string | null;
|
|
46
|
+
user_agent: string | null;
|
|
47
|
+
provider_id: string;
|
|
48
|
+
idp_refresh_token_enc: string | null;
|
|
49
|
+
idp_refresh_expires_at: string | null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function mapRow(row: SessionRow): SessionRecord {
|
|
53
|
+
return {
|
|
54
|
+
id: row.id,
|
|
55
|
+
familyId: row.family_id,
|
|
56
|
+
userId: row.user_id,
|
|
57
|
+
...(row.tenant_id ? { tenantId: row.tenant_id } : {}),
|
|
58
|
+
authEpoch: row.auth_epoch,
|
|
59
|
+
refreshTokenHash: row.refresh_token_hash,
|
|
60
|
+
createdAt: parseISO(row.created_at),
|
|
61
|
+
lastUsedAt: parseISO(row.last_used_at),
|
|
62
|
+
idleExpiresAt: parseISO(row.idle_expires_at),
|
|
63
|
+
absoluteExpiresAt: parseISO(row.absolute_expires_at),
|
|
64
|
+
...(row.revoked_at ? { revokedAt: parseISO(row.revoked_at) } : {}),
|
|
65
|
+
...(row.replaced_by ? { replacedBy: row.replaced_by } : {}),
|
|
66
|
+
...(row.ip ? { ip: row.ip } : {}),
|
|
67
|
+
...(row.user_agent ? { userAgent: row.user_agent } : {}),
|
|
68
|
+
providerId: row.provider_id as SessionRecord["providerId"],
|
|
69
|
+
...(row.idp_refresh_token_enc
|
|
70
|
+
? { idpRefreshTokenEnc: row.idp_refresh_token_enc }
|
|
71
|
+
: {}),
|
|
72
|
+
...(row.idp_refresh_expires_at
|
|
73
|
+
? { idpRefreshExpiresAt: parseISO(row.idp_refresh_expires_at) }
|
|
74
|
+
: {}),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export class LocalSessionStore implements SessionStore {
|
|
79
|
+
private db: DatabaseWrapper;
|
|
80
|
+
|
|
81
|
+
constructor(db: DatabaseWrapper) {
|
|
82
|
+
this.db = db;
|
|
83
|
+
ensureTable(db, DDL);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async create(record: SessionRecord): Promise<void> {
|
|
87
|
+
this.db.prepare(
|
|
88
|
+
`INSERT INTO lt_sessions (
|
|
89
|
+
id, family_id, user_id, tenant_id, auth_epoch, refresh_token_hash,
|
|
90
|
+
created_at, last_used_at, idle_expires_at, absolute_expires_at,
|
|
91
|
+
revoked_at, replaced_by, ip, user_agent, provider_id,
|
|
92
|
+
idp_refresh_token_enc, idp_refresh_expires_at
|
|
93
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
94
|
+
).run(
|
|
95
|
+
record.id,
|
|
96
|
+
record.familyId,
|
|
97
|
+
record.userId,
|
|
98
|
+
record.tenantId ?? null,
|
|
99
|
+
record.authEpoch,
|
|
100
|
+
record.refreshTokenHash,
|
|
101
|
+
record.createdAt.toISOString(),
|
|
102
|
+
record.lastUsedAt.toISOString(),
|
|
103
|
+
record.idleExpiresAt.toISOString(),
|
|
104
|
+
record.absoluteExpiresAt.toISOString(),
|
|
105
|
+
record.revokedAt ? record.revokedAt.toISOString() : null,
|
|
106
|
+
record.replacedBy ?? null,
|
|
107
|
+
record.ip ?? null,
|
|
108
|
+
record.userAgent ?? null,
|
|
109
|
+
record.providerId,
|
|
110
|
+
record.idpRefreshTokenEnc ?? null,
|
|
111
|
+
record.idpRefreshExpiresAt ? record.idpRefreshExpiresAt.toISOString() : null,
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async findByRefreshTokenHash(hash: string): Promise<SessionRecord | null> {
|
|
116
|
+
const row = this.db.prepare(
|
|
117
|
+
`SELECT * FROM lt_sessions WHERE refresh_token_hash = ?`,
|
|
118
|
+
).get(hash) as unknown as SessionRow | undefined;
|
|
119
|
+
return row ? mapRow(row) : null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async findByFamilyId(familyId: string): Promise<SessionRecord | null> {
|
|
123
|
+
const active = this.db.prepare(
|
|
124
|
+
`SELECT * FROM lt_sessions
|
|
125
|
+
WHERE family_id = ? AND replaced_by IS NULL AND revoked_at IS NULL
|
|
126
|
+
ORDER BY created_at DESC LIMIT 1`,
|
|
127
|
+
).get(familyId) as unknown as SessionRow | undefined;
|
|
128
|
+
if (active) return mapRow(active);
|
|
129
|
+
const fallback = this.db.prepare(
|
|
130
|
+
`SELECT * FROM lt_sessions WHERE family_id = ? ORDER BY created_at DESC LIMIT 1`,
|
|
131
|
+
).get(familyId) as unknown as SessionRow | undefined;
|
|
132
|
+
return fallback ? mapRow(fallback) : null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async rotate(oldId: string, next: SessionRecord): Promise<void> {
|
|
136
|
+
// sql.js is synchronous and single-threaded; two writes are sufficient.
|
|
137
|
+
this.db.prepare(
|
|
138
|
+
`UPDATE lt_sessions SET replaced_by = ?, last_used_at = ? WHERE id = ?`,
|
|
139
|
+
).run(next.id, next.createdAt.toISOString(), oldId);
|
|
140
|
+
await this.create(next);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async revokeFamily(familyId: string, _reason: string): Promise<void> {
|
|
144
|
+
const now = nowISO();
|
|
145
|
+
this.db.prepare(
|
|
146
|
+
`UPDATE lt_sessions SET revoked_at = ? WHERE family_id = ? AND revoked_at IS NULL`,
|
|
147
|
+
).run(now, familyId);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async revokeAllForUser(userId: string, _reason: string): Promise<void> {
|
|
151
|
+
const now = nowISO();
|
|
152
|
+
this.db.prepare(
|
|
153
|
+
`UPDATE lt_sessions SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL`,
|
|
154
|
+
).run(now, userId);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async touch(id: string, lastUsedAt: Date): Promise<void> {
|
|
158
|
+
this.db.prepare(
|
|
159
|
+
`UPDATE lt_sessions SET last_used_at = ? WHERE id = ?`,
|
|
160
|
+
).run(lastUsedAt.toISOString(), id);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async listForUser(userId: string): Promise<SessionRecord[]> {
|
|
164
|
+
const rows = this.db.prepare(
|
|
165
|
+
`SELECT * FROM lt_sessions WHERE user_id = ? ORDER BY created_at DESC`,
|
|
166
|
+
).all(userId) as unknown as SessionRow[];
|
|
167
|
+
return rows.map(mapRow);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -252,15 +252,16 @@ export class LocalThreadMessageQueueStore implements IMessageQueueStore {
|
|
|
252
252
|
return row.count;
|
|
253
253
|
}
|
|
254
254
|
|
|
255
|
-
async getThreadsWithPendingMessages(): Promise<ThreadInfo[]> {
|
|
255
|
+
async getThreadsWithPendingMessages(tenantId?: string): Promise<ThreadInfo[]> {
|
|
256
256
|
const rows = this.db.prepare(
|
|
257
257
|
`SELECT tenant_id, assistant_id, thread_id, workspace_id, project_id,
|
|
258
258
|
MAX(status = 'pending') AS has_pending
|
|
259
259
|
FROM lt_thread_message_queue
|
|
260
260
|
WHERE status IN ('pending', 'processing')
|
|
261
|
+
${tenantId ? "AND tenant_id = ?" : ""}
|
|
261
262
|
GROUP BY tenant_id, assistant_id, thread_id, workspace_id, project_id
|
|
262
263
|
ORDER BY thread_id`,
|
|
263
|
-
).all() as { tenant_id: string; assistant_id: string; thread_id: string; workspace_id: string | null; project_id: string | null; has_pending: number }[];
|
|
264
|
+
).all(...(tenantId ? [tenantId] : [])) as { tenant_id: string; assistant_id: string; thread_id: string; workspace_id: string | null; project_id: string | null; has_pending: number }[];
|
|
264
265
|
return rows.map((r) => ({
|
|
265
266
|
tenantId: r.tenant_id,
|
|
266
267
|
assistantId: r.assistant_id,
|
|
@@ -3,10 +3,14 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { DatabaseWrapper } from "../database";
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
import {
|
|
7
|
+
classifyThreadMetadata,
|
|
8
|
+
toThreadMonitorRecord,
|
|
9
|
+
type ThreadStore,
|
|
10
|
+
type Thread,
|
|
11
|
+
type CreateThreadRequest,
|
|
12
|
+
type ThreadMonitorQuery,
|
|
13
|
+
type ThreadMonitorRecord,
|
|
10
14
|
} from "@axiom-lattice/protocols";
|
|
11
15
|
import { nowISO, parseISO } from "../database";
|
|
12
16
|
import { MigrationManager } from "../migrations/migration";
|
|
@@ -82,6 +86,45 @@ export class LocalThreadStore implements ThreadStore {
|
|
|
82
86
|
return threads;
|
|
83
87
|
}
|
|
84
88
|
|
|
89
|
+
async listThreadsByTenant(
|
|
90
|
+
tenantId: string,
|
|
91
|
+
query: ThreadMonitorQuery = {},
|
|
92
|
+
): Promise<{ records: ThreadMonitorRecord[]; total: number }> {
|
|
93
|
+
const limit = Math.min(200, Math.max(1, Math.floor(query.limit ?? 50)));
|
|
94
|
+
const offset = Math.max(0, Math.floor(query.offset ?? 0));
|
|
95
|
+
const createdAfter = query.createdAfter
|
|
96
|
+
? Date.parse(query.createdAfter)
|
|
97
|
+
: undefined;
|
|
98
|
+
|
|
99
|
+
const rows = this.db.prepare(
|
|
100
|
+
`SELECT * FROM lt_threads WHERE tenant_id = ? ORDER BY created_at DESC, id DESC`,
|
|
101
|
+
).all(tenantId) as unknown as ThreadRow[];
|
|
102
|
+
|
|
103
|
+
const filtered = rows
|
|
104
|
+
.map(mapRowToThread)
|
|
105
|
+
.filter((thread) => {
|
|
106
|
+
if (query.assistantId && thread.assistantId !== query.assistantId) {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
if (
|
|
110
|
+
createdAfter !== undefined &&
|
|
111
|
+
Number.isFinite(createdAfter) &&
|
|
112
|
+
thread.createdAt.getTime() < createdAfter
|
|
113
|
+
) {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
if (query.kind && classifyThreadMetadata(thread.metadata) !== query.kind) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
return true;
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
records: filtered.slice(offset, offset + limit).map(toThreadMonitorRecord),
|
|
124
|
+
total: filtered.length,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
85
128
|
async getThreadById(tenantId: string, threadId: string): Promise<Thread | undefined> {
|
|
86
129
|
const row = this.db.prepare(
|
|
87
130
|
`SELECT * FROM lt_threads WHERE tenant_id = ? AND id = ?`,
|
|
@@ -18,6 +18,7 @@ CREATE TABLE IF NOT EXISTS lt_users (
|
|
|
18
18
|
email TEXT NOT NULL,
|
|
19
19
|
name TEXT NOT NULL,
|
|
20
20
|
status TEXT NOT NULL DEFAULT 'pending',
|
|
21
|
+
auth_epoch TEXT,
|
|
21
22
|
metadata TEXT DEFAULT '{}',
|
|
22
23
|
created_at TEXT NOT NULL,
|
|
23
24
|
updated_at TEXT NOT NULL
|
|
@@ -31,6 +32,7 @@ interface UserRow {
|
|
|
31
32
|
email: string;
|
|
32
33
|
name: string;
|
|
33
34
|
status: string;
|
|
35
|
+
auth_epoch: string | null;
|
|
34
36
|
metadata: string;
|
|
35
37
|
created_at: string;
|
|
36
38
|
updated_at: string;
|
|
@@ -42,6 +44,12 @@ export class LocalUserStore implements UserStore {
|
|
|
42
44
|
constructor(db: DatabaseWrapper) {
|
|
43
45
|
this.db = db;
|
|
44
46
|
ensureTable(db, DDL);
|
|
47
|
+
const columns = db.prepare(`PRAGMA table_info(lt_users)`).all() as unknown as Array<{
|
|
48
|
+
name: string;
|
|
49
|
+
}>;
|
|
50
|
+
if (!columns.some((column) => column.name === "auth_epoch")) {
|
|
51
|
+
db.exec(`ALTER TABLE lt_users ADD COLUMN auth_epoch TEXT`);
|
|
52
|
+
}
|
|
45
53
|
}
|
|
46
54
|
|
|
47
55
|
async getAllUsers(): Promise<User[]> {
|
|
@@ -102,6 +110,7 @@ export class LocalUserStore implements UserStore {
|
|
|
102
110
|
if (updates.email !== undefined) { setClauses.push("email = ?"); values.push(updates.email); }
|
|
103
111
|
if (updates.name !== undefined) { setClauses.push("name = ?"); values.push(updates.name); }
|
|
104
112
|
if (updates.status !== undefined) { setClauses.push("status = ?"); values.push(updates.status); }
|
|
113
|
+
if (updates.authEpoch !== undefined) { setClauses.push("auth_epoch = ?"); values.push(updates.authEpoch); }
|
|
105
114
|
if (updates.metadata !== undefined) { setClauses.push("metadata = ?"); values.push(JSON.stringify(updates.metadata)); }
|
|
106
115
|
|
|
107
116
|
if (setClauses.length === 0) return existing;
|
|
@@ -130,6 +139,7 @@ function mapRowToUser(row: UserRow): User {
|
|
|
130
139
|
email: row.email,
|
|
131
140
|
name: row.name,
|
|
132
141
|
status: row.status as UserStatus,
|
|
142
|
+
...(row.auth_epoch ? { authEpoch: row.auth_epoch } : {}),
|
|
133
143
|
metadata: JSON.parse(row.metadata || "{}"),
|
|
134
144
|
createdAt: parseISO(row.created_at),
|
|
135
145
|
updatedAt: parseISO(row.updated_at),
|