@tinyweb_dev/agent-framework-agent 0.1.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/LICENSE +21 -0
- package/README.md +279 -0
- package/package.json +41 -0
- package/src/agent.ts +317 -0
- package/src/attachments.ts +155 -0
- package/src/bus/bus.ts +89 -0
- package/src/bus/index.ts +1 -0
- package/src/define-tool.ts +41 -0
- package/src/events.ts +162 -0
- package/src/http-handlers.ts +251 -0
- package/src/index.ts +120 -0
- package/src/loop-guard.ts +99 -0
- package/src/mcp/client.ts +110 -0
- package/src/mcp/index.ts +1 -0
- package/src/permission.ts +72 -0
- package/src/plugin/apply.ts +89 -0
- package/src/plugin/index.ts +3 -0
- package/src/plugin/loader.ts +42 -0
- package/src/plugin/types.ts +134 -0
- package/src/prompt/index.ts +90 -0
- package/src/prompt/objective.ts +104 -0
- package/src/prompt/response-style.ts +59 -0
- package/src/prompt/tool-use-guidelines.ts +57 -0
- package/src/prompt/tool-use.ts +27 -0
- package/src/runtime.ts +22 -0
- package/src/session/adapter.ts +37 -0
- package/src/session/compaction.ts +160 -0
- package/src/session/index.ts +11 -0
- package/src/session/memory.ts +154 -0
- package/src/session/overflow.ts +50 -0
- package/src/session/postgres.ts +330 -0
- package/src/session/processor.ts +500 -0
- package/src/session/replay.ts +140 -0
- package/src/session/schema.ts +140 -0
- package/src/session/sqlite.ts +281 -0
- package/src/session-api.ts +103 -0
- package/src/skill/index.ts +113 -0
- package/src/sse-handler.ts +67 -0
- package/src/transcript.ts +126 -0
|
@@ -0,0 +1,330 @@
|
|
|
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 deleteSession = (id: SessionID | string): Effect.Effect<void> =>
|
|
305
|
+
Effect.tryPromise({
|
|
306
|
+
try: async () => {
|
|
307
|
+
await db.delete(messages).where(eq(messages.session_id, id))
|
|
308
|
+
await db.delete(sessions).where(eq(sessions.id, id))
|
|
309
|
+
},
|
|
310
|
+
catch: (err) => err as Error,
|
|
311
|
+
}).pipe(Effect.orDie)
|
|
312
|
+
|
|
313
|
+
return {
|
|
314
|
+
createSession,
|
|
315
|
+
getSession,
|
|
316
|
+
upsertSession,
|
|
317
|
+
listSessions,
|
|
318
|
+
updateSession,
|
|
319
|
+
appendMessage,
|
|
320
|
+
getMessages,
|
|
321
|
+
deleteMessage,
|
|
322
|
+
deleteSession,
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
type AssistantMessageRow = {
|
|
327
|
+
modelId?: string
|
|
328
|
+
providerId?: string
|
|
329
|
+
usage?: unknown
|
|
330
|
+
}
|