@tinyweb_dev/agent-framework-agent 0.2.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 -470
  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 -186
  116. package/src/http-handlers.ts +0 -251
  117. package/src/index.ts +0 -128
  118. package/src/loop-guard.ts +0 -99
  119. package/src/mcp/client.ts +0 -129
  120. package/src/permission.ts +0 -114
  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 -46
  132. package/src/session/compaction.ts +0 -160
  133. package/src/session/index.ts +0 -18
  134. package/src/session/memory.ts +0 -169
  135. package/src/session/overflow.ts +0 -50
  136. package/src/session/postgres.ts +0 -355
  137. package/src/session/processor.ts +0 -865
  138. package/src/session/replay.ts +0 -151
  139. package/src/session/schema.ts +0 -156
  140. package/src/session/sqlite.ts +0 -309
  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
@@ -1,90 +0,0 @@
1
- /**
2
- * Framework-owned system-prompt section composer.
3
- *
4
- * Pattern: Roo Code extension / OpenCode build the final system prompt by
5
- * concatenating named, `====`-divided sections. Each section has a single
6
- * responsibility (TOOL USE, GUIDELINES, RESPONSE STYLE) and is authored in
7
- * the framework — application developers only contribute their ROLE / domain
8
- * block.
9
- *
10
- * Public flow (consumed by `defineAgent` in [`agent.ts`](../agent.ts:1)):
11
- *
12
- * const finalPrompt = composeSystemPrompt({
13
- * role: userProvidedRolePrompt,
14
- * sections: { toolUseGuidelines: { maxCallsPerTurn: 3 } },
15
- * })
16
- *
17
- * Order is fixed and intentional:
18
- * 1. ROLE ← user-authored persona/domain prompt
19
- * 2. TOOL USE ← framework-owned (how the tool API works)
20
- * 3. TOOL USE GUIDE. ← framework-owned (when to pick which tool)
21
- * 4. OBJECTIVE ← framework-owned (proactive helpfulness mindset)
22
- * 5. RESPONSE STYLE ← framework-owned (no-repeat-card etc.)
23
- *
24
- * Each section can be individually disabled (`enabled: false`) for advanced
25
- * consumers who want full control. By default all framework sections are on.
26
- */
27
-
28
- import { toolUseSection } from "./tool-use"
29
- import { toolUseGuidelinesSection, type ToolUseGuidelinesConfig } from "./tool-use-guidelines"
30
- import { objectiveSection, type ObjectiveConfig, type ObjectiveKind } from "./objective"
31
- import { responseStyleSection, type ResponseStyleConfig, type ResponseStyleKind } from "./response-style"
32
-
33
- export { toolUseSection, toolUseGuidelinesSection, objectiveSection, responseStyleSection }
34
- export type { ToolUseGuidelinesConfig, ObjectiveConfig, ObjectiveKind, ResponseStyleConfig, ResponseStyleKind }
35
-
36
- export type SectionToggle<T> = boolean | T
37
-
38
- export type PromptSectionsConfig = {
39
- /** TOOL USE block (how tool calls work). Default: enabled. */
40
- readonly toolUse?: boolean
41
- /** TOOL USE GUIDELINES (anti-loop, intent-matching). Default: enabled. */
42
- readonly toolUseGuidelines?: SectionToggle<ToolUseGuidelinesConfig>
43
- /** OBJECTIVE block (proactive helpfulness, no-bail mindset). Default: enabled with kind="chat". */
44
- readonly objective?: SectionToggle<ObjectiveConfig>
45
- /** RESPONSE STYLE block. Default: enabled with kind="chat". */
46
- readonly responseStyle?: SectionToggle<ResponseStyleConfig>
47
- }
48
-
49
- const resolveToggle = <T>(toggle: SectionToggle<T> | undefined, defaults: T): T | undefined => {
50
- if (toggle === false) return undefined
51
- if (toggle === undefined || toggle === true) return defaults
52
- return toggle
53
- }
54
-
55
- export type ComposeSystemPromptInput = {
56
- /** User-authored ROLE / domain prompt. Inserted first, verbatim. */
57
- readonly role?: string
58
- /** Per-section toggles. Omit for default framework behavior. */
59
- readonly sections?: PromptSectionsConfig
60
- }
61
-
62
- export const composeSystemPrompt = (input: ComposeSystemPromptInput): string => {
63
- const parts: string[] = []
64
- const role = input.role?.trim()
65
- if (role && role.length > 0) parts.push(role)
66
-
67
- const sections = input.sections ?? {}
68
-
69
- if (sections.toolUse !== false) {
70
- parts.push(toolUseSection())
71
- }
72
-
73
- const guidelinesCfg = resolveToggle<ToolUseGuidelinesConfig>(sections.toolUseGuidelines, {})
74
- if (guidelinesCfg) {
75
- parts.push(toolUseGuidelinesSection(guidelinesCfg))
76
- }
77
-
78
- const objectiveCfg = resolveToggle<ObjectiveConfig>(sections.objective, {})
79
- if (objectiveCfg) {
80
- parts.push(objectiveSection(objectiveCfg))
81
- }
82
-
83
- const styleCfg = resolveToggle<ResponseStyleConfig>(sections.responseStyle, {})
84
- if (styleCfg) {
85
- const rendered = responseStyleSection(styleCfg)
86
- if (rendered.length > 0) parts.push(rendered)
87
- }
88
-
89
- return parts.join("\n\n")
90
- }
@@ -1,104 +0,0 @@
1
- /**
2
- * OBJECTIVE section — framework-owned block that defines HOW the agent
3
- * approaches each user turn. Counter-balances TOOL USE GUIDELINES (which
4
- * is anti-loop / restrictive) with a proactive mindset:
5
- *
6
- * "Try to help. Don't give up early. If you don't know, search."
7
- *
8
- * Pattern adapted from Roo Code extension:
9
- * roo-code-extension/src/core/prompts/sections/objective.ts
10
- *
11
- * Roo's original is tuned for autonomous code agents (multi-step task
12
- * completion with `attempt_completion`). This version is rewritten for
13
- * conversational chat assistants — the primary failure mode we see is
14
- * not over-tool-calling, but the opposite: the model bailing with
15
- * "I don't have updated info" when a search tool is right there.
16
- *
17
- * Two modes:
18
- * - "chat" (default) — proactive helpfulness, search when knowledge is
19
- * stale or unknown, ask only when truly ambiguous.
20
- * - "task" — Roo-style iterative task completion (kept for parity, useful
21
- * for pilot/automation agents that drive devices or codebases).
22
- */
23
-
24
- export type ObjectiveKind = "chat" | "task"
25
-
26
- export type ObjectiveConfig = {
27
- /** Default "chat". Use "task" for autonomous multi-step agents. */
28
- readonly kind?: ObjectiveKind
29
- }
30
-
31
- const chatObjective = (): string =>
32
- [
33
- "====",
34
- "",
35
- "OBJECTIVE",
36
- "",
37
- "Your job is to be GENUINELY HELPFUL to the user. Treat every question as",
38
- "something you want to answer well — not something to deflect.",
39
- "",
40
- "1. UNDERSTAND the user's actual intent before responding. Re-read the last",
41
- " few turns of conversation; questions like \"giám đốc là ai?\" or \"thì sao?\"",
42
- " only make sense in context of the prior topic. Resolve pronouns and",
43
- " topic references from history before deciding how to answer.",
44
- "",
45
- "2. DECIDE: can you answer well from your own knowledge?",
46
- " - YES → answer directly, concisely, in the user's language.",
47
- " - NO, or the answer needs FRESH data (people, prices, current events,",
48
- " specific companies, recent news) → use the most relevant tool to find",
49
- " out. Do NOT bail with \"I don't have updated info\" when a search tool",
50
- " is available. Search first, then answer with what you found.",
51
- "",
52
- "3. BE PROACTIVE, NOT LAZY:",
53
- " - If the user asks about a specific entity (a company, person, product)",
54
- " and you are not confident your knowledge is current, search.",
55
- " - If a search returns partial info, share what you found and explicitly",
56
- " state what is still unknown — don't pretend nothing was found.",
57
- " - Follow-up questions inherit the topic of the previous turn. \"giám đốc",
58
- " là ai?\" right after a question about company X means \"who is X's CEO?\"",
59
- " — search for that, don't reply \"I don't know which company\".",
60
- "",
61
- "4. ASK ONLY WHEN TRULY AMBIGUOUS. A clarifying question is appropriate when",
62
- " the request is missing information you cannot infer (e.g. user says",
63
- " \"book a flight\" with no destination). It is NOT appropriate as an escape",
64
- " hatch when you simply didn't try to find the answer.",
65
- "",
66
- "5. RESPECT THE TOOL CAPS in TOOL USE GUIDELINES — but use the budget you",
67
- " have. If you have 3 tool calls allowed and you've used 0, and the user's",
68
- " question clearly needs a search, USE one. The cap is a ceiling, not a",
69
- " target to avoid.",
70
- "",
71
- "6. END EACH TURN with a complete, useful answer. Don't stop mid-thought,",
72
- " don't promise to \"check later\", don't return only a tool result without",
73
- " summarizing it in plain language for the user.",
74
- ].join("\n")
75
-
76
- const taskObjective = (): string =>
77
- [
78
- "====",
79
- "",
80
- "OBJECTIVE",
81
- "",
82
- "You accomplish a given task iteratively, breaking it down into clear steps",
83
- "and working through them methodically.",
84
- "",
85
- "1. Analyze the user's task and set clear, achievable goals. Prioritize them",
86
- " in a logical order.",
87
- "2. Work through goals sequentially, using tools one at a time. Each tool",
88
- " call should be informed by the previous result.",
89
- "3. Before calling a tool, analyze the context. Determine which tool is most",
90
- " relevant and whether all required parameters are present or inferable.",
91
- " If a required parameter is missing and cannot be inferred, ask the user",
92
- " instead of guessing.",
93
- "4. When the task is complete, present the final result clearly. Do not",
94
- " continue with extra tool calls \"to be safe\".",
95
- "5. If the user provides feedback, use it to improve and try again — but do",
96
- " not engage in pointless back-and-forth. Don't end responses with open",
97
- " offers for further assistance.",
98
- ].join("\n")
99
-
100
- export const objectiveSection = (config: ObjectiveConfig = {}): string => {
101
- const kind = config.kind ?? "chat"
102
- if (kind === "task") return taskObjective()
103
- return chatObjective()
104
- }
@@ -1,59 +0,0 @@
1
- /**
2
- * RESPONSE STYLE section — framework-owned block that governs HOW the
3
- * assistant phrases its final answer after a tool call completes.
4
- *
5
- * Default flavor: chat-style. The host UI already renders tool result cards
6
- * with structured data, so the model should NOT repeat numbers/names that
7
- * are already visible — it should add at most one line of commentary.
8
- *
9
- * The full text is suppressed when `kind === "off"`. When `kind === "verbose"`
10
- * we drop the no-repeat constraint (useful for code-agent / pilot flows where
11
- * the model needs to narrate every step).
12
- */
13
- export type ResponseStyleKind = "chat" | "verbose" | "off"
14
-
15
- export type ResponseStyleConfig = {
16
- /** Default: "chat". */
17
- readonly kind?: ResponseStyleKind
18
- }
19
-
20
- const chatStyle = (): string =>
21
- [
22
- "====",
23
- "",
24
- "RESPONSE STYLE",
25
- "",
26
- "Your replies are rendered next to a tool-result card that already shows",
27
- "structured data to the user. Therefore:",
28
- "",
29
- "- Do NOT repeat numbers, names, dates, units, codes, or any field value",
30
- " that is already visible on the tool-result card.",
31
- "- After a tool call, write AT MOST one short sentence of commentary,",
32
- " insight, warning, or follow-up suggestion — something the card does not",
33
- " already say.",
34
- "- If you have nothing useful to add, reply with a single short ack such",
35
- " as \"Here you go.\" / \"Done.\" / \"That's the latest.\" — but never restate",
36
- " the card contents.",
37
- "- If the user asked multiple things in one message and you called several",
38
- " tools, write ONE combined sentence with brief observations — do not list",
39
- " the numbers again.",
40
- "- Match the user's language. Keep replies short and direct.",
41
- ].join("\n")
42
-
43
- const verboseStyle = (): string =>
44
- [
45
- "====",
46
- "",
47
- "RESPONSE STYLE",
48
- "",
49
- "Narrate your reasoning and actions so the user can follow along. Summarise",
50
- "tool results in your own words. Keep paragraphs short. Match the user's",
51
- "language. Do not pad with filler.",
52
- ].join("\n")
53
-
54
- export const responseStyleSection = (config: ResponseStyleConfig = {}): string => {
55
- const kind = config.kind ?? "chat"
56
- if (kind === "off") return ""
57
- if (kind === "verbose") return verboseStyle()
58
- return chatStyle()
59
- }
@@ -1,57 +0,0 @@
1
- /**
2
- * TOOL USE GUIDELINES section — framework-owned block that constrains HOW
3
- * the model should select and chain tools. Designed to prevent the two most
4
- * common failure modes we see in production:
5
- *
6
- * 1. Keyword-trigger looping — calling weather() because the user said
7
- * "city name", even when the actual intent is travel recommendations.
8
- * 2. Same-args retry storms — the model re-invoking a tool with identical
9
- * arguments after a failure (or "to make sure").
10
- *
11
- * Pattern adapted from opencode and Roo Code extension:
12
- * roo-code-extension/src/core/prompts/sections/tool-use-guidelines.ts
13
- *
14
- * The configurable cap (`maxCallsPerTurn`) lets consumers tune aggressiveness
15
- * — pilot/code-agent flows often want 20+, chat assistants want 3.
16
- */
17
- export type ToolUseGuidelinesConfig = {
18
- /** Max distinct tool calls per turn. Default 3 — tuned for chat assistants. */
19
- readonly maxCallsPerTurn?: number
20
- }
21
-
22
- const DEFAULT_MAX_CALLS_PER_TURN = 3
23
-
24
- export const toolUseGuidelinesSection = (config: ToolUseGuidelinesConfig = {}): string => {
25
- const maxCalls = config.maxCallsPerTurn ?? DEFAULT_MAX_CALLS_PER_TURN
26
- return [
27
- "====",
28
- "",
29
- "TOOL USE GUIDELINES",
30
- "",
31
- "1. READ the user's intent before picking a tool. Do NOT pick a tool just",
32
- " because a keyword in the message matches the tool name. Example: if the",
33
- " user asks for travel recommendations about a city, that does NOT mean",
34
- " you should call a weather tool — pick the search/recommendation tool.",
35
- "",
36
- "2. Prefer answering directly when the question is conversational, opinion-",
37
- " based, or covered by your general knowledge. Tools exist for fresh,",
38
- " external, or computed data — not for restating things you already know.",
39
- "",
40
- "3. If multiple tools could plausibly fit, pick the most specific one. If",
41
- " you are not confident, answer directly instead of guessing a tool.",
42
- "",
43
- "4. ANTI-LOOP RULES (strict):",
44
- " - Do NOT call the same tool twice with identical arguments in one turn.",
45
- " - If a tool returns an error, do NOT retry it. Briefly tell the user",
46
- " what failed and stop.",
47
- ` - Hard cap: at most ${maxCalls} tool call(s) per turn. After reaching the`,
48
- " cap you MUST stop calling tools and answer with whatever data you",
49
- " already collected.",
50
- " - Once a tool has returned enough data to answer the user, STOP. Do not",
51
- " call additional tools \"to be safe\" or to corroborate.",
52
- "",
53
- "5. Each tool call must be informed by the previous result. Do not plan a",
54
- " chain of calls up front and execute it blindly — read each result and",
55
- " decide whether the next call is still needed.",
56
- ].join("\n")
57
- }
@@ -1,27 +0,0 @@
1
- /**
2
- * TOOL USE section — framework-owned block that explains the general
3
- * tool-calling contract to the model.
4
- *
5
- * Pattern adapted from opencode and Roo Code extension:
6
- * roo-code-extension/src/core/prompts/sections/tool-use.ts
7
- *
8
- * This block stays generic. Per-tool descriptions come from the tool registry
9
- * itself (LLM provider-native tool spec) and the consumer agent's ROLE block.
10
- */
11
- export const toolUseSection = (): string =>
12
- [
13
- "====",
14
- "",
15
- "TOOL USE",
16
- "",
17
- "You have access to a set of tools provided by the host application. Tools are",
18
- "invoked through the provider-native function-calling mechanism — you do NOT",
19
- "write tool calls as text, JSON, or XML inside your assistant content.",
20
- "",
21
- "- Each tool call must specify a registered tool name and arguments matching",
22
- " that tool's parameter schema.",
23
- "- Tool results are returned as a separate `tool` message in the conversation",
24
- " history. Read the result before deciding the next action.",
25
- "- You may call multiple tools across a single turn when it genuinely helps,",
26
- " but every call must be justified by the user's intent.",
27
- ].join("\n")
package/src/runtime.ts DELETED
@@ -1,22 +0,0 @@
1
- import { LLMClient, RequestExecutor } from "@tinyweb-agent-framework/llm"
2
- import { Layer, ManagedRuntime } from "effect"
3
-
4
- const mainLayer = LLMClient.layer.pipe(Layer.provide(RequestExecutor.defaultLayer))
5
-
6
- export type AgentRuntime = ManagedRuntime.ManagedRuntime<typeof LLMClient.Service, never>
7
-
8
- let cached: AgentRuntime | undefined
9
-
10
- export const createRuntime = (): AgentRuntime => ManagedRuntime.make(mainLayer)
11
-
12
- export const defaultRuntime = (): AgentRuntime => {
13
- if (cached) return cached
14
- cached = createRuntime()
15
- return cached
16
- }
17
-
18
- export const disposeDefaultRuntime = async () => {
19
- if (!cached) return
20
- await cached.dispose()
21
- cached = undefined
22
- }
@@ -1,46 +0,0 @@
1
- import { Effect } from "effect"
2
- import type { Session, CreateSessionInput, Message, MessageID, SessionID } from "./schema"
3
-
4
- export type GetMessagesOpts = {
5
- readonly limit?: number
6
- readonly before?: MessageID
7
- }
8
-
9
- export type ListSessionsOpts = {
10
- readonly limit?: number
11
- /** Opaque cursor returned by previous call's `nextCursor`. */
12
- readonly cursor?: string
13
- readonly agentName?: string
14
- readonly ownerId?: string
15
- }
16
-
17
- export type ListSessionsResult = {
18
- readonly items: ReadonlyArray<Session.Info>
19
- readonly nextCursor?: string
20
- }
21
-
22
- export type SessionPatch = {
23
- readonly title?: string
24
- readonly metadata?: Record<string, unknown>
25
- }
26
-
27
- export type SessionStore = {
28
- createSession(input: CreateSessionInput): Effect.Effect<Session.Info>
29
- getSession(id: SessionID | string): Effect.Effect<Session.Info | undefined>
30
- upsertSession(input: CreateSessionInput & { id?: SessionID | string }): Effect.Effect<Session.Info>
31
- listSessions(opts?: ListSessionsOpts): Effect.Effect<ListSessionsResult>
32
- updateSession(id: SessionID | string, patch: SessionPatch): Effect.Effect<Session.Info | undefined>
33
- appendMessage(sessionId: SessionID | string, msg: Message): Effect.Effect<void>
34
- getMessages(sessionId: SessionID | string, opts?: GetMessagesOpts): Effect.Effect<Message[]>
35
- deleteMessage(sessionId: SessionID | string, messageId: MessageID | string): Effect.Effect<void>
36
- deleteSession(id: SessionID | string): Effect.Effect<void>
37
- /**
38
- * Optional in-place message update (used by tool-approval resolve/resume).
39
- * Stores that omit this fall back to deleteMessage + appendMessage.
40
- */
41
- updateMessage?(
42
- sessionId: SessionID | string,
43
- messageId: MessageID | string,
44
- msg: Message,
45
- ): Effect.Effect<void>
46
- }
@@ -1,160 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/opencode/src/session/compaction.ts
2
- //
3
- // Auto-compaction. Replaces a leading slice of the conversation with a
4
- // summarisation marker so subsequent turns replay only [marker, ...tail].
5
- // Critically we NEVER delete/recreate the session — the sessionId, owner and
6
- // metadata stay stable; only the message log is appended to.
7
- import { LLM, LLMClient, type ModelRef } from "@tinyweb-agent-framework/llm"
8
- import { Effect } from "effect"
9
- import type { SessionStore } from "./adapter"
10
- import { estimateTokens } from "./overflow"
11
- import {
12
- findCompactionPart,
13
- makeCompactionMessage,
14
- type Message,
15
- type MessageID,
16
- type SessionID,
17
- type TextPart,
18
- } from "./schema"
19
-
20
- const SUMMARY_PROMPT = `You are a conversation summarizer. Summarize the entire conversation below into a concise factual summary (1-3 paragraphs) that preserves: user intent, key facts established, decisions made, and outstanding tasks. Do not add commentary.`
21
-
22
- const SUMMARY_FALLBACK_MAX_CHARS = 200_000
23
-
24
- const partText = (part: unknown): string => {
25
- const tagged = part as { type?: string; text?: string; summary?: string }
26
- if (tagged.type === "text") return tagged.text ?? ""
27
- if (tagged.type === "reasoning") return tagged.text ?? ""
28
- if (tagged.type === "compaction") return `[previous summary] ${tagged.summary ?? ""}`
29
- return ""
30
- }
31
-
32
- const messageToWireText = (msg: Message): string => {
33
- const role = msg.role.toUpperCase()
34
- const text = msg.parts
35
- .map((p) => partText(p))
36
- .filter((s) => s.length > 0)
37
- .join("\n")
38
- return `[${role}] ${text}`
39
- }
40
-
41
- /**
42
- * Trim transcript to fit inside the summariser's own context window. Mirrors
43
- * opencode's `truncateToolOutput` pattern — when even the summariser would
44
- * overflow, prefer the head + tail of each message.
45
- */
46
- const truncateForSummary = (transcript: string, max: number): string => {
47
- if (transcript.length <= max) return transcript
48
- const half = Math.floor(max / 2) - 64
49
- return `${transcript.slice(0, half)}\n\n[... ${transcript.length - max} chars elided ...]\n\n${transcript.slice(-half)}`
50
- }
51
-
52
- export type CompactInput = {
53
- readonly sessionId: SessionID | string
54
- readonly store: SessionStore
55
- readonly model: ModelRef
56
- /** Number of trailing turns to keep verbatim. Default 4. */
57
- readonly keepRecent?: number
58
- /** True when triggered by a ContextOverflowReason from the previous turn. */
59
- readonly overflow?: boolean
60
- }
61
-
62
- export type CompactResult = {
63
- readonly compacted: boolean
64
- readonly summary?: string
65
- readonly markerId?: MessageID
66
- readonly tailStartId?: MessageID
67
- /** Approximate prompt tokens BEFORE compaction (estimateTokens of the head slice). */
68
- readonly prevTokens?: number
69
- /** Approximate prompt tokens AFTER compaction (`[marker, ...tail]`). */
70
- readonly newTokens?: number
71
- /** USD cost of the summariser call when the route surfaces it. */
72
- readonly cost?: number
73
- /** Model id used for the summarisation call. Today: same as the main agent. */
74
- readonly modelId?: string
75
- }
76
-
77
- /**
78
- * Run an auto-compaction pass. Appends a marker user message that summarises
79
- * the leading slice of history; replay logic in `replay.ts` will then emit
80
- * only `[marker, ...tail]` for subsequent LLM calls.
81
- *
82
- * Idempotent: if the most recent compaction marker has nothing prior to
83
- * summarise we no-op.
84
- */
85
- export const compact = (
86
- input: CompactInput,
87
- ): Effect.Effect<CompactResult, unknown, typeof LLMClient.Service> =>
88
- Effect.gen(function* () {
89
- const keepRecent = input.keepRecent ?? 4
90
- const all = yield* input.store.getMessages(input.sessionId)
91
- if (all.length <= keepRecent + 1) return { compacted: false } satisfies CompactResult
92
-
93
- // Find the last existing marker so we don't re-summarise already-summarised history.
94
- const lastMarkerIdx = (() => {
95
- for (let i = all.length - 1; i >= 0; i--) {
96
- if (findCompactionPart(all[i]!)) return i
97
- }
98
- return -1
99
- })()
100
-
101
- const head = all.slice(lastMarkerIdx + 1, Math.max(lastMarkerIdx + 1, all.length - keepRecent))
102
- if (head.length === 0) return { compacted: false } satisfies CompactResult
103
-
104
- const tail = all.slice(all.length - keepRecent)
105
- const tailStartId = tail[0]?.id
106
-
107
- const transcript = truncateForSummary(
108
- head.map(messageToWireText).join("\n\n"),
109
- SUMMARY_FALLBACK_MAX_CHARS,
110
- )
111
- const request = LLM.request({
112
- model: input.model,
113
- system: SUMMARY_PROMPT,
114
- messages: [LLM.user(`Conversation transcript to summarize:\n\n${transcript}`)],
115
- })
116
- const response = yield* LLMClient.generate(request)
117
- const summary = response.text.trim().length > 0 ? response.text : extractFallbackSummary(head)
118
-
119
- const marker = makeCompactionMessage({
120
- summary,
121
- tailStartId,
122
- auto: true,
123
- overflow: input.overflow ?? false,
124
- })
125
- yield* input.store.appendMessage(input.sessionId, marker)
126
-
127
- // Token accounting for the UI affordance. `prevTokens` is the size of the
128
- // slice we replaced; `newTokens` is the resulting view (marker + tail).
129
- // We deliberately use `estimateTokens` (cheap, provider-agnostic) rather
130
- // than the provider's usage object — providers don't agree on what counts.
131
- const prevTokens = estimateTokens(head)
132
- const newTokens = estimateTokens([marker, ...tail])
133
-
134
- // Cost / model id are best-effort: not every route fills `response.usage.cost`
135
- // and we never want a missing field to abort the compaction.
136
- const usage = response.usage as { cost?: number } | undefined
137
- const cost = typeof usage?.cost === "number" ? usage.cost : undefined
138
-
139
- return {
140
- compacted: true,
141
- summary,
142
- markerId: marker.id,
143
- tailStartId,
144
- prevTokens,
145
- newTokens,
146
- cost,
147
- modelId: input.model.id,
148
- } satisfies CompactResult
149
- })
150
-
151
- /** Best-effort offline summary when the summariser returns empty text. */
152
- const extractFallbackSummary = (msgs: ReadonlyArray<Message>): string => {
153
- const lines = msgs.flatMap((m) =>
154
- m.parts
155
- .map((p) => ((p as TextPart).type === "text" ? (p as TextPart).text : ""))
156
- .filter((s) => s.length > 0),
157
- )
158
- const head = lines.slice(0, 4).join(" ")
159
- return `Compacted ${msgs.length} prior message(s). ${head.slice(0, 400)}`
160
- }
@@ -1,18 +0,0 @@
1
- export * from "./schema"
2
- export * from "./adapter"
3
- export { makeMemoryStore } from "./memory"
4
- // NOTE: `makeSqliteStore` / `makePostgresStore` are NOT re-exported here to
5
- // avoid pulling `bun:sqlite` / `postgres` into bundlers (Next.js webpack, etc.)
6
- // when the consumer doesn't actually use them. Import them directly:
7
- // import { makeSqliteStore } from "@tinyweb-agent-framework/agent/session/sqlite"
8
- // import { makePostgresStore } from "@tinyweb-agent-framework/agent/session/postgres"
9
- export {
10
- makeProcessor,
11
- persistMessageUpdate,
12
- type Processor,
13
- type ProcessorConfig,
14
- type TurnInput,
15
- type ResumeInput,
16
- } from "./processor"
17
- export { estimateTokens, isOverflow } from "./overflow"
18
- export { compact, type CompactInput } from "./compaction"