@tinyweb_dev/agent-framework-agent 0.2.0 → 0.3.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/agent.d.ts +116 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/attachments.d.ts +41 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/bus/bus.d.ts +46 -0
- package/dist/bus/bus.d.ts.map +1 -0
- package/dist/bus/index.d.ts +2 -0
- package/dist/bus/index.d.ts.map +1 -0
- package/dist/define-tool.d.ts +13 -0
- package/dist/define-tool.d.ts.map +1 -0
- package/dist/events.d.ts +136 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/http-handlers.cjs +253 -0
- package/dist/http-handlers.cjs.map +1 -0
- package/dist/http-handlers.d.ts +49 -0
- package/dist/http-handlers.d.ts.map +1 -0
- package/dist/http-handlers.js +251 -0
- package/dist/http-handlers.js.map +1 -0
- package/dist/index.cjs +2073 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2015 -0
- package/dist/index.js.map +1 -0
- package/dist/loop-guard.d.ts +42 -0
- package/dist/loop-guard.d.ts.map +1 -0
- package/dist/mcp/client.d.ts +25 -0
- package/dist/mcp/client.d.ts.map +1 -0
- package/dist/mcp/index.cjs +66 -0
- package/dist/mcp/index.cjs.map +1 -0
- package/{src/mcp/index.ts → dist/mcp/index.d.ts} +2 -1
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +63 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/permission.d.ts +26 -0
- package/dist/permission.d.ts.map +1 -0
- package/dist/plugin/apply.d.ts +12 -0
- package/dist/plugin/apply.d.ts.map +1 -0
- package/dist/plugin/index.cjs +63 -0
- package/dist/plugin/index.cjs.map +1 -0
- package/dist/plugin/index.d.ts +4 -0
- package/dist/plugin/index.d.ts.map +1 -0
- package/dist/plugin/index.js +52 -0
- package/dist/plugin/index.js.map +1 -0
- package/dist/plugin/loader.d.ts +3 -0
- package/dist/plugin/loader.d.ts.map +1 -0
- package/dist/plugin/types.d.ts +98 -0
- package/dist/plugin/types.d.ts.map +1 -0
- package/dist/prompt/index.d.ts +51 -0
- package/dist/prompt/index.d.ts.map +1 -0
- package/dist/prompt/objective.d.ts +29 -0
- package/dist/prompt/objective.d.ts.map +1 -0
- package/dist/prompt/response-style.d.ts +19 -0
- package/dist/prompt/response-style.d.ts.map +1 -0
- package/dist/prompt/tool-use-guidelines.d.ts +22 -0
- package/dist/prompt/tool-use-guidelines.d.ts.map +1 -0
- package/dist/prompt/tool-use.d.ts +12 -0
- package/dist/prompt/tool-use.d.ts.map +1 -0
- package/dist/runtime.d.ts +7 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/session/adapter.d.ts +40 -0
- package/dist/session/adapter.d.ts.map +1 -0
- package/dist/session/compaction.d.ts +37 -0
- package/dist/session/compaction.d.ts.map +1 -0
- package/dist/session/index.d.ts +7 -0
- package/dist/session/index.d.ts.map +1 -0
- package/dist/session/memory.cjs +130 -0
- package/dist/session/memory.cjs.map +1 -0
- package/dist/session/memory.d.ts +3 -0
- package/dist/session/memory.d.ts.map +1 -0
- package/dist/session/memory.js +128 -0
- package/dist/session/memory.js.map +1 -0
- package/dist/session/overflow.d.ts +19 -0
- package/dist/session/overflow.d.ts.map +1 -0
- package/dist/session/postgres.cjs +245 -0
- package/dist/session/postgres.cjs.map +1 -0
- package/dist/session/postgres.d.ts +10 -0
- package/dist/session/postgres.d.ts.map +1 -0
- package/dist/session/postgres.js +243 -0
- package/dist/session/postgres.js.map +1 -0
- package/dist/session/processor.d.ts +52 -0
- package/dist/session/processor.d.ts.map +1 -0
- package/dist/session/replay.d.ts +4 -0
- package/dist/session/replay.d.ts.map +1 -0
- package/dist/session/schema.d.ts +104 -0
- package/dist/session/schema.d.ts.map +1 -0
- package/dist/session/sqlite.cjs +236 -0
- package/dist/session/sqlite.cjs.map +1 -0
- package/dist/session/sqlite.d.ts +3 -0
- package/dist/session/sqlite.d.ts.map +1 -0
- package/dist/session/sqlite.js +234 -0
- package/dist/session/sqlite.js.map +1 -0
- package/dist/session-api.cjs +56 -0
- package/dist/session-api.cjs.map +1 -0
- package/dist/session-api.d.ts +36 -0
- package/dist/session-api.d.ts.map +1 -0
- package/dist/session-api.js +54 -0
- package/dist/session-api.js.map +1 -0
- package/dist/skill/index.cjs +81 -0
- package/dist/skill/index.cjs.map +1 -0
- package/dist/skill/index.d.ts +10 -0
- package/dist/skill/index.d.ts.map +1 -0
- package/dist/skill/index.js +78 -0
- package/dist/skill/index.js.map +1 -0
- package/dist/sse-handler.d.ts +27 -0
- package/dist/sse-handler.d.ts.map +1 -0
- package/dist/transcript.d.ts +81 -0
- package/dist/transcript.d.ts.map +1 -0
- package/package.json +54 -19
- package/src/agent.ts +0 -470
- package/src/attachments.ts +0 -155
- package/src/bus/bus.ts +0 -89
- package/src/bus/index.ts +0 -1
- package/src/define-tool.ts +0 -41
- package/src/events.ts +0 -186
- package/src/http-handlers.ts +0 -251
- package/src/index.ts +0 -128
- package/src/loop-guard.ts +0 -99
- package/src/mcp/client.ts +0 -129
- package/src/permission.ts +0 -114
- package/src/plugin/apply.ts +0 -89
- package/src/plugin/index.ts +0 -3
- package/src/plugin/loader.ts +0 -42
- package/src/plugin/types.ts +0 -134
- package/src/prompt/index.ts +0 -90
- package/src/prompt/objective.ts +0 -104
- package/src/prompt/response-style.ts +0 -59
- package/src/prompt/tool-use-guidelines.ts +0 -57
- package/src/prompt/tool-use.ts +0 -27
- package/src/runtime.ts +0 -22
- package/src/session/adapter.ts +0 -46
- package/src/session/compaction.ts +0 -160
- package/src/session/index.ts +0 -18
- package/src/session/memory.ts +0 -169
- package/src/session/overflow.ts +0 -50
- package/src/session/postgres.ts +0 -355
- package/src/session/processor.ts +0 -865
- package/src/session/replay.ts +0 -151
- package/src/session/schema.ts +0 -156
- package/src/session/sqlite.ts +0 -309
- package/src/session-api.ts +0 -103
- package/src/skill/index.ts +0 -113
- package/src/sse-handler.ts +0 -67
- package/src/transcript.ts +0 -126
package/src/session/memory.ts
DELETED
|
@@ -1,169 +0,0 @@
|
|
|
1
|
-
import { Effect } from "effect"
|
|
2
|
-
import type { ListSessionsOpts, ListSessionsResult, SessionPatch, SessionStore, GetMessagesOpts } from "./adapter"
|
|
3
|
-
import {
|
|
4
|
-
newSessionID,
|
|
5
|
-
type CreateSessionInput,
|
|
6
|
-
type Message,
|
|
7
|
-
type MessageID,
|
|
8
|
-
type Session,
|
|
9
|
-
type SessionID,
|
|
10
|
-
} from "./schema"
|
|
11
|
-
|
|
12
|
-
type Entry = { info: Session.Info; messages: Message[] }
|
|
13
|
-
|
|
14
|
-
type Cursor = { readonly updatedAt: number; readonly id: string }
|
|
15
|
-
|
|
16
|
-
const encodeCursor = (cursor: Cursor): string =>
|
|
17
|
-
Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url")
|
|
18
|
-
|
|
19
|
-
const decodeCursor = (raw: string): Cursor | undefined => {
|
|
20
|
-
const json = Buffer.from(raw, "base64url").toString("utf8")
|
|
21
|
-
const parsed = JSON.parse(json) as Partial<Cursor>
|
|
22
|
-
if (typeof parsed.updatedAt !== "number" || typeof parsed.id !== "string") return undefined
|
|
23
|
-
return { updatedAt: parsed.updatedAt, id: parsed.id }
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export const makeMemoryStore = (): SessionStore => {
|
|
27
|
-
const store = new Map<string, Entry>()
|
|
28
|
-
|
|
29
|
-
const createSession = (input: CreateSessionInput): Effect.Effect<Session.Info> => {
|
|
30
|
-
const now = Date.now()
|
|
31
|
-
const info: Session.Info = {
|
|
32
|
-
id: newSessionID(),
|
|
33
|
-
agentName: input.agentName,
|
|
34
|
-
title: input.title,
|
|
35
|
-
metadata: input.metadata,
|
|
36
|
-
createdAt: now,
|
|
37
|
-
updatedAt: now,
|
|
38
|
-
}
|
|
39
|
-
store.set(info.id, { info, messages: [] })
|
|
40
|
-
return Effect.succeed(info)
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const getSession = (id: SessionID | string): Effect.Effect<Session.Info | undefined> =>
|
|
44
|
-
Effect.succeed(store.get(id)?.info)
|
|
45
|
-
|
|
46
|
-
const upsertSession = (
|
|
47
|
-
input: CreateSessionInput & { id?: SessionID | string },
|
|
48
|
-
): Effect.Effect<Session.Info> => {
|
|
49
|
-
const existing = input.id ? store.get(input.id) : undefined
|
|
50
|
-
if (existing) return Effect.succeed(existing.info)
|
|
51
|
-
if (!input.id) return createSession(input)
|
|
52
|
-
const now = Date.now()
|
|
53
|
-
const info: Session.Info = {
|
|
54
|
-
id: input.id as SessionID,
|
|
55
|
-
agentName: input.agentName,
|
|
56
|
-
title: input.title,
|
|
57
|
-
metadata: input.metadata,
|
|
58
|
-
createdAt: now,
|
|
59
|
-
updatedAt: now,
|
|
60
|
-
}
|
|
61
|
-
store.set(info.id, { info, messages: [] })
|
|
62
|
-
return Effect.succeed(info)
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const listSessions = (opts?: ListSessionsOpts): Effect.Effect<ListSessionsResult> => {
|
|
66
|
-
const limit = opts?.limit ?? 50
|
|
67
|
-
const filtered = Array.from(store.values())
|
|
68
|
-
.map((e) => e.info)
|
|
69
|
-
.filter((info) => (opts?.agentName ? info.agentName === opts.agentName : true))
|
|
70
|
-
.filter((info) =>
|
|
71
|
-
opts?.ownerId ? (info.metadata as { ownerId?: string } | undefined)?.ownerId === opts.ownerId : true,
|
|
72
|
-
)
|
|
73
|
-
.sort((a, b) => {
|
|
74
|
-
if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt
|
|
75
|
-
return b.id.localeCompare(a.id)
|
|
76
|
-
})
|
|
77
|
-
|
|
78
|
-
const cursor = opts?.cursor ? decodeCursor(opts.cursor) : undefined
|
|
79
|
-
const startIdx = cursor
|
|
80
|
-
? filtered.findIndex(
|
|
81
|
-
(info) =>
|
|
82
|
-
info.updatedAt < cursor.updatedAt ||
|
|
83
|
-
(info.updatedAt === cursor.updatedAt && info.id.localeCompare(cursor.id) < 0),
|
|
84
|
-
)
|
|
85
|
-
: 0
|
|
86
|
-
if (startIdx === -1) return Effect.succeed({ items: [] })
|
|
87
|
-
|
|
88
|
-
const page = filtered.slice(startIdx, startIdx + limit)
|
|
89
|
-
const tail = page[page.length - 1]
|
|
90
|
-
const hasMore = startIdx + limit < filtered.length
|
|
91
|
-
const nextCursor = hasMore && tail ? encodeCursor({ updatedAt: tail.updatedAt, id: tail.id }) : undefined
|
|
92
|
-
return Effect.succeed({ items: page, nextCursor })
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const updateSession = (
|
|
96
|
-
id: SessionID | string,
|
|
97
|
-
patch: SessionPatch,
|
|
98
|
-
): Effect.Effect<Session.Info | undefined> => {
|
|
99
|
-
const entry = store.get(id)
|
|
100
|
-
if (!entry) return Effect.succeed(undefined)
|
|
101
|
-
entry.info = {
|
|
102
|
-
...entry.info,
|
|
103
|
-
...(patch.title !== undefined ? { title: patch.title } : {}),
|
|
104
|
-
...(patch.metadata !== undefined ? { metadata: patch.metadata } : {}),
|
|
105
|
-
updatedAt: Date.now(),
|
|
106
|
-
}
|
|
107
|
-
return Effect.succeed(entry.info)
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
const appendMessage = (sessionId: SessionID | string, msg: Message): Effect.Effect<void> => {
|
|
111
|
-
const entry = store.get(sessionId)
|
|
112
|
-
if (!entry) return Effect.void
|
|
113
|
-
entry.messages.push(msg)
|
|
114
|
-
entry.info = { ...entry.info, updatedAt: Date.now() }
|
|
115
|
-
return Effect.void
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
const getMessages = (sessionId: SessionID | string, opts?: GetMessagesOpts): Effect.Effect<Message[]> => {
|
|
119
|
-
const msgs = store.get(sessionId)?.messages ?? []
|
|
120
|
-
const sliced = opts?.before ? msgs.slice(0, msgs.findIndex((m) => m.id === opts.before)) : msgs
|
|
121
|
-
const limited = opts?.limit ? sliced.slice(-opts.limit) : sliced
|
|
122
|
-
return Effect.succeed([...limited])
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
const deleteMessage = (
|
|
126
|
-
sessionId: SessionID | string,
|
|
127
|
-
messageId: MessageID | string,
|
|
128
|
-
): Effect.Effect<void> => {
|
|
129
|
-
const entry = store.get(sessionId)
|
|
130
|
-
if (!entry) return Effect.void
|
|
131
|
-
const idx = entry.messages.findIndex((m) => m.id === messageId)
|
|
132
|
-
if (idx === -1) return Effect.void
|
|
133
|
-
entry.messages.splice(idx, 1)
|
|
134
|
-
entry.info = { ...entry.info, updatedAt: Date.now() }
|
|
135
|
-
return Effect.void
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const updateMessage = (
|
|
139
|
-
sessionId: SessionID | string,
|
|
140
|
-
messageId: MessageID | string,
|
|
141
|
-
msg: Message,
|
|
142
|
-
): Effect.Effect<void> => {
|
|
143
|
-
const entry = store.get(sessionId)
|
|
144
|
-
if (!entry) return Effect.void
|
|
145
|
-
const idx = entry.messages.findIndex((m) => m.id === messageId)
|
|
146
|
-
if (idx === -1) return Effect.void
|
|
147
|
-
entry.messages[idx] = msg
|
|
148
|
-
entry.info = { ...entry.info, updatedAt: Date.now() }
|
|
149
|
-
return Effect.void
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
const deleteSession = (id: SessionID | string): Effect.Effect<void> => {
|
|
153
|
-
store.delete(id)
|
|
154
|
-
return Effect.void
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
return {
|
|
158
|
-
createSession,
|
|
159
|
-
getSession,
|
|
160
|
-
upsertSession,
|
|
161
|
-
listSessions,
|
|
162
|
-
updateSession,
|
|
163
|
-
appendMessage,
|
|
164
|
-
getMessages,
|
|
165
|
-
deleteMessage,
|
|
166
|
-
updateMessage,
|
|
167
|
-
deleteSession,
|
|
168
|
-
}
|
|
169
|
-
}
|
package/src/session/overflow.ts
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
// Adapted from opencode@v1.14.48 packages/opencode/src/session/overflow.ts
|
|
2
|
-
//
|
|
3
|
-
// Token-budget helpers used by the auto-compaction pre-flight check. We
|
|
4
|
-
// deliberately keep this provider-agnostic — the agent layer feeds in a
|
|
5
|
-
// `ModelLimits` (from `ModelRef`) and a reserved output buffer.
|
|
6
|
-
import type { ModelLimits } from "@tinyweb-agent-framework/llm"
|
|
7
|
-
import type { Message, ReasoningPart, TextPart } from "./schema"
|
|
8
|
-
|
|
9
|
-
const DEFAULT_OUTPUT_RESERVE = 20_000
|
|
10
|
-
|
|
11
|
-
const textFromPart = (part: { type: string }): string => {
|
|
12
|
-
if ((part as TextPart).type === "text") return (part as TextPart).text
|
|
13
|
-
if ((part as ReasoningPart).type === "reasoning") return (part as ReasoningPart).text
|
|
14
|
-
return ""
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/** Approximate tokens by chars/4. Cheap, provider-agnostic. */
|
|
18
|
-
export const estimateTokens = (msgs: ReadonlyArray<Message>): number => {
|
|
19
|
-
const totalChars = msgs.reduce(
|
|
20
|
-
(acc, msg) => acc + msg.parts.reduce((sum, part) => sum + textFromPart(part as { type: string }).length, 0),
|
|
21
|
-
0,
|
|
22
|
-
)
|
|
23
|
-
return Math.ceil(totalChars / 4)
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export type UsableInput = {
|
|
27
|
-
readonly limits: ModelLimits | undefined
|
|
28
|
-
/** Override reserved output buffer. Default min(20_000, limits.output). */
|
|
29
|
-
readonly reservedTokens?: number
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Compute the usable input budget. Returns `Infinity` when the model exposes
|
|
34
|
-
* no `context` limit, mirroring opencode behaviour (no enforced cap).
|
|
35
|
-
*/
|
|
36
|
-
export const usable = (input: UsableInput): number => {
|
|
37
|
-
const context = input.limits?.context
|
|
38
|
-
if (context === undefined || context <= 0) return Number.POSITIVE_INFINITY
|
|
39
|
-
const output = input.limits?.output ?? DEFAULT_OUTPUT_RESERVE
|
|
40
|
-
const reserved = input.reservedTokens ?? Math.min(DEFAULT_OUTPUT_RESERVE, output)
|
|
41
|
-
const budget = context - reserved
|
|
42
|
-
return budget > 0 ? budget : Math.floor(context * 0.9)
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** True when estimated tokens would overflow the usable budget. */
|
|
46
|
-
export const isOverflowEstimate = (tokens: number, budget: number): boolean => tokens >= budget
|
|
47
|
-
|
|
48
|
-
/** Convenience: estimate + compare in one call. */
|
|
49
|
-
export const isOverflow = (msgs: ReadonlyArray<Message>, budget: number): boolean =>
|
|
50
|
-
isOverflowEstimate(estimateTokens(msgs), budget)
|
package/src/session/postgres.ts
DELETED
|
@@ -1,355 +0,0 @@
|
|
|
1
|
-
// PostgresStore — Postgres-backed SessionStore using drizzle-orm/postgres-js.
|
|
2
|
-
//
|
|
3
|
-
// Requires the consumer to install `postgres` as a peer dependency:
|
|
4
|
-
// bun add postgres
|
|
5
|
-
//
|
|
6
|
-
// Usage:
|
|
7
|
-
// import postgres from "postgres"
|
|
8
|
-
// const sql = postgres(process.env.DATABASE_URL!)
|
|
9
|
-
// const store = makePostgresStore(sql)
|
|
10
|
-
|
|
11
|
-
import { drizzle } from "drizzle-orm/postgres-js"
|
|
12
|
-
import { bigint, jsonb, pgTable, text } from "drizzle-orm/pg-core"
|
|
13
|
-
import { and, desc, eq, lt, or, sql } from "drizzle-orm"
|
|
14
|
-
import { Effect } from "effect"
|
|
15
|
-
import type { ListSessionsOpts, ListSessionsResult, SessionPatch, SessionStore, GetMessagesOpts } from "./adapter"
|
|
16
|
-
import {
|
|
17
|
-
newSessionID,
|
|
18
|
-
type CreateSessionInput,
|
|
19
|
-
type Message,
|
|
20
|
-
type MessageID,
|
|
21
|
-
type Session,
|
|
22
|
-
type SessionID,
|
|
23
|
-
} from "./schema"
|
|
24
|
-
|
|
25
|
-
// Drizzle schema — snake_case per AGENTS.md
|
|
26
|
-
const sessions = pgTable("sessions", {
|
|
27
|
-
id: text("id").primaryKey(),
|
|
28
|
-
agent_name: text("agent_name").notNull(),
|
|
29
|
-
title: text("title"),
|
|
30
|
-
metadata: jsonb("metadata"),
|
|
31
|
-
owner_id: text("owner_id"),
|
|
32
|
-
created_at: bigint("created_at", { mode: "number" }).notNull(),
|
|
33
|
-
updated_at: bigint("updated_at", { mode: "number" }).notNull(),
|
|
34
|
-
})
|
|
35
|
-
|
|
36
|
-
const messages = pgTable("messages", {
|
|
37
|
-
id: text("id").primaryKey(),
|
|
38
|
-
session_id: text("session_id").notNull(),
|
|
39
|
-
role: text("role").notNull(),
|
|
40
|
-
parts: jsonb("parts").notNull(),
|
|
41
|
-
model_id: text("model_id"),
|
|
42
|
-
provider_id: text("provider_id"),
|
|
43
|
-
usage: jsonb("usage"),
|
|
44
|
-
created_at: bigint("created_at", { mode: "number" }).notNull(),
|
|
45
|
-
})
|
|
46
|
-
|
|
47
|
-
const CREATE_SESSIONS = `
|
|
48
|
-
CREATE TABLE IF NOT EXISTS sessions (
|
|
49
|
-
id TEXT PRIMARY KEY,
|
|
50
|
-
agent_name TEXT NOT NULL,
|
|
51
|
-
title TEXT,
|
|
52
|
-
metadata JSONB,
|
|
53
|
-
owner_id TEXT,
|
|
54
|
-
created_at BIGINT NOT NULL,
|
|
55
|
-
updated_at BIGINT NOT NULL
|
|
56
|
-
)
|
|
57
|
-
`
|
|
58
|
-
|
|
59
|
-
const ADD_OWNER_COLUMN = `ALTER TABLE sessions ADD COLUMN IF NOT EXISTS owner_id TEXT`
|
|
60
|
-
|
|
61
|
-
const CREATE_MESSAGES = `
|
|
62
|
-
CREATE TABLE IF NOT EXISTS messages (
|
|
63
|
-
id TEXT PRIMARY KEY,
|
|
64
|
-
session_id TEXT NOT NULL,
|
|
65
|
-
role TEXT NOT NULL,
|
|
66
|
-
parts JSONB NOT NULL,
|
|
67
|
-
model_id TEXT,
|
|
68
|
-
provider_id TEXT,
|
|
69
|
-
usage JSONB,
|
|
70
|
-
created_at BIGINT NOT NULL
|
|
71
|
-
)
|
|
72
|
-
`
|
|
73
|
-
|
|
74
|
-
const CREATE_INDEXES = [
|
|
75
|
-
`CREATE INDEX IF NOT EXISTS sessions_updated_at_idx ON sessions(updated_at DESC, id DESC)`,
|
|
76
|
-
`CREATE INDEX IF NOT EXISTS sessions_owner_idx ON sessions(owner_id)`,
|
|
77
|
-
`CREATE INDEX IF NOT EXISTS messages_session_created_idx ON messages(session_id, created_at, id)`,
|
|
78
|
-
]
|
|
79
|
-
|
|
80
|
-
// The `postgres-js` Sql client. We type it loosely because the
|
|
81
|
-
// `postgres` package is a peer dep that consumers install themselves.
|
|
82
|
-
export type PostgresClient = {
|
|
83
|
-
readonly unsafe: (sql: string) => Promise<unknown>
|
|
84
|
-
} & object
|
|
85
|
-
|
|
86
|
-
export type PostgresStoreOptions = {
|
|
87
|
-
/** Skip auto-running CREATE TABLE IF NOT EXISTS on init (default: false) */
|
|
88
|
-
readonly skipMigrate?: boolean
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const rowToInfo = (row: typeof sessions.$inferSelect): Session.Info => {
|
|
92
|
-
const baseMetadata = (row.metadata as Record<string, unknown> | null) ?? undefined
|
|
93
|
-
const metadata = row.owner_id
|
|
94
|
-
? { ...(baseMetadata ?? {}), ownerId: row.owner_id }
|
|
95
|
-
: baseMetadata
|
|
96
|
-
return {
|
|
97
|
-
id: row.id as SessionID,
|
|
98
|
-
agentName: row.agent_name,
|
|
99
|
-
title: row.title ?? undefined,
|
|
100
|
-
metadata,
|
|
101
|
-
createdAt: row.created_at,
|
|
102
|
-
updatedAt: row.updated_at,
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const rowToMessage = (row: typeof messages.$inferSelect): Message => row.parts as Message
|
|
107
|
-
|
|
108
|
-
type Cursor = { readonly updatedAt: number; readonly id: string }
|
|
109
|
-
|
|
110
|
-
const encodeCursor = (cursor: Cursor): string =>
|
|
111
|
-
Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url")
|
|
112
|
-
|
|
113
|
-
const decodeCursor = (raw: string): Cursor | undefined => {
|
|
114
|
-
const parsed = JSON.parse(Buffer.from(raw, "base64url").toString("utf8")) as Partial<Cursor>
|
|
115
|
-
if (typeof parsed.updatedAt !== "number" || typeof parsed.id !== "string") return undefined
|
|
116
|
-
return { updatedAt: parsed.updatedAt, id: parsed.id }
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
const ownerFromMetadata = (metadata: Record<string, unknown> | undefined): string | null => {
|
|
120
|
-
const owner = (metadata as { ownerId?: unknown } | undefined)?.ownerId
|
|
121
|
-
return typeof owner === "string" ? owner : null
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
export const makePostgresStore = async (
|
|
125
|
-
client: PostgresClient,
|
|
126
|
-
options: PostgresStoreOptions = {},
|
|
127
|
-
): Promise<SessionStore> => {
|
|
128
|
-
const db = drizzle(client as never)
|
|
129
|
-
|
|
130
|
-
if (!options.skipMigrate) {
|
|
131
|
-
const runner = client as unknown as { unsafe: (sql: string) => Promise<unknown> }
|
|
132
|
-
await runner.unsafe(CREATE_SESSIONS)
|
|
133
|
-
await runner.unsafe(ADD_OWNER_COLUMN)
|
|
134
|
-
await runner.unsafe(CREATE_MESSAGES)
|
|
135
|
-
for (const stmt of CREATE_INDEXES) await runner.unsafe(stmt)
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const createSession = (input: CreateSessionInput): Effect.Effect<Session.Info> =>
|
|
139
|
-
Effect.tryPromise({
|
|
140
|
-
try: async () => {
|
|
141
|
-
const now = Date.now()
|
|
142
|
-
const info: Session.Info = {
|
|
143
|
-
id: newSessionID(),
|
|
144
|
-
agentName: input.agentName,
|
|
145
|
-
title: input.title,
|
|
146
|
-
metadata: input.metadata,
|
|
147
|
-
createdAt: now,
|
|
148
|
-
updatedAt: now,
|
|
149
|
-
}
|
|
150
|
-
await db.insert(sessions).values({
|
|
151
|
-
id: info.id,
|
|
152
|
-
agent_name: info.agentName,
|
|
153
|
-
title: info.title ?? null,
|
|
154
|
-
metadata: info.metadata ?? null,
|
|
155
|
-
owner_id: ownerFromMetadata(info.metadata),
|
|
156
|
-
created_at: info.createdAt,
|
|
157
|
-
updated_at: info.updatedAt,
|
|
158
|
-
})
|
|
159
|
-
return info
|
|
160
|
-
},
|
|
161
|
-
catch: (err) => err as Error,
|
|
162
|
-
}).pipe(Effect.orDie)
|
|
163
|
-
|
|
164
|
-
const getSession = (id: SessionID | string): Effect.Effect<Session.Info | undefined> =>
|
|
165
|
-
Effect.tryPromise({
|
|
166
|
-
try: async () => {
|
|
167
|
-
const rows = await db.select().from(sessions).where(eq(sessions.id, id))
|
|
168
|
-
const row = rows[0]
|
|
169
|
-
return row ? rowToInfo(row) : undefined
|
|
170
|
-
},
|
|
171
|
-
catch: (err) => err as Error,
|
|
172
|
-
}).pipe(Effect.orDie)
|
|
173
|
-
|
|
174
|
-
const upsertSession = (
|
|
175
|
-
input: CreateSessionInput & { id?: SessionID | string },
|
|
176
|
-
): Effect.Effect<Session.Info> =>
|
|
177
|
-
Effect.gen(function* () {
|
|
178
|
-
if (input.id) {
|
|
179
|
-
const existing = yield* getSession(input.id)
|
|
180
|
-
if (existing) return existing
|
|
181
|
-
}
|
|
182
|
-
return yield* createSession(input)
|
|
183
|
-
})
|
|
184
|
-
|
|
185
|
-
const listSessions = (opts?: ListSessionsOpts): Effect.Effect<ListSessionsResult> =>
|
|
186
|
-
Effect.tryPromise({
|
|
187
|
-
try: async () => {
|
|
188
|
-
const limit = opts?.limit ?? 50
|
|
189
|
-
const filters = [
|
|
190
|
-
opts?.agentName ? eq(sessions.agent_name, opts.agentName) : undefined,
|
|
191
|
-
opts?.ownerId ? eq(sessions.owner_id, opts.ownerId) : undefined,
|
|
192
|
-
].filter((c): c is Exclude<typeof c, undefined> => c !== undefined)
|
|
193
|
-
|
|
194
|
-
const cursor = opts?.cursor ? decodeCursor(opts.cursor) : undefined
|
|
195
|
-
const cursorClause = cursor
|
|
196
|
-
? or(
|
|
197
|
-
lt(sessions.updated_at, cursor.updatedAt),
|
|
198
|
-
and(eq(sessions.updated_at, cursor.updatedAt), lt(sessions.id, cursor.id)),
|
|
199
|
-
)
|
|
200
|
-
: undefined
|
|
201
|
-
const whereClause = cursorClause
|
|
202
|
-
? and(...filters, cursorClause)
|
|
203
|
-
: filters.length > 0
|
|
204
|
-
? and(...filters)
|
|
205
|
-
: undefined
|
|
206
|
-
|
|
207
|
-
const rows = await db
|
|
208
|
-
.select()
|
|
209
|
-
.from(sessions)
|
|
210
|
-
.where(whereClause)
|
|
211
|
-
.orderBy(desc(sessions.updated_at), desc(sessions.id))
|
|
212
|
-
.limit(limit + 1)
|
|
213
|
-
|
|
214
|
-
const hasMore = rows.length > limit
|
|
215
|
-
const page = hasMore ? rows.slice(0, limit) : rows
|
|
216
|
-
const tail = page[page.length - 1]
|
|
217
|
-
const nextCursor = hasMore && tail ? encodeCursor({ updatedAt: tail.updated_at, id: tail.id }) : undefined
|
|
218
|
-
|
|
219
|
-
return { items: page.map(rowToInfo), nextCursor }
|
|
220
|
-
},
|
|
221
|
-
catch: (err) => err as Error,
|
|
222
|
-
}).pipe(Effect.orDie)
|
|
223
|
-
|
|
224
|
-
const updateSession = (
|
|
225
|
-
id: SessionID | string,
|
|
226
|
-
patch: SessionPatch,
|
|
227
|
-
): Effect.Effect<Session.Info | undefined> =>
|
|
228
|
-
Effect.tryPromise({
|
|
229
|
-
try: async () => {
|
|
230
|
-
const existing = (await db.select().from(sessions).where(eq(sessions.id, id)))[0]
|
|
231
|
-
if (!existing) return undefined
|
|
232
|
-
const setClause: Partial<typeof sessions.$inferInsert> = { updated_at: Date.now() }
|
|
233
|
-
if (patch.title !== undefined) setClause.title = patch.title
|
|
234
|
-
if (patch.metadata !== undefined) {
|
|
235
|
-
setClause.metadata = patch.metadata
|
|
236
|
-
setClause.owner_id = ownerFromMetadata(patch.metadata)
|
|
237
|
-
}
|
|
238
|
-
await db.update(sessions).set(setClause).where(eq(sessions.id, id))
|
|
239
|
-
const row = (await db.select().from(sessions).where(eq(sessions.id, id)))[0]
|
|
240
|
-
return row ? rowToInfo(row) : undefined
|
|
241
|
-
},
|
|
242
|
-
catch: (err) => err as Error,
|
|
243
|
-
}).pipe(Effect.orDie)
|
|
244
|
-
|
|
245
|
-
const appendMessage = (sessionId: SessionID | string, msg: Message): Effect.Effect<void> =>
|
|
246
|
-
Effect.tryPromise({
|
|
247
|
-
try: async () => {
|
|
248
|
-
const msgRow = msg as AssistantMessageRow
|
|
249
|
-
const now = Date.now()
|
|
250
|
-
await db.insert(messages).values({
|
|
251
|
-
id: msg.id,
|
|
252
|
-
session_id: sessionId,
|
|
253
|
-
role: msg.role,
|
|
254
|
-
parts: msg as unknown as Record<string, unknown>,
|
|
255
|
-
model_id: msgRow.modelId ?? null,
|
|
256
|
-
provider_id: msgRow.providerId ?? null,
|
|
257
|
-
usage: (msgRow.usage as Record<string, unknown> | undefined) ?? null,
|
|
258
|
-
created_at: now,
|
|
259
|
-
})
|
|
260
|
-
await db.update(sessions).set({ updated_at: now }).where(eq(sessions.id, sessionId))
|
|
261
|
-
},
|
|
262
|
-
catch: (err) => err as Error,
|
|
263
|
-
}).pipe(Effect.orDie)
|
|
264
|
-
|
|
265
|
-
const getMessages = (
|
|
266
|
-
sessionId: SessionID | string,
|
|
267
|
-
opts?: GetMessagesOpts,
|
|
268
|
-
): Effect.Effect<Message[]> =>
|
|
269
|
-
Effect.tryPromise({
|
|
270
|
-
try: async () => {
|
|
271
|
-
const beforeClause = opts?.before
|
|
272
|
-
? lt(
|
|
273
|
-
messages.created_at,
|
|
274
|
-
sql<number>`(SELECT created_at FROM messages WHERE id = ${opts.before})`,
|
|
275
|
-
)
|
|
276
|
-
: undefined
|
|
277
|
-
const where = beforeClause
|
|
278
|
-
? and(eq(messages.session_id, sessionId), beforeClause)
|
|
279
|
-
: eq(messages.session_id, sessionId)
|
|
280
|
-
const rows = await db
|
|
281
|
-
.select()
|
|
282
|
-
.from(messages)
|
|
283
|
-
.where(where)
|
|
284
|
-
.orderBy(messages.created_at, messages.id)
|
|
285
|
-
const limited = opts?.limit ? rows.slice(-opts.limit) : rows
|
|
286
|
-
return limited.map(rowToMessage)
|
|
287
|
-
},
|
|
288
|
-
catch: (err) => err as Error,
|
|
289
|
-
}).pipe(Effect.orDie)
|
|
290
|
-
|
|
291
|
-
const deleteMessage = (
|
|
292
|
-
sessionId: SessionID | string,
|
|
293
|
-
messageId: MessageID | string,
|
|
294
|
-
): Effect.Effect<void> =>
|
|
295
|
-
Effect.tryPromise({
|
|
296
|
-
try: async () => {
|
|
297
|
-
await db
|
|
298
|
-
.delete(messages)
|
|
299
|
-
.where(and(eq(messages.session_id, sessionId), eq(messages.id, messageId)))
|
|
300
|
-
},
|
|
301
|
-
catch: (err) => err as Error,
|
|
302
|
-
}).pipe(Effect.orDie)
|
|
303
|
-
|
|
304
|
-
const updateMessage = (
|
|
305
|
-
sessionId: SessionID | string,
|
|
306
|
-
messageId: MessageID | string,
|
|
307
|
-
msg: Message,
|
|
308
|
-
): Effect.Effect<void> =>
|
|
309
|
-
Effect.tryPromise({
|
|
310
|
-
try: async () => {
|
|
311
|
-
const msgRow = msg as AssistantMessageRow
|
|
312
|
-
const now = Date.now()
|
|
313
|
-
await db
|
|
314
|
-
.update(messages)
|
|
315
|
-
.set({
|
|
316
|
-
role: msg.role,
|
|
317
|
-
parts: msg as unknown as Record<string, unknown>,
|
|
318
|
-
model_id: msgRow.modelId ?? null,
|
|
319
|
-
provider_id: msgRow.providerId ?? null,
|
|
320
|
-
usage: (msgRow.usage as Record<string, unknown> | undefined) ?? null,
|
|
321
|
-
})
|
|
322
|
-
.where(and(eq(messages.session_id, sessionId), eq(messages.id, messageId)))
|
|
323
|
-
await db.update(sessions).set({ updated_at: now }).where(eq(sessions.id, sessionId))
|
|
324
|
-
},
|
|
325
|
-
catch: (err) => err as Error,
|
|
326
|
-
}).pipe(Effect.orDie)
|
|
327
|
-
|
|
328
|
-
const deleteSession = (id: SessionID | string): Effect.Effect<void> =>
|
|
329
|
-
Effect.tryPromise({
|
|
330
|
-
try: async () => {
|
|
331
|
-
await db.delete(messages).where(eq(messages.session_id, id))
|
|
332
|
-
await db.delete(sessions).where(eq(sessions.id, id))
|
|
333
|
-
},
|
|
334
|
-
catch: (err) => err as Error,
|
|
335
|
-
}).pipe(Effect.orDie)
|
|
336
|
-
|
|
337
|
-
return {
|
|
338
|
-
createSession,
|
|
339
|
-
getSession,
|
|
340
|
-
upsertSession,
|
|
341
|
-
listSessions,
|
|
342
|
-
updateSession,
|
|
343
|
-
appendMessage,
|
|
344
|
-
getMessages,
|
|
345
|
-
deleteMessage,
|
|
346
|
-
updateMessage,
|
|
347
|
-
deleteSession,
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
type AssistantMessageRow = {
|
|
352
|
-
modelId?: string
|
|
353
|
-
providerId?: string
|
|
354
|
-
usage?: unknown
|
|
355
|
-
}
|