@tinyweb_dev/agent-framework-agent 0.2.0 → 0.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.
Files changed (144) hide show
  1. package/dist/agent.d.ts +116 -0
  2. package/dist/agent.d.ts.map +1 -0
  3. package/dist/attachments.d.ts +41 -0
  4. package/dist/attachments.d.ts.map +1 -0
  5. package/dist/bus/bus.d.ts +46 -0
  6. package/dist/bus/bus.d.ts.map +1 -0
  7. package/dist/bus/index.d.ts +2 -0
  8. package/dist/bus/index.d.ts.map +1 -0
  9. package/dist/define-tool.d.ts +13 -0
  10. package/dist/define-tool.d.ts.map +1 -0
  11. package/dist/events.d.ts +136 -0
  12. package/dist/events.d.ts.map +1 -0
  13. package/dist/http-handlers.cjs +253 -0
  14. package/dist/http-handlers.cjs.map +1 -0
  15. package/dist/http-handlers.d.ts +49 -0
  16. package/dist/http-handlers.d.ts.map +1 -0
  17. package/dist/http-handlers.js +251 -0
  18. package/dist/http-handlers.js.map +1 -0
  19. package/dist/index.cjs +2073 -0
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.ts +19 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +2015 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/loop-guard.d.ts +42 -0
  26. package/dist/loop-guard.d.ts.map +1 -0
  27. package/dist/mcp/client.d.ts +25 -0
  28. package/dist/mcp/client.d.ts.map +1 -0
  29. package/dist/mcp/index.cjs +66 -0
  30. package/dist/mcp/index.cjs.map +1 -0
  31. package/{src/mcp/index.ts → dist/mcp/index.d.ts} +2 -1
  32. package/dist/mcp/index.d.ts.map +1 -0
  33. package/dist/mcp/index.js +63 -0
  34. package/dist/mcp/index.js.map +1 -0
  35. package/dist/permission.d.ts +26 -0
  36. package/dist/permission.d.ts.map +1 -0
  37. package/dist/plugin/apply.d.ts +12 -0
  38. package/dist/plugin/apply.d.ts.map +1 -0
  39. package/dist/plugin/index.cjs +63 -0
  40. package/dist/plugin/index.cjs.map +1 -0
  41. package/dist/plugin/index.d.ts +4 -0
  42. package/dist/plugin/index.d.ts.map +1 -0
  43. package/dist/plugin/index.js +52 -0
  44. package/dist/plugin/index.js.map +1 -0
  45. package/dist/plugin/loader.d.ts +3 -0
  46. package/dist/plugin/loader.d.ts.map +1 -0
  47. package/dist/plugin/types.d.ts +98 -0
  48. package/dist/plugin/types.d.ts.map +1 -0
  49. package/dist/prompt/index.d.ts +51 -0
  50. package/dist/prompt/index.d.ts.map +1 -0
  51. package/dist/prompt/objective.d.ts +29 -0
  52. package/dist/prompt/objective.d.ts.map +1 -0
  53. package/dist/prompt/response-style.d.ts +19 -0
  54. package/dist/prompt/response-style.d.ts.map +1 -0
  55. package/dist/prompt/tool-use-guidelines.d.ts +22 -0
  56. package/dist/prompt/tool-use-guidelines.d.ts.map +1 -0
  57. package/dist/prompt/tool-use.d.ts +12 -0
  58. package/dist/prompt/tool-use.d.ts.map +1 -0
  59. package/dist/runtime.d.ts +7 -0
  60. package/dist/runtime.d.ts.map +1 -0
  61. package/dist/session/adapter.d.ts +40 -0
  62. package/dist/session/adapter.d.ts.map +1 -0
  63. package/dist/session/compaction.d.ts +37 -0
  64. package/dist/session/compaction.d.ts.map +1 -0
  65. package/dist/session/index.d.ts +7 -0
  66. package/dist/session/index.d.ts.map +1 -0
  67. package/dist/session/memory.cjs +130 -0
  68. package/dist/session/memory.cjs.map +1 -0
  69. package/dist/session/memory.d.ts +3 -0
  70. package/dist/session/memory.d.ts.map +1 -0
  71. package/dist/session/memory.js +128 -0
  72. package/dist/session/memory.js.map +1 -0
  73. package/dist/session/overflow.d.ts +19 -0
  74. package/dist/session/overflow.d.ts.map +1 -0
  75. package/dist/session/postgres.cjs +245 -0
  76. package/dist/session/postgres.cjs.map +1 -0
  77. package/dist/session/postgres.d.ts +10 -0
  78. package/dist/session/postgres.d.ts.map +1 -0
  79. package/dist/session/postgres.js +243 -0
  80. package/dist/session/postgres.js.map +1 -0
  81. package/dist/session/processor.d.ts +52 -0
  82. package/dist/session/processor.d.ts.map +1 -0
  83. package/dist/session/replay.d.ts +4 -0
  84. package/dist/session/replay.d.ts.map +1 -0
  85. package/dist/session/schema.d.ts +104 -0
  86. package/dist/session/schema.d.ts.map +1 -0
  87. package/dist/session/sqlite.cjs +236 -0
  88. package/dist/session/sqlite.cjs.map +1 -0
  89. package/dist/session/sqlite.d.ts +3 -0
  90. package/dist/session/sqlite.d.ts.map +1 -0
  91. package/dist/session/sqlite.js +234 -0
  92. package/dist/session/sqlite.js.map +1 -0
  93. package/dist/session-api.cjs +56 -0
  94. package/dist/session-api.cjs.map +1 -0
  95. package/dist/session-api.d.ts +36 -0
  96. package/dist/session-api.d.ts.map +1 -0
  97. package/dist/session-api.js +54 -0
  98. package/dist/session-api.js.map +1 -0
  99. package/dist/skill/index.cjs +81 -0
  100. package/dist/skill/index.cjs.map +1 -0
  101. package/dist/skill/index.d.ts +10 -0
  102. package/dist/skill/index.d.ts.map +1 -0
  103. package/dist/skill/index.js +78 -0
  104. package/dist/skill/index.js.map +1 -0
  105. package/dist/sse-handler.d.ts +27 -0
  106. package/dist/sse-handler.d.ts.map +1 -0
  107. package/dist/transcript.d.ts +81 -0
  108. package/dist/transcript.d.ts.map +1 -0
  109. package/package.json +54 -19
  110. package/src/agent.ts +0 -470
  111. package/src/attachments.ts +0 -155
  112. package/src/bus/bus.ts +0 -89
  113. package/src/bus/index.ts +0 -1
  114. package/src/define-tool.ts +0 -41
  115. package/src/events.ts +0 -186
  116. package/src/http-handlers.ts +0 -251
  117. package/src/index.ts +0 -128
  118. package/src/loop-guard.ts +0 -99
  119. package/src/mcp/client.ts +0 -129
  120. package/src/permission.ts +0 -114
  121. package/src/plugin/apply.ts +0 -89
  122. package/src/plugin/index.ts +0 -3
  123. package/src/plugin/loader.ts +0 -42
  124. package/src/plugin/types.ts +0 -134
  125. package/src/prompt/index.ts +0 -90
  126. package/src/prompt/objective.ts +0 -104
  127. package/src/prompt/response-style.ts +0 -59
  128. package/src/prompt/tool-use-guidelines.ts +0 -57
  129. package/src/prompt/tool-use.ts +0 -27
  130. package/src/runtime.ts +0 -22
  131. package/src/session/adapter.ts +0 -46
  132. package/src/session/compaction.ts +0 -160
  133. package/src/session/index.ts +0 -18
  134. package/src/session/memory.ts +0 -169
  135. package/src/session/overflow.ts +0 -50
  136. package/src/session/postgres.ts +0 -355
  137. package/src/session/processor.ts +0 -865
  138. package/src/session/replay.ts +0 -151
  139. package/src/session/schema.ts +0 -156
  140. package/src/session/sqlite.ts +0 -309
  141. package/src/session-api.ts +0 -103
  142. package/src/skill/index.ts +0 -113
  143. package/src/sse-handler.ts +0 -67
  144. package/src/transcript.ts +0 -126
@@ -1,151 +0,0 @@
1
- import { LLM, type ContentPart, type Message as LLMMessage } from "@tinyweb-agent-framework/llm"
2
- import { findCompactionPart, type ImagePart, type Message, type TextPart, type ToolPart } from "./schema"
3
-
4
- const COMPACTION_PREFIX = "[Compacted conversation summary]"
5
-
6
- /**
7
- * Hard cap on the serialised size (in characters, ~4 chars/token) of a
8
- * single tool result when replayed into the LLM. Adapted from
9
- * opencode@v1.14.48 — `truncateToolOutput` — to prevent a single huge
10
- * `read_page`/`screenshot`/`get_content` output from blowing the context
11
- * window all on its own and making compaction retry impossible to satisfy.
12
- *
13
- * 60 000 chars ≈ 15k tokens — generous enough that small/medium tool calls
14
- * pass through unchanged, but capped well below any model's context window
15
- * even when several tool calls are stacked back-to-back.
16
- */
17
- const MAX_TOOL_OUTPUT_CHARS = 60_000
18
-
19
- const TRUNCATION_NOTE = (elided: number) =>
20
- `\n\n[... ${elided} chars elided by tinyweb-agent — output exceeded ${MAX_TOOL_OUTPUT_CHARS} chars ...]\n\n`
21
-
22
- const truncateToolOutput = (output: unknown): unknown => {
23
- if (output === undefined || output === null) return output
24
- if (typeof output === "string") {
25
- if (output.length <= MAX_TOOL_OUTPUT_CHARS) return output
26
- const half = Math.floor(MAX_TOOL_OUTPUT_CHARS / 2) - 64
27
- return `${output.slice(0, half)}${TRUNCATION_NOTE(output.length - MAX_TOOL_OUTPUT_CHARS)}${output.slice(-half)}`
28
- }
29
- // Non-string: stringify and only mutate when it overflows.
30
- const serialised = (() => {
31
- try {
32
- return JSON.stringify(output)
33
- } catch {
34
- return String(output)
35
- }
36
- })()
37
- if (serialised.length <= MAX_TOOL_OUTPUT_CHARS) return output
38
- const half = Math.floor(MAX_TOOL_OUTPUT_CHARS / 2) - 64
39
- return `${serialised.slice(0, half)}${TRUNCATION_NOTE(serialised.length - MAX_TOOL_OUTPUT_CHARS)}${serialised.slice(-half)}`
40
- }
41
-
42
- const textOf = (msg: Message): string =>
43
- msg.parts
44
- .map((p) => ((p as TextPart).type === "text" ? (p as TextPart).text : ""))
45
- .filter((s) => s.length > 0)
46
- .join("\n")
47
-
48
- /**
49
- * Replay app-level history into wire-level LLM messages.
50
- *
51
- * Faithful to the agentic loop: every assistant turn that called tools is
52
- * rebuilt as an `assistant` message carrying both its text and `tool-call`
53
- * parts, followed by one `tool` message per completed `tool-result`. This is
54
- * what lets the model "remember" what it did across user turns — without it
55
- * the second user prompt would see only naked text and answer "no context".
56
- *
57
- * Marker-aware: if any message carries a `CompactionPart`, replay starts from
58
- * the most recent marker and emits the marker's summary as a synthetic user
59
- * message, followed by the tail (messages after the marker).
60
- */
61
- const imagePartToMedia = (part: ImagePart): ContentPart | undefined => {
62
- const data = part.url ?? part.data
63
- if (!data) return undefined
64
- return { type: "media", mediaType: part.mediaType ?? "image/png", data }
65
- }
66
-
67
- const expandMessage = (msg: Message): LLMMessage[] => {
68
- if (msg.role === "user") {
69
- const content: ContentPart[] = []
70
- const text = textOf(msg)
71
- if (text.length > 0) content.push({ type: "text", text })
72
- for (const p of msg.parts) {
73
- if ((p as { type: string }).type !== "image") continue
74
- const media = imagePartToMedia(p as ImagePart)
75
- if (media) content.push(media)
76
- }
77
- return content.length > 0 ? [LLM.user(content)] : []
78
- }
79
-
80
- // Assistant: split parts into text + tool-call, then emit follow-up tool messages.
81
- const text = textOf(msg)
82
- const toolParts = msg.parts.filter((p): p is ToolPart => (p as { type: string }).type === "tool")
83
- // Replay only terminal tool states that have a result the model can pair with.
84
- // pending-approval / approved (not yet executed) / running / pending are skipped —
85
- // resume() executes them first, then rewrites state to complete|error.
86
- const completed = toolParts.filter(
87
- (t) => t.state === "complete" || t.state === "error" || t.state === "rejected",
88
- )
89
-
90
- // Skip entirely if nothing replayable (avoids empty assistant frames).
91
- if (text.length === 0 && completed.length === 0) return []
92
-
93
- // Build assistant content: text first, then tool-call parts (only for completed
94
- // calls — partial/cancelled tool calls have no result to pair with).
95
- const assistantContent: Array<ReturnType<typeof LLM.text> | ReturnType<typeof LLM.toolCall>> = []
96
- if (text.length > 0) assistantContent.push(LLM.text(text))
97
- for (const t of completed) {
98
- assistantContent.push(LLM.toolCall({ id: t.callID, name: t.name, input: t.input }))
99
- }
100
-
101
- const out: LLMMessage[] = []
102
- if (assistantContent.length > 0) out.push(LLM.assistant(assistantContent))
103
-
104
- // Emit one tool-result message per completed tool. Errors round-trip as
105
- // resultType: "error" so the model sees the failure message verbatim.
106
- //
107
- // Tool outputs are truncated to MAX_TOOL_OUTPUT_CHARS before replay so a
108
- // single oversized result (e.g. `browser__read_page`, `browser__screenshot`)
109
- // cannot single-handedly overflow the context window — which would make
110
- // compaction retry impossible to satisfy and surface as "compaction retry
111
- // exhausted" to the caller.
112
- for (const t of completed) {
113
- const isError = t.state === "error" || t.state === "rejected"
114
- const result =
115
- t.output !== undefined
116
- ? t.output
117
- : isError
118
- ? { message: t.state === "rejected" ? "User denied tool execution" : "Tool failed" }
119
- : undefined
120
- out.push(
121
- LLM.toolMessage({
122
- id: t.callID,
123
- name: t.name,
124
- result: truncateToolOutput(result),
125
- resultType: isError ? "error" : "json",
126
- }),
127
- )
128
- }
129
-
130
- return out
131
- }
132
-
133
- export const historyToLLMMessages = (messages: ReadonlyArray<Message>): LLMMessage[] => {
134
- // Find the *last* compaction marker — only the most recent matters.
135
- let markerIdx = -1
136
- for (let i = messages.length - 1; i >= 0; i--) {
137
- if (findCompactionPart(messages[i]!)) {
138
- markerIdx = i
139
- break
140
- }
141
- }
142
-
143
- if (markerIdx === -1) {
144
- return messages.flatMap(expandMessage)
145
- }
146
-
147
- const marker = findCompactionPart(messages[markerIdx]!)!
148
- const seed = LLM.user(`${COMPACTION_PREFIX}\n${marker.summary}`)
149
- const tail = messages.slice(markerIdx + 1)
150
- return [seed, ...tail.flatMap(expandMessage)]
151
- }
@@ -1,156 +0,0 @@
1
- import { Id } from "@tinyweb-agent-framework/core"
2
-
3
- // Session identifiers
4
- export type SessionID = string & { readonly _brand: "SessionID" }
5
- export type MessageID = string & { readonly _brand: "MessageID" }
6
- export type PartID = string & { readonly _brand: "PartID" }
7
-
8
- export const newSessionID = (): SessionID => Id.prefixed("ses") as SessionID
9
- export const newMessageID = (): MessageID => Id.prefixed("msg") as MessageID
10
- export const newPartID = (): PartID => Id.prefixed("prt") as PartID
11
-
12
- // Session info
13
- export type CreateSessionInput = {
14
- readonly agentName: string
15
- readonly title?: string
16
- readonly metadata?: Record<string, unknown>
17
- }
18
-
19
- export namespace Session {
20
- export type Info = {
21
- readonly id: SessionID
22
- readonly agentName: string
23
- readonly title?: string
24
- readonly metadata?: Record<string, unknown>
25
- readonly createdAt: number
26
- readonly updatedAt: number
27
- }
28
- }
29
-
30
- // Message part types (app-level, separate from LLM wire format)
31
- export type TextPart = {
32
- readonly type: "text"
33
- readonly text: string
34
- }
35
-
36
- export type ImagePart = {
37
- readonly type: "image"
38
- readonly url?: string
39
- readonly data?: string // base64
40
- readonly mediaType?: string
41
- }
42
-
43
- export type ReasoningPart = {
44
- readonly type: "reasoning"
45
- readonly text: string
46
- }
47
-
48
- /**
49
- * Lifecycle of a tool call inside an assistant message.
50
- *
51
- * Approval flow (interrupt mode):
52
- * running → pending-approval → approved → running → complete
53
- * └→ rejected → error
54
- */
55
- export type ToolPartState =
56
- | "pending"
57
- | "running"
58
- | "complete"
59
- | "error"
60
- | "pending-approval"
61
- | "approved"
62
- | "rejected"
63
-
64
- export type ToolPart = {
65
- readonly id: PartID
66
- readonly type: "tool"
67
- readonly callID: string
68
- readonly name: string
69
- readonly state: ToolPartState
70
- readonly input: unknown
71
- readonly output?: unknown
72
- readonly metadata?: Record<string, unknown>
73
- }
74
-
75
- /**
76
- * Marker part inserted by the auto-compaction flow. Sits on a synthetic user
77
- * message that replaces the summarised tail of the conversation. `tailStartId`
78
- * is the id of the first non-compacted message that should still be replayed.
79
- */
80
- export type CompactionPart = {
81
- readonly type: "compaction"
82
- readonly summary: string
83
- readonly tailStartId?: MessageID
84
- readonly auto: boolean
85
- readonly overflow: boolean
86
- }
87
-
88
- // Messages
89
- export type UserMessage = {
90
- readonly id: MessageID
91
- readonly role: "user"
92
- readonly parts: ReadonlyArray<TextPart | ImagePart | CompactionPart>
93
- }
94
-
95
- export type AssistantMessage = {
96
- readonly id: MessageID
97
- readonly role: "assistant"
98
- readonly parts: ReadonlyArray<TextPart | ToolPart | ReasoningPart>
99
- readonly modelId?: string
100
- readonly providerId?: string
101
- readonly usage?: {
102
- readonly inputTokens?: number
103
- readonly outputTokens?: number
104
- readonly totalTokens?: number
105
- }
106
- }
107
-
108
- export type Message = UserMessage | AssistantMessage
109
-
110
- // Helpers to construct messages
111
- export type MakeUserMessageInput =
112
- | string
113
- | {
114
- readonly text: string
115
- readonly images?: ReadonlyArray<ImagePart>
116
- }
117
-
118
- export const makeUserMessage = (input: MakeUserMessageInput): UserMessage => {
119
- const text = typeof input === "string" ? input : input.text
120
- const images = typeof input === "string" ? [] : (input.images ?? [])
121
- const parts: Array<TextPart | ImagePart> = []
122
- if (text.length > 0) parts.push({ type: "text", text })
123
- for (const img of images) parts.push(img)
124
- return { id: newMessageID(), role: "user", parts }
125
- }
126
-
127
- export const makeAssistantMessage = (parts: AssistantMessage["parts"]): AssistantMessage => ({
128
- id: newMessageID(),
129
- role: "assistant",
130
- parts,
131
- })
132
-
133
- /** Build a synthetic user message that carries a compaction marker. */
134
- export const makeCompactionMessage = (input: {
135
- readonly summary: string
136
- readonly tailStartId?: MessageID
137
- readonly auto?: boolean
138
- readonly overflow?: boolean
139
- }): UserMessage => ({
140
- id: newMessageID(),
141
- role: "user",
142
- parts: [
143
- {
144
- type: "compaction",
145
- summary: input.summary,
146
- tailStartId: input.tailStartId,
147
- auto: input.auto ?? true,
148
- overflow: input.overflow ?? false,
149
- },
150
- ],
151
- })
152
-
153
- export const findCompactionPart = (msg: Message): CompactionPart | undefined => {
154
- if (msg.role !== "user") return undefined
155
- return msg.parts.find((p): p is CompactionPart => (p as { type: string }).type === "compaction")
156
- }
@@ -1,309 +0,0 @@
1
- import { Database } from "bun:sqlite"
2
- import { drizzle } from "drizzle-orm/bun-sqlite"
3
- import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"
4
- import { and, desc, eq, lt, or, sql } from "drizzle-orm"
5
- import { Effect } from "effect"
6
- import { mkdirSync } from "node:fs"
7
- import { dirname } from "node:path"
8
- import type { ListSessionsOpts, ListSessionsResult, SessionPatch, SessionStore, GetMessagesOpts } from "./adapter"
9
- import {
10
- newSessionID,
11
- type CreateSessionInput,
12
- type Message,
13
- type MessageID,
14
- type Session,
15
- type SessionID,
16
- } from "./schema"
17
-
18
- // Drizzle schema — snake_case per AGENTS.md
19
- const sessions = sqliteTable("sessions", {
20
- id: text("id").primaryKey(),
21
- agent_name: text("agent_name").notNull(),
22
- title: text("title"),
23
- metadata: text("metadata"), // JSON
24
- owner_id: text("owner_id"),
25
- created_at: integer("created_at").notNull(),
26
- updated_at: integer("updated_at").notNull(),
27
- })
28
-
29
- const messages = sqliteTable("messages", {
30
- id: text("id").primaryKey(),
31
- session_id: text("session_id").notNull(),
32
- role: text("role").notNull(),
33
- parts: text("parts").notNull(), // JSON
34
- model_id: text("model_id"),
35
- provider_id: text("provider_id"),
36
- usage: text("usage"), // JSON
37
- created_at: integer("created_at").notNull(),
38
- })
39
-
40
- const CREATE_SESSIONS = `
41
- CREATE TABLE IF NOT EXISTS sessions (
42
- id TEXT PRIMARY KEY,
43
- agent_name TEXT NOT NULL,
44
- title TEXT,
45
- metadata TEXT,
46
- owner_id TEXT,
47
- created_at INTEGER NOT NULL,
48
- updated_at INTEGER NOT NULL
49
- )
50
- `
51
-
52
- const ADD_OWNER_COLUMN = `ALTER TABLE sessions ADD COLUMN owner_id TEXT`
53
-
54
- const CREATE_MESSAGES = `
55
- CREATE TABLE IF NOT EXISTS messages (
56
- id TEXT PRIMARY KEY,
57
- session_id TEXT NOT NULL,
58
- role TEXT NOT NULL,
59
- parts TEXT NOT NULL,
60
- model_id TEXT,
61
- provider_id TEXT,
62
- usage TEXT,
63
- created_at INTEGER NOT NULL
64
- )
65
- `
66
-
67
- const CREATE_INDEXES = [
68
- `CREATE INDEX IF NOT EXISTS sessions_updated_at_idx ON sessions(updated_at DESC, id DESC)`,
69
- `CREATE INDEX IF NOT EXISTS sessions_owner_idx ON sessions(owner_id)`,
70
- `CREATE INDEX IF NOT EXISTS messages_session_created_idx ON messages(session_id, created_at, id)`,
71
- ]
72
-
73
- const rowToInfo = (row: typeof sessions.$inferSelect): Session.Info => {
74
- const baseMetadata = row.metadata ? (JSON.parse(row.metadata) as Record<string, unknown>) : undefined
75
- const metadata = row.owner_id
76
- ? { ...(baseMetadata ?? {}), ownerId: row.owner_id }
77
- : baseMetadata
78
- return {
79
- id: row.id as SessionID,
80
- agentName: row.agent_name,
81
- title: row.title ?? undefined,
82
- metadata,
83
- createdAt: row.created_at,
84
- updatedAt: row.updated_at,
85
- }
86
- }
87
-
88
- const rowToMessage = (row: typeof messages.$inferSelect): Message => JSON.parse(row.parts) as Message
89
-
90
- type Cursor = { readonly updatedAt: number; readonly id: string }
91
-
92
- const encodeCursor = (cursor: Cursor): string =>
93
- Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url")
94
-
95
- const decodeCursor = (raw: string): Cursor | undefined => {
96
- const parsed = JSON.parse(Buffer.from(raw, "base64url").toString("utf8")) as Partial<Cursor>
97
- if (typeof parsed.updatedAt !== "number" || typeof parsed.id !== "string") return undefined
98
- return { updatedAt: parsed.updatedAt, id: parsed.id }
99
- }
100
-
101
- export const makeSqliteStore = (dbPath = "./.tinyweb-agent/agent.db"): SessionStore => {
102
- mkdirSync(dirname(dbPath), { recursive: true })
103
- const sqlite = new Database(dbPath)
104
- sqlite.exec(CREATE_SESSIONS)
105
- // Idempotent ALTER for owner_id (added in v2). Ignore "duplicate column".
106
- try {
107
- sqlite.exec(ADD_OWNER_COLUMN)
108
- } catch {
109
- // column already exists
110
- }
111
- sqlite.exec(CREATE_MESSAGES)
112
- for (const stmt of CREATE_INDEXES) sqlite.exec(stmt)
113
- const db = drizzle({ client: sqlite })
114
-
115
- const ownerFromMetadata = (metadata: Record<string, unknown> | undefined): string | null => {
116
- const owner = (metadata as { ownerId?: unknown } | undefined)?.ownerId
117
- return typeof owner === "string" ? owner : null
118
- }
119
-
120
- const createSession = (input: CreateSessionInput): Effect.Effect<Session.Info> => {
121
- const now = Date.now()
122
- const info: Session.Info = {
123
- id: newSessionID(),
124
- agentName: input.agentName,
125
- title: input.title,
126
- metadata: input.metadata,
127
- createdAt: now,
128
- updatedAt: now,
129
- }
130
- db.insert(sessions)
131
- .values({
132
- id: info.id,
133
- agent_name: info.agentName,
134
- title: info.title,
135
- metadata: info.metadata ? JSON.stringify(info.metadata) : null,
136
- owner_id: ownerFromMetadata(info.metadata),
137
- created_at: info.createdAt,
138
- updated_at: info.updatedAt,
139
- })
140
- .run()
141
- return Effect.succeed(info)
142
- }
143
-
144
- const getSession = (id: SessionID | string): Effect.Effect<Session.Info | undefined> => {
145
- const rows = db.select().from(sessions).where(eq(sessions.id, id)).all()
146
- const row = rows[0]
147
- return Effect.succeed(row ? rowToInfo(row) : undefined)
148
- }
149
-
150
- const upsertSession = (
151
- input: CreateSessionInput & { id?: SessionID | string },
152
- ): Effect.Effect<Session.Info> => {
153
- if (input.id) {
154
- const rows = db.select().from(sessions).where(eq(sessions.id, input.id)).all()
155
- const row = rows[0]
156
- if (row) return Effect.succeed(rowToInfo(row))
157
- }
158
- return createSession(input)
159
- }
160
-
161
- const listSessions = (opts?: ListSessionsOpts): Effect.Effect<ListSessionsResult> => {
162
- const limit = opts?.limit ?? 50
163
- const filters = [
164
- opts?.agentName ? eq(sessions.agent_name, opts.agentName) : undefined,
165
- opts?.ownerId ? eq(sessions.owner_id, opts.ownerId) : undefined,
166
- ].filter((c): c is Exclude<typeof c, undefined> => c !== undefined)
167
-
168
- const cursor = opts?.cursor ? decodeCursor(opts.cursor) : undefined
169
- const cursorClause = cursor
170
- ? or(
171
- lt(sessions.updated_at, cursor.updatedAt),
172
- and(eq(sessions.updated_at, cursor.updatedAt), lt(sessions.id, cursor.id)),
173
- )
174
- : undefined
175
- const whereClause = cursorClause ? and(...filters, cursorClause) : filters.length > 0 ? and(...filters) : undefined
176
-
177
- const rows = db
178
- .select()
179
- .from(sessions)
180
- .where(whereClause)
181
- .orderBy(desc(sessions.updated_at), desc(sessions.id))
182
- .limit(limit + 1)
183
- .all()
184
-
185
- const hasMore = rows.length > limit
186
- const page = hasMore ? rows.slice(0, limit) : rows
187
- const tail = page[page.length - 1]
188
- const nextCursor = hasMore && tail ? encodeCursor({ updatedAt: tail.updated_at, id: tail.id }) : undefined
189
-
190
- return Effect.succeed({ items: page.map(rowToInfo), nextCursor })
191
- }
192
-
193
- const updateSession = (
194
- id: SessionID | string,
195
- patch: SessionPatch,
196
- ): Effect.Effect<Session.Info | undefined> => {
197
- const existing = db.select().from(sessions).where(eq(sessions.id, id)).all()[0]
198
- if (!existing) return Effect.succeed(undefined)
199
- const setClause: Partial<typeof sessions.$inferInsert> = { updated_at: Date.now() }
200
- if (patch.title !== undefined) setClause.title = patch.title
201
- if (patch.metadata !== undefined) {
202
- setClause.metadata = JSON.stringify(patch.metadata)
203
- setClause.owner_id = ownerFromMetadata(patch.metadata)
204
- }
205
- db.update(sessions).set(setClause).where(eq(sessions.id, id)).run()
206
- const row = db.select().from(sessions).where(eq(sessions.id, id)).all()[0]
207
- return Effect.succeed(row ? rowToInfo(row) : undefined)
208
- }
209
-
210
- const appendMessage = (sessionId: SessionID | string, msg: Message): Effect.Effect<void> => {
211
- const msgRow = msg as AssistantMessageRow
212
- const now = Date.now()
213
- // Idempotent: overflow-retry / double-finalize must not crash on PK.
214
- const existing = db.select().from(messages).where(eq(messages.id, msg.id)).all()[0]
215
- if (existing) {
216
- db.update(sessions).set({ updated_at: now }).where(eq(sessions.id, sessionId)).run()
217
- return Effect.void
218
- }
219
- db.insert(messages)
220
- .values({
221
- id: msg.id,
222
- session_id: sessionId,
223
- role: msg.role,
224
- parts: JSON.stringify(msg),
225
- model_id: msgRow.modelId,
226
- provider_id: msgRow.providerId,
227
- usage: msgRow.usage ? JSON.stringify(msgRow.usage) : null,
228
- created_at: now,
229
- })
230
- .run()
231
- db.update(sessions).set({ updated_at: now }).where(eq(sessions.id, sessionId)).run()
232
- return Effect.void
233
- }
234
-
235
- const getMessages = (sessionId: SessionID | string, opts?: GetMessagesOpts): Effect.Effect<Message[]> => {
236
- const beforeClause = opts?.before
237
- ? lt(
238
- messages.created_at,
239
- sql<number>`(SELECT created_at FROM messages WHERE id = ${opts.before})`,
240
- )
241
- : undefined
242
- const where = beforeClause ? and(eq(messages.session_id, sessionId), beforeClause) : eq(messages.session_id, sessionId)
243
- const rows = db
244
- .select()
245
- .from(messages)
246
- .where(where)
247
- .orderBy(messages.created_at, messages.id)
248
- .all()
249
- const limited = opts?.limit ? rows.slice(-opts.limit) : rows
250
- return Effect.succeed(limited.map(rowToMessage))
251
- }
252
-
253
- const deleteMessage = (
254
- sessionId: SessionID | string,
255
- messageId: MessageID | string,
256
- ): Effect.Effect<void> => {
257
- db.delete(messages)
258
- .where(and(eq(messages.session_id, sessionId), eq(messages.id, messageId)))
259
- .run()
260
- return Effect.void
261
- }
262
-
263
- const updateMessage = (
264
- sessionId: SessionID | string,
265
- messageId: MessageID | string,
266
- msg: Message,
267
- ): Effect.Effect<void> => {
268
- const msgRow = msg as AssistantMessageRow
269
- const now = Date.now()
270
- db.update(messages)
271
- .set({
272
- role: msg.role,
273
- parts: JSON.stringify(msg),
274
- model_id: msgRow.modelId ?? null,
275
- provider_id: msgRow.providerId ?? null,
276
- usage: msgRow.usage ? JSON.stringify(msgRow.usage) : null,
277
- })
278
- .where(and(eq(messages.session_id, sessionId), eq(messages.id, messageId)))
279
- .run()
280
- db.update(sessions).set({ updated_at: now }).where(eq(sessions.id, sessionId)).run()
281
- return Effect.void
282
- }
283
-
284
- const deleteSession = (id: SessionID | string): Effect.Effect<void> => {
285
- db.delete(messages).where(eq(messages.session_id, id)).run()
286
- db.delete(sessions).where(eq(sessions.id, id)).run()
287
- return Effect.void
288
- }
289
-
290
- return {
291
- createSession,
292
- getSession,
293
- upsertSession,
294
- listSessions,
295
- updateSession,
296
- appendMessage,
297
- getMessages,
298
- deleteMessage,
299
- updateMessage,
300
- deleteSession,
301
- }
302
- }
303
-
304
- // Internal helper type for assistant message fields
305
- type AssistantMessageRow = {
306
- modelId?: string
307
- providerId?: string
308
- usage?: unknown
309
- }