@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.
- package/dist/agent.d.ts +116 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/attachments.d.ts +41 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/bus/bus.d.ts +46 -0
- package/dist/bus/bus.d.ts.map +1 -0
- package/dist/bus/index.d.ts +2 -0
- package/dist/bus/index.d.ts.map +1 -0
- package/dist/define-tool.d.ts +13 -0
- package/dist/define-tool.d.ts.map +1 -0
- package/dist/events.d.ts +136 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/http-handlers.cjs +253 -0
- package/dist/http-handlers.cjs.map +1 -0
- package/dist/http-handlers.d.ts +49 -0
- package/dist/http-handlers.d.ts.map +1 -0
- package/dist/http-handlers.js +251 -0
- package/dist/http-handlers.js.map +1 -0
- package/dist/index.cjs +2073 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2015 -0
- package/dist/index.js.map +1 -0
- package/dist/loop-guard.d.ts +42 -0
- package/dist/loop-guard.d.ts.map +1 -0
- package/dist/mcp/client.d.ts +25 -0
- package/dist/mcp/client.d.ts.map +1 -0
- package/dist/mcp/index.cjs +66 -0
- package/dist/mcp/index.cjs.map +1 -0
- package/{src/mcp/index.ts → dist/mcp/index.d.ts} +2 -1
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +63 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/permission.d.ts +26 -0
- package/dist/permission.d.ts.map +1 -0
- package/dist/plugin/apply.d.ts +12 -0
- package/dist/plugin/apply.d.ts.map +1 -0
- package/dist/plugin/index.cjs +63 -0
- package/dist/plugin/index.cjs.map +1 -0
- package/dist/plugin/index.d.ts +4 -0
- package/dist/plugin/index.d.ts.map +1 -0
- package/dist/plugin/index.js +52 -0
- package/dist/plugin/index.js.map +1 -0
- package/dist/plugin/loader.d.ts +3 -0
- package/dist/plugin/loader.d.ts.map +1 -0
- package/dist/plugin/types.d.ts +98 -0
- package/dist/plugin/types.d.ts.map +1 -0
- package/dist/prompt/index.d.ts +51 -0
- package/dist/prompt/index.d.ts.map +1 -0
- package/dist/prompt/objective.d.ts +29 -0
- package/dist/prompt/objective.d.ts.map +1 -0
- package/dist/prompt/response-style.d.ts +19 -0
- package/dist/prompt/response-style.d.ts.map +1 -0
- package/dist/prompt/tool-use-guidelines.d.ts +22 -0
- package/dist/prompt/tool-use-guidelines.d.ts.map +1 -0
- package/dist/prompt/tool-use.d.ts +12 -0
- package/dist/prompt/tool-use.d.ts.map +1 -0
- package/dist/runtime.d.ts +7 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/session/adapter.d.ts +40 -0
- package/dist/session/adapter.d.ts.map +1 -0
- package/dist/session/compaction.d.ts +37 -0
- package/dist/session/compaction.d.ts.map +1 -0
- package/dist/session/index.d.ts +7 -0
- package/dist/session/index.d.ts.map +1 -0
- package/dist/session/memory.cjs +130 -0
- package/dist/session/memory.cjs.map +1 -0
- package/dist/session/memory.d.ts +3 -0
- package/dist/session/memory.d.ts.map +1 -0
- package/dist/session/memory.js +128 -0
- package/dist/session/memory.js.map +1 -0
- package/dist/session/overflow.d.ts +19 -0
- package/dist/session/overflow.d.ts.map +1 -0
- package/dist/session/postgres.cjs +245 -0
- package/dist/session/postgres.cjs.map +1 -0
- package/dist/session/postgres.d.ts +10 -0
- package/dist/session/postgres.d.ts.map +1 -0
- package/dist/session/postgres.js +243 -0
- package/dist/session/postgres.js.map +1 -0
- package/dist/session/processor.d.ts +52 -0
- package/dist/session/processor.d.ts.map +1 -0
- package/dist/session/replay.d.ts +4 -0
- package/dist/session/replay.d.ts.map +1 -0
- package/dist/session/schema.d.ts +104 -0
- package/dist/session/schema.d.ts.map +1 -0
- package/dist/session/sqlite.cjs +236 -0
- package/dist/session/sqlite.cjs.map +1 -0
- package/dist/session/sqlite.d.ts +3 -0
- package/dist/session/sqlite.d.ts.map +1 -0
- package/dist/session/sqlite.js +234 -0
- package/dist/session/sqlite.js.map +1 -0
- package/dist/session-api.cjs +56 -0
- package/dist/session-api.cjs.map +1 -0
- package/dist/session-api.d.ts +36 -0
- package/dist/session-api.d.ts.map +1 -0
- package/dist/session-api.js +54 -0
- package/dist/session-api.js.map +1 -0
- package/dist/skill/index.cjs +81 -0
- package/dist/skill/index.cjs.map +1 -0
- package/dist/skill/index.d.ts +10 -0
- package/dist/skill/index.d.ts.map +1 -0
- package/dist/skill/index.js +78 -0
- package/dist/skill/index.js.map +1 -0
- package/dist/sse-handler.d.ts +27 -0
- package/dist/sse-handler.d.ts.map +1 -0
- package/dist/transcript.d.ts +81 -0
- package/dist/transcript.d.ts.map +1 -0
- package/package.json +54 -19
- package/src/agent.ts +0 -470
- package/src/attachments.ts +0 -155
- package/src/bus/bus.ts +0 -89
- package/src/bus/index.ts +0 -1
- package/src/define-tool.ts +0 -41
- package/src/events.ts +0 -186
- package/src/http-handlers.ts +0 -251
- package/src/index.ts +0 -128
- package/src/loop-guard.ts +0 -99
- package/src/mcp/client.ts +0 -129
- package/src/permission.ts +0 -114
- package/src/plugin/apply.ts +0 -89
- package/src/plugin/index.ts +0 -3
- package/src/plugin/loader.ts +0 -42
- package/src/plugin/types.ts +0 -134
- package/src/prompt/index.ts +0 -90
- package/src/prompt/objective.ts +0 -104
- package/src/prompt/response-style.ts +0 -59
- package/src/prompt/tool-use-guidelines.ts +0 -57
- package/src/prompt/tool-use.ts +0 -27
- package/src/runtime.ts +0 -22
- package/src/session/adapter.ts +0 -46
- package/src/session/compaction.ts +0 -160
- package/src/session/index.ts +0 -18
- package/src/session/memory.ts +0 -169
- package/src/session/overflow.ts +0 -50
- package/src/session/postgres.ts +0 -355
- package/src/session/processor.ts +0 -865
- package/src/session/replay.ts +0 -151
- package/src/session/schema.ts +0 -156
- package/src/session/sqlite.ts +0 -309
- package/src/session-api.ts +0 -103
- package/src/skill/index.ts +0 -113
- package/src/sse-handler.ts +0 -67
- package/src/transcript.ts +0 -126
package/src/bus/bus.ts
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import { Effect, PubSub, Stream } from "effect"
|
|
2
|
-
import type { Message, SessionID } from "../session/schema"
|
|
3
|
-
import type { AgentEvent } from "../events"
|
|
4
|
-
|
|
5
|
-
// Bus event union — type-tagged for filtering
|
|
6
|
-
export type SessionStartedEvent = {
|
|
7
|
-
readonly type: "session-started"
|
|
8
|
-
readonly sessionId: SessionID | string
|
|
9
|
-
readonly agentName: string
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export type SessionMessageEvent = {
|
|
13
|
-
readonly type: "session-message"
|
|
14
|
-
readonly sessionId: SessionID | string
|
|
15
|
-
readonly message: Message
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export type SessionIdleEvent = {
|
|
19
|
-
readonly type: "session-idle"
|
|
20
|
-
readonly sessionId: SessionID | string
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export type ToolExecutingEvent = {
|
|
24
|
-
readonly type: "tool-executing"
|
|
25
|
-
readonly sessionId: SessionID | string
|
|
26
|
-
readonly callID: string
|
|
27
|
-
readonly name: string
|
|
28
|
-
readonly input: unknown
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export type ToolCompletedEvent = {
|
|
32
|
-
readonly type: "tool-completed"
|
|
33
|
-
readonly sessionId: SessionID | string
|
|
34
|
-
readonly callID: string
|
|
35
|
-
readonly name: string
|
|
36
|
-
readonly output: unknown
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export type AgentEventBusEvent = {
|
|
40
|
-
readonly type: "agent-event"
|
|
41
|
-
readonly sessionId: SessionID | string
|
|
42
|
-
readonly event: AgentEvent
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export type BusEvent =
|
|
46
|
-
| SessionStartedEvent
|
|
47
|
-
| SessionMessageEvent
|
|
48
|
-
| SessionIdleEvent
|
|
49
|
-
| ToolExecutingEvent
|
|
50
|
-
| ToolCompletedEvent
|
|
51
|
-
| AgentEventBusEvent
|
|
52
|
-
|
|
53
|
-
export type Bus = {
|
|
54
|
-
readonly publish: (event: BusEvent) => Effect.Effect<void>
|
|
55
|
-
readonly subscribe: <K extends BusEvent["type"]>(
|
|
56
|
-
type: K,
|
|
57
|
-
) => Stream.Stream<Extract<BusEvent, { type: K }>>
|
|
58
|
-
readonly subscribeAll: () => Stream.Stream<BusEvent>
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export const makeBus = (): Bus => {
|
|
62
|
-
const pubsubEffect = PubSub.unbounded<BusEvent>()
|
|
63
|
-
let cached: PubSub.PubSub<BusEvent> | undefined
|
|
64
|
-
|
|
65
|
-
const get = (): Effect.Effect<PubSub.PubSub<BusEvent>> => {
|
|
66
|
-
if (cached) return Effect.succeed(cached)
|
|
67
|
-
return pubsubEffect.pipe(
|
|
68
|
-
Effect.tap((p) => {
|
|
69
|
-
cached = p
|
|
70
|
-
return Effect.void
|
|
71
|
-
}),
|
|
72
|
-
)
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const publish = (event: BusEvent): Effect.Effect<void> =>
|
|
76
|
-
Effect.flatMap(get(), (pubsub) => Effect.asVoid(PubSub.publish(pubsub, event)))
|
|
77
|
-
|
|
78
|
-
const subscribeAll = (): Stream.Stream<BusEvent> =>
|
|
79
|
-
Stream.unwrap(Effect.map(get(), (pubsub) => Stream.fromPubSub(pubsub)))
|
|
80
|
-
|
|
81
|
-
const subscribe = <K extends BusEvent["type"]>(
|
|
82
|
-
type: K,
|
|
83
|
-
): Stream.Stream<Extract<BusEvent, { type: K }>> =>
|
|
84
|
-
subscribeAll().pipe(
|
|
85
|
-
Stream.filter((e): e is Extract<BusEvent, { type: K }> => e.type === type),
|
|
86
|
-
)
|
|
87
|
-
|
|
88
|
-
return { publish, subscribe, subscribeAll }
|
|
89
|
-
}
|
package/src/bus/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from "./bus"
|
package/src/define-tool.ts
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { Tool, ToolFailure, type ToolSchema } from "@tinyweb-agent-framework/llm"
|
|
2
|
-
import { Effect, Schema } from "effect"
|
|
3
|
-
|
|
4
|
-
export type ToolExecuteAsync<Params, Success> = (input: Params) => Promise<Success>
|
|
5
|
-
export type ToolExecuteEffect<Params, Success> = (
|
|
6
|
-
input: Params,
|
|
7
|
-
) => Effect.Effect<Success, ToolFailure>
|
|
8
|
-
|
|
9
|
-
export type DefineToolConfig<P extends ToolSchema<any>, S extends ToolSchema<any>> = {
|
|
10
|
-
readonly name?: string
|
|
11
|
-
readonly description: string
|
|
12
|
-
readonly parameters: P
|
|
13
|
-
readonly success?: S
|
|
14
|
-
readonly execute:
|
|
15
|
-
| ToolExecuteAsync<Schema.Schema.Type<P>, Schema.Schema.Type<S>>
|
|
16
|
-
| ToolExecuteEffect<Schema.Schema.Type<P>, Schema.Schema.Type<S>>
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
const wrapExecute = <Params, Success>(
|
|
20
|
-
execute: ToolExecuteAsync<Params, Success> | ToolExecuteEffect<Params, Success>,
|
|
21
|
-
) =>
|
|
22
|
-
(input: Params): Effect.Effect<Success, ToolFailure> => {
|
|
23
|
-
const result = execute(input)
|
|
24
|
-
if (Effect.isEffect(result)) return result as Effect.Effect<Success, ToolFailure>
|
|
25
|
-
return Effect.tryPromise({
|
|
26
|
-
try: () => result as Promise<Success>,
|
|
27
|
-
catch: (cause) => new ToolFailure({ message: cause instanceof Error ? cause.message : String(cause) }),
|
|
28
|
-
})
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function defineTool<P extends ToolSchema<any>, S extends ToolSchema<any> = typeof Schema.Unknown>(
|
|
32
|
-
config: DefineToolConfig<P, S>,
|
|
33
|
-
) {
|
|
34
|
-
const success = (config.success ?? Schema.Unknown) as S
|
|
35
|
-
return Tool.make({
|
|
36
|
-
description: config.description,
|
|
37
|
-
parameters: config.parameters,
|
|
38
|
-
success,
|
|
39
|
-
execute: wrapExecute(config.execute),
|
|
40
|
-
})
|
|
41
|
-
}
|
package/src/events.ts
DELETED
|
@@ -1,186 +0,0 @@
|
|
|
1
|
-
import type { LLMEvent } from "@tinyweb-agent-framework/llm"
|
|
2
|
-
|
|
3
|
-
export type TextDeltaEvent = {
|
|
4
|
-
readonly type: "text-delta"
|
|
5
|
-
readonly id: string
|
|
6
|
-
readonly text: string
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export type TextEndEvent = {
|
|
10
|
-
readonly type: "text-end"
|
|
11
|
-
readonly id: string
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export type ReasoningDeltaEvent = {
|
|
15
|
-
readonly type: "reasoning-delta"
|
|
16
|
-
readonly id: string
|
|
17
|
-
readonly text: string
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export type ToolCallEvent = {
|
|
21
|
-
readonly type: "tool-call"
|
|
22
|
-
readonly id: string
|
|
23
|
-
readonly name: string
|
|
24
|
-
readonly input: unknown
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export type ToolResultEvent = {
|
|
28
|
-
readonly type: "tool-result"
|
|
29
|
-
readonly id: string
|
|
30
|
-
readonly name: string
|
|
31
|
-
readonly result: unknown
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export type ToolErrorEvent = {
|
|
35
|
-
readonly type: "tool-error"
|
|
36
|
-
readonly id: string
|
|
37
|
-
readonly name: string
|
|
38
|
-
readonly message: string
|
|
39
|
-
/** Optional structured payload (e.g. tool-interrupt metadata). */
|
|
40
|
-
readonly metadata?: Record<string, unknown>
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Emitted when a tool with permission rule `"ask"` (interrupt mode) is
|
|
45
|
-
* intercepted before execution. Host UIs should render an approve/reject
|
|
46
|
-
* control and later call `agent.resolveApproval` + `agent.resume`.
|
|
47
|
-
*/
|
|
48
|
-
export type ToolApprovalRequestEvent = {
|
|
49
|
-
readonly type: "tool-approval-request"
|
|
50
|
-
readonly id: string
|
|
51
|
-
readonly name: string
|
|
52
|
-
readonly input: unknown
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export type StepFinishEvent = {
|
|
56
|
-
readonly type: "step-finish"
|
|
57
|
-
readonly index: number
|
|
58
|
-
readonly reason: string
|
|
59
|
-
readonly usage?: unknown
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export type FinishEvent = {
|
|
63
|
-
readonly type: "finish"
|
|
64
|
-
readonly reason: string
|
|
65
|
-
readonly usage?: unknown
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export type ErrorEvent = {
|
|
69
|
-
readonly type: "error"
|
|
70
|
-
readonly message: string
|
|
71
|
-
readonly retryable?: boolean
|
|
72
|
-
/**
|
|
73
|
-
* Optional structured code for client-side branching (e.g.
|
|
74
|
-
* `"attachment_too_large"`, `"attachment_unsupported_type"`).
|
|
75
|
-
* Free-form string — consumers should treat unknown codes as generic errors.
|
|
76
|
-
*/
|
|
77
|
-
readonly code?: string
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Source of an auto-compaction (context-condense) pass.
|
|
82
|
-
*
|
|
83
|
-
* - `preflight` — the agent estimated the upcoming prompt would exceed the
|
|
84
|
-
* usable budget and ran `compact()` BEFORE the provider call. Cheaper and
|
|
85
|
-
* more controllable.
|
|
86
|
-
* - `overflow-retry` — the provider returned `ContextOverflowReason`; the
|
|
87
|
-
* agent ran `compact()` and retried the same turn once. Surfaced so UIs
|
|
88
|
-
* can show "context overflow — recovering…" copy distinct from a regular
|
|
89
|
-
* pre-flight condense.
|
|
90
|
-
* - `manual` — RESERVED. Not emitted yet (no manual trigger exists), but
|
|
91
|
-
* reserved on the discriminated union so adding a "Condense Now" button
|
|
92
|
-
* later doesn't break consumers' exhaustive switches.
|
|
93
|
-
*/
|
|
94
|
-
export type CondenseTrigger = "preflight" | "overflow-retry" | "manual"
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Emitted IMMEDIATELY before `compact()` runs. UI consumers should render a
|
|
98
|
-
* spinner/pill — compaction can take 2–5s on a long thread because it makes
|
|
99
|
-
* its own LLM call.
|
|
100
|
-
*/
|
|
101
|
-
export type ContextCondenseStartEvent = {
|
|
102
|
-
readonly type: "context-condense-start"
|
|
103
|
-
readonly trigger: CondenseTrigger
|
|
104
|
-
/** Estimated prompt tokens the agent would have sent without compacting. */
|
|
105
|
-
readonly estimatedTokens?: number
|
|
106
|
-
/** The usable budget (`limits.context − reserved`) that the estimate exceeded. */
|
|
107
|
-
readonly budgetTokens?: number
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Emitted after a SUCCESSFUL compaction. Carries the summariser's output plus
|
|
112
|
-
* before/after token counts and (when the route exposes it) the call cost.
|
|
113
|
-
* This is the persistent, replay-friendly record of what happened.
|
|
114
|
-
*/
|
|
115
|
-
export type ContextCondenseEvent = {
|
|
116
|
-
readonly type: "context-condense"
|
|
117
|
-
readonly trigger: CondenseTrigger
|
|
118
|
-
/** Compaction summary text — already truncated if the summariser overflowed. */
|
|
119
|
-
readonly summary: string
|
|
120
|
-
/** ID of the persisted compaction marker user message — cross-references `sessions.messages(...)`. */
|
|
121
|
-
readonly markerId: string
|
|
122
|
-
/** Approximate input tokens BEFORE compaction (estimateTokens of the head slice). */
|
|
123
|
-
readonly prevTokens?: number
|
|
124
|
-
/** Approximate input tokens AFTER compaction (estimateTokens of `[marker, ...tail]`). */
|
|
125
|
-
readonly newTokens?: number
|
|
126
|
-
/** USD cost of the summariser LLM call when the route surfaces it. */
|
|
127
|
-
readonly cost?: number
|
|
128
|
-
/** Model id used for the summariser (today: same as the main agent model). */
|
|
129
|
-
readonly modelId?: string
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* Emitted when `compact()` itself errored or, on the `overflow-retry` path,
|
|
134
|
-
* when the post-compaction retry still overflowed (`retryExhausted: true`).
|
|
135
|
-
*
|
|
136
|
-
* Distinct from the generic `error` event so UIs can render it inline next
|
|
137
|
-
* to the condense spinner without tearing down the assistant turn.
|
|
138
|
-
*/
|
|
139
|
-
export type ContextCondenseErrorEvent = {
|
|
140
|
-
readonly type: "context-condense-error"
|
|
141
|
-
readonly trigger: CondenseTrigger
|
|
142
|
-
readonly message: string
|
|
143
|
-
/** True ONLY on the second consecutive overflow — replaces the old "compaction retry exhausted" message. */
|
|
144
|
-
readonly retryExhausted?: boolean
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
export type AgentEvent =
|
|
148
|
-
| TextDeltaEvent
|
|
149
|
-
| TextEndEvent
|
|
150
|
-
| ReasoningDeltaEvent
|
|
151
|
-
| ToolCallEvent
|
|
152
|
-
| ToolResultEvent
|
|
153
|
-
| ToolErrorEvent
|
|
154
|
-
| ToolApprovalRequestEvent
|
|
155
|
-
| StepFinishEvent
|
|
156
|
-
| FinishEvent
|
|
157
|
-
| ErrorEvent
|
|
158
|
-
| ContextCondenseStartEvent
|
|
159
|
-
| ContextCondenseEvent
|
|
160
|
-
| ContextCondenseErrorEvent
|
|
161
|
-
|
|
162
|
-
/** Finish reason used when the turn stops waiting for user tool approval. */
|
|
163
|
-
export const FINISH_REASON_APPROVAL_REQUIRED = "approval-required" as const
|
|
164
|
-
|
|
165
|
-
export const fromLLMEvent = (event: LLMEvent): AgentEvent | undefined => {
|
|
166
|
-
if (event.type === "text-delta") return { type: "text-delta", id: event.id, text: event.text }
|
|
167
|
-
if (event.type === "text-end") return { type: "text-end", id: event.id }
|
|
168
|
-
if (event.type === "reasoning-delta") return { type: "reasoning-delta", id: event.id, text: event.text }
|
|
169
|
-
if (event.type === "tool-call") return { type: "tool-call", id: event.id, name: event.name, input: event.input }
|
|
170
|
-
if (event.type === "tool-result")
|
|
171
|
-
return { type: "tool-result", id: event.id, name: event.name, result: event.result.value }
|
|
172
|
-
if (event.type === "tool-error")
|
|
173
|
-
return {
|
|
174
|
-
type: "tool-error",
|
|
175
|
-
id: event.id,
|
|
176
|
-
name: event.name,
|
|
177
|
-
message: event.message,
|
|
178
|
-
metadata: event.metadata,
|
|
179
|
-
}
|
|
180
|
-
if (event.type === "step-finish")
|
|
181
|
-
return { type: "step-finish", index: event.index, reason: event.reason, usage: event.usage }
|
|
182
|
-
if (event.type === "request-finish") return { type: "finish", reason: event.reason, usage: event.usage }
|
|
183
|
-
if (event.type === "provider-error")
|
|
184
|
-
return { type: "error", message: event.message, retryable: event.retryable }
|
|
185
|
-
return undefined
|
|
186
|
-
}
|
package/src/http-handlers.ts
DELETED
|
@@ -1,251 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,128 +0,0 @@
|
|
|
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 ResumeInput,
|
|
10
|
-
type ResolveApprovalInput,
|
|
11
|
-
type ResolveApprovalResult,
|
|
12
|
-
type RunOnceResult,
|
|
13
|
-
type ToHTTPHandlersOptions,
|
|
14
|
-
} from "./agent"
|
|
15
|
-
export { defineTool, type DefineToolConfig } from "./define-tool"
|
|
16
|
-
|
|
17
|
-
// System-prompt section composer (Roo-style blocks)
|
|
18
|
-
export {
|
|
19
|
-
composeSystemPrompt,
|
|
20
|
-
toolUseSection,
|
|
21
|
-
toolUseGuidelinesSection,
|
|
22
|
-
objectiveSection,
|
|
23
|
-
responseStyleSection,
|
|
24
|
-
type ComposeSystemPromptInput,
|
|
25
|
-
type PromptSectionsConfig,
|
|
26
|
-
type ToolUseGuidelinesConfig,
|
|
27
|
-
type ObjectiveConfig,
|
|
28
|
-
type ObjectiveKind,
|
|
29
|
-
type ResponseStyleConfig,
|
|
30
|
-
type ResponseStyleKind,
|
|
31
|
-
} from "./prompt"
|
|
32
|
-
|
|
33
|
-
// Session-level Promise SDK
|
|
34
|
-
export {
|
|
35
|
-
makeSessionAPI,
|
|
36
|
-
type SessionAPI,
|
|
37
|
-
type CreateSessionAPIInput,
|
|
38
|
-
type ListSessionsAPIOpts,
|
|
39
|
-
type MakeSessionAPIConfig,
|
|
40
|
-
type MessagesAPIResult,
|
|
41
|
-
} from "./session-api"
|
|
42
|
-
|
|
43
|
-
// HTTP handlers (REST endpoints for SessionAPI + chat)
|
|
44
|
-
export {
|
|
45
|
-
makeHTTPHandlers,
|
|
46
|
-
type HTTPHandlers,
|
|
47
|
-
type HTTPHandler,
|
|
48
|
-
type HTTPReq,
|
|
49
|
-
type HTTPRes,
|
|
50
|
-
type MakeHTTPHandlersConfig,
|
|
51
|
-
type AuthorizeFn,
|
|
52
|
-
type ChatFormat,
|
|
53
|
-
type ChatRunInput,
|
|
54
|
-
} from "./http-handlers"
|
|
55
|
-
|
|
56
|
-
// Attachments
|
|
57
|
-
export {
|
|
58
|
-
validateAttachments,
|
|
59
|
-
DEFAULT_IMAGE_MIMES,
|
|
60
|
-
DEFAULT_MAX_BYTES_PER_FILE,
|
|
61
|
-
DEFAULT_MAX_BYTES_TOTAL,
|
|
62
|
-
DEFAULT_MAX_COUNT,
|
|
63
|
-
type AttachmentInput,
|
|
64
|
-
type AttachmentErrorCode,
|
|
65
|
-
type ValidateAttachmentsConfig,
|
|
66
|
-
type ValidateResult,
|
|
67
|
-
type ValidateOk,
|
|
68
|
-
type ValidateErr,
|
|
69
|
-
} from "./attachments"
|
|
70
|
-
|
|
71
|
-
// Events
|
|
72
|
-
export type {
|
|
73
|
-
AgentEvent,
|
|
74
|
-
TextDeltaEvent,
|
|
75
|
-
TextEndEvent,
|
|
76
|
-
ReasoningDeltaEvent,
|
|
77
|
-
ToolCallEvent,
|
|
78
|
-
ToolResultEvent,
|
|
79
|
-
ToolErrorEvent,
|
|
80
|
-
ToolApprovalRequestEvent,
|
|
81
|
-
StepFinishEvent,
|
|
82
|
-
FinishEvent,
|
|
83
|
-
ErrorEvent,
|
|
84
|
-
} from "./events"
|
|
85
|
-
export { fromLLMEvent, FINISH_REASON_APPROVAL_REQUIRED } from "./events"
|
|
86
|
-
|
|
87
|
-
// Transcript helpers — consumer-side fallback for persisting display_response turns
|
|
88
|
-
export {
|
|
89
|
-
collectAssistantText,
|
|
90
|
-
makeAssistantTextAccumulator,
|
|
91
|
-
type AssistantTextAccumulator,
|
|
92
|
-
type CollectAssistantTextOptions,
|
|
93
|
-
} from "./transcript"
|
|
94
|
-
|
|
95
|
-
// Runtime
|
|
96
|
-
export { createRuntime, defaultRuntime, disposeDefaultRuntime, type AgentRuntime } from "./runtime"
|
|
97
|
-
|
|
98
|
-
// Session + storage
|
|
99
|
-
export * from "./session"
|
|
100
|
-
|
|
101
|
-
// Bus
|
|
102
|
-
export * from "./bus"
|
|
103
|
-
|
|
104
|
-
// SSE / streaming handler
|
|
105
|
-
export { makeSSEHandler, writeEventsToResponse, type SSEFormat, type SSEHandlerOptions } from "./sse-handler"
|
|
106
|
-
|
|
107
|
-
// Permission
|
|
108
|
-
export {
|
|
109
|
-
applyPermission,
|
|
110
|
-
resolveRule,
|
|
111
|
-
isToolInterruptMetadata,
|
|
112
|
-
toolInterruptFailure,
|
|
113
|
-
TOOL_INTERRUPT_KIND,
|
|
114
|
-
type PermissionAskHandler,
|
|
115
|
-
type PermissionAskMode,
|
|
116
|
-
type PermissionAskRequest,
|
|
117
|
-
type PermissionConfig,
|
|
118
|
-
type PermissionRule,
|
|
119
|
-
} from "./permission"
|
|
120
|
-
|
|
121
|
-
// Plugin / Hooks
|
|
122
|
-
export * from "./plugin"
|
|
123
|
-
|
|
124
|
-
// MCP client
|
|
125
|
-
export { connectMcp, connectAllMcp, type McpServerConfig, type McpStdioConfig, type McpHttpConfig, type McpConfig, type McpClient } from "./mcp"
|
|
126
|
-
|
|
127
|
-
// Skill system
|
|
128
|
-
export { loadSkills, makeSkillTool, type SkillInfo } from "./skill"
|