@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tinyweb-agent-framework contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,279 @@
1
+ # @tinyweb-agent-framework/agent
2
+
3
+ Public entry point for building agents. Combines the `llm`, `tool`, `protocol`, and `core` packages into a friendly Promise/AsyncIterator API. **Effect-TS is hidden** from the public surface.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ bun add @tinyweb-agent-framework/agent @tinyweb-agent-framework/llm
9
+ ```
10
+
11
+ ## `defineAgent(config)`
12
+
13
+ ```ts
14
+ import { defineAgent } from "@tinyweb-agent-framework/agent"
15
+ import { OpenAI } from "@tinyweb-agent-framework/llm"
16
+
17
+ const agent = defineAgent({
18
+ name: "my-agent",
19
+ model: OpenAI.chat("gpt-4o-mini", { apiKey: process.env.OPENAI_API_KEY! }),
20
+ systemPrompt: "Helpful, concise.",
21
+ // tools, permission, plugins, mcp, skillDirs, store, stopWhen, generation … all optional
22
+ })
23
+ ```
24
+
25
+ ### Streaming
26
+
27
+ ```ts
28
+ for await (const event of agent.run({ prompt: "Hello", sessionId: "abc" })) {
29
+ if (event.type === "text-delta") process.stdout.write(event.text)
30
+ if (event.type === "tool-call") console.log("[tool]", event.name, event.input)
31
+ }
32
+ ```
33
+
34
+ ### One-shot
35
+
36
+ ```ts
37
+ const { text, usage } = await agent.runOnce({ prompt: "Summarise Bun in one line" })
38
+ ```
39
+
40
+ ### Express / HTTP
41
+
42
+ ```ts
43
+ const handler = agent.toSSEHandler({ format: "ai-sdk" }) // or "tinyweb"
44
+ app.post("/agent", (req, res) => handler({ prompt: req.body.prompt }, res))
45
+ ```
46
+
47
+ ## `defineTool(config)`
48
+
49
+ ```ts
50
+ import { defineTool } from "@tinyweb-agent-framework/agent"
51
+ import { Schema } from "effect"
52
+
53
+ const slugify = defineTool({
54
+ description: "Slugify a string",
55
+ parameters: Schema.Struct({ text: Schema.String }),
56
+ execute: async ({ text }) =>
57
+ ({ slug: text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") }),
58
+ })
59
+ ```
60
+
61
+ Effect-style `execute` is also accepted (return `Effect<S, ToolFailure>`).
62
+
63
+ ## Sessions, history & storage
64
+
65
+ Pass `sessionId` to `agent.run({...})` or `agent.runOnce({...})` and the agent automatically:
66
+
67
+ 1. Persists every user prompt and assistant reply to the configured store.
68
+ 2. Replays the full conversation into the LLM on the next turn.
69
+
70
+ ```ts
71
+ for await (const event of agent.run({ sessionId: "user-42-thread-1", prompt: "Hello" })) {
72
+ if (event.type === "text-delta") process.stdout.write(event.text)
73
+ }
74
+
75
+ // Later — model still remembers
76
+ await agent.runOnce({ sessionId: "user-42-thread-1", prompt: "What did I say?" })
77
+ ```
78
+
79
+ ### Storage adapters
80
+
81
+ ```ts
82
+ // In-memory (default — process-lifetime)
83
+ import { makeMemoryStore } from "@tinyweb-agent-framework/agent"
84
+
85
+ // SQLite via bun:sqlite (single file, zero config)
86
+ import { makeSqliteStore } from "@tinyweb-agent-framework/agent/session/sqlite"
87
+
88
+ // Postgres via drizzle-orm/postgres-js (peer dep: postgres)
89
+ import { makePostgresStore } from "@tinyweb-agent-framework/agent/session/postgres"
90
+
91
+ const agent = defineAgent({
92
+ ...,
93
+ store: makeSqliteStore("./agent.db"),
94
+ })
95
+ ```
96
+
97
+ The SQLite/Postgres adapters live at **subpaths** so bundlers that don't understand `bun:sqlite` (Next.js webpack, etc.) won't try to resolve them for stateless apps.
98
+
99
+ ### Session SDK — `agent.sessions.*`
100
+
101
+ Every agent exposes a Promise-based SDK to manage sessions and history. No Effect, no boilerplate:
102
+
103
+ ```ts
104
+ const session = await agent.sessions.create({
105
+ title: "My chat",
106
+ metadata: { lang: "vi" },
107
+ ownerId: "user-42", // denormalised to an indexed column for fast list-by-owner
108
+ })
109
+
110
+ const { items, nextCursor } = await agent.sessions.list({
111
+ limit: 50,
112
+ ownerId: "user-42",
113
+ })
114
+
115
+ const messages = await agent.sessions.messages(session.id, { limit: 100 })
116
+
117
+ await agent.sessions.setTitle(session.id, "Renamed")
118
+ await agent.sessions.deleteMessage(session.id, lastMsgId)
119
+ await agent.sessions.delete(session.id)
120
+ ```
121
+
122
+ Full surface:
123
+
124
+ ```ts
125
+ agent.sessions.create({ title?, metadata?, ownerId? }) → Session.Info
126
+ agent.sessions.list({ limit?, cursor?, ownerId? }) → { items, nextCursor? }
127
+ agent.sessions.get(sessionId) → Session.Info | undefined
128
+ agent.sessions.delete(sessionId) → void
129
+ agent.sessions.setTitle(sessionId, title) → void
130
+ agent.sessions.setMetadata(sessionId, metadata) → void
131
+ agent.sessions.patch(sessionId, { title?, metadata? }) → Session.Info
132
+ agent.sessions.messages(sessionId, { limit?, cursor? }) → { items, nextCursor? }
133
+ agent.sessions.deleteMessage(sessionId, messageId) → void
134
+ ```
135
+
136
+ `list` results are sorted newest-first by `updatedAt` and use cursor-based pagination (base64url-encoded — opaque to callers; just round-trip `nextCursor` into the next request). `messages` returns oldest-first.
137
+
138
+ ### REST endpoints — `agent.toHTTPHandlers()`
139
+
140
+ `agent.toHTTPHandlers()` returns ready-to-mount handlers `(req, res) => Promise<void>` compatible with **Express, Hono, Fastify, native `node:http`, and Bun.serve** (any framework that exposes `req.method`/`req.url`/`req.params`/`req.body`/`res.setHeader`/`res.write`/`res.end`).
141
+
142
+ ```ts
143
+ import express from "express"
144
+
145
+ const app = express()
146
+ app.use(express.json())
147
+
148
+ const api = agent.toHTTPHandlers({
149
+ defaultFormat: "ai-sdk", // SSE format for /chat
150
+ authorize: async (req) => ({ // optional: derive ownerId from auth
151
+ ownerId: req.headers["x-user-id"] as string,
152
+ }),
153
+ })
154
+
155
+ const router = express.Router({ mergeParams: true })
156
+ router.get("/", api.listSessions)
157
+ router.post("/", api.createSession)
158
+ router.get("/:id", api.getSession)
159
+ router.patch("/:id", api.updateSession)
160
+ router.delete("/:id", api.deleteSession)
161
+ router.get("/:id/messages", api.listMessages)
162
+ router.delete("/:id/messages/:mid", api.deleteMessage)
163
+ router.post("/:id/chat", api.chat)
164
+ app.use("/sessions", router)
165
+
166
+ app.listen(3000)
167
+ ```
168
+
169
+ REST surface:
170
+
171
+ | Method | Path | Returns |
172
+ |----------|----------------------------------------|------------------------------------------|
173
+ | `GET` | `/sessions?limit&cursor&ownerId` | `{ items, nextCursor? }` |
174
+ | `POST` | `/sessions` `{title?, metadata?, ownerId?}` | `Session.Info` |
175
+ | `GET` | `/sessions/:id` | `Session.Info` |
176
+ | `PATCH` | `/sessions/:id` `{title?, metadata?}` | `Session.Info` |
177
+ | `DELETE` | `/sessions/:id` | `204` |
178
+ | `GET` | `/sessions/:id/messages?limit&cursor` | `{ items, nextCursor? }` (oldest-first) |
179
+ | `DELETE` | `/sessions/:id/messages/:mid` | `204` |
180
+ | `POST` | `/sessions/:id/chat` `{prompt}` or `{messages}` | `text/event-stream` (SSE) |
181
+
182
+ The `chat` handler streams in `defaultFormat` (`"tinyweb"` JSON or `"ai-sdk"` Vercel AI SDK Data Stream). Override per request with `?format=ai-sdk`.
183
+
184
+ The `authorize` hook runs before every handler; return `{ ownerId }` to enforce session ownership (`ownerId` is matched against `metadata.ownerId` on each session). Throw or return `{}` to fall back to no-auth.
185
+
186
+ ### Next.js App Router
187
+
188
+ Skip `toHTTPHandlers()` and call `agent.sessions.*` directly — Next.js routes already have their own Request/Response model:
189
+
190
+ ```ts
191
+ // app/api/sessions/[id]/messages/route.ts
192
+ import { agent } from "@/lib/agent"
193
+
194
+ export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
195
+ const { id } = await params
196
+ const result = await agent.sessions.messages(id, { limit: 100 })
197
+ return Response.json(result)
198
+ }
199
+ ```
200
+
201
+ See `examples/next-chat-ui/` for the full app.
202
+
203
+ ## Permission
204
+
205
+ ```ts
206
+ const agent = defineAgent({
207
+ // ...
208
+ tools: { web_fetch, shell_exec },
209
+ permission: { web_fetch: "allow", shell_exec: "ask" }, // or just "allow" | "ask" | "deny"
210
+ askHandler: async ({ toolName, input }) => {
211
+ // confirm with the user via UI / Slack / etc.
212
+ return true
213
+ },
214
+ })
215
+ ```
216
+
217
+ ## MCP servers
218
+
219
+ ```ts
220
+ const agent = defineAgent({
221
+ // ...
222
+ mcp: {
223
+ fs: { type: "stdio", command: "npx", args: ["@modelcontextprotocol/server-filesystem", "/tmp"] },
224
+ api: { type: "http", url: "https://example.com/mcp" },
225
+ },
226
+ })
227
+ // Tools auto-namespaced as fs__read_file, api__do_thing, ...
228
+ ```
229
+
230
+ ## Skills
231
+
232
+ Drop `SKILL.md` files in:
233
+ - `./skills/**/SKILL.md`
234
+ - `~/.tinyweb-agent/skills/**/SKILL.md`
235
+ - Any extra dirs you pass via `skillDirs: [...]`
236
+
237
+ Each must include YAML frontmatter:
238
+
239
+ ```markdown
240
+ ---
241
+ name: vietnamese-blog
242
+ description: Write Vietnamese blog posts in the company tone of voice
243
+ ---
244
+
245
+ Detailed instructions go here…
246
+ ```
247
+
248
+ The agent gains a `skill` tool — the LLM calls it with `{ name }` and gets the markdown body back.
249
+
250
+ ## Plugins / Hooks
251
+
252
+ ```ts
253
+ const myPlugin = async ({ agentName }) => ({
254
+ async "chat.params"(_, out) {
255
+ out.temperature = 0.2
256
+ },
257
+ async "tool.execute.before"({ tool }, out) {
258
+ console.log("[before]", tool, out.args)
259
+ },
260
+ })
261
+
262
+ const agent = defineAgent({ ..., plugins: [myPlugin] })
263
+ ```
264
+
265
+ Supported hooks: `event`, `chat.message`, `chat.params`, `chat.headers`, `tool.execute.before`, `tool.execute.after`, `tool.definition`, `permission.ask`, `experimental.chat.system.transform`.
266
+
267
+ ## Bus
268
+
269
+ In-process pub/sub via `PubSub.unbounded`:
270
+
271
+ ```ts
272
+ import { makeBus } from "@tinyweb-agent-framework/agent"
273
+ const bus = makeBus()
274
+ // publish / subscribe<K> / subscribeAll
275
+ ```
276
+
277
+ ## License
278
+
279
+ MIT
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/package.json",
3
+ "name": "@tinyweb_dev/agent-framework-agent",
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "scripts": {
8
+ "typecheck": "tsc --noEmit",
9
+ "test": "bun test --timeout 30000"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "exports": {
17
+ ".": "./src/index.ts",
18
+ "./plugin": "./src/plugin/index.ts",
19
+ "./mcp": "./src/mcp/index.ts",
20
+ "./skill": "./src/skill/index.ts",
21
+ "./session/sqlite": "./src/session/sqlite.ts",
22
+ "./session/postgres": "./src/session/postgres.ts",
23
+ "./session/memory": "./src/session/memory.ts",
24
+ "./session-api": "./src/session-api.ts",
25
+ "./http-handlers": "./src/http-handlers.ts"
26
+ },
27
+ "devDependencies": {
28
+ "@tsconfig/bun": "1.0.9",
29
+ "@types/bun": "1.3.12",
30
+ "typescript": "5.8.2"
31
+ },
32
+ "dependencies": {
33
+ "@modelcontextprotocol/sdk": "1.12.0",
34
+ "drizzle-orm": "1.0.0-beta.19-d95b7a4",
35
+ "effect": "4.0.0-beta.59",
36
+ "ulid": "3.0.1",
37
+ "@tinyweb_dev/agent-framework-core": "0.1.0",
38
+ "@tinyweb_dev/agent-framework-llm": "0.1.0",
39
+ "@tinyweb_dev/agent-framework-protocol": "0.1.0"
40
+ }
41
+ }
package/src/agent.ts ADDED
@@ -0,0 +1,317 @@
1
+ import {
2
+ LLM,
3
+ LLMClient,
4
+ type ExecutableTools,
5
+ type GenerationOptions,
6
+ type LLMResponse,
7
+ type ModelRef,
8
+ type StopCondition,
9
+ type Tools,
10
+ } from "@tinyweb-agent-framework/llm"
11
+ import { Effect } from "effect"
12
+ import type { AttachmentInput } from "./attachments"
13
+ import { compact } from "./session/compaction"
14
+ import { estimateTokens, usable } from "./session/overflow"
15
+ import { type AgentEvent } from "./events"
16
+ import { applyPermission, type PermissionAskHandler, type PermissionConfig } from "./permission"
17
+ import { defaultRuntime, type AgentRuntime } from "./runtime"
18
+ import { makeProcessor } from "./session/processor"
19
+ import { makeMemoryStore } from "./session/memory"
20
+ import type { SessionStore } from "./session/adapter"
21
+ import { historyToLLMMessages } from "./session/replay"
22
+ import { makeSSEHandler, type SSEHandlerOptions } from "./sse-handler"
23
+ import { loadPlugins, type Hooks, type PluginEntry } from "./plugin"
24
+ import { connectAllMcp, type McpConfig } from "./mcp"
25
+ import { loadSkills, makeSkillTool } from "./skill"
26
+ import { makeSessionAPI, type SessionAPI } from "./session-api"
27
+ import { makeHTTPHandlers, type AuthorizeFn, type ChatFormat, type HTTPHandlers } from "./http-handlers"
28
+ import { composeSystemPrompt, type PromptSectionsConfig } from "./prompt"
29
+
30
+ /**
31
+ * Auto-compaction policy. The agent estimates input tokens on every turn and,
32
+ * when the estimate crosses the model's usable budget, summarises the leading
33
+ * slice of the conversation into a marker user message before calling the LLM.
34
+ * On a `ContextOverflowReason` from the provider the agent retries once with
35
+ * a freshly compacted history.
36
+ */
37
+ export type CompactionConfig = {
38
+ /** Default: true. Set to false to opt out entirely. */
39
+ readonly auto?: boolean
40
+ /** Reserved output buffer. Default `min(20_000, model.limits.output)`. */
41
+ readonly reservedTokens?: number
42
+ /** Number of trailing turns kept verbatim. Default 4. */
43
+ readonly preserveRecentTurns?: number
44
+ }
45
+
46
+ export type DefineAgentConfig<T extends Tools> = {
47
+ readonly name: string
48
+ readonly model: ModelRef
49
+ /**
50
+ * The agent's ROLE / persona block. Verbatim — no transformation.
51
+ *
52
+ * Framework-owned blocks (TOOL USE, TOOL USE GUIDELINES, RESPONSE STYLE) are
53
+ * automatically appended after this. Disable or tune them via
54
+ * `promptSections`. To skip the framework blocks entirely set
55
+ * `promptSections: { toolUse: false, toolUseGuidelines: false, responseStyle: false }`.
56
+ */
57
+ readonly systemPrompt?: string
58
+ /**
59
+ * Per-section toggles for the framework-owned prompt blocks. Defaults: all
60
+ * enabled with chat-style response rules. See [`prompt/index.ts`](./prompt/index.ts:1).
61
+ */
62
+ readonly promptSections?: PromptSectionsConfig
63
+ readonly tools?: T
64
+ readonly stopWhen?: StopCondition
65
+ readonly generation?: GenerationOptions.Input
66
+ readonly runtime?: AgentRuntime
67
+ readonly store?: SessionStore
68
+ readonly permission?: PermissionConfig
69
+ readonly askHandler?: PermissionAskHandler
70
+ /** Plugins to load — inline Plugin fn, path string, or [path, options] tuple */
71
+ readonly plugins?: PluginEntry[]
72
+ /** MCP servers to connect — Record<serverName, McpServerConfig> */
73
+ readonly mcp?: McpConfig
74
+ /** Extra directories to scan for SKILL.md files */
75
+ readonly skillDirs?: string[]
76
+ /** Auto-compaction tuning. Defaults are sane; pass `{ auto: false }` to disable. */
77
+ readonly compaction?: CompactionConfig
78
+ }
79
+
80
+ export type RunInput = {
81
+ readonly prompt: string
82
+ readonly sessionId?: string
83
+ readonly attachments?: ReadonlyArray<AttachmentInput>
84
+ }
85
+
86
+ export type RunOnceResult = {
87
+ readonly text: string
88
+ readonly usage: LLMResponse["usage"]
89
+ readonly events: LLMResponse["events"]
90
+ }
91
+
92
+ export type ToHTTPHandlersOptions = {
93
+ readonly authorize?: AuthorizeFn
94
+ readonly defaultFormat?: ChatFormat
95
+ }
96
+
97
+ export type Agent = {
98
+ readonly name: string
99
+ readonly run: (input: RunInput) => AsyncIterable<AgentEvent>
100
+ readonly runOnce: (input: RunInput) => Promise<RunOnceResult>
101
+ readonly toSSEHandler: (options?: SSEHandlerOptions) => ReturnType<typeof makeSSEHandler>
102
+ readonly sessions: SessionAPI
103
+ readonly toHTTPHandlers: (options?: ToHTTPHandlersOptions) => HTTPHandlers
104
+ }
105
+
106
+ let defaultStore: SessionStore | undefined
107
+ const getDefaultStore = (): SessionStore => {
108
+ if (defaultStore) return defaultStore
109
+ // Default to MemoryStore — SQLite must be opted into explicitly via
110
+ // `store: makeSqliteStore()` to keep this package usable in environments
111
+ // without bun:sqlite (e.g. Next.js/webpack server runtime).
112
+ defaultStore = makeMemoryStore()
113
+ return defaultStore
114
+ }
115
+
116
+ // ---------------------------------------------------------------------------
117
+ // buildTools — merge user tools + MCP tools + optional skill tool
118
+ // ---------------------------------------------------------------------------
119
+
120
+ async function buildTools(
121
+ config: DefineAgentConfig<Tools>,
122
+ loadedHooks: Hooks[],
123
+ ): Promise<ExecutableTools> {
124
+ const baseTools: ExecutableTools = (config.tools ?? {}) as ExecutableTools
125
+
126
+ // MCP tools
127
+ let mcpTools: ExecutableTools = {}
128
+ if (config.mcp && Object.keys(config.mcp).length > 0) {
129
+ const { tools } = await connectAllMcp(config.mcp)
130
+ mcpTools = tools
131
+ }
132
+
133
+ // Skill tool
134
+ let skillToolRecord: ExecutableTools = {}
135
+ if (config.skillDirs !== undefined || Object.keys(baseTools).length > 0) {
136
+ const skills = await loadSkills(config.skillDirs)
137
+ if (skills.length > 0) skillToolRecord = { skill: makeSkillTool(skills) }
138
+ }
139
+
140
+ const merged: ExecutableTools = { ...skillToolRecord, ...mcpTools, ...baseTools }
141
+
142
+ // Apply plugin tool.definition hooks — mutate description/parameters per tool
143
+ for (const hooks of loadedHooks) {
144
+ if (!hooks["tool.definition"]) continue
145
+ for (const [toolId, tool] of Object.entries(merged)) {
146
+ const output = { description: tool.description, parameters: tool._definition.inputSchema }
147
+ await hooks["tool.definition"]!({ toolId }, output)
148
+ // We only propagate description mutation for now (parameters schema is read-only at runtime)
149
+ if (output.description !== tool.description) {
150
+ ;(tool as { description: string }).description = output.description
151
+ }
152
+ }
153
+ }
154
+
155
+ return applyPermission(merged, config.permission, config.askHandler)
156
+ }
157
+
158
+ // ---------------------------------------------------------------------------
159
+ // defineAgent
160
+ // ---------------------------------------------------------------------------
161
+
162
+ export const defineAgent = <T extends Tools = Tools>(config: DefineAgentConfig<T>): Agent => {
163
+ const rt = (): AgentRuntime => config.runtime ?? defaultRuntime()
164
+ const store = config.store ?? getDefaultStore()
165
+ // Default cap is intentionally generous — agentic loops (browser automation,
166
+ // MCP tool chains) commonly exceed 10 rounds. The tool runtime already
167
+ // terminates naturally when the model's `finish_reason !== "tool-calls"`,
168
+ // so this is purely a safety ceiling against runaway loops. Override per
169
+ // agent via `stopWhen: LLM.stepCountIs(N)` if you need a different policy.
170
+ const stopWhen = config.stopWhen ?? LLM.stepCountIs(100)
171
+ // Compose final system prompt once: user-authored ROLE + framework-owned
172
+ // TOOL USE / GUIDELINES / RESPONSE STYLE blocks. See `./prompt/index.ts`.
173
+ const resolvedSystemPrompt = composeSystemPrompt({
174
+ role: config.systemPrompt,
175
+ sections: config.promptSections,
176
+ })
177
+ const compactionCfg = {
178
+ auto: config.compaction?.auto !== false,
179
+ reservedTokens: config.compaction?.reservedTokens,
180
+ preserveRecentTurns: config.compaction?.preserveRecentTurns,
181
+ }
182
+
183
+ // Build tools lazily on first use (async — MCP / skills may need network/fs)
184
+ let toolsPromise: Promise<ExecutableTools> | undefined
185
+
186
+ const getTools = (): Promise<ExecutableTools> => {
187
+ if (!toolsPromise) {
188
+ const pluginInput = { agentName: config.name, directory: process.cwd() }
189
+ toolsPromise = loadPlugins(config.plugins ?? [], pluginInput).then((loaded) => {
190
+ const hooks = loaded.map((l) => l.hooks)
191
+ return buildTools(config, hooks)
192
+ })
193
+ }
194
+ return toolsPromise
195
+ }
196
+
197
+ const run = (input: RunInput): AsyncIterable<AgentEvent> => {
198
+ // Return an AsyncIterable that initialises tools once then delegates to processor
199
+ let innerIter: AsyncIterator<AgentEvent> | undefined
200
+ return {
201
+ [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {
202
+ return {
203
+ async next() {
204
+ if (!innerIter) {
205
+ const tools = await getTools()
206
+ const processor = makeProcessor({
207
+ agentName: config.name,
208
+ model: config.model,
209
+ store,
210
+ runtime: rt(),
211
+ systemPrompt: resolvedSystemPrompt,
212
+ tools,
213
+ stopWhen,
214
+ generation: config.generation,
215
+ compaction: compactionCfg,
216
+ })
217
+ innerIter = processor.runTurn(input)[Symbol.asyncIterator]()
218
+ }
219
+ return innerIter.next()
220
+ },
221
+ async return(value) {
222
+ return innerIter ? (innerIter.return ? innerIter.return(value) : { done: true, value }) : { done: true, value }
223
+ },
224
+ }
225
+ },
226
+ }
227
+ }
228
+
229
+ const runOnce = async (input: RunInput): Promise<RunOnceResult> => {
230
+ const tools = await getTools()
231
+ const budget = usable({
232
+ limits: config.model.limits,
233
+ reservedTokens: compactionCfg.reservedTokens,
234
+ })
235
+ const keepRecent = compactionCfg.preserveRecentTurns ?? 4
236
+
237
+ const result = await rt().runPromise(
238
+ Effect.gen(function* () {
239
+ const session = yield* store.upsertSession({ id: input.sessionId, agentName: config.name })
240
+
241
+ // Pre-flight: compact if estimate would overflow the usable budget.
242
+ if (compactionCfg.auto) {
243
+ const history = yield* store.getMessages(session.id)
244
+ const promptTokens = Math.ceil(input.prompt.length / 4)
245
+ const systemTokens = Math.ceil(resolvedSystemPrompt.length / 4)
246
+ if (estimateTokens(history) + promptTokens + systemTokens >= budget) {
247
+ yield* compact({
248
+ sessionId: session.id,
249
+ store,
250
+ model: config.model,
251
+ keepRecent,
252
+ overflow: false,
253
+ })
254
+ }
255
+ }
256
+
257
+ const attempt = () =>
258
+ Effect.gen(function* () {
259
+ const history = yield* store.getMessages(session.id)
260
+ const userContent: Array<{ type: "text"; text: string } | { type: "media"; mediaType: string; data: string; filename?: string }> = []
261
+ if (input.prompt.length > 0) userContent.push({ type: "text", text: input.prompt })
262
+ for (const a of input.attachments ?? [])
263
+ userContent.push({ type: "media", mediaType: a.mediaType, data: a.url ?? a.data ?? "", filename: a.filename })
264
+ const userMsg = userContent.length === 0 ? LLM.user(input.prompt) : LLM.user(userContent)
265
+ const request = LLM.request({
266
+ model: config.model,
267
+ system: resolvedSystemPrompt,
268
+ messages: [...historyToLLMMessages([...history]), userMsg],
269
+ generation: config.generation,
270
+ })
271
+ return yield* LLMClient.generate({ request, tools, stopWhen })
272
+ })
273
+
274
+ // Post-flight: catch ContextOverflow once, compact with overflow=true, retry once.
275
+ let didRetry = false
276
+ const response = yield* attempt().pipe(
277
+ Effect.catchTag("LLM.Error", (err) => {
278
+ if (err.reason._tag === "ContextOverflow" && compactionCfg.auto && !didRetry) {
279
+ didRetry = true
280
+ return Effect.gen(function* () {
281
+ yield* compact({
282
+ sessionId: session.id,
283
+ store,
284
+ model: config.model,
285
+ keepRecent,
286
+ overflow: true,
287
+ })
288
+ return yield* attempt()
289
+ })
290
+ }
291
+ return Effect.fail(err)
292
+ }),
293
+ )
294
+ return response
295
+ }),
296
+ )
297
+ return { text: result.text, usage: result.usage, events: result.events }
298
+ }
299
+
300
+ const toSSEHandler = (options?: SSEHandlerOptions) => makeSSEHandler(run, options)
301
+
302
+ const sessions = makeSessionAPI({
303
+ agentName: config.name,
304
+ store,
305
+ runtime: config.runtime,
306
+ })
307
+
308
+ const toHTTPHandlers = (options?: ToHTTPHandlersOptions): HTTPHandlers =>
309
+ makeHTTPHandlers({
310
+ api: sessions,
311
+ run: (input) => run({ prompt: input.prompt, sessionId: input.sessionId, attachments: input.attachments }),
312
+ authorize: options?.authorize,
313
+ defaultFormat: options?.defaultFormat,
314
+ })
315
+
316
+ return { name: config.name, run, runOnce, toSSEHandler, sessions, toHTTPHandlers }
317
+ }