@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.
@@ -0,0 +1,140 @@
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
+ export type ToolPart = {
49
+ readonly id: PartID
50
+ readonly type: "tool"
51
+ readonly callID: string
52
+ readonly name: string
53
+ readonly state: "pending" | "running" | "complete" | "error"
54
+ readonly input: unknown
55
+ readonly output?: unknown
56
+ readonly metadata?: Record<string, unknown>
57
+ }
58
+
59
+ /**
60
+ * Marker part inserted by the auto-compaction flow. Sits on a synthetic user
61
+ * message that replaces the summarised tail of the conversation. `tailStartId`
62
+ * is the id of the first non-compacted message that should still be replayed.
63
+ */
64
+ export type CompactionPart = {
65
+ readonly type: "compaction"
66
+ readonly summary: string
67
+ readonly tailStartId?: MessageID
68
+ readonly auto: boolean
69
+ readonly overflow: boolean
70
+ }
71
+
72
+ // Messages
73
+ export type UserMessage = {
74
+ readonly id: MessageID
75
+ readonly role: "user"
76
+ readonly parts: ReadonlyArray<TextPart | ImagePart | CompactionPart>
77
+ }
78
+
79
+ export type AssistantMessage = {
80
+ readonly id: MessageID
81
+ readonly role: "assistant"
82
+ readonly parts: ReadonlyArray<TextPart | ToolPart | ReasoningPart>
83
+ readonly modelId?: string
84
+ readonly providerId?: string
85
+ readonly usage?: {
86
+ readonly inputTokens?: number
87
+ readonly outputTokens?: number
88
+ readonly totalTokens?: number
89
+ }
90
+ }
91
+
92
+ export type Message = UserMessage | AssistantMessage
93
+
94
+ // Helpers to construct messages
95
+ export type MakeUserMessageInput =
96
+ | string
97
+ | {
98
+ readonly text: string
99
+ readonly images?: ReadonlyArray<ImagePart>
100
+ }
101
+
102
+ export const makeUserMessage = (input: MakeUserMessageInput): UserMessage => {
103
+ const text = typeof input === "string" ? input : input.text
104
+ const images = typeof input === "string" ? [] : (input.images ?? [])
105
+ const parts: Array<TextPart | ImagePart> = []
106
+ if (text.length > 0) parts.push({ type: "text", text })
107
+ for (const img of images) parts.push(img)
108
+ return { id: newMessageID(), role: "user", parts }
109
+ }
110
+
111
+ export const makeAssistantMessage = (parts: AssistantMessage["parts"]): AssistantMessage => ({
112
+ id: newMessageID(),
113
+ role: "assistant",
114
+ parts,
115
+ })
116
+
117
+ /** Build a synthetic user message that carries a compaction marker. */
118
+ export const makeCompactionMessage = (input: {
119
+ readonly summary: string
120
+ readonly tailStartId?: MessageID
121
+ readonly auto?: boolean
122
+ readonly overflow?: boolean
123
+ }): UserMessage => ({
124
+ id: newMessageID(),
125
+ role: "user",
126
+ parts: [
127
+ {
128
+ type: "compaction",
129
+ summary: input.summary,
130
+ tailStartId: input.tailStartId,
131
+ auto: input.auto ?? true,
132
+ overflow: input.overflow ?? false,
133
+ },
134
+ ],
135
+ })
136
+
137
+ export const findCompactionPart = (msg: Message): CompactionPart | undefined => {
138
+ if (msg.role !== "user") return undefined
139
+ return msg.parts.find((p): p is CompactionPart => (p as { type: string }).type === "compaction")
140
+ }
@@ -0,0 +1,281 @@
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
+ db.insert(messages)
214
+ .values({
215
+ id: msg.id,
216
+ session_id: sessionId,
217
+ role: msg.role,
218
+ parts: JSON.stringify(msg),
219
+ model_id: msgRow.modelId,
220
+ provider_id: msgRow.providerId,
221
+ usage: msgRow.usage ? JSON.stringify(msgRow.usage) : null,
222
+ created_at: now,
223
+ })
224
+ .run()
225
+ db.update(sessions).set({ updated_at: now }).where(eq(sessions.id, sessionId)).run()
226
+ return Effect.void
227
+ }
228
+
229
+ const getMessages = (sessionId: SessionID | string, opts?: GetMessagesOpts): Effect.Effect<Message[]> => {
230
+ const beforeClause = opts?.before
231
+ ? lt(
232
+ messages.created_at,
233
+ sql<number>`(SELECT created_at FROM messages WHERE id = ${opts.before})`,
234
+ )
235
+ : undefined
236
+ const where = beforeClause ? and(eq(messages.session_id, sessionId), beforeClause) : eq(messages.session_id, sessionId)
237
+ const rows = db
238
+ .select()
239
+ .from(messages)
240
+ .where(where)
241
+ .orderBy(messages.created_at, messages.id)
242
+ .all()
243
+ const limited = opts?.limit ? rows.slice(-opts.limit) : rows
244
+ return Effect.succeed(limited.map(rowToMessage))
245
+ }
246
+
247
+ const deleteMessage = (
248
+ sessionId: SessionID | string,
249
+ messageId: MessageID | string,
250
+ ): Effect.Effect<void> => {
251
+ db.delete(messages)
252
+ .where(and(eq(messages.session_id, sessionId), eq(messages.id, messageId)))
253
+ .run()
254
+ return Effect.void
255
+ }
256
+
257
+ const deleteSession = (id: SessionID | string): Effect.Effect<void> => {
258
+ db.delete(messages).where(eq(messages.session_id, id)).run()
259
+ db.delete(sessions).where(eq(sessions.id, id)).run()
260
+ return Effect.void
261
+ }
262
+
263
+ return {
264
+ createSession,
265
+ getSession,
266
+ upsertSession,
267
+ listSessions,
268
+ updateSession,
269
+ appendMessage,
270
+ getMessages,
271
+ deleteMessage,
272
+ deleteSession,
273
+ }
274
+ }
275
+
276
+ // Internal helper type for assistant message fields
277
+ type AssistantMessageRow = {
278
+ modelId?: string
279
+ providerId?: string
280
+ usage?: unknown
281
+ }
@@ -0,0 +1,103 @@
1
+ // SessionAPI — Promise-based session CRUD facade for consumers.
2
+ // Hides Effect runtime. Used by the SDK / HTTP handlers / app routes.
3
+
4
+ import { Effect } from "effect"
5
+ import { defaultRuntime, type AgentRuntime } from "./runtime"
6
+ import type {
7
+ ListSessionsOpts,
8
+ ListSessionsResult,
9
+ GetMessagesOpts,
10
+ SessionPatch,
11
+ SessionStore,
12
+ } from "./session/adapter"
13
+ import type { Message, MessageID, Session, SessionID } from "./session/schema"
14
+
15
+ export type CreateSessionAPIInput = {
16
+ readonly title?: string
17
+ readonly metadata?: Record<string, unknown>
18
+ readonly ownerId?: string
19
+ }
20
+
21
+ export type ListSessionsAPIOpts = {
22
+ readonly limit?: number
23
+ readonly cursor?: string
24
+ readonly ownerId?: string
25
+ }
26
+
27
+ export type MessagesAPIResult = {
28
+ readonly items: ReadonlyArray<Message>
29
+ /** Optional cursor for older messages (when `before` was used and more remain). */
30
+ readonly nextCursor?: string
31
+ }
32
+
33
+ export interface SessionAPI {
34
+ create(input?: CreateSessionAPIInput): Promise<Session.Info>
35
+ list(opts?: ListSessionsAPIOpts): Promise<ListSessionsResult>
36
+ get(id: SessionID | string): Promise<Session.Info | undefined>
37
+ delete(id: SessionID | string): Promise<void>
38
+ setTitle(id: SessionID | string, title: string): Promise<Session.Info | undefined>
39
+ setMetadata(id: SessionID | string, metadata: Record<string, unknown>): Promise<Session.Info | undefined>
40
+ patch(id: SessionID | string, patch: SessionPatch): Promise<Session.Info | undefined>
41
+ messages(sessionId: SessionID | string, opts?: GetMessagesOpts): Promise<MessagesAPIResult>
42
+ deleteMessage(sessionId: SessionID | string, messageId: MessageID | string): Promise<void>
43
+ }
44
+
45
+ export type MakeSessionAPIConfig = {
46
+ readonly agentName: string
47
+ readonly store: SessionStore
48
+ readonly runtime?: AgentRuntime
49
+ }
50
+
51
+ const withOwner = (
52
+ input: CreateSessionAPIInput | undefined,
53
+ metadata: Record<string, unknown> | undefined,
54
+ ): Record<string, unknown> | undefined => {
55
+ if (!input?.ownerId) return metadata
56
+ return { ...(metadata ?? {}), ownerId: input.ownerId }
57
+ }
58
+
59
+ export const makeSessionAPI = (config: MakeSessionAPIConfig): SessionAPI => {
60
+ const rt = (): AgentRuntime => config.runtime ?? defaultRuntime()
61
+ const run = <A>(effect: Effect.Effect<A>): Promise<A> => rt().runPromise(effect)
62
+
63
+ return {
64
+ create: (input) =>
65
+ run(
66
+ config.store.createSession({
67
+ agentName: config.agentName,
68
+ title: input?.title,
69
+ metadata: withOwner(input, input?.metadata),
70
+ }),
71
+ ),
72
+
73
+ list: (opts) =>
74
+ run(
75
+ config.store.listSessions({
76
+ limit: opts?.limit,
77
+ cursor: opts?.cursor,
78
+ agentName: config.agentName,
79
+ ownerId: opts?.ownerId,
80
+ }),
81
+ ),
82
+
83
+ get: (id) => run(config.store.getSession(id)),
84
+
85
+ delete: (id) => run(config.store.deleteSession(id)),
86
+
87
+ setTitle: (id, title) => run(config.store.updateSession(id, { title })),
88
+
89
+ setMetadata: (id, metadata) => run(config.store.updateSession(id, { metadata })),
90
+
91
+ patch: (id, patch) => run(config.store.updateSession(id, patch)),
92
+
93
+ messages: async (sessionId, opts) => {
94
+ const items = await run(config.store.getMessages(sessionId, opts))
95
+ // If a limit was supplied and we hit it, surface the oldest id as a "before" cursor.
96
+ const nextCursor =
97
+ opts?.limit && items.length === opts.limit && items[0] ? (items[0].id as string) : undefined
98
+ return { items, nextCursor }
99
+ },
100
+
101
+ deleteMessage: (sessionId, messageId) => run(config.store.deleteMessage(sessionId, messageId)),
102
+ }
103
+ }
@@ -0,0 +1,113 @@
1
+ // Adapted from opencode@v1.14.48 packages/opencode/src/skill/
2
+
3
+ import { readdir, readFile } from "node:fs/promises"
4
+ import { join, dirname } from "node:path"
5
+ import { homedir } from "node:os"
6
+
7
+ // ---------------------------------------------------------------------------
8
+ // Skill types
9
+ // ---------------------------------------------------------------------------
10
+
11
+ export type SkillInfo = {
12
+ readonly name: string
13
+ readonly description?: string
14
+ readonly location: string
15
+ readonly content: string
16
+ }
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Frontmatter parsing — minimal YAML-ish subset (name: / description:)
20
+ // ---------------------------------------------------------------------------
21
+
22
+ function parseFrontmatter(raw: string): { name?: string; description?: string; body: string } {
23
+ if (!raw.startsWith("---")) return { body: raw }
24
+ const end = raw.indexOf("\n---", 3)
25
+ if (end === -1) return { body: raw }
26
+ const fm = raw.slice(3, end).trim()
27
+ const body = raw.slice(end + 4).trim()
28
+ const name = fm.match(/^name:\s*(.+)$/m)?.[1]?.trim()
29
+ const description = fm.match(/^description:\s*(.+)$/m)?.[1]?.trim()
30
+ return { name, description, body }
31
+ }
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Scan a directory recursively for SKILL.md files
35
+ // ---------------------------------------------------------------------------
36
+
37
+ async function scanDir(dir: string): Promise<SkillInfo[]> {
38
+ const results: SkillInfo[] = []
39
+ let entries: { name: string; isDirectory: () => boolean }[] = []
40
+ try {
41
+ entries = await readdir(dir, { withFileTypes: true })
42
+ } catch {
43
+ return results
44
+ }
45
+ for (const entry of entries) {
46
+ const full = join(dir, entry.name)
47
+ if (entry.isDirectory()) {
48
+ const nested = await scanDir(full)
49
+ results.push(...nested)
50
+ } else if (entry.name === "SKILL.md") {
51
+ const raw = await readFile(full, "utf-8").catch(() => "")
52
+ if (!raw) continue
53
+ const { name, description, body } = parseFrontmatter(raw)
54
+ if (!name) continue
55
+ results.push({ name, description, location: full, content: body || raw })
56
+ }
57
+ }
58
+ return results
59
+ }
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // Default skill directories
63
+ // ---------------------------------------------------------------------------
64
+
65
+ function defaultSkillDirs(): string[] {
66
+ return [
67
+ join(process.cwd(), "skills"),
68
+ join(homedir(), ".tinyweb-agent", "skills"),
69
+ ]
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // loadSkills — scan all dirs and return deduplicated skill list
74
+ // ---------------------------------------------------------------------------
75
+
76
+ export async function loadSkills(extraDirs: string[] = []): Promise<SkillInfo[]> {
77
+ const dirs = [...defaultSkillDirs(), ...extraDirs]
78
+ const all: SkillInfo[] = []
79
+ for (const dir of dirs) {
80
+ const found = await scanDir(dir)
81
+ all.push(...found)
82
+ }
83
+ // Deduplicate by name, last-wins
84
+ const byName = new Map<string, SkillInfo>()
85
+ for (const skill of all) {
86
+ byName.set(skill.name, skill)
87
+ }
88
+ return Array.from(byName.values())
89
+ }
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // makeSkillTool — returns an AnyExecutableTool that retrieves skill content
93
+ // ---------------------------------------------------------------------------
94
+
95
+ import { Tool, ToolFailure } from "@tinyweb-agent-framework/llm"
96
+ import { Effect, Schema } from "effect"
97
+
98
+ export function makeSkillTool(skills: SkillInfo[]): Tool.AnyExecutableTool {
99
+ const byName = new Map(skills.map((s) => [s.name, s]))
100
+ const names = skills.map((s) => s.name).join(", ")
101
+
102
+ return Tool.make({
103
+ description: `Load skill instructions by name. Available skills: ${names || "(none)"}. Returns the skill's markdown content.`,
104
+ parameters: Schema.Struct({ name: Schema.String }),
105
+ success: Schema.Struct({ name: Schema.String, content: Schema.String }),
106
+ execute: (input) => {
107
+ const skill = byName.get(input.name)
108
+ if (!skill)
109
+ return Effect.fail(new ToolFailure({ message: `Skill "${input.name}" not found. Available: ${names || "(none)"}` }))
110
+ return Effect.succeed({ name: skill.name, content: skill.content })
111
+ },
112
+ }) as Tool.AnyExecutableTool
113
+ }
@@ -0,0 +1,67 @@
1
+ import {
2
+ AI_SDK_HEADERS,
3
+ encodeSSE,
4
+ toAISDKDataStream,
5
+ type AgentEvent as ProtocolAgentEvent,
6
+ } from "@tinyweb-agent-framework/protocol"
7
+ import type { AgentEvent } from "./events"
8
+
9
+ export type SSEFormat = "tinyweb" | "ai-sdk"
10
+
11
+ export type SSEHandlerOptions = {
12
+ readonly format?: SSEFormat
13
+ }
14
+
15
+ // Minimal duck-typed Node http req/res shapes so the handler stays node:http-free.
16
+ type NodeReq = {
17
+ readonly method?: string
18
+ readonly url?: string
19
+ // body is consumer-provided; handler reads via on('data') events.
20
+ on?: (event: string, listener: (...args: unknown[]) => void) => unknown
21
+ }
22
+
23
+ type NodeRes = {
24
+ setHeader: (name: string, value: string) => unknown
25
+ write: (chunk: string | Uint8Array) => unknown
26
+ end: (chunk?: string | Uint8Array) => unknown
27
+ flushHeaders?: () => unknown
28
+ on?: (event: string, listener: (...args: unknown[]) => void) => unknown
29
+ }
30
+
31
+ const TINYWEB_HEADERS: Readonly<Record<string, string>> = {
32
+ "Content-Type": "text/event-stream",
33
+ "Cache-Control": "no-cache, no-transform",
34
+ Connection: "keep-alive",
35
+ }
36
+
37
+ // Bridge a server's stream of AgentEvents to an outbound HTTP response in either
38
+ // the framework's native SSE format or the Vercel AI SDK Data Stream format.
39
+ export const writeEventsToResponse = async (
40
+ events: AsyncIterable<AgentEvent>,
41
+ res: NodeRes,
42
+ format: SSEFormat = "tinyweb",
43
+ ): Promise<void> => {
44
+ const headers = format === "ai-sdk" ? AI_SDK_HEADERS : TINYWEB_HEADERS
45
+ for (const [name, value] of Object.entries(headers)) res.setHeader(name, value)
46
+ if (typeof res.flushHeaders === "function") res.flushHeaders()
47
+ for await (const event of events) {
48
+ const protocolEvent = event as ProtocolAgentEvent
49
+ const line = format === "ai-sdk" ? toAISDKDataStream(protocolEvent) : encodeSSE(protocolEvent)
50
+ if (line.length > 0) res.write(line)
51
+ }
52
+ res.end()
53
+ }
54
+
55
+ // Build a Node http-style handler for an agent. Caller is responsible for parsing
56
+ // the request body and supplying { prompt, sessionId? } to `getInput`.
57
+ export const makeSSEHandler = (
58
+ run: (input: { prompt: string; sessionId?: string }) => AsyncIterable<AgentEvent>,
59
+ options: SSEHandlerOptions = {},
60
+ ) => {
61
+ const format = options.format ?? "tinyweb"
62
+ return async (input: { prompt: string; sessionId?: string }, res: NodeRes): Promise<void> => {
63
+ await writeEventsToResponse(run(input), res, format)
64
+ }
65
+ }
66
+
67
+ export type { NodeReq, NodeRes }