@tinyweb_dev/agent-framework-agent 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist/agent.d.ts +116 -0
  2. package/dist/agent.d.ts.map +1 -0
  3. package/dist/attachments.d.ts +41 -0
  4. package/dist/attachments.d.ts.map +1 -0
  5. package/dist/bus/bus.d.ts +46 -0
  6. package/dist/bus/bus.d.ts.map +1 -0
  7. package/dist/bus/index.d.ts +2 -0
  8. package/dist/bus/index.d.ts.map +1 -0
  9. package/dist/define-tool.d.ts +13 -0
  10. package/dist/define-tool.d.ts.map +1 -0
  11. package/dist/events.d.ts +136 -0
  12. package/dist/events.d.ts.map +1 -0
  13. package/dist/http-handlers.cjs +253 -0
  14. package/dist/http-handlers.cjs.map +1 -0
  15. package/dist/http-handlers.d.ts +49 -0
  16. package/dist/http-handlers.d.ts.map +1 -0
  17. package/dist/http-handlers.js +251 -0
  18. package/dist/http-handlers.js.map +1 -0
  19. package/dist/index.cjs +2073 -0
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.ts +19 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +2015 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/loop-guard.d.ts +42 -0
  26. package/dist/loop-guard.d.ts.map +1 -0
  27. package/dist/mcp/client.d.ts +25 -0
  28. package/dist/mcp/client.d.ts.map +1 -0
  29. package/dist/mcp/index.cjs +66 -0
  30. package/dist/mcp/index.cjs.map +1 -0
  31. package/{src/mcp/index.ts → dist/mcp/index.d.ts} +2 -1
  32. package/dist/mcp/index.d.ts.map +1 -0
  33. package/dist/mcp/index.js +63 -0
  34. package/dist/mcp/index.js.map +1 -0
  35. package/dist/permission.d.ts +26 -0
  36. package/dist/permission.d.ts.map +1 -0
  37. package/dist/plugin/apply.d.ts +12 -0
  38. package/dist/plugin/apply.d.ts.map +1 -0
  39. package/dist/plugin/index.cjs +63 -0
  40. package/dist/plugin/index.cjs.map +1 -0
  41. package/dist/plugin/index.d.ts +4 -0
  42. package/dist/plugin/index.d.ts.map +1 -0
  43. package/dist/plugin/index.js +52 -0
  44. package/dist/plugin/index.js.map +1 -0
  45. package/dist/plugin/loader.d.ts +3 -0
  46. package/dist/plugin/loader.d.ts.map +1 -0
  47. package/dist/plugin/types.d.ts +98 -0
  48. package/dist/plugin/types.d.ts.map +1 -0
  49. package/dist/prompt/index.d.ts +51 -0
  50. package/dist/prompt/index.d.ts.map +1 -0
  51. package/dist/prompt/objective.d.ts +29 -0
  52. package/dist/prompt/objective.d.ts.map +1 -0
  53. package/dist/prompt/response-style.d.ts +19 -0
  54. package/dist/prompt/response-style.d.ts.map +1 -0
  55. package/dist/prompt/tool-use-guidelines.d.ts +22 -0
  56. package/dist/prompt/tool-use-guidelines.d.ts.map +1 -0
  57. package/dist/prompt/tool-use.d.ts +12 -0
  58. package/dist/prompt/tool-use.d.ts.map +1 -0
  59. package/dist/runtime.d.ts +7 -0
  60. package/dist/runtime.d.ts.map +1 -0
  61. package/dist/session/adapter.d.ts +40 -0
  62. package/dist/session/adapter.d.ts.map +1 -0
  63. package/dist/session/compaction.d.ts +37 -0
  64. package/dist/session/compaction.d.ts.map +1 -0
  65. package/dist/session/index.d.ts +7 -0
  66. package/dist/session/index.d.ts.map +1 -0
  67. package/dist/session/memory.cjs +130 -0
  68. package/dist/session/memory.cjs.map +1 -0
  69. package/dist/session/memory.d.ts +3 -0
  70. package/dist/session/memory.d.ts.map +1 -0
  71. package/dist/session/memory.js +128 -0
  72. package/dist/session/memory.js.map +1 -0
  73. package/dist/session/overflow.d.ts +19 -0
  74. package/dist/session/overflow.d.ts.map +1 -0
  75. package/dist/session/postgres.cjs +245 -0
  76. package/dist/session/postgres.cjs.map +1 -0
  77. package/dist/session/postgres.d.ts +10 -0
  78. package/dist/session/postgres.d.ts.map +1 -0
  79. package/dist/session/postgres.js +243 -0
  80. package/dist/session/postgres.js.map +1 -0
  81. package/dist/session/processor.d.ts +52 -0
  82. package/dist/session/processor.d.ts.map +1 -0
  83. package/dist/session/replay.d.ts +4 -0
  84. package/dist/session/replay.d.ts.map +1 -0
  85. package/dist/session/schema.d.ts +104 -0
  86. package/dist/session/schema.d.ts.map +1 -0
  87. package/dist/session/sqlite.cjs +236 -0
  88. package/dist/session/sqlite.cjs.map +1 -0
  89. package/dist/session/sqlite.d.ts +3 -0
  90. package/dist/session/sqlite.d.ts.map +1 -0
  91. package/dist/session/sqlite.js +234 -0
  92. package/dist/session/sqlite.js.map +1 -0
  93. package/dist/session-api.cjs +56 -0
  94. package/dist/session-api.cjs.map +1 -0
  95. package/dist/session-api.d.ts +36 -0
  96. package/dist/session-api.d.ts.map +1 -0
  97. package/dist/session-api.js +54 -0
  98. package/dist/session-api.js.map +1 -0
  99. package/dist/skill/index.cjs +81 -0
  100. package/dist/skill/index.cjs.map +1 -0
  101. package/dist/skill/index.d.ts +10 -0
  102. package/dist/skill/index.d.ts.map +1 -0
  103. package/dist/skill/index.js +78 -0
  104. package/dist/skill/index.js.map +1 -0
  105. package/dist/sse-handler.d.ts +27 -0
  106. package/dist/sse-handler.d.ts.map +1 -0
  107. package/dist/transcript.d.ts +81 -0
  108. package/dist/transcript.d.ts.map +1 -0
  109. package/package.json +54 -19
  110. package/src/agent.ts +0 -317
  111. package/src/attachments.ts +0 -155
  112. package/src/bus/bus.ts +0 -89
  113. package/src/bus/index.ts +0 -1
  114. package/src/define-tool.ts +0 -41
  115. package/src/events.ts +0 -162
  116. package/src/http-handlers.ts +0 -251
  117. package/src/index.ts +0 -120
  118. package/src/loop-guard.ts +0 -99
  119. package/src/mcp/client.ts +0 -110
  120. package/src/permission.ts +0 -72
  121. package/src/plugin/apply.ts +0 -89
  122. package/src/plugin/index.ts +0 -3
  123. package/src/plugin/loader.ts +0 -42
  124. package/src/plugin/types.ts +0 -134
  125. package/src/prompt/index.ts +0 -90
  126. package/src/prompt/objective.ts +0 -104
  127. package/src/prompt/response-style.ts +0 -59
  128. package/src/prompt/tool-use-guidelines.ts +0 -57
  129. package/src/prompt/tool-use.ts +0 -27
  130. package/src/runtime.ts +0 -22
  131. package/src/session/adapter.ts +0 -37
  132. package/src/session/compaction.ts +0 -160
  133. package/src/session/index.ts +0 -11
  134. package/src/session/memory.ts +0 -154
  135. package/src/session/overflow.ts +0 -50
  136. package/src/session/postgres.ts +0 -330
  137. package/src/session/processor.ts +0 -500
  138. package/src/session/replay.ts +0 -140
  139. package/src/session/schema.ts +0 -140
  140. package/src/session/sqlite.ts +0 -281
  141. package/src/session-api.ts +0 -103
  142. package/src/skill/index.ts +0 -113
  143. package/src/sse-handler.ts +0 -67
  144. package/src/transcript.ts +0 -126
@@ -0,0 +1,116 @@
1
+ import { type GenerationOptions, type LLMResponse, type ModelRef, type StopCondition, type Tools } from "@tinyweb_dev/agent-framework-llm";
2
+ import type { AttachmentInput } from "./attachments";
3
+ import { type AgentEvent } from "./events";
4
+ import { type PermissionAskHandler, type PermissionAskMode, type PermissionConfig } from "./permission";
5
+ import { type AgentRuntime } from "./runtime";
6
+ import type { SessionStore } from "./session/adapter";
7
+ import { makeSSEHandler, type SSEHandlerOptions } from "./sse-handler";
8
+ import { type PluginEntry } from "./plugin";
9
+ import { type McpConfig } from "./mcp";
10
+ import { type SessionAPI } from "./session-api";
11
+ import { type AuthorizeFn, type ChatFormat, type HTTPHandlers } from "./http-handlers";
12
+ import { type PromptSectionsConfig } from "./prompt";
13
+ /**
14
+ * Auto-compaction policy. The agent estimates input tokens on every turn and,
15
+ * when the estimate crosses the model's usable budget, summarises the leading
16
+ * slice of the conversation into a marker user message before calling the LLM.
17
+ * On a `ContextOverflowReason` from the provider the agent retries once with
18
+ * a freshly compacted history.
19
+ */
20
+ export type CompactionConfig = {
21
+ /** Default: true. Set to false to opt out entirely. */
22
+ readonly auto?: boolean;
23
+ /** Reserved output buffer. Default `min(20_000, model.limits.output)`. */
24
+ readonly reservedTokens?: number;
25
+ /** Number of trailing turns kept verbatim. Default 4. */
26
+ readonly preserveRecentTurns?: number;
27
+ };
28
+ export type DefineAgentConfig<T extends Tools> = {
29
+ readonly name: string;
30
+ readonly model: ModelRef;
31
+ /**
32
+ * The agent's ROLE / persona block. Verbatim — no transformation.
33
+ *
34
+ * Framework-owned blocks (TOOL USE, TOOL USE GUIDELINES, RESPONSE STYLE) are
35
+ * automatically appended after this. Disable or tune them via
36
+ * `promptSections`. To skip the framework blocks entirely set
37
+ * `promptSections: { toolUse: false, toolUseGuidelines: false, responseStyle: false }`.
38
+ */
39
+ readonly systemPrompt?: string;
40
+ /**
41
+ * Per-section toggles for the framework-owned prompt blocks. Defaults: all
42
+ * enabled with chat-style response rules. See [`prompt/index.ts`](./prompt/index.ts:1).
43
+ */
44
+ readonly promptSections?: PromptSectionsConfig;
45
+ readonly tools?: T;
46
+ readonly stopWhen?: StopCondition;
47
+ readonly generation?: GenerationOptions.Input;
48
+ readonly runtime?: AgentRuntime;
49
+ readonly store?: SessionStore;
50
+ readonly permission?: PermissionConfig;
51
+ readonly askHandler?: PermissionAskHandler;
52
+ /**
53
+ * How `"ask"` permission rules are enforced.
54
+ * - `"handler"` (default) — block on `askHandler` Promise (CLI / in-process UI).
55
+ * - `"interrupt"` — persist `pending-approval` ToolPart and stop the turn;
56
+ * host later calls `resolveApproval` + `resume`. Preferred for durable UIs.
57
+ */
58
+ readonly askMode?: PermissionAskMode;
59
+ /** Plugins to load — inline Plugin fn, path string, or [path, options] tuple */
60
+ readonly plugins?: PluginEntry[];
61
+ /** MCP servers to connect — Record<serverName, McpServerConfig> */
62
+ readonly mcp?: McpConfig;
63
+ /** Extra directories to scan for SKILL.md files */
64
+ readonly skillDirs?: string[];
65
+ /** Auto-compaction tuning. Defaults are sane; pass `{ auto: false }` to disable. */
66
+ readonly compaction?: CompactionConfig;
67
+ };
68
+ export type RunInput = {
69
+ readonly prompt: string;
70
+ readonly sessionId?: string;
71
+ readonly attachments?: ReadonlyArray<AttachmentInput>;
72
+ };
73
+ export type ResumeInput = {
74
+ readonly sessionId: string;
75
+ };
76
+ export type ResolveApprovalInput = {
77
+ readonly sessionId: string;
78
+ /** Tool call id (`ToolPart.callID` / SSE `tool-approval-request.id`). */
79
+ readonly callID: string;
80
+ readonly approved: boolean;
81
+ };
82
+ export type ResolveApprovalResult = {
83
+ readonly callID: string;
84
+ readonly state: "approved" | "rejected";
85
+ readonly toolName: string;
86
+ readonly input: unknown;
87
+ };
88
+ export type RunOnceResult = {
89
+ readonly text: string;
90
+ readonly usage: LLMResponse["usage"];
91
+ readonly events: LLMResponse["events"];
92
+ };
93
+ export type ToHTTPHandlersOptions = {
94
+ readonly authorize?: AuthorizeFn;
95
+ readonly defaultFormat?: ChatFormat;
96
+ };
97
+ export type Agent = {
98
+ readonly name: string;
99
+ readonly run: (input: RunInput) => AsyncIterable<AgentEvent>;
100
+ readonly runOnce: (input: RunInput) => Promise<RunOnceResult>;
101
+ /**
102
+ * Mark a `pending-approval` tool call as approved or rejected (persisted in
103
+ * the SessionStore). Does NOT execute the tool — call `resume` afterwards.
104
+ */
105
+ readonly resolveApproval: (input: ResolveApprovalInput) => Promise<ResolveApprovalResult>;
106
+ /**
107
+ * Continue a session after approvals were resolved. Executes approved tools,
108
+ * records denials, then streams a follow-up LLM turn.
109
+ */
110
+ readonly resume: (input: ResumeInput) => AsyncIterable<AgentEvent>;
111
+ readonly toSSEHandler: (options?: SSEHandlerOptions) => ReturnType<typeof makeSSEHandler>;
112
+ readonly sessions: SessionAPI;
113
+ readonly toHTTPHandlers: (options?: ToHTTPHandlersOptions) => HTTPHandlers;
114
+ };
115
+ export declare const defineAgent: <T extends Tools = Tools>(config: DefineAgentConfig<T>) => Agent;
116
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAChB,KAAK,QAAQ,EACb,KAAK,a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CAAA;IAC7B,QAAQ,CAAC,cAAc,EAAE,CAAC,OAAO,CAAC,EAAE,qBAAqB,KAAK,YAAY,CAAA;CAC3E,CAAA;AA6ED,eAAO,MAAM,WAAW,GAAI,CAAC,SAAS,KAAK,GAAG,KAAK,EAAE,QAAQ,iBAAiB,CAAC,CAAC,CAAC,KAAG,KAwPjF,CAAA"}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Public attachment shape forwarded from HTTP/UI → agent.run.
3
+ * MVP: image-only, base64 inline OR pre-uploaded URL.
4
+ * Validation enforced both client-side (chat-ui) and server-side (http-handlers).
5
+ */
6
+ export type AttachmentInput = {
7
+ readonly type: "image";
8
+ readonly mediaType: string;
9
+ /** Either `data` (raw base64, no `data:` prefix) OR `url` (http/https/file/data:). Exactly one. */
10
+ readonly data?: string;
11
+ readonly url?: string;
12
+ readonly filename?: string;
13
+ };
14
+ export type AttachmentErrorCode = "attachment_too_large" | "attachment_unsupported_type" | "attachment_invalid" | "attachment_too_many";
15
+ export type ValidateAttachmentsConfig = {
16
+ readonly imageMimes?: ReadonlySet<string>;
17
+ readonly maxBytesPerFile?: number;
18
+ readonly maxBytesTotal?: number;
19
+ readonly maxCount?: number;
20
+ };
21
+ export type ValidateOk = {
22
+ readonly ok: true;
23
+ readonly value: ReadonlyArray<AttachmentInput>;
24
+ };
25
+ export type ValidateErr = {
26
+ readonly ok: false;
27
+ readonly code: AttachmentErrorCode;
28
+ readonly message: string;
29
+ };
30
+ export type ValidateResult = ValidateOk | ValidateErr;
31
+ export declare const DEFAULT_IMAGE_MIMES: ReadonlySet<string>;
32
+ export declare const DEFAULT_MAX_BYTES_PER_FILE: number;
33
+ export declare const DEFAULT_MAX_BYTES_TOTAL: number;
34
+ export declare const DEFAULT_MAX_COUNT = 4;
35
+ /**
36
+ * Validate raw attachments. Pure function — no I/O. First failure short-circuits.
37
+ *
38
+ * Order: count → per-item (mime, exactly-one-of, size) → total size.
39
+ */
40
+ export declare const validateAttachments: (raw: unknown, config?: ValidateAttachmentsConfig) => ValidateResult;
41
+ //# sourceMappingURL=attachments.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachments.d.ts","sourceRoot":"","sources":["../src/attachments.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;IACtB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,mGAAmG;IACnG,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAC3B,CAAA;AAED,MAAM,MAAM,mBAAmB,GAC3B,sBAAsB,GACtB,6BAA6B,GAC7B,oBAAoB,GACpB,qBAAqB,CAAA;AAEzB,MAAM,MAAM,yBAAyB,GAAG;IACtC,QAAQ,CAAC,UAAU,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAA;IACzC,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAA;IACjC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAA;IAC/B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAC3B,CAAA;AAED,MAAM,MAAM,UAAU,GAAG;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,eAAe,CAAC,CAAA;CAAE,CAAA;AAC9F,MAAM,MAAM,WAAW,GAAG;IACxB,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAA;IAClB,QAAQ,CAAC,IAAI,EAAE,mBAAmB,CAAA;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CACzB,CAAA;AACD,MAAM,MAAM,cAAc,GAAG,UAAU,GAAG,WAAW,CAAA;AAErD,eAAO,MAAM,mBAAmB,EAAE,WAAW,CAAC,MAAM,CAAmE,CAAA;AACvH,eAAO,MAAM,0BAA0B,QAAkB,CAAA;AACzD,eAAO,MAAM,uBAAuB,QAAmB,CAAA;AACvD,eAAO,MAAM,iBAAiB,IAAI,CAAA;AAalC;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,GAC9B,KAAK,OAAO,EACZ,SAAS,yBAAyB,KACjC,cA+FF,CAAA"}
@@ -0,0 +1,46 @@
1
+ import { Effect, Stream } from "effect";
2
+ import type { Message, SessionID } from "../session/schema";
3
+ import type { AgentEvent } from "../events";
4
+ export type SessionStartedEvent = {
5
+ readonly type: "session-started";
6
+ readonly sessionId: SessionID | string;
7
+ readonly agentName: string;
8
+ };
9
+ export type SessionMessageEvent = {
10
+ readonly type: "session-message";
11
+ readonly sessionId: SessionID | string;
12
+ readonly message: Message;
13
+ };
14
+ export type SessionIdleEvent = {
15
+ readonly type: "session-idle";
16
+ readonly sessionId: SessionID | string;
17
+ };
18
+ export type ToolExecutingEvent = {
19
+ readonly type: "tool-executing";
20
+ readonly sessionId: SessionID | string;
21
+ readonly callID: string;
22
+ readonly name: string;
23
+ readonly input: unknown;
24
+ };
25
+ export type ToolCompletedEvent = {
26
+ readonly type: "tool-completed";
27
+ readonly sessionId: SessionID | string;
28
+ readonly callID: string;
29
+ readonly name: string;
30
+ readonly output: unknown;
31
+ };
32
+ export type AgentEventBusEvent = {
33
+ readonly type: "agent-event";
34
+ readonly sessionId: SessionID | string;
35
+ readonly event: AgentEvent;
36
+ };
37
+ export type BusEvent = SessionStartedEvent | SessionMessageEvent | SessionIdleEvent | ToolExecutingEvent | ToolCompletedEvent | AgentEventBusEvent;
38
+ export type Bus = {
39
+ readonly publish: (event: BusEvent) => Effect.Effect<void>;
40
+ readonly subscribe: <K extends BusEvent["type"]>(type: K) => Stream.Stream<Extract<BusEvent, {
41
+ type: K;
42
+ }>>;
43
+ readonly subscribeAll: () => Stream.Stream<BusEvent>;
44
+ };
45
+ export declare const makeBus: () => Bus;
46
+ //# sourceMappingUR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QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAA;CACzB,CAAA;AAED,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAA;IAC5B,QAAQ,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM,CAAA;IACtC,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAA;CAC3B,CAAA;AAED,MAAM,MAAM,QAAQ,GAChB,mBAAmB,GACnB,mBAAmB,GACnB,gBAAgB,GAChB,kBAAkB,GAClB,kBAAkB,GAClB,kBAAkB,CAAA;AAEtB,MAAM,MAAM,GAAG,GAAG;IAChB,QAAQ,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,QAAQ,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IAC1D,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,QAAQ,CAAC,MAAM,CAAC,EAC7C,IAAI,EAAE,CAAC,KACJ,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE;QAAE,IAAI,EAAE,CAAC,CAAA;KAAE,CAAC,CAAC,CAAA;IAClD,QAAQ,CAAC,YAAY,EAAE,MAAM,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;CACrD,CAAA;AAED,eAAO,MAAM,OAAO,QAAO,GA4B1B,CAAA"}
@@ -0,0 +1,2 @@
1
+ export * from "./bus";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bus/index.ts"],"names":[],"mappings":"AAAA,cAAc,OAAO,CAAA"}
@@ -0,0 +1,13 @@
1
+ import { ToolFailure, type ToolSchema } from "@tinyweb_dev/agent-framework-llm";
2
+ import { Effect, Schema } from "effect";
3
+ export type ToolExecuteAsync<Params, Success> = (input: Params) => Promise<Success>;
4
+ export type ToolExecuteEffect<Params, Success> = (input: Params) => Effect.Effect<Success, ToolFailure>;
5
+ export type DefineToolConfig<P extends ToolSchema<any>, S extends ToolSchema<any>> = {
6
+ readonly name?: string;
7
+ readonly description: string;
8
+ readonly parameters: P;
9
+ readonly success?: S;
10
+ readonly execute: ToolExecuteAsync<Schema.Schema.Type<P>, Schema.Schema.Type<S>> | ToolExecuteEffect<Schema.Schema.Type<P>, Schema.Schema.Type<S>>;
11
+ };
12
+ export declare function defineTool<P extends ToolSchema<any>, S extends ToolSchema<any> = typeof Schema.Unknown>(config: DefineToolConfig<P, S>): import("@tinyweb_dev/agent-framework-llm").ExecutableTool<P, S>;
13
+ //# sourceMappingURL=define-tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"define-tool.d.ts","sourceRoot":"","sources":["../src/define-tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,WAAW,EAAE,KAAK,UAAU,EAAE,MAAM,8BAA8B,CAAA;AACjF,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAEvC,MAAM,MAAM,gBAAgB,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;AACnF,MAAM,MAAM,iBAAiB,CAAC,MAAM,EAAE,OAAO,IAAI,CAC/C,KAAK,EAAE,MAAM,KACV,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,WAAW,CAAC,CAAA;AAExC,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,UAAU,CAAC,GAAG,CAAC,IAAI;IACnF,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAA;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;IACpB,QAAQ,CAAC,OAAO,EACZ,gBAAgB,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAC9D,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;CACpE,CAAA;AAcD,wBAAgB,UAAU,CAAC,CAAC,SAAS,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,UAAU,CAAC,GAAG,CAAC,GAAG,OAAO,MAAM,CAAC,OAAO,EACrG,MAAM,EAAE,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAAC,+DAS/B"}
@@ -0,0 +1,136 @@
1
+ import type { LLMEvent } from "@tinyweb_dev/agent-framework-llm";
2
+ export type TextDeltaEvent = {
3
+ readonly type: "text-delta";
4
+ readonly id: string;
5
+ readonly text: string;
6
+ };
7
+ export type TextEndEvent = {
8
+ readonly type: "text-end";
9
+ readonly id: string;
10
+ };
11
+ export type ReasoningDeltaEvent = {
12
+ readonly type: "reasoning-delta";
13
+ readonly id: string;
14
+ readonly text: string;
15
+ };
16
+ export type ToolCallEvent = {
17
+ readonly type: "tool-call";
18
+ readonly id: string;
19
+ readonly name: string;
20
+ readonly input: unknown;
21
+ };
22
+ export type ToolResultEvent = {
23
+ readonly type: "tool-result";
24
+ readonly id: string;
25
+ readonly name: string;
26
+ readonly result: unknown;
27
+ };
28
+ export type ToolErrorEvent = {
29
+ readonly type: "tool-error";
30
+ readonly id: string;
31
+ readonly name: string;
32
+ readonly message: string;
33
+ /** Optional structured payload (e.g. tool-interrupt metadata). */
34
+ readonly metadata?: Record<string, unknown>;
35
+ };
36
+ /**
37
+ * Emitted when a tool with permission rule `"ask"` (interrupt mode) is
38
+ * intercepted before execution. Host UIs should render an approve/reject
39
+ * control and later call `agent.resolveApproval` + `agent.resume`.
40
+ */
41
+ export type ToolApprovalRequestEvent = {
42
+ readonly type: "tool-approval-request";
43
+ readonly id: string;
44
+ readonly name: string;
45
+ readonly input: unknown;
46
+ };
47
+ export type StepFinishEvent = {
48
+ readonly type: "step-finish";
49
+ readonly index: number;
50
+ readonly reason: string;
51
+ readonly usage?: unknown;
52
+ };
53
+ export type FinishEvent = {
54
+ readonly type: "finish";
55
+ readonly reason: string;
56
+ readonly usage?: unknown;
57
+ };
58
+ export type ErrorEvent = {
59
+ readonly type: "error";
60
+ readonly message: string;
61
+ readonly retryable?: boolean;
62
+ /**
63
+ * Optional structured code for client-side branching (e.g.
64
+ * `"attachment_too_large"`, `"attachment_unsupported_type"`).
65
+ * Free-form string — consumers should treat unknown codes as generic errors.
66
+ */
67
+ readonly code?: string;
68
+ };
69
+ /**
70
+ * Source of an auto-compaction (context-condense) pass.
71
+ *
72
+ * - `preflight` — the agent estimated the upcoming prompt would exceed the
73
+ * usable budget and ran `compact()` BEFORE the provider call. Cheaper and
74
+ * more controllable.
75
+ * - `overflow-retry` — the provider returned `ContextOverflowReason`; the
76
+ * agent ran `compact()` and retried the same turn once. Surfaced so UIs
77
+ * can show "context overflow — recovering…" copy distinct from a regular
78
+ * pre-flight condense.
79
+ * - `manual` — RESERVED. Not emitted yet (no manual trigger exists), but
80
+ * reserved on the discriminated union so adding a "Condense Now" button
81
+ * later doesn't break consumers' exhaustive switches.
82
+ */
83
+ export type CondenseTrigger = "preflight" | "overflow-retry" | "manual";
84
+ /**
85
+ * Emitted IMMEDIATELY before `compact()` runs. UI consumers should render a
86
+ * spinner/pill — compaction can take 2–5s on a long thread because it makes
87
+ * its own LLM call.
88
+ */
89
+ export type ContextCondenseStartEvent = {
90
+ readonly type: "context-condense-start";
91
+ readonly trigger: CondenseTrigger;
92
+ /** Estimated prompt tokens the agent would have sent without compacting. */
93
+ readonly estimatedTokens?: number;
94
+ /** The usable budget (`limits.context − reserved`) that the estimate exceeded. */
95
+ readonly budgetTokens?: number;
96
+ };
97
+ /**
98
+ * Emitted after a SUCCESSFUL compaction. Carries the summariser's output plus
99
+ * before/after token counts and (when the route exposes it) the call cost.
100
+ * This is the persistent, replay-friendly record of what happened.
101
+ */
102
+ export type ContextCondenseEvent = {
103
+ readonly type: "context-condense";
104
+ readonly trigger: CondenseTrigger;
105
+ /** Compaction summary text — already truncated if the summariser overflowed. */
106
+ readonly summary: string;
107
+ /** ID of the persisted compaction marker user message — cross-references `sessions.messages(...)`. */
108
+ readonly markerId: string;
109
+ /** Approximate input tokens BEFORE compaction (estimateTokens of the head slice). */
110
+ readonly prevTokens?: number;
111
+ /** Approximate input tokens AFTER compaction (estimateTokens of `[marker, ...tail]`). */
112
+ readonly newTokens?: number;
113
+ /** USD cost of the summariser LLM call when the route surfaces it. */
114
+ readonly cost?: number;
115
+ /** Model id used for the summariser (today: same as the main agent model). */
116
+ readonly modelId?: string;
117
+ };
118
+ /**
119
+ * Emitted when `compact()` itself errored or, on the `overflow-retry` path,
120
+ * when the post-compaction retry still overflowed (`retryExhausted: true`).
121
+ *
122
+ * Distinct from the generic `error` event so UIs can render it inline next
123
+ * to the condense spinner without tearing down the assistant turn.
124
+ */
125
+ export type ContextCondenseErrorEvent = {
126
+ readonly type: "context-condense-error";
127
+ readonly trigger: CondenseTrigger;
128
+ readonly message: string;
129
+ /** True ONLY on the second consecutive overflow — replaces the old "compaction retry exhausted" message. */
130
+ readonly retryExhausted?: boolean;
131
+ };
132
+ export type AgentEvent = TextDeltaEvent | TextEndEvent | ReasoningDeltaEvent | ToolCallEvent | ToolResultEvent | ToolErrorEvent | ToolApprovalRequestEvent | StepFinishEvent | FinishEvent | ErrorEvent | ContextCondenseStartEvent | ContextCondenseEvent | ContextCondenseErrorEvent;
133
+ /** Finish reason used when the turn stops waiting for user tool approval. */
134
+ export declare const FINISH_REASON_APPROVAL_REQUIRED: "approval-required";
135
+ export declare const fromLLMEvent: (event: LLMEvent) => AgentEvent | undefined;
136
+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GAAI,OAAO,QAAQ,KAAG,UAAU,GAAG,SAqB3D,CAAA"}
@@ -0,0 +1,253 @@
1
+ 'use strict';
2
+
3
+ var protocol = require('@tinyweb_dev/agent-framework-protocol');
4
+
5
+ // src/http-handlers.ts
6
+
7
+ // src/attachments.ts
8
+ var DEFAULT_IMAGE_MIMES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
9
+ var DEFAULT_MAX_BYTES_PER_FILE = 8 * 1024 * 1024;
10
+ var DEFAULT_MAX_BYTES_TOTAL = 16 * 1024 * 1024;
11
+ var DEFAULT_MAX_COUNT = 4;
12
+ var base64ByteLength = (b64) => {
13
+ const idx = b64.indexOf("base64,");
14
+ const body = idx >= 0 ? b64.slice(idx + "base64,".length) : b64;
15
+ const padding = body.endsWith("==") ? 2 : body.endsWith("=") ? 1 : 0;
16
+ return Math.max(0, Math.floor(body.length * 3 / 4) - padding);
17
+ };
18
+ var isHttpOrFile = (s) => s.startsWith("http://") || s.startsWith("https://") || s.startsWith("file://") || s.startsWith("data:");
19
+ var validateAttachments = (raw, config) => {
20
+ if (raw === void 0 || raw === null) return { ok: true, value: [] };
21
+ if (!Array.isArray(raw))
22
+ return { ok: false, code: "attachment_invalid", message: "attachments must be an array" };
23
+ const imageMimes = config?.imageMimes ?? DEFAULT_IMAGE_MIMES;
24
+ const maxBytesPerFile = config?.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;
25
+ const maxBytesTotal = config?.maxBytesTotal ?? DEFAULT_MAX_BYTES_TOTAL;
26
+ const maxCount = config?.maxCount ?? DEFAULT_MAX_COUNT;
27
+ if (raw.length > maxCount)
28
+ return {
29
+ ok: false,
30
+ code: "attachment_too_many",
31
+ message: `Too many attachments (max ${maxCount}, received ${raw.length})`
32
+ };
33
+ const out = [];
34
+ let totalBytes = 0;
35
+ for (let i = 0; i < raw.length; i++) {
36
+ const item = raw[i];
37
+ if (!item || typeof item !== "object")
38
+ return { ok: false, code: "attachment_invalid", message: `attachments[${i}] must be an object` };
39
+ const obj = item;
40
+ if (obj.type !== "image")
41
+ return {
42
+ ok: false,
43
+ code: "attachment_unsupported_type",
44
+ message: `attachments[${i}].type must be "image" (received ${String(obj.type)})`
45
+ };
46
+ const mediaType = obj.mediaType;
47
+ if (typeof mediaType !== "string" || mediaType.length === 0)
48
+ return { ok: false, code: "attachment_invalid", message: `attachments[${i}].mediaType is required` };
49
+ if (!imageMimes.has(mediaType))
50
+ return {
51
+ ok: false,
52
+ code: "attachment_unsupported_type",
53
+ message: `Unsupported attachment type: ${mediaType}`
54
+ };
55
+ const data = typeof obj.data === "string" ? obj.data : void 0;
56
+ const url = typeof obj.url === "string" ? obj.url : void 0;
57
+ if (!data && !url)
58
+ return {
59
+ ok: false,
60
+ code: "attachment_invalid",
61
+ message: `attachments[${i}] requires either "data" (base64) or "url"`
62
+ };
63
+ if (data && url)
64
+ return {
65
+ ok: false,
66
+ code: "attachment_invalid",
67
+ message: `attachments[${i}] must not set both "data" and "url"`
68
+ };
69
+ if (url && !isHttpOrFile(url))
70
+ return {
71
+ ok: false,
72
+ code: "attachment_invalid",
73
+ message: `attachments[${i}].url must be http(s)/file/data scheme`
74
+ };
75
+ if (data) {
76
+ const bytes = base64ByteLength(data);
77
+ if (bytes === 0)
78
+ return { ok: false, code: "attachment_invalid", message: `attachments[${i}].data is empty or malformed` };
79
+ if (bytes > maxBytesPerFile)
80
+ return {
81
+ ok: false,
82
+ code: "attachment_too_large",
83
+ message: `Attachment ${obj.filename ?? `#${i}`} exceeds ${maxBytesPerFile} bytes (got ${bytes})`
84
+ };
85
+ totalBytes += bytes;
86
+ if (totalBytes > maxBytesTotal)
87
+ return {
88
+ ok: false,
89
+ code: "attachment_too_large",
90
+ message: `Total attachment bytes exceed ${maxBytesTotal} (got ${totalBytes})`
91
+ };
92
+ }
93
+ out.push({
94
+ type: "image",
95
+ mediaType,
96
+ data,
97
+ url,
98
+ filename: typeof obj.filename === "string" ? obj.filename : void 0
99
+ });
100
+ }
101
+ return { ok: true, value: out };
102
+ };
103
+
104
+ // src/http-handlers.ts
105
+ var isReadableLike = (body) => typeof body === "object" && body !== null && typeof body.on === "function";
106
+ var readBody = async (req) => {
107
+ if (req.body !== void 0 && req.body !== null && typeof req.body === "object" && !isReadableLike(req.body)) {
108
+ return req.body;
109
+ }
110
+ if (typeof req.on !== "function") return void 0;
111
+ const chunks = [];
112
+ await new Promise((resolve, reject) => {
113
+ const onData = (...args) => chunks.push(Buffer.from(args[0]));
114
+ const onEnd = () => resolve();
115
+ const onErr = (...args) => reject(args[0]);
116
+ req.on("data", onData);
117
+ req.on("end", onEnd);
118
+ req.on("error", onErr);
119
+ });
120
+ const raw = Buffer.concat(chunks).toString("utf8");
121
+ if (raw.length === 0) return void 0;
122
+ return JSON.parse(raw);
123
+ };
124
+ var parseUrl = (req) => {
125
+ const host = req.headers?.["host"] ?? "localhost";
126
+ return new URL(req.url ?? "/", `http://${host}`);
127
+ };
128
+ var param = (req, key, url, index) => {
129
+ if (req.params && typeof req.params[key] === "string") return req.params[key];
130
+ const segs = url.pathname.split("/").filter(Boolean);
131
+ return segs[index];
132
+ };
133
+ var sendJSON = (res, status, body) => {
134
+ res.statusCode = status;
135
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
136
+ res.end(JSON.stringify(body));
137
+ };
138
+ var sendError = (res, status, message) => sendJSON(res, status, { error: message });
139
+ var TINYWEB_HEADERS = {
140
+ "Content-Type": "text/event-stream",
141
+ "Cache-Control": "no-cache, no-transform",
142
+ Connection: "keep-alive"
143
+ };
144
+ var makeHTTPHandlers = (config) => {
145
+ const defaultFormat = config.defaultFormat ?? "tinyweb";
146
+ const ownerOf = async (req) => {
147
+ if (!config.authorize) return void 0;
148
+ const result = await config.authorize(req);
149
+ return result?.ownerId;
150
+ };
151
+ const listSessions = async (req, res) => {
152
+ const url = parseUrl(req);
153
+ const limit = url.searchParams.get("limit");
154
+ const cursor = url.searchParams.get("cursor") ?? void 0;
155
+ const ownerOverride = url.searchParams.get("ownerId") ?? void 0;
156
+ const owner = await ownerOf(req) ?? ownerOverride;
157
+ const result = await config.api.list({
158
+ limit: limit ? Number(limit) : void 0,
159
+ cursor,
160
+ ownerId: owner
161
+ });
162
+ sendJSON(res, 200, result);
163
+ };
164
+ const createSession = async (req, res) => {
165
+ const body = await readBody(req) ?? {};
166
+ const ownerHook = await ownerOf(req);
167
+ const session = await config.api.create({
168
+ title: body.title,
169
+ metadata: body.metadata,
170
+ ownerId: ownerHook ?? body.ownerId
171
+ });
172
+ sendJSON(res, 201, session);
173
+ };
174
+ const getSession = async (req, res) => {
175
+ const url = parseUrl(req);
176
+ const id = param(req, "id", url, 1);
177
+ if (!id) return sendError(res, 400, "missing session id");
178
+ const session = await config.api.get(id);
179
+ if (!session) return sendError(res, 404, "session not found");
180
+ sendJSON(res, 200, session);
181
+ };
182
+ const updateSession = async (req, res) => {
183
+ const url = parseUrl(req);
184
+ const id = param(req, "id", url, 1);
185
+ if (!id) return sendError(res, 400, "missing session id");
186
+ const body = await readBody(req) ?? {};
187
+ const updated = await config.api.patch(id, { title: body.title, metadata: body.metadata });
188
+ if (!updated) return sendError(res, 404, "session not found");
189
+ sendJSON(res, 200, updated);
190
+ };
191
+ const deleteSession = async (req, res) => {
192
+ const url = parseUrl(req);
193
+ const id = param(req, "id", url, 1);
194
+ if (!id) return sendError(res, 400, "missing session id");
195
+ await config.api.delete(id);
196
+ sendJSON(res, 200, { ok: true });
197
+ };
198
+ const listMessages = async (req, res) => {
199
+ const url = parseUrl(req);
200
+ const id = param(req, "id", url, 1);
201
+ if (!id) return sendError(res, 400, "missing session id");
202
+ const limit = url.searchParams.get("limit");
203
+ const before = url.searchParams.get("before") ?? void 0;
204
+ const result = await config.api.messages(id, {
205
+ limit: limit ? Number(limit) : void 0,
206
+ before
207
+ });
208
+ sendJSON(res, 200, result);
209
+ };
210
+ const deleteMessage = async (req, res) => {
211
+ const url = parseUrl(req);
212
+ const id = param(req, "id", url, 1);
213
+ const mid = param(req, "mid", url, 3);
214
+ if (!id || !mid) return sendError(res, 400, "missing ids");
215
+ await config.api.deleteMessage(id, mid);
216
+ sendJSON(res, 200, { ok: true });
217
+ };
218
+ const chat = async (req, res) => {
219
+ const url = parseUrl(req);
220
+ const id = param(req, "id", url, 1);
221
+ if (!id) return sendError(res, 400, "missing session id");
222
+ const body = await readBody(req) ?? {};
223
+ const prompt = body.prompt?.trim() ?? "";
224
+ const validation = validateAttachments(body.attachments, config.attachments);
225
+ if (!validation.ok) return sendJSON(res, 400, { error: validation.message, code: validation.code });
226
+ const attachments = validation.value;
227
+ if (!prompt && attachments.length === 0) return sendError(res, 400, "missing prompt");
228
+ const format = body.format ?? defaultFormat;
229
+ const headers = format === "ai-sdk" ? protocol.AI_SDK_HEADERS : TINYWEB_HEADERS;
230
+ for (const [name, value] of Object.entries(headers)) res.setHeader(name, value);
231
+ if (typeof res.flushHeaders === "function") res.flushHeaders();
232
+ for await (const event of config.run({ prompt, sessionId: id, attachments })) {
233
+ const proto = event;
234
+ const line = format === "ai-sdk" ? protocol.toAISDKDataStream(proto) : protocol.encodeSSE(proto);
235
+ if (line.length > 0) res.write(line);
236
+ }
237
+ res.end();
238
+ };
239
+ return {
240
+ listSessions,
241
+ createSession,
242
+ getSession,
243
+ updateSession,
244
+ deleteSession,
245
+ listMessages,
246
+ deleteMessage,
247
+ chat
248
+ };
249
+ };
250
+
251
+ exports.makeHTTPHandlers = makeHTTPHandlers;
252
+ //# sourceMappingURL=http-handlers.cjs.map
253
+ //# sourceMappingURL=http-handlers.cjs.map