@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,251 @@
|
|
|
1
|
+
// makeHTTPHandlers — REST endpoints around a SessionAPI + agent.run.
|
|
2
|
+
//
|
|
3
|
+
// Returns a flat object of `(req, res) => Promise<void>` handlers usable in
|
|
4
|
+
// Express, Hono adapter, raw `node:http`, or Bun.serve via thin adapters.
|
|
5
|
+
//
|
|
6
|
+
// Endpoints (typical mount paths shown — caller wires them):
|
|
7
|
+
// GET /sessions → listSessions
|
|
8
|
+
// POST /sessions → createSession
|
|
9
|
+
// GET /sessions/:id → getSession
|
|
10
|
+
// PATCH /sessions/:id → updateSession (title? metadata?)
|
|
11
|
+
// DELETE /sessions/:id → deleteSession
|
|
12
|
+
// GET /sessions/:id/messages → listMessages (?limit, ?before, ?cursor)
|
|
13
|
+
// DELETE /sessions/:id/messages/:mid → deleteMessage
|
|
14
|
+
// POST /sessions/:id/chat → chat (SSE)
|
|
15
|
+
|
|
16
|
+
import { encodeSSE, toAISDKDataStream, AI_SDK_HEADERS, type AgentEvent as ProtocolAgentEvent } from "@tinyweb-agent-framework/protocol"
|
|
17
|
+
import { validateAttachments, type AttachmentInput, type ValidateAttachmentsConfig } from "./attachments"
|
|
18
|
+
import type { AgentEvent } from "./events"
|
|
19
|
+
import type { SessionAPI } from "./session-api"
|
|
20
|
+
|
|
21
|
+
// Duck-typed Node-like req/res (compatible with Express + node:http).
|
|
22
|
+
export type HTTPReq = {
|
|
23
|
+
readonly method?: string
|
|
24
|
+
readonly url?: string
|
|
25
|
+
readonly headers?: Record<string, string | string[] | undefined>
|
|
26
|
+
readonly body?: unknown
|
|
27
|
+
readonly params?: Record<string, string>
|
|
28
|
+
on?: (event: string, listener: (...args: unknown[]) => void) => unknown
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type HTTPRes = {
|
|
32
|
+
setHeader: (name: string, value: string) => unknown
|
|
33
|
+
statusCode?: number
|
|
34
|
+
write: (chunk: string | Uint8Array) => unknown
|
|
35
|
+
end: (chunk?: string | Uint8Array) => unknown
|
|
36
|
+
flushHeaders?: () => unknown
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type HTTPHandler = (req: HTTPReq, res: HTTPRes) => Promise<void>
|
|
40
|
+
|
|
41
|
+
export type ChatRunInput = {
|
|
42
|
+
readonly prompt: string
|
|
43
|
+
readonly sessionId: string
|
|
44
|
+
readonly attachments?: ReadonlyArray<AttachmentInput>
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type ChatFormat = "tinyweb" | "ai-sdk"
|
|
48
|
+
|
|
49
|
+
export type AuthorizeFn = (
|
|
50
|
+
req: HTTPReq,
|
|
51
|
+
) => Promise<{ ownerId?: string } | undefined> | { ownerId?: string } | undefined
|
|
52
|
+
|
|
53
|
+
export type MakeHTTPHandlersConfig = {
|
|
54
|
+
readonly api: SessionAPI
|
|
55
|
+
readonly run: (input: ChatRunInput) => AsyncIterable<AgentEvent>
|
|
56
|
+
readonly authorize?: AuthorizeFn
|
|
57
|
+
readonly defaultFormat?: ChatFormat
|
|
58
|
+
readonly attachments?: ValidateAttachmentsConfig
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type HTTPHandlers = {
|
|
62
|
+
readonly listSessions: HTTPHandler
|
|
63
|
+
readonly createSession: HTTPHandler
|
|
64
|
+
readonly getSession: HTTPHandler
|
|
65
|
+
readonly updateSession: HTTPHandler
|
|
66
|
+
readonly deleteSession: HTTPHandler
|
|
67
|
+
readonly listMessages: HTTPHandler
|
|
68
|
+
readonly deleteMessage: HTTPHandler
|
|
69
|
+
readonly chat: HTTPHandler
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---------- helpers ----------
|
|
73
|
+
|
|
74
|
+
const isReadableLike = (
|
|
75
|
+
body: unknown,
|
|
76
|
+
): body is { on: (event: string, listener: (chunk: unknown) => void) => unknown } =>
|
|
77
|
+
typeof body === "object" && body !== null && typeof (body as { on?: unknown }).on === "function"
|
|
78
|
+
|
|
79
|
+
const readBody = async (req: HTTPReq): Promise<unknown> => {
|
|
80
|
+
// Already parsed (Express + express.json()).
|
|
81
|
+
if (req.body !== undefined && req.body !== null && typeof req.body === "object" && !isReadableLike(req.body)) {
|
|
82
|
+
return req.body
|
|
83
|
+
}
|
|
84
|
+
if (typeof req.on !== "function") return undefined
|
|
85
|
+
const chunks: Buffer[] = []
|
|
86
|
+
await new Promise<void>((resolve, reject) => {
|
|
87
|
+
const onData = (...args: unknown[]) => chunks.push(Buffer.from(args[0] as Uint8Array))
|
|
88
|
+
const onEnd = () => resolve()
|
|
89
|
+
const onErr = (...args: unknown[]) => reject(args[0])
|
|
90
|
+
req.on!("data", onData)
|
|
91
|
+
req.on!("end", onEnd)
|
|
92
|
+
req.on!("error", onErr)
|
|
93
|
+
})
|
|
94
|
+
const raw = Buffer.concat(chunks).toString("utf8")
|
|
95
|
+
if (raw.length === 0) return undefined
|
|
96
|
+
return JSON.parse(raw)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const parseUrl = (req: HTTPReq): URL => {
|
|
100
|
+
const host = (req.headers?.["host"] as string | undefined) ?? "localhost"
|
|
101
|
+
return new URL(req.url ?? "/", `http://${host}`)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const param = (req: HTTPReq, key: string, url: URL, index: number): string | undefined => {
|
|
105
|
+
if (req.params && typeof req.params[key] === "string") return req.params[key]
|
|
106
|
+
// Fallback: positional path segment after "/sessions/".
|
|
107
|
+
const segs = url.pathname.split("/").filter(Boolean)
|
|
108
|
+
return segs[index]
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const sendJSON = (res: HTTPRes, status: number, body: unknown): void => {
|
|
112
|
+
res.statusCode = status
|
|
113
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8")
|
|
114
|
+
res.end(JSON.stringify(body))
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const sendError = (res: HTTPRes, status: number, message: string): void =>
|
|
118
|
+
sendJSON(res, status, { error: message })
|
|
119
|
+
|
|
120
|
+
const TINYWEB_HEADERS: Readonly<Record<string, string>> = {
|
|
121
|
+
"Content-Type": "text/event-stream",
|
|
122
|
+
"Cache-Control": "no-cache, no-transform",
|
|
123
|
+
Connection: "keep-alive",
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ---------- factory ----------
|
|
127
|
+
|
|
128
|
+
export const makeHTTPHandlers = (config: MakeHTTPHandlersConfig): HTTPHandlers => {
|
|
129
|
+
const defaultFormat: ChatFormat = config.defaultFormat ?? "tinyweb"
|
|
130
|
+
|
|
131
|
+
const ownerOf = async (req: HTTPReq): Promise<string | undefined> => {
|
|
132
|
+
if (!config.authorize) return undefined
|
|
133
|
+
const result = await config.authorize(req)
|
|
134
|
+
return result?.ownerId
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const listSessions: HTTPHandler = async (req, res) => {
|
|
138
|
+
const url = parseUrl(req)
|
|
139
|
+
const limit = url.searchParams.get("limit")
|
|
140
|
+
const cursor = url.searchParams.get("cursor") ?? undefined
|
|
141
|
+
const ownerOverride = url.searchParams.get("ownerId") ?? undefined
|
|
142
|
+
const owner = (await ownerOf(req)) ?? ownerOverride
|
|
143
|
+
const result = await config.api.list({
|
|
144
|
+
limit: limit ? Number(limit) : undefined,
|
|
145
|
+
cursor,
|
|
146
|
+
ownerId: owner,
|
|
147
|
+
})
|
|
148
|
+
sendJSON(res, 200, result)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const createSession: HTTPHandler = async (req, res) => {
|
|
152
|
+
const body = ((await readBody(req)) as {
|
|
153
|
+
title?: string
|
|
154
|
+
metadata?: Record<string, unknown>
|
|
155
|
+
ownerId?: string
|
|
156
|
+
}) ?? {}
|
|
157
|
+
const ownerHook = await ownerOf(req)
|
|
158
|
+
const session = await config.api.create({
|
|
159
|
+
title: body.title,
|
|
160
|
+
metadata: body.metadata,
|
|
161
|
+
ownerId: ownerHook ?? body.ownerId,
|
|
162
|
+
})
|
|
163
|
+
sendJSON(res, 201, session)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const getSession: HTTPHandler = async (req, res) => {
|
|
167
|
+
const url = parseUrl(req)
|
|
168
|
+
const id = param(req, "id", url, 1)
|
|
169
|
+
if (!id) return sendError(res, 400, "missing session id")
|
|
170
|
+
const session = await config.api.get(id)
|
|
171
|
+
if (!session) return sendError(res, 404, "session not found")
|
|
172
|
+
sendJSON(res, 200, session)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const updateSession: HTTPHandler = async (req, res) => {
|
|
176
|
+
const url = parseUrl(req)
|
|
177
|
+
const id = param(req, "id", url, 1)
|
|
178
|
+
if (!id) return sendError(res, 400, "missing session id")
|
|
179
|
+
const body = ((await readBody(req)) as { title?: string; metadata?: Record<string, unknown> }) ?? {}
|
|
180
|
+
const updated = await config.api.patch(id, { title: body.title, metadata: body.metadata })
|
|
181
|
+
if (!updated) return sendError(res, 404, "session not found")
|
|
182
|
+
sendJSON(res, 200, updated)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const deleteSession: HTTPHandler = async (req, res) => {
|
|
186
|
+
const url = parseUrl(req)
|
|
187
|
+
const id = param(req, "id", url, 1)
|
|
188
|
+
if (!id) return sendError(res, 400, "missing session id")
|
|
189
|
+
await config.api.delete(id)
|
|
190
|
+
sendJSON(res, 200, { ok: true })
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const listMessages: HTTPHandler = async (req, res) => {
|
|
194
|
+
const url = parseUrl(req)
|
|
195
|
+
const id = param(req, "id", url, 1)
|
|
196
|
+
if (!id) return sendError(res, 400, "missing session id")
|
|
197
|
+
const limit = url.searchParams.get("limit")
|
|
198
|
+
const before = url.searchParams.get("before") ?? undefined
|
|
199
|
+
const result = await config.api.messages(id, {
|
|
200
|
+
limit: limit ? Number(limit) : undefined,
|
|
201
|
+
before: before as never,
|
|
202
|
+
})
|
|
203
|
+
sendJSON(res, 200, result)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const deleteMessage: HTTPHandler = async (req, res) => {
|
|
207
|
+
const url = parseUrl(req)
|
|
208
|
+
const id = param(req, "id", url, 1)
|
|
209
|
+
const mid = param(req, "mid", url, 3)
|
|
210
|
+
if (!id || !mid) return sendError(res, 400, "missing ids")
|
|
211
|
+
await config.api.deleteMessage(id, mid)
|
|
212
|
+
sendJSON(res, 200, { ok: true })
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const chat: HTTPHandler = async (req, res) => {
|
|
216
|
+
const url = parseUrl(req)
|
|
217
|
+
const id = param(req, "id", url, 1)
|
|
218
|
+
if (!id) return sendError(res, 400, "missing session id")
|
|
219
|
+
const body = ((await readBody(req)) as {
|
|
220
|
+
prompt?: string
|
|
221
|
+
format?: ChatFormat
|
|
222
|
+
attachments?: unknown
|
|
223
|
+
}) ?? {}
|
|
224
|
+
const prompt = body.prompt?.trim() ?? ""
|
|
225
|
+
const validation = validateAttachments(body.attachments, config.attachments)
|
|
226
|
+
if (!validation.ok) return sendJSON(res, 400, { error: validation.message, code: validation.code })
|
|
227
|
+
const attachments = validation.value
|
|
228
|
+
if (!prompt && attachments.length === 0) return sendError(res, 400, "missing prompt")
|
|
229
|
+
const format = body.format ?? defaultFormat
|
|
230
|
+
const headers = format === "ai-sdk" ? AI_SDK_HEADERS : TINYWEB_HEADERS
|
|
231
|
+
for (const [name, value] of Object.entries(headers)) res.setHeader(name, value)
|
|
232
|
+
if (typeof res.flushHeaders === "function") res.flushHeaders()
|
|
233
|
+
for await (const event of config.run({ prompt, sessionId: id, attachments })) {
|
|
234
|
+
const proto = event as ProtocolAgentEvent
|
|
235
|
+
const line = format === "ai-sdk" ? toAISDKDataStream(proto) : encodeSSE(proto)
|
|
236
|
+
if (line.length > 0) res.write(line)
|
|
237
|
+
}
|
|
238
|
+
res.end()
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
listSessions,
|
|
243
|
+
createSession,
|
|
244
|
+
getSession,
|
|
245
|
+
updateSession,
|
|
246
|
+
deleteSession,
|
|
247
|
+
listMessages,
|
|
248
|
+
deleteMessage,
|
|
249
|
+
chat,
|
|
250
|
+
}
|
|
251
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
export const VERSION = "0.0.1"
|
|
2
|
+
|
|
3
|
+
// Public agent API
|
|
4
|
+
export {
|
|
5
|
+
defineAgent,
|
|
6
|
+
type Agent,
|
|
7
|
+
type DefineAgentConfig,
|
|
8
|
+
type RunInput,
|
|
9
|
+
type RunOnceResult,
|
|
10
|
+
type ToHTTPHandlersOptions,
|
|
11
|
+
} from "./agent"
|
|
12
|
+
export { defineTool, type DefineToolConfig } from "./define-tool"
|
|
13
|
+
|
|
14
|
+
// System-prompt section composer (Roo-style blocks)
|
|
15
|
+
export {
|
|
16
|
+
composeSystemPrompt,
|
|
17
|
+
toolUseSection,
|
|
18
|
+
toolUseGuidelinesSection,
|
|
19
|
+
objectiveSection,
|
|
20
|
+
responseStyleSection,
|
|
21
|
+
type ComposeSystemPromptInput,
|
|
22
|
+
type PromptSectionsConfig,
|
|
23
|
+
type ToolUseGuidelinesConfig,
|
|
24
|
+
type ObjectiveConfig,
|
|
25
|
+
type ObjectiveKind,
|
|
26
|
+
type ResponseStyleConfig,
|
|
27
|
+
type ResponseStyleKind,
|
|
28
|
+
} from "./prompt"
|
|
29
|
+
|
|
30
|
+
// Session-level Promise SDK
|
|
31
|
+
export {
|
|
32
|
+
makeSessionAPI,
|
|
33
|
+
type SessionAPI,
|
|
34
|
+
type CreateSessionAPIInput,
|
|
35
|
+
type ListSessionsAPIOpts,
|
|
36
|
+
type MakeSessionAPIConfig,
|
|
37
|
+
type MessagesAPIResult,
|
|
38
|
+
} from "./session-api"
|
|
39
|
+
|
|
40
|
+
// HTTP handlers (REST endpoints for SessionAPI + chat)
|
|
41
|
+
export {
|
|
42
|
+
makeHTTPHandlers,
|
|
43
|
+
type HTTPHandlers,
|
|
44
|
+
type HTTPHandler,
|
|
45
|
+
type HTTPReq,
|
|
46
|
+
type HTTPRes,
|
|
47
|
+
type MakeHTTPHandlersConfig,
|
|
48
|
+
type AuthorizeFn,
|
|
49
|
+
type ChatFormat,
|
|
50
|
+
type ChatRunInput,
|
|
51
|
+
} from "./http-handlers"
|
|
52
|
+
|
|
53
|
+
// Attachments
|
|
54
|
+
export {
|
|
55
|
+
validateAttachments,
|
|
56
|
+
DEFAULT_IMAGE_MIMES,
|
|
57
|
+
DEFAULT_MAX_BYTES_PER_FILE,
|
|
58
|
+
DEFAULT_MAX_BYTES_TOTAL,
|
|
59
|
+
DEFAULT_MAX_COUNT,
|
|
60
|
+
type AttachmentInput,
|
|
61
|
+
type AttachmentErrorCode,
|
|
62
|
+
type ValidateAttachmentsConfig,
|
|
63
|
+
type ValidateResult,
|
|
64
|
+
type ValidateOk,
|
|
65
|
+
type ValidateErr,
|
|
66
|
+
} from "./attachments"
|
|
67
|
+
|
|
68
|
+
// Events
|
|
69
|
+
export type {
|
|
70
|
+
AgentEvent,
|
|
71
|
+
TextDeltaEvent,
|
|
72
|
+
TextEndEvent,
|
|
73
|
+
ReasoningDeltaEvent,
|
|
74
|
+
ToolCallEvent,
|
|
75
|
+
ToolResultEvent,
|
|
76
|
+
ToolErrorEvent,
|
|
77
|
+
StepFinishEvent,
|
|
78
|
+
FinishEvent,
|
|
79
|
+
ErrorEvent,
|
|
80
|
+
} from "./events"
|
|
81
|
+
export { fromLLMEvent } from "./events"
|
|
82
|
+
|
|
83
|
+
// Transcript helpers — consumer-side fallback for persisting display_response turns
|
|
84
|
+
export {
|
|
85
|
+
collectAssistantText,
|
|
86
|
+
makeAssistantTextAccumulator,
|
|
87
|
+
type AssistantTextAccumulator,
|
|
88
|
+
type CollectAssistantTextOptions,
|
|
89
|
+
} from "./transcript"
|
|
90
|
+
|
|
91
|
+
// Runtime
|
|
92
|
+
export { createRuntime, defaultRuntime, disposeDefaultRuntime, type AgentRuntime } from "./runtime"
|
|
93
|
+
|
|
94
|
+
// Session + storage
|
|
95
|
+
export * from "./session"
|
|
96
|
+
|
|
97
|
+
// Bus
|
|
98
|
+
export * from "./bus"
|
|
99
|
+
|
|
100
|
+
// SSE / streaming handler
|
|
101
|
+
export { makeSSEHandler, writeEventsToResponse, type SSEFormat, type SSEHandlerOptions } from "./sse-handler"
|
|
102
|
+
|
|
103
|
+
// Permission
|
|
104
|
+
export {
|
|
105
|
+
applyPermission,
|
|
106
|
+
resolveRule,
|
|
107
|
+
type PermissionAskHandler,
|
|
108
|
+
type PermissionAskRequest,
|
|
109
|
+
type PermissionConfig,
|
|
110
|
+
type PermissionRule,
|
|
111
|
+
} from "./permission"
|
|
112
|
+
|
|
113
|
+
// Plugin / Hooks
|
|
114
|
+
export * from "./plugin"
|
|
115
|
+
|
|
116
|
+
// MCP client
|
|
117
|
+
export { connectMcp, connectAllMcp, type McpServerConfig, type McpStdioConfig, type McpHttpConfig, type McpConfig, type McpClient } from "./mcp"
|
|
118
|
+
|
|
119
|
+
// Skill system
|
|
120
|
+
export { loadSkills, makeSkillTool, type SkillInfo } from "./skill"
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { Tool, ToolFailure, type AnyExecutableTool, type ExecutableTools } from "@tinyweb-agent-framework/llm"
|
|
2
|
+
import { Effect } from "effect"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Loop-guard configuration. The guard wraps each tool in an
|
|
6
|
+
* `ExecutableTools` record so that identical `(toolName, JSON.stringify(args))`
|
|
7
|
+
* invocations short-circuit with a `ToolFailure` instead of running the
|
|
8
|
+
* tool body. This stops a runaway model that keeps re-invoking the same
|
|
9
|
+
* tool with the same args within a single agent turn (see
|
|
10
|
+
* [`.manager/bugs/0002-next-chat-agent-tool-loop-and-missing-stop-button.md`](../../../.manager/bugs/0002-next-chat-agent-tool-loop-and-missing-stop-button.md)).
|
|
11
|
+
*
|
|
12
|
+
* Scope:
|
|
13
|
+
* • The seen-set is **per `applyLoopGuard()` invocation**. Because
|
|
14
|
+
* `buildTools` runs once per `defineAgent`, and the typical pattern
|
|
15
|
+
* is one `defineAgent` per chat turn (e.g.
|
|
16
|
+
* [`examples/next-chat/lib/agent.ts`](../../../examples/next-chat/lib/agent.ts)),
|
|
17
|
+
* the seen-set naturally resets each turn.
|
|
18
|
+
* • For long-lived agents that span multiple turns (e.g. an HTTP server
|
|
19
|
+
* building the agent once at boot), the guard is currently
|
|
20
|
+
* conservative — duplicate calls across turns will also be blocked.
|
|
21
|
+
* If that becomes a problem we can add a turn-scoped reset hook.
|
|
22
|
+
*
|
|
23
|
+
* Behaviour on trip:
|
|
24
|
+
* • Returns `ToolFailure` with a clear message instructing the LLM to
|
|
25
|
+
* stop calling the tool. The processor surfaces this as a regular
|
|
26
|
+
* `tool-error` event so the UI renders an inline error pill (no
|
|
27
|
+
* stream crash).
|
|
28
|
+
*/
|
|
29
|
+
export type LoopGuardConfig = {
|
|
30
|
+
readonly enabled: boolean
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const DEFAULT_CONFIG: LoopGuardConfig = { enabled: true }
|
|
34
|
+
|
|
35
|
+
const tripFailure = (toolName: string): ToolFailure =>
|
|
36
|
+
new ToolFailure({
|
|
37
|
+
message:
|
|
38
|
+
`Loop guard: tool "${toolName}" was already invoked with identical arguments ` +
|
|
39
|
+
`earlier in this turn. Stop calling it and answer the user with the data ` +
|
|
40
|
+
`you already have.`,
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Stable JSON stringify with sorted keys so `{a:1,b:2}` and `{b:2,a:1}`
|
|
45
|
+
* produce the same signature. Falls back to `String(input)` for circular
|
|
46
|
+
* or non-serialisable inputs (which we still want to dedup on best-effort).
|
|
47
|
+
*/
|
|
48
|
+
const signature = (toolName: string, input: unknown): string => {
|
|
49
|
+
const safe = stableStringify(input)
|
|
50
|
+
return toolName + ":" + safe
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const stableStringify = (value: unknown): string => {
|
|
54
|
+
if (value === null || value === undefined) return "null"
|
|
55
|
+
if (typeof value !== "object") return JSON.stringify(value)
|
|
56
|
+
if (Array.isArray(value)) return "[" + value.map(stableStringify).join(",") + "]"
|
|
57
|
+
const obj = value as Record<string, unknown>
|
|
58
|
+
const keys = Object.keys(obj).sort()
|
|
59
|
+
return "{" + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + "}"
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const wrapTool = (name: string, base: AnyExecutableTool, seen: Set<string>): AnyExecutableTool =>
|
|
63
|
+
Tool.make({
|
|
64
|
+
description: base.description,
|
|
65
|
+
parameters: base.parameters,
|
|
66
|
+
success: base.success,
|
|
67
|
+
execute: (input: unknown) => {
|
|
68
|
+
const sig = signature(name, input)
|
|
69
|
+
if (seen.has(sig)) return Effect.fail(tripFailure(name))
|
|
70
|
+
seen.add(sig)
|
|
71
|
+
return base.execute(input)
|
|
72
|
+
},
|
|
73
|
+
}) as AnyExecutableTool
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Wrap every tool in `tools` with the loop guard. Returns the original
|
|
77
|
+
* record unchanged when `config.enabled === false`.
|
|
78
|
+
*
|
|
79
|
+
* Typical wiring (inside the agent package — see [`agent.ts`](agent.ts:1)):
|
|
80
|
+
*
|
|
81
|
+
* ```ts
|
|
82
|
+
* const guarded = applyLoopGuard(merged, { enabled: config.loopGuard !== false })
|
|
83
|
+
* return applyPermission(guarded, config.permission, config.askHandler)
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
export const applyLoopGuard = (
|
|
87
|
+
tools: ExecutableTools,
|
|
88
|
+
config: LoopGuardConfig = DEFAULT_CONFIG,
|
|
89
|
+
): ExecutableTools => {
|
|
90
|
+
if (!config.enabled) return tools
|
|
91
|
+
const seen = new Set<string>()
|
|
92
|
+
const out: Record<string, AnyExecutableTool> = {}
|
|
93
|
+
for (const name of Object.keys(tools)) {
|
|
94
|
+
const tool = tools[name]
|
|
95
|
+
if (!tool) continue
|
|
96
|
+
out[name] = wrapTool(name, tool, seen)
|
|
97
|
+
}
|
|
98
|
+
return out as ExecutableTools
|
|
99
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// Adapted from opencode@v1.14.48 packages/opencode/src/mcp/
|
|
2
|
+
|
|
3
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
|
|
4
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
|
|
5
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
|
|
6
|
+
import { Effect, Schema } from "effect"
|
|
7
|
+
import { Tool, ToolFailure } from "@tinyweb-agent-framework/llm"
|
|
8
|
+
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
// Config types
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
|
|
13
|
+
export type McpStdioConfig = {
|
|
14
|
+
readonly type: "stdio"
|
|
15
|
+
readonly command: string
|
|
16
|
+
readonly args?: string[]
|
|
17
|
+
readonly env?: Record<string, string>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type McpHttpConfig = {
|
|
21
|
+
readonly type: "http"
|
|
22
|
+
readonly url: string
|
|
23
|
+
readonly headers?: Record<string, string>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type McpServerConfig = McpStdioConfig | McpHttpConfig
|
|
27
|
+
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// McpClient — holds connected client + tools
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
export type McpClient = {
|
|
33
|
+
readonly name: string
|
|
34
|
+
readonly tools: Record<string, Tool.AnyExecutableTool>
|
|
35
|
+
readonly disconnect: () => Promise<void>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
// Helpers
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
const jsonSchema = Schema.Record(Schema.String, Schema.Unknown)
|
|
43
|
+
|
|
44
|
+
function buildTool(serverName: string, mcpTool: { name: string; description?: string; inputSchema: unknown }, client: Client): Tool.AnyExecutableTool {
|
|
45
|
+
const toolName = `${serverName}__${mcpTool.name}`
|
|
46
|
+
const parameters = (mcpTool.inputSchema ?? { type: "object", properties: {} }) as Record<string, unknown>
|
|
47
|
+
|
|
48
|
+
return Tool.make({
|
|
49
|
+
description: mcpTool.description ?? toolName,
|
|
50
|
+
parameters: jsonSchema,
|
|
51
|
+
success: Schema.Unknown,
|
|
52
|
+
execute: (input) =>
|
|
53
|
+
Effect.tryPromise({
|
|
54
|
+
try: async () => {
|
|
55
|
+
const result = await client.callTool({ name: mcpTool.name, arguments: input as Record<string, unknown> })
|
|
56
|
+
// MCP callTool returns {content: [{type, text?}], isError?}
|
|
57
|
+
if (result.isError) {
|
|
58
|
+
const text = (result.content as { type: string; text?: string }[]).map((c) => c.text ?? "").join("\n")
|
|
59
|
+
throw new Error(text || "MCP tool returned error")
|
|
60
|
+
}
|
|
61
|
+
const text = (result.content as { type: string; text?: string }[]).map((c) => c.text ?? "").join("\n")
|
|
62
|
+
return text
|
|
63
|
+
},
|
|
64
|
+
catch: (err) => new ToolFailure({ message: String(err) }),
|
|
65
|
+
}),
|
|
66
|
+
}) as Tool.AnyExecutableTool
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
// connectMcp
|
|
71
|
+
// ---------------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
export async function connectMcp(name: string, config: McpServerConfig): Promise<McpClient> {
|
|
74
|
+
const client = new Client({ name: "tinyweb-agent", version: "0.0.1" })
|
|
75
|
+
|
|
76
|
+
const transport =
|
|
77
|
+
config.type === "stdio"
|
|
78
|
+
? new StdioClientTransport({ command: config.command, args: config.args, env: config.env })
|
|
79
|
+
: new StreamableHTTPClientTransport(new URL(config.url), { requestInit: { headers: config.headers ?? {} } })
|
|
80
|
+
|
|
81
|
+
await client.connect(transport)
|
|
82
|
+
|
|
83
|
+
const listResult = await client.listTools()
|
|
84
|
+
const tools: Record<string, Tool.AnyExecutableTool> = {}
|
|
85
|
+
for (const mcpTool of listResult.tools) {
|
|
86
|
+
const namespaced = `${name}__${mcpTool.name}`
|
|
87
|
+
tools[namespaced] = buildTool(name, mcpTool, client)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
name,
|
|
92
|
+
tools,
|
|
93
|
+
disconnect: () => client.close(),
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ---------------------------------------------------------------------------
|
|
98
|
+
// connectAllMcp — connect multiple servers, merge tools
|
|
99
|
+
// ---------------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
export type McpConfig = Record<string, McpServerConfig>
|
|
102
|
+
|
|
103
|
+
export async function connectAllMcp(configs: McpConfig): Promise<{ clients: McpClient[]; tools: Record<string, Tool.AnyExecutableTool> }> {
|
|
104
|
+
const clients = await Promise.all(Object.entries(configs).map(([name, config]) => connectMcp(name, config)))
|
|
105
|
+
const tools: Record<string, Tool.AnyExecutableTool> = {}
|
|
106
|
+
for (const mcp of clients) {
|
|
107
|
+
Object.assign(tools, mcp.tools)
|
|
108
|
+
}
|
|
109
|
+
return { clients, tools }
|
|
110
|
+
}
|
package/src/mcp/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { connectMcp, connectAllMcp, type McpServerConfig, type McpStdioConfig, type McpHttpConfig, type McpConfig, type McpClient } from "./client"
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Tool, ToolFailure, type AnyExecutableTool, type ExecutableTools } from "@tinyweb-agent-framework/llm"
|
|
2
|
+
import { Effect } from "effect"
|
|
3
|
+
|
|
4
|
+
export type PermissionRule = "allow" | "ask" | "deny"
|
|
5
|
+
|
|
6
|
+
export type PermissionConfig = PermissionRule | Readonly<Record<string, PermissionRule>>
|
|
7
|
+
|
|
8
|
+
export type PermissionAskRequest = {
|
|
9
|
+
readonly toolName: string
|
|
10
|
+
readonly input: unknown
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type PermissionAskHandler = (request: PermissionAskRequest) => Promise<boolean>
|
|
14
|
+
|
|
15
|
+
export const resolveRule = (config: PermissionConfig | undefined, toolName: string): PermissionRule => {
|
|
16
|
+
if (config === undefined) return "allow"
|
|
17
|
+
if (typeof config === "string") return config
|
|
18
|
+
return config[toolName] ?? "allow"
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const deniedFailure = (toolName: string): ToolFailure =>
|
|
22
|
+
new ToolFailure({ message: `Tool "${toolName}" denied by permission policy` })
|
|
23
|
+
|
|
24
|
+
const askDeniedFailure = (toolName: string): ToolFailure =>
|
|
25
|
+
new ToolFailure({ message: `Tool "${toolName}" denied by permission ask handler` })
|
|
26
|
+
|
|
27
|
+
const wrapTool = (
|
|
28
|
+
name: string,
|
|
29
|
+
base: AnyExecutableTool,
|
|
30
|
+
rule: PermissionRule,
|
|
31
|
+
askHandler: PermissionAskHandler | undefined,
|
|
32
|
+
): AnyExecutableTool => {
|
|
33
|
+
if (rule === "allow") return base
|
|
34
|
+
if (rule === "deny") {
|
|
35
|
+
return Tool.make({
|
|
36
|
+
description: base.description,
|
|
37
|
+
parameters: base.parameters,
|
|
38
|
+
success: base.success,
|
|
39
|
+
execute: () => Effect.fail(deniedFailure(name)),
|
|
40
|
+
}) as AnyExecutableTool
|
|
41
|
+
}
|
|
42
|
+
return Tool.make({
|
|
43
|
+
description: base.description,
|
|
44
|
+
parameters: base.parameters,
|
|
45
|
+
success: base.success,
|
|
46
|
+
execute: (input: unknown) =>
|
|
47
|
+
Effect.gen(function* () {
|
|
48
|
+
const allowed = yield* Effect.tryPromise({
|
|
49
|
+
try: () => (askHandler ? askHandler({ toolName: name, input }) : Promise.resolve(false)),
|
|
50
|
+
catch: (cause) => new ToolFailure({ message: `Permission ask handler threw: ${String(cause)}` }),
|
|
51
|
+
})
|
|
52
|
+
if (!allowed) return yield* Effect.fail(askDeniedFailure(name))
|
|
53
|
+
return yield* base.execute(input)
|
|
54
|
+
}),
|
|
55
|
+
}) as AnyExecutableTool
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const applyPermission = (
|
|
59
|
+
tools: ExecutableTools,
|
|
60
|
+
config: PermissionConfig | undefined,
|
|
61
|
+
askHandler: PermissionAskHandler | undefined,
|
|
62
|
+
): ExecutableTools => {
|
|
63
|
+
if (config === undefined) return tools
|
|
64
|
+
const out: Record<string, AnyExecutableTool> = {}
|
|
65
|
+
const names = Object.keys(tools)
|
|
66
|
+
for (const name of names) {
|
|
67
|
+
const tool = tools[name]
|
|
68
|
+
if (!tool) continue
|
|
69
|
+
out[name] = wrapTool(name, tool, resolveRule(config, name), askHandler)
|
|
70
|
+
}
|
|
71
|
+
return out as ExecutableTools
|
|
72
|
+
}
|