@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.
- 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
|
@@ -0,0 +1,51 @@
|
|
|
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
|
+
import { toolUseSection } from "./tool-use";
|
|
28
|
+
import { toolUseGuidelinesSection, type ToolUseGuidelinesConfig } from "./tool-use-guidelines";
|
|
29
|
+
import { objectiveSection, type ObjectiveConfig, type ObjectiveKind } from "./objective";
|
|
30
|
+
import { responseStyleSection, type ResponseStyleConfig, type ResponseStyleKind } from "./response-style";
|
|
31
|
+
export { toolUseSection, toolUseGuidelinesSection, objectiveSection, responseStyleSection };
|
|
32
|
+
export type { ToolUseGuidelinesConfig, ObjectiveConfig, ObjectiveKind, ResponseStyleConfig, ResponseStyleKind };
|
|
33
|
+
export type SectionToggle<T> = boolean | T;
|
|
34
|
+
export type PromptSectionsConfig = {
|
|
35
|
+
/** TOOL USE block (how tool calls work). Default: enabled. */
|
|
36
|
+
readonly toolUse?: boolean;
|
|
37
|
+
/** TOOL USE GUIDELINES (anti-loop, intent-matching). Default: enabled. */
|
|
38
|
+
readonly toolUseGuidelines?: SectionToggle<ToolUseGuidelinesConfig>;
|
|
39
|
+
/** OBJECTIVE block (proactive helpfulness, no-bail mindset). Default: enabled with kind="chat". */
|
|
40
|
+
readonly objective?: SectionToggle<ObjectiveConfig>;
|
|
41
|
+
/** RESPONSE STYLE block. Default: enabled with kind="chat". */
|
|
42
|
+
readonly responseStyle?: SectionToggle<ResponseStyleConfig>;
|
|
43
|
+
};
|
|
44
|
+
export type ComposeSystemPromptInput = {
|
|
45
|
+
/** User-authored ROLE / domain prompt. Inserted first, verbatim. */
|
|
46
|
+
readonly role?: string;
|
|
47
|
+
/** Per-section toggles. Omit for default framework behavior. */
|
|
48
|
+
readonly sections?: PromptSectionsConfig;
|
|
49
|
+
};
|
|
50
|
+
export declare const composeSystemPrompt: (input: ComposeSystemPromptInput) => string;
|
|
51
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/prompt/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAC3C,OAAO,EAAE,wBAAwB,EAAE,KAAK,uBAAuB,EAAE,MAAM,uBAAuB,CAAA;AAC9F,OAAO,EAAE,gBAAgB,EAAE,KAAK,eAAe,EAAE,KAAK,aAAa,EAAE,MAAM,aAAa,CAAA;AACxF,OAAO,EAAE,oBAAoB,EAAE,KAAK,mBAAmB,EAAE,KAAK,iBAAiB,EAAE,MAAM,kBAAkB,CAAA;AAEzG,OAAO,EAAE,cAAc,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,CAAA;AAC3F,YAAY,EAAE,uBAAuB,EAAE,eAAe,EAAE,aAAa,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,CAAA;AAE/G,MAAM,MAAM,aAAa,CAAC,CAAC,IAAI,OAAO,GAAG,CAAC,CAAA;AAE1C,MAAM,MAAM,oBAAoB,GAAG;IACjC,8DAA8D;IAC9D,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAA;IAC1B,0EAA0E;IAC1E,QAAQ,CAAC,iBAAiB,CAAC,EAAE,aAAa,CAAC,uBAAuB,CAAC,CAAA;IACnE,mGAAmG;IACnG,QAAQ,CAAC,SAAS,CAAC,EAAE,aAAa,CAAC,eAAe,CAAC,CAAA;IACnD,+DAA+D;IAC/D,QAAQ,CAAC,aAAa,CAAC,EAAE,aAAa,CAAC,mBAAmB,CAAC,CAAA;CAC5D,CAAA;AAQD,MAAM,MAAM,wBAAwB,GAAG;IACrC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;IACtB,gEAAgE;IAChE,QAAQ,CAAC,QAAQ,CAAC,EAAE,oBAAoB,CAAA;CACzC,CAAA;AAED,eAAO,MAAM,mBAAmB,GAAI,OAAO,wBAAwB,KAAG,MA4BrE,CAAA"}
|
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
export type ObjectiveKind = "chat" | "task";
|
|
24
|
+
export type ObjectiveConfig = {
|
|
25
|
+
/** Default "chat". Use "task" for autonomous multi-step agents. */
|
|
26
|
+
readonly kind?: ObjectiveKind;
|
|
27
|
+
};
|
|
28
|
+
export declare const objectiveSection: (config?: ObjectiveConfig) => string;
|
|
29
|
+
//# sourceMappingURL=objective.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"objective.d.ts","sourceRoot":"","sources":["../../src/prompt/objective.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,CAAA;AAE3C,MAAM,MAAM,eAAe,GAAG;IAC5B,mEAAmE;IACnE,QAAQ,CAAC,IAAI,CAAC,EAAE,aAAa,CAAA;CAC9B,CAAA;AAuED,eAAO,MAAM,gBAAgB,GAAI,SAAQ,eAAoB,KAAG,MAI/D,CAAA"}
|
|
@@ -0,0 +1,19 @@
|
|
|
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
|
+
export type ResponseStyleConfig = {
|
|
15
|
+
/** Default: "chat". */
|
|
16
|
+
readonly kind?: ResponseStyleKind;
|
|
17
|
+
};
|
|
18
|
+
export declare const responseStyleSection: (config?: ResponseStyleConfig) => string;
|
|
19
|
+
//# sourceMappingURL=response-style.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"response-style.d.ts","sourceRoot":"","sources":["../../src/prompt/response-style.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,SAAS,GAAG,KAAK,CAAA;AAE1D,MAAM,MAAM,mBAAmB,GAAG;IAChC,uBAAuB;IACvB,QAAQ,CAAC,IAAI,CAAC,EAAE,iBAAiB,CAAA;CAClC,CAAA;AAoCD,eAAO,MAAM,oBAAoB,GAAI,SAAQ,mBAAwB,KAAG,MAKvE,CAAA"}
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
+
export declare const toolUseGuidelinesSection: (config?: ToolUseGuidelinesConfig) => string;
|
|
22
|
+
//# sourceMappingURL=tool-use-guidelines.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-use-guidelines.d.ts","sourceRoot":"","sources":["../../src/prompt/tool-use-guidelines.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,uBAAuB,GAAG;IACpC,+EAA+E;IAC/E,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAA;CAClC,CAAA;AAID,eAAO,MAAM,wBAAwB,GAAI,SAAQ,uBAA4B,KAAG,MAiC/E,CAAA"}
|
|
@@ -0,0 +1,12 @@
|
|
|
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 declare const toolUseSection: () => string;
|
|
12
|
+
//# sourceMappingURL=tool-use.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-use.d.ts","sourceRoot":"","sources":["../../src/prompt/tool-use.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,QAAO,MAgBpB,CAAA"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { LLMClient } from "@tinyweb_dev/agent-framework-llm";
|
|
2
|
+
import { ManagedRuntime } from "effect";
|
|
3
|
+
export type AgentRuntime = ManagedRuntime.ManagedRuntime<typeof LLMClient.Service, never>;
|
|
4
|
+
export declare const createRuntime: () => AgentRuntime;
|
|
5
|
+
export declare const defaultRuntime: () => AgentRuntime;
|
|
6
|
+
export declare const disposeDefaultRuntime: () => Promise<void>;
|
|
7
|
+
//# sourceMappingURL=runtime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAmB,MAAM,8BAA8B,CAAA;AACzE,OAAO,EAAS,cAAc,EAAE,MAAM,QAAQ,CAAA;AAI9C,MAAM,MAAM,YAAY,GAAG,cAAc,CAAC,cAAc,CAAC,OAAO,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;AAIzF,eAAO,MAAM,aAAa,QAAO,YAA8C,CAAA;AAE/E,eAAO,MAAM,cAAc,QAAO,YAIjC,CAAA;AAED,eAAO,MAAM,qBAAqB,qBAIjC,CAAA"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { Session, CreateSessionInput, Message, MessageID, SessionID } from "./schema";
|
|
3
|
+
export type GetMessagesOpts = {
|
|
4
|
+
readonly limit?: number;
|
|
5
|
+
readonly before?: MessageID;
|
|
6
|
+
};
|
|
7
|
+
export type ListSessionsOpts = {
|
|
8
|
+
readonly limit?: number;
|
|
9
|
+
/** Opaque cursor returned by previous call's `nextCursor`. */
|
|
10
|
+
readonly cursor?: string;
|
|
11
|
+
readonly agentName?: string;
|
|
12
|
+
readonly ownerId?: string;
|
|
13
|
+
};
|
|
14
|
+
export type ListSessionsResult = {
|
|
15
|
+
readonly items: ReadonlyArray<Session.Info>;
|
|
16
|
+
readonly nextCursor?: string;
|
|
17
|
+
};
|
|
18
|
+
export type SessionPatch = {
|
|
19
|
+
readonly title?: string;
|
|
20
|
+
readonly metadata?: Record<string, unknown>;
|
|
21
|
+
};
|
|
22
|
+
export type SessionStore = {
|
|
23
|
+
createSession(input: CreateSessionInput): Effect.Effect<Session.Info>;
|
|
24
|
+
getSession(id: SessionID | string): Effect.Effect<Session.Info | undefined>;
|
|
25
|
+
upsertSession(input: CreateSessionInput & {
|
|
26
|
+
id?: SessionID | string;
|
|
27
|
+
}): Effect.Effect<Session.Info>;
|
|
28
|
+
listSessions(opts?: ListSessionsOpts): Effect.Effect<ListSessionsResult>;
|
|
29
|
+
updateSession(id: SessionID | string, patch: SessionPatch): Effect.Effect<Session.Info | undefined>;
|
|
30
|
+
appendMessage(sessionId: SessionID | string, msg: Message): Effect.Effect<void>;
|
|
31
|
+
getMessages(sessionId: SessionID | string, opts?: GetMessagesOpts): Effect.Effect<Message[]>;
|
|
32
|
+
deleteMessage(sessionId: SessionID | string, messageId: MessageID | string): Effect.Effect<void>;
|
|
33
|
+
deleteSession(id: SessionID | string): Effect.Effect<void>;
|
|
34
|
+
/**
|
|
35
|
+
* Optional in-place message update (used by tool-approval resolve/resume).
|
|
36
|
+
* Stores that omit this fall back to deleteMessage + appendMessage.
|
|
37
|
+
*/
|
|
38
|
+
updateMessage?(sessionId: SessionID | string, messageId: MessageID | string, msg: Message): Effect.Effect<void>;
|
|
39
|
+
};
|
|
40
|
+
//# sourceMappingURL=adapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/session/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/B,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,OAAO,E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AAE,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAA;IACxE,aAAa,CAAC,EAAE,EAAE,SAAS,GAAG,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,CAAA;IACnG,aAAa,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IAC/E,WAAW,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM,EAAE,IAAI,CAAC,EAAE,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAA;IAC5F,aAAa,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM,EAAE,SAAS,EAAE,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IAChG,aAAa,CAAC,EAAE,EAAE,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IAC1D;;;OAGG;IACH,aAAa,CAAC,CACZ,SAAS,EAAE,SAAS,GAAG,MAAM,EAC7B,SAAS,EAAE,SAAS,GAAG,MAAM,EAC7B,GAAG,EAAE,OAAO,GACX,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;CACvB,CAAA"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { LLMClient, type ModelRef } from "@tinyweb_dev/agent-framework-llm";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import type { SessionStore } from "./adapter";
|
|
4
|
+
import { type MessageID, type SessionID } from "./schema";
|
|
5
|
+
export type CompactInput = {
|
|
6
|
+
readonly sessionId: SessionID | string;
|
|
7
|
+
readonly store: SessionStore;
|
|
8
|
+
readonly model: ModelRef;
|
|
9
|
+
/** Number of trailing turns to keep verbatim. Default 4. */
|
|
10
|
+
readonly keepRecent?: number;
|
|
11
|
+
/** True when triggered by a ContextOverflowReason from the previous turn. */
|
|
12
|
+
readonly overflow?: boolean;
|
|
13
|
+
};
|
|
14
|
+
export type CompactResult = {
|
|
15
|
+
readonly compacted: boolean;
|
|
16
|
+
readonly summary?: string;
|
|
17
|
+
readonly markerId?: MessageID;
|
|
18
|
+
readonly tailStartId?: MessageID;
|
|
19
|
+
/** Approximate prompt tokens BEFORE compaction (estimateTokens of the head slice). */
|
|
20
|
+
readonly prevTokens?: number;
|
|
21
|
+
/** Approximate prompt tokens AFTER compaction (`[marker, ...tail]`). */
|
|
22
|
+
readonly newTokens?: number;
|
|
23
|
+
/** USD cost of the summariser call when the route surfaces it. */
|
|
24
|
+
readonly cost?: number;
|
|
25
|
+
/** Model id used for the summarisation call. Today: same as the main agent. */
|
|
26
|
+
readonly modelId?: string;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Run an auto-compaction pass. Appends a marker user message that summarises
|
|
30
|
+
* the leading slice of history; replay logic in `replay.ts` will then emit
|
|
31
|
+
* only `[marker, ...tail]` for subsequent LLM calls.
|
|
32
|
+
*
|
|
33
|
+
* Idempotent: if the most recent compaction marker has nothing prior to
|
|
34
|
+
* summarise we no-op.
|
|
35
|
+
*/
|
|
36
|
+
export declare const compact: (input: CompactInput) => Effect.Effect<CompactResult, unknown, typeof LLMClient.Service>;
|
|
37
|
+
//# sourceMappingURL=compaction.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../src/session/compaction.ts"],"names":[],"mappings":"AAMA,OAAO,EAAO,SAAS,EAAE,KAAK,QAAQ,EAAE,MAAM,8BAA8B,CAAA;AAC5E,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAE7C,OAAO,EAIL,KAAK,SAAS,EACd,KAAK,SAAS,EAEf,MAAM,UAAU,CAAA;AAkCjB,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM,CAAA;IACtC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAA;IAC5B,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAA;IACxB,4DAA4D;IAC5D,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;IAC5B,6EAA6E;IAC7E,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;CAC5B,CAAA;AAED,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAA;IAC3B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAA;IAC7B,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,CAAA;IAChC,sFAAsF;IACtF,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;IAC5B,wEAAwE;IACxE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAC3B,kEAAkE;IAClE,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;IACtB,+EAA+E;IAC/E,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,OAAO,GAClB,OAAO,YAAY,KAClB,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,OAAO,EAAE,OAAO,SAAS,CAAC,OAAO,CA8D7D,CAAA"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export * from "./schema";
|
|
2
|
+
export * from "./adapter";
|
|
3
|
+
export { makeMemoryStore } from "./memory";
|
|
4
|
+
export { makeProcessor, persistMessageUpdate, type Processor, type ProcessorConfig, type TurnInput, type ResumeInput, } from "./processor";
|
|
5
|
+
export { estimateTokens, isOverflow } from "./overflow";
|
|
6
|
+
export { compact, type CompactInput } from "./compaction";
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/session/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAA;AAM1C,OAAO,EACL,aAAa,EACb,oBAAoB,EACpB,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,KAAK,WAAW,GACjB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AACvD,OAAO,EAAE,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAA"}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var effect = require('effect');
|
|
4
|
+
var core = require('@tinyweb_dev/agent-framework-core');
|
|
5
|
+
|
|
6
|
+
// src/session/memory.ts
|
|
7
|
+
var newSessionID = () => core.Id.prefixed("ses");
|
|
8
|
+
|
|
9
|
+
// src/session/memory.ts
|
|
10
|
+
var encodeCursor = (cursor) => Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
|
|
11
|
+
var decodeCursor = (raw) => {
|
|
12
|
+
const json = Buffer.from(raw, "base64url").toString("utf8");
|
|
13
|
+
const parsed = JSON.parse(json);
|
|
14
|
+
if (typeof parsed.updatedAt !== "number" || typeof parsed.id !== "string") return void 0;
|
|
15
|
+
return { updatedAt: parsed.updatedAt, id: parsed.id };
|
|
16
|
+
};
|
|
17
|
+
var makeMemoryStore = () => {
|
|
18
|
+
const store = /* @__PURE__ */ new Map();
|
|
19
|
+
const createSession = (input) => {
|
|
20
|
+
const now = Date.now();
|
|
21
|
+
const info = {
|
|
22
|
+
id: newSessionID(),
|
|
23
|
+
agentName: input.agentName,
|
|
24
|
+
title: input.title,
|
|
25
|
+
metadata: input.metadata,
|
|
26
|
+
createdAt: now,
|
|
27
|
+
updatedAt: now
|
|
28
|
+
};
|
|
29
|
+
store.set(info.id, { info, messages: [] });
|
|
30
|
+
return effect.Effect.succeed(info);
|
|
31
|
+
};
|
|
32
|
+
const getSession = (id) => effect.Effect.succeed(store.get(id)?.info);
|
|
33
|
+
const upsertSession = (input) => {
|
|
34
|
+
const existing = input.id ? store.get(input.id) : void 0;
|
|
35
|
+
if (existing) return effect.Effect.succeed(existing.info);
|
|
36
|
+
if (!input.id) return createSession(input);
|
|
37
|
+
const now = Date.now();
|
|
38
|
+
const info = {
|
|
39
|
+
id: input.id,
|
|
40
|
+
agentName: input.agentName,
|
|
41
|
+
title: input.title,
|
|
42
|
+
metadata: input.metadata,
|
|
43
|
+
createdAt: now,
|
|
44
|
+
updatedAt: now
|
|
45
|
+
};
|
|
46
|
+
store.set(info.id, { info, messages: [] });
|
|
47
|
+
return effect.Effect.succeed(info);
|
|
48
|
+
};
|
|
49
|
+
const listSessions = (opts) => {
|
|
50
|
+
const limit = opts?.limit ?? 50;
|
|
51
|
+
const filtered = Array.from(store.values()).map((e) => e.info).filter((info) => opts?.agentName ? info.agentName === opts.agentName : true).filter(
|
|
52
|
+
(info) => opts?.ownerId ? info.metadata?.ownerId === opts.ownerId : true
|
|
53
|
+
).sort((a, b) => {
|
|
54
|
+
if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt;
|
|
55
|
+
return b.id.localeCompare(a.id);
|
|
56
|
+
});
|
|
57
|
+
const cursor = opts?.cursor ? decodeCursor(opts.cursor) : void 0;
|
|
58
|
+
const startIdx = cursor ? filtered.findIndex(
|
|
59
|
+
(info) => info.updatedAt < cursor.updatedAt || info.updatedAt === cursor.updatedAt && info.id.localeCompare(cursor.id) < 0
|
|
60
|
+
) : 0;
|
|
61
|
+
if (startIdx === -1) return effect.Effect.succeed({ items: [] });
|
|
62
|
+
const page = filtered.slice(startIdx, startIdx + limit);
|
|
63
|
+
const tail = page[page.length - 1];
|
|
64
|
+
const hasMore = startIdx + limit < filtered.length;
|
|
65
|
+
const nextCursor = hasMore && tail ? encodeCursor({ updatedAt: tail.updatedAt, id: tail.id }) : void 0;
|
|
66
|
+
return effect.Effect.succeed({ items: page, nextCursor });
|
|
67
|
+
};
|
|
68
|
+
const updateSession = (id, patch) => {
|
|
69
|
+
const entry = store.get(id);
|
|
70
|
+
if (!entry) return effect.Effect.succeed(void 0);
|
|
71
|
+
entry.info = {
|
|
72
|
+
...entry.info,
|
|
73
|
+
...patch.title !== void 0 ? { title: patch.title } : {},
|
|
74
|
+
...patch.metadata !== void 0 ? { metadata: patch.metadata } : {},
|
|
75
|
+
updatedAt: Date.now()
|
|
76
|
+
};
|
|
77
|
+
return effect.Effect.succeed(entry.info);
|
|
78
|
+
};
|
|
79
|
+
const appendMessage = (sessionId, msg) => {
|
|
80
|
+
const entry = store.get(sessionId);
|
|
81
|
+
if (!entry) return effect.Effect.void;
|
|
82
|
+
entry.messages.push(msg);
|
|
83
|
+
entry.info = { ...entry.info, updatedAt: Date.now() };
|
|
84
|
+
return effect.Effect.void;
|
|
85
|
+
};
|
|
86
|
+
const getMessages = (sessionId, opts) => {
|
|
87
|
+
const msgs = store.get(sessionId)?.messages ?? [];
|
|
88
|
+
const sliced = opts?.before ? msgs.slice(0, msgs.findIndex((m) => m.id === opts.before)) : msgs;
|
|
89
|
+
const limited = opts?.limit ? sliced.slice(-opts.limit) : sliced;
|
|
90
|
+
return effect.Effect.succeed([...limited]);
|
|
91
|
+
};
|
|
92
|
+
const deleteMessage = (sessionId, messageId) => {
|
|
93
|
+
const entry = store.get(sessionId);
|
|
94
|
+
if (!entry) return effect.Effect.void;
|
|
95
|
+
const idx = entry.messages.findIndex((m) => m.id === messageId);
|
|
96
|
+
if (idx === -1) return effect.Effect.void;
|
|
97
|
+
entry.messages.splice(idx, 1);
|
|
98
|
+
entry.info = { ...entry.info, updatedAt: Date.now() };
|
|
99
|
+
return effect.Effect.void;
|
|
100
|
+
};
|
|
101
|
+
const updateMessage = (sessionId, messageId, msg) => {
|
|
102
|
+
const entry = store.get(sessionId);
|
|
103
|
+
if (!entry) return effect.Effect.void;
|
|
104
|
+
const idx = entry.messages.findIndex((m) => m.id === messageId);
|
|
105
|
+
if (idx === -1) return effect.Effect.void;
|
|
106
|
+
entry.messages[idx] = msg;
|
|
107
|
+
entry.info = { ...entry.info, updatedAt: Date.now() };
|
|
108
|
+
return effect.Effect.void;
|
|
109
|
+
};
|
|
110
|
+
const deleteSession = (id) => {
|
|
111
|
+
store.delete(id);
|
|
112
|
+
return effect.Effect.void;
|
|
113
|
+
};
|
|
114
|
+
return {
|
|
115
|
+
createSession,
|
|
116
|
+
getSession,
|
|
117
|
+
upsertSession,
|
|
118
|
+
listSessions,
|
|
119
|
+
updateSession,
|
|
120
|
+
appendMessage,
|
|
121
|
+
getMessages,
|
|
122
|
+
deleteMessage,
|
|
123
|
+
updateMessage,
|
|
124
|
+
deleteSession
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
exports.makeMemoryStore = makeMemoryStore;
|
|
129
|
+
//# sourceMappingURL=memory.cjs.map
|
|
130
|
+
//# sourceMappingURL=memory.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/session/schema.ts","../../src/session/memory.ts"],"names":["Id","Effect"],"mappings":";;;;;;AAOO,IAAM,YAAA,GAAe,MAAiBA,OAAA,CAAG,QAAA,CAAS,KAAK,CAAA;;;ACQ9D,IAAM,YAAA,GAAe,CAAC,MAAA,KACpB,MAAA,CAAO,IAAA,CAAK,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA,EAAG,MAAM,CAAA,CAAE,QAAA,CAAS,WAAW,CAAA;AAElE,IAAM,YAAA,GAAe,CAAC,GAAA,KAAoC;AACxD,EAAA,MAAM,OAAO,MAAA,CAAO,IAAA,CAAK,KAAK,WAAW,CAAA,CAAE,SAAS,MAAM,CAAA;AAC1D,E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AA,KAAgD;AACrE,IAAA,KAAA,CAAM,OAAO,EAAE,CAAA;AACf,IAAA,OAAOA,aAAA,CAAO,IAAA;AAAA,EAChB,CAAA;AAEA,EAAA,OAAO;AAAA,IACL,aAAA;AAAA,IACA,UAAA;AAAA,IACA,aAAA;AAAA,IACA,YAAA;AAAA,IACA,aAAA;AAAA,IACA,aAAA;AAAA,IACA,WAAA;AAAA,IACA,aAAA;AAAA,IACA,aAAA;AAAA,IACA;AAAA,GACF;AACF","file":"memory.cjs","sourcesContent":["import { Id } from \"@tinyweb_dev/agent-framework-core\"\n\n// Session identifiers\nexport type SessionID = string & { readonly _brand: \"SessionID\" }\nexport type MessageID = string & { readonly _brand: \"MessageID\" }\nexport type PartID = string & { readonly _brand: \"PartID\" }\n\nexport const newSessionID = (): SessionID => Id.prefixed(\"ses\") as SessionID\nexport const newMessageID = (): MessageID => Id.prefixed(\"msg\") as MessageID\nexport const newPartID = (): PartID => Id.prefixed(\"prt\") as PartID\n\n// Session info\nexport type CreateSessionInput = {\n readonly agentName: string\n readonly title?: string\n readonly metadata?: Record<string, unknown>\n}\n\nexport namespace Session {\n export type Info = {\n readonly id: SessionID\n readonly agentName: string\n readonly title?: string\n readonly metadata?: Record<string, unknown>\n readonly createdAt: number\n readonly updatedAt: number\n }\n}\n\n// Message part types (app-level, separate from LLM wire format)\nexport type TextPart = {\n readonly type: \"text\"\n readonly text: string\n}\n\nexport type ImagePart = {\n readonly type: \"image\"\n readonly url?: string\n readonly data?: string // base64\n readonly mediaType?: string\n}\n\nexport type ReasoningPart = {\n readonly type: \"reasoning\"\n readonly text: string\n}\n\n/**\n * Lifecycle of a tool call inside an assistant message.\n *\n * Approval flow (interrupt mode):\n * running → pending-approval → approved → running → complete\n * └→ rejected → error\n */\nexport type ToolPartState =\n | \"pending\"\n | \"running\"\n | \"complete\"\n | \"error\"\n | \"pending-approval\"\n | \"approved\"\n | \"rejected\"\n\nexport type ToolPart = {\n readonly id: PartID\n readonly type: \"tool\"\n readonly callID: string\n readonly name: string\n readonly state: ToolPartState\n readonly input: unknown\n readonly output?: unknown\n readonly metadata?: Record<string, unknown>\n}\n\n/**\n * Marker part inserted by the auto-compaction flow. Sits on a synthetic user\n * message that replaces the summarised tail of the conversation. `tailStartId`\n * is the id of the first non-compacted message that should still be replayed.\n */\nexport type CompactionPart = {\n readonly type: \"compaction\"\n readonly summary: string\n readonly tailStartId?: MessageID\n readonly auto: boolean\n readonly overflow: boolean\n}\n\n// Messages\nexport type UserMessage = {\n readonly id: MessageID\n readonly role: \"user\"\n readonly parts: ReadonlyArray<TextPart | ImagePart | CompactionPart>\n}\n\nexport type AssistantMessage = {\n readonly id: MessageID\n readonly role: \"assistant\"\n readonly parts: ReadonlyArray<TextPart | ToolPart | ReasoningPart>\n readonly modelId?: string\n readonly providerId?: string\n readonly usage?: {\n readonly inputTokens?: number\n readonly outputTokens?: number\n readonly totalTokens?: number\n }\n}\n\nexport type Message = UserMessage | AssistantMessage\n\n// Helpers to construct messages\nexport type MakeUserMessageInput =\n | string\n | {\n readonly text: string\n readonly images?: ReadonlyArray<ImagePart>\n }\n\nexport const makeUserMessage = (input: MakeUserMessageInput): UserMessage => {\n const text = typeof input === \"string\" ? input : input.text\n const images = typeof input === \"string\" ? [] : (input.images ?? [])\n const parts: Array<TextPart | ImagePart> = []\n if (text.length > 0) parts.push({ type: \"text\", text })\n for (const img of images) parts.push(img)\n return { id: newMessageID(), role: \"user\", parts }\n}\n\nexport const makeAssistantMessage = (parts: AssistantMessage[\"parts\"]): AssistantMessage => ({\n id: newMessageID(),\n role: \"assistant\",\n parts,\n})\n\n/** Build a synthetic user message that carries a compaction marker. */\nexport const makeCompactionMessage = (input: {\n readonly summary: string\n readonly tailStartId?: MessageID\n readonly auto?: boolean\n readonly overflow?: boolean\n}): UserMessage => ({\n id: newMessageID(),\n role: \"user\",\n parts: [\n {\n type: \"compaction\",\n summary: input.summary,\n tailStartId: input.tailStartId,\n auto: input.auto ?? true,\n overflow: input.overflow ?? false,\n },\n ],\n})\n\nexport const findCompactionPart = (msg: Message): CompactionPart | undefined => {\n if (msg.role !== \"user\") return undefined\n return msg.parts.find((p): p is CompactionPart => (p as { type: string }).type === \"compaction\")\n}\n","import { Effect } from \"effect\"\nimport type { ListSessionsOpts, ListSessionsResult, SessionPatch, SessionStore, GetMessagesOpts } from \"./adapter\"\nimport {\n newSessionID,\n type CreateSessionInput,\n type Message,\n type MessageID,\n type Session,\n type SessionID,\n} from \"./schema\"\n\ntype Entry = { info: Session.Info; messages: Message[] }\n\ntype Cursor = { readonly updatedAt: number; readonly id: string }\n\nconst encodeCursor = (cursor: Cursor): string =>\n Buffer.from(JSON.stringify(cursor), \"utf8\").toString(\"base64url\")\n\nconst decodeCursor = (raw: string): Cursor | undefined => {\n const json = Buffer.from(raw, \"base64url\").toString(\"utf8\")\n const parsed = JSON.parse(json) as Partial<Cursor>\n if (typeof parsed.updatedAt !== \"number\" || typeof parsed.id !== \"string\") return undefined\n return { updatedAt: parsed.updatedAt, id: parsed.id }\n}\n\nexport const makeMemoryStore = (): SessionStore => {\n const store = new Map<string, Entry>()\n\n const createSession = (input: CreateSessionInput): Effect.Effect<Session.Info> => {\n const now = Date.now()\n const info: Session.Info = {\n id: newSessionID(),\n agentName: input.agentName,\n title: input.title,\n metadata: input.metadata,\n createdAt: now,\n updatedAt: now,\n }\n store.set(info.id, { info, messages: [] })\n return Effect.succeed(info)\n }\n\n const getSession = (id: SessionID | string): Effect.Effect<Session.Info | undefined> =>\n Effect.succeed(store.get(id)?.info)\n\n const upsertSession = (\n input: CreateSessionInput & { id?: SessionID | string },\n ): Effect.Effect<Session.Info> => {\n const existing = input.id ? store.get(input.id) : undefined\n if (existing) return Effect.succeed(existing.info)\n if (!input.id) return createSession(input)\n const now = Date.now()\n const info: Session.Info = {\n id: input.id as SessionID,\n agentName: input.agentName,\n title: input.title,\n metadata: input.metadata,\n createdAt: now,\n updatedAt: now,\n }\n store.set(info.id, { info, messages: [] })\n return Effect.succeed(info)\n }\n\n const listSessions = (opts?: ListSessionsOpts): Effect.Effect<ListSessionsResult> => {\n const limit = opts?.limit ?? 50\n const filtered = Array.from(store.values())\n .map((e) => e.info)\n .filter((info) => (opts?.agentName ? info.agentName === opts.agentName : true))\n .filter((info) =>\n opts?.ownerId ? (info.metadata as { ownerId?: string } | undefined)?.ownerId === opts.ownerId : true,\n )\n .sort((a, b) => {\n if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt\n return b.id.localeCompare(a.id)\n })\n\n const cursor = opts?.cursor ? decodeCursor(opts.cursor) : undefined\n const startIdx = cursor\n ? filtered.findIndex(\n (info) =>\n info.updatedAt < cursor.updatedAt ||\n (info.updatedAt === cursor.updatedAt && info.id.localeCompare(cursor.id) < 0),\n )\n : 0\n if (startIdx === -1) return Effect.succeed({ items: [] })\n\n const page = filtered.slice(startIdx, startIdx + limit)\n const tail = page[page.length - 1]\n const hasMore = startIdx + limit < filtered.length\n const nextCursor = hasMore && tail ? encodeCursor({ updatedAt: tail.updatedAt, id: tail.id }) : undefined\n return Effect.succeed({ items: page, nextCursor })\n }\n\n const updateSession = (\n id: SessionID | string,\n patch: SessionPatch,\n ): Effect.Effect<Session.Info | undefined> => {\n const entry = store.get(id)\n if (!entry) return Effect.succeed(undefined)\n entry.info = {\n ...entry.info,\n ...(patch.title !== undefined ? { title: patch.title } : {}),\n ...(patch.metadata !== undefined ? { metadata: patch.metadata } : {}),\n updatedAt: Date.now(),\n }\n return Effect.succeed(entry.info)\n }\n\n const appendMessage = (sessionId: SessionID | string, msg: Message): Effect.Effect<void> => {\n const entry = store.get(sessionId)\n if (!entry) return Effect.void\n entry.messages.push(msg)\n entry.info = { ...entry.info, updatedAt: Date.now() }\n return Effect.void\n }\n\n const getMessages = (sessionId: SessionID | string, opts?: GetMessagesOpts): Effect.Effect<Message[]> => {\n const msgs = store.get(sessionId)?.messages ?? []\n const sliced = opts?.before ? msgs.slice(0, msgs.findIndex((m) => m.id === opts.before)) : msgs\n const limited = opts?.limit ? sliced.slice(-opts.limit) : sliced\n return Effect.succeed([...limited])\n }\n\n const deleteMessage = (\n sessionId: SessionID | string,\n messageId: MessageID | string,\n ): Effect.Effect<void> => {\n const entry = store.get(sessionId)\n if (!entry) return Effect.void\n const idx = entry.messages.findIndex((m) => m.id === messageId)\n if (idx === -1) return Effect.void\n entry.messages.splice(idx, 1)\n entry.info = { ...entry.info, updatedAt: Date.now() }\n return Effect.void\n }\n \n const updateMessage = (\n sessionId: SessionID | string,\n messageId: MessageID | string,\n msg: Message,\n ): Effect.Effect<void> => {\n const entry = store.get(sessionId)\n if (!entry) return Effect.void\n const idx = entry.messages.findIndex((m) => m.id === messageId)\n if (idx === -1) return Effect.void\n entry.messages[idx] = msg\n entry.info = { ...entry.info, updatedAt: Date.now() }\n return Effect.void\n }\n \n const deleteSession = (id: SessionID | string): Effect.Effect<void> => {\n store.delete(id)\n return Effect.void\n }\n \n return {\n createSession,\n getSession,\n upsertSession,\n listSessions,\n updateSession,\n appendMessage,\n getMessages,\n deleteMessage,\n updateMessage,\n deleteSession,\n }\n }\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/session/memory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAsD,YAAY,EAAmB,MAAM,WAAW,CAAA;AAwBlH,eAAO,MAAM,eAAe,QAAO,YA+IhC,CAAA"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { Effect } from 'effect';
|
|
2
|
+
import { Id } from '@tinyweb_dev/agent-framework-core';
|
|
3
|
+
|
|
4
|
+
// src/session/memory.ts
|
|
5
|
+
var newSessionID = () => Id.prefixed("ses");
|
|
6
|
+
|
|
7
|
+
// src/session/memory.ts
|
|
8
|
+
var encodeCursor = (cursor) => Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
|
|
9
|
+
var decodeCursor = (raw) => {
|
|
10
|
+
const json = Buffer.from(raw, "base64url").toString("utf8");
|
|
11
|
+
const parsed = JSON.parse(json);
|
|
12
|
+
if (typeof parsed.updatedAt !== "number" || typeof parsed.id !== "string") return void 0;
|
|
13
|
+
return { updatedAt: parsed.updatedAt, id: parsed.id };
|
|
14
|
+
};
|
|
15
|
+
var makeMemoryStore = () => {
|
|
16
|
+
const store = /* @__PURE__ */ new Map();
|
|
17
|
+
const createSession = (input) => {
|
|
18
|
+
const now = Date.now();
|
|
19
|
+
const info = {
|
|
20
|
+
id: newSessionID(),
|
|
21
|
+
agentName: input.agentName,
|
|
22
|
+
title: input.title,
|
|
23
|
+
metadata: input.metadata,
|
|
24
|
+
createdAt: now,
|
|
25
|
+
updatedAt: now
|
|
26
|
+
};
|
|
27
|
+
store.set(info.id, { info, messages: [] });
|
|
28
|
+
return Effect.succeed(info);
|
|
29
|
+
};
|
|
30
|
+
const getSession = (id) => Effect.succeed(store.get(id)?.info);
|
|
31
|
+
const upsertSession = (input) => {
|
|
32
|
+
const existing = input.id ? store.get(input.id) : void 0;
|
|
33
|
+
if (existing) return Effect.succeed(existing.info);
|
|
34
|
+
if (!input.id) return createSession(input);
|
|
35
|
+
const now = Date.now();
|
|
36
|
+
const info = {
|
|
37
|
+
id: input.id,
|
|
38
|
+
agentName: input.agentName,
|
|
39
|
+
title: input.title,
|
|
40
|
+
metadata: input.metadata,
|
|
41
|
+
createdAt: now,
|
|
42
|
+
updatedAt: now
|
|
43
|
+
};
|
|
44
|
+
store.set(info.id, { info, messages: [] });
|
|
45
|
+
return Effect.succeed(info);
|
|
46
|
+
};
|
|
47
|
+
const listSessions = (opts) => {
|
|
48
|
+
const limit = opts?.limit ?? 50;
|
|
49
|
+
const filtered = Array.from(store.values()).map((e) => e.info).filter((info) => opts?.agentName ? info.agentName === opts.agentName : true).filter(
|
|
50
|
+
(info) => opts?.ownerId ? info.metadata?.ownerId === opts.ownerId : true
|
|
51
|
+
).sort((a, b) => {
|
|
52
|
+
if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt;
|
|
53
|
+
return b.id.localeCompare(a.id);
|
|
54
|
+
});
|
|
55
|
+
const cursor = opts?.cursor ? decodeCursor(opts.cursor) : void 0;
|
|
56
|
+
const startIdx = cursor ? filtered.findIndex(
|
|
57
|
+
(info) => info.updatedAt < cursor.updatedAt || info.updatedAt === cursor.updatedAt && info.id.localeCompare(cursor.id) < 0
|
|
58
|
+
) : 0;
|
|
59
|
+
if (startIdx === -1) return Effect.succeed({ items: [] });
|
|
60
|
+
const page = filtered.slice(startIdx, startIdx + limit);
|
|
61
|
+
const tail = page[page.length - 1];
|
|
62
|
+
const hasMore = startIdx + limit < filtered.length;
|
|
63
|
+
const nextCursor = hasMore && tail ? encodeCursor({ updatedAt: tail.updatedAt, id: tail.id }) : void 0;
|
|
64
|
+
return Effect.succeed({ items: page, nextCursor });
|
|
65
|
+
};
|
|
66
|
+
const updateSession = (id, patch) => {
|
|
67
|
+
const entry = store.get(id);
|
|
68
|
+
if (!entry) return Effect.succeed(void 0);
|
|
69
|
+
entry.info = {
|
|
70
|
+
...entry.info,
|
|
71
|
+
...patch.title !== void 0 ? { title: patch.title } : {},
|
|
72
|
+
...patch.metadata !== void 0 ? { metadata: patch.metadata } : {},
|
|
73
|
+
updatedAt: Date.now()
|
|
74
|
+
};
|
|
75
|
+
return Effect.succeed(entry.info);
|
|
76
|
+
};
|
|
77
|
+
const appendMessage = (sessionId, msg) => {
|
|
78
|
+
const entry = store.get(sessionId);
|
|
79
|
+
if (!entry) return Effect.void;
|
|
80
|
+
entry.messages.push(msg);
|
|
81
|
+
entry.info = { ...entry.info, updatedAt: Date.now() };
|
|
82
|
+
return Effect.void;
|
|
83
|
+
};
|
|
84
|
+
const getMessages = (sessionId, opts) => {
|
|
85
|
+
const msgs = store.get(sessionId)?.messages ?? [];
|
|
86
|
+
const sliced = opts?.before ? msgs.slice(0, msgs.findIndex((m) => m.id === opts.before)) : msgs;
|
|
87
|
+
const limited = opts?.limit ? sliced.slice(-opts.limit) : sliced;
|
|
88
|
+
return Effect.succeed([...limited]);
|
|
89
|
+
};
|
|
90
|
+
const deleteMessage = (sessionId, messageId) => {
|
|
91
|
+
const entry = store.get(sessionId);
|
|
92
|
+
if (!entry) return Effect.void;
|
|
93
|
+
const idx = entry.messages.findIndex((m) => m.id === messageId);
|
|
94
|
+
if (idx === -1) return Effect.void;
|
|
95
|
+
entry.messages.splice(idx, 1);
|
|
96
|
+
entry.info = { ...entry.info, updatedAt: Date.now() };
|
|
97
|
+
return Effect.void;
|
|
98
|
+
};
|
|
99
|
+
const updateMessage = (sessionId, messageId, msg) => {
|
|
100
|
+
const entry = store.get(sessionId);
|
|
101
|
+
if (!entry) return Effect.void;
|
|
102
|
+
const idx = entry.messages.findIndex((m) => m.id === messageId);
|
|
103
|
+
if (idx === -1) return Effect.void;
|
|
104
|
+
entry.messages[idx] = msg;
|
|
105
|
+
entry.info = { ...entry.info, updatedAt: Date.now() };
|
|
106
|
+
return Effect.void;
|
|
107
|
+
};
|
|
108
|
+
const deleteSession = (id) => {
|
|
109
|
+
store.delete(id);
|
|
110
|
+
return Effect.void;
|
|
111
|
+
};
|
|
112
|
+
return {
|
|
113
|
+
createSession,
|
|
114
|
+
getSession,
|
|
115
|
+
upsertSession,
|
|
116
|
+
listSessions,
|
|
117
|
+
updateSession,
|
|
118
|
+
appendMessage,
|
|
119
|
+
getMessages,
|
|
120
|
+
deleteMessage,
|
|
121
|
+
updateMessage,
|
|
122
|
+
deleteSession
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
export { makeMemoryStore };
|
|
127
|
+
//# sourceMappingURL=memory.js.map
|
|
128
|
+
//# sourceMappingURL=memory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/session/schema.ts","../../src/session/memory.ts"],"names":[],"mappings":";;;;AAOO,IAAM,YAAA,GAAe,MAAiB,EAAA,CAAG,QAAA,CAAS,KAAK,CAAA;;;ACQ9D,IAAM,YAAA,GAAe,CAAC,MAAA,KACpB,MA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,CAAS,GAAG,CAAA,GAAI,GAAA;AACtB,IAAA,KAAA,CAAM,IAAA,GAAO,EAAE,GAAG,KAAA,CAAM,MAAM,SAAA,EAAW,IAAA,CAAK,KAAI,EAAE;AACpD,IAAA,OAAO,MAAA,CAAO,IAAA;AAAA,EAChB,CAAA;AAEA,EAAA,MAAM,aAAA,GAAgB,CAAC,EAAA,KAAgD;AACrE,IAAA,KAAA,CAAM,OAAO,EAAE,CAAA;AACf,IAAA,OAAO,MAAA,CAAO,IAAA;AAAA,EAChB,CAAA;AAEA,EAAA,OAAO;AAAA,IACL,aAAA;AAAA,IACA,UAAA;AAAA,IACA,aAAA;AAAA,IACA,YAAA;AAAA,IACA,aAAA;AAAA,IACA,aAAA;AAAA,IACA,WAAA;AAAA,IACA,aAAA;AAAA,IACA,aAAA;AAAA,IACA;AAAA,GACF;AACF","file":"memory.js","sourcesContent":["import { Id } from \"@tinyweb_dev/agent-framework-core\"\n\n// Session identifiers\nexport type SessionID = string & { readonly _brand: \"SessionID\" }\nexport type MessageID = string & { readonly _brand: \"MessageID\" }\nexport type PartID = string & { readonly _brand: \"PartID\" }\n\nexport const newSessionID = (): SessionID => Id.prefixed(\"ses\") as SessionID\nexport const newMessageID = (): MessageID => Id.prefixed(\"msg\") as MessageID\nexport const newPartID = (): PartID => Id.prefixed(\"prt\") as PartID\n\n// Session info\nexport type CreateSessionInput = {\n readonly agentName: string\n readonly title?: string\n readonly metadata?: Record<string, unknown>\n}\n\nexport namespace Session {\n export type Info = {\n readonly id: SessionID\n readonly agentName: string\n readonly title?: string\n readonly metadata?: Record<string, unknown>\n readonly createdAt: number\n readonly updatedAt: number\n }\n}\n\n// Message part types (app-level, separate from LLM wire format)\nexport type TextPart = {\n readonly type: \"text\"\n readonly text: string\n}\n\nexport type ImagePart = {\n readonly type: \"image\"\n readonly url?: string\n readonly data?: string // base64\n readonly mediaType?: string\n}\n\nexport type ReasoningPart = {\n readonly type: \"reasoning\"\n readonly text: string\n}\n\n/**\n * Lifecycle of a tool call inside an assistant message.\n *\n * Approval flow (interrupt mode):\n * running → pending-approval → approved → running → complete\n * └→ rejected → error\n */\nexport type ToolPartState =\n | \"pending\"\n | \"running\"\n | \"complete\"\n | \"error\"\n | \"pending-approval\"\n | \"approved\"\n | \"rejected\"\n\nexport type ToolPart = {\n readonly id: PartID\n readonly type: \"tool\"\n readonly callID: string\n readonly name: string\n readonly state: ToolPartState\n readonly input: unknown\n readonly output?: unknown\n readonly metadata?: Record<string, unknown>\n}\n\n/**\n * Marker part inserted by the auto-compaction flow. Sits on a synthetic user\n * message that replaces the summarised tail of the conversation. `tailStartId`\n * is the id of the first non-compacted message that should still be replayed.\n */\nexport type CompactionPart = {\n readonly type: \"compaction\"\n readonly summary: string\n readonly tailStartId?: MessageID\n readonly auto: boolean\n readonly overflow: boolean\n}\n\n// Messages\nexport type UserMessage = {\n readonly id: MessageID\n readonly role: \"user\"\n readonly parts: ReadonlyArray<TextPart | ImagePart | CompactionPart>\n}\n\nexport type AssistantMessage = {\n readonly id: MessageID\n readonly role: \"assistant\"\n readonly parts: ReadonlyArray<TextPart | ToolPart | ReasoningPart>\n readonly modelId?: string\n readonly providerId?: string\n readonly usage?: {\n readonly inputTokens?: number\n readonly outputTokens?: number\n readonly totalTokens?: number\n }\n}\n\nexport type Message = UserMessage | AssistantMessage\n\n// Helpers to construct messages\nexport type MakeUserMessageInput =\n | string\n | {\n readonly text: string\n readonly images?: ReadonlyArray<ImagePart>\n }\n\nexport const makeUserMessage = (input: MakeUserMessageInput): UserMessage => {\n const text = typeof input === \"string\" ? input : input.text\n const images = typeof input === \"string\" ? [] : (input.images ?? [])\n const parts: Array<TextPart | ImagePart> = []\n if (text.length > 0) parts.push({ type: \"text\", text })\n for (const img of images) parts.push(img)\n return { id: newMessageID(), role: \"user\", parts }\n}\n\nexport const makeAssistantMessage = (parts: AssistantMessage[\"parts\"]): AssistantMessage => ({\n id: newMessageID(),\n role: \"assistant\",\n parts,\n})\n\n/** Build a synthetic user message that carries a compaction marker. */\nexport const makeCompactionMessage = (input: {\n readonly summary: string\n readonly tailStartId?: MessageID\n readonly auto?: boolean\n readonly overflow?: boolean\n}): UserMessage => ({\n id: newMessageID(),\n role: \"user\",\n parts: [\n {\n type: \"compaction\",\n summary: input.summary,\n tailStartId: input.tailStartId,\n auto: input.auto ?? true,\n overflow: input.overflow ?? false,\n },\n ],\n})\n\nexport const findCompactionPart = (msg: Message): CompactionPart | undefined => {\n if (msg.role !== \"user\") return undefined\n return msg.parts.find((p): p is CompactionPart => (p as { type: string }).type === \"compaction\")\n}\n","import { Effect } from \"effect\"\nimport type { ListSessionsOpts, ListSessionsResult, SessionPatch, SessionStore, GetMessagesOpts } from \"./adapter\"\nimport {\n newSessionID,\n type CreateSessionInput,\n type Message,\n type MessageID,\n type Session,\n type SessionID,\n} from \"./schema\"\n\ntype Entry = { info: Session.Info; messages: Message[] }\n\ntype Cursor = { readonly updatedAt: number; readonly id: string }\n\nconst encodeCursor = (cursor: Cursor): string =>\n Buffer.from(JSON.stringify(cursor), \"utf8\").toString(\"base64url\")\n\nconst decodeCursor = (raw: string): Cursor | undefined => {\n const json = Buffer.from(raw, \"base64url\").toString(\"utf8\")\n const parsed = JSON.parse(json) as Partial<Cursor>\n if (typeof parsed.updatedAt !== \"number\" || typeof parsed.id !== \"string\") return undefined\n return { updatedAt: parsed.updatedAt, id: parsed.id }\n}\n\nexport const makeMemoryStore = (): SessionStore => {\n const store = new Map<string, Entry>()\n\n const createSession = (input: CreateSessionInput): Effect.Effect<Session.Info> => {\n const now = Date.now()\n const info: Session.Info = {\n id: newSessionID(),\n agentName: input.agentName,\n title: input.title,\n metadata: input.metadata,\n createdAt: now,\n updatedAt: now,\n }\n store.set(info.id, { info, messages: [] })\n return Effect.succeed(info)\n }\n\n const getSession = (id: SessionID | string): Effect.Effect<Session.Info | undefined> =>\n Effect.succeed(store.get(id)?.info)\n\n const upsertSession = (\n input: CreateSessionInput & { id?: SessionID | string },\n ): Effect.Effect<Session.Info> => {\n const existing = input.id ? store.get(input.id) : undefined\n if (existing) return Effect.succeed(existing.info)\n if (!input.id) return createSession(input)\n const now = Date.now()\n const info: Session.Info = {\n id: input.id as SessionID,\n agentName: input.agentName,\n title: input.title,\n metadata: input.metadata,\n createdAt: now,\n updatedAt: now,\n }\n store.set(info.id, { info, messages: [] })\n return Effect.succeed(info)\n }\n\n const listSessions = (opts?: ListSessionsOpts): Effect.Effect<ListSessionsResult> => {\n const limit = opts?.limit ?? 50\n const filtered = Array.from(store.values())\n .map((e) => e.info)\n .filter((info) => (opts?.agentName ? info.agentName === opts.agentName : true))\n .filter((info) =>\n opts?.ownerId ? (info.metadata as { ownerId?: string } | undefined)?.ownerId === opts.ownerId : true,\n )\n .sort((a, b) => {\n if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt\n return b.id.localeCompare(a.id)\n })\n\n const cursor = opts?.cursor ? decodeCursor(opts.cursor) : undefined\n const startIdx = cursor\n ? filtered.findIndex(\n (info) =>\n info.updatedAt < cursor.updatedAt ||\n (info.updatedAt === cursor.updatedAt && info.id.localeCompare(cursor.id) < 0),\n )\n : 0\n if (startIdx === -1) return Effect.succeed({ items: [] })\n\n const page = filtered.slice(startIdx, startIdx + limit)\n const tail = page[page.length - 1]\n const hasMore = startIdx + limit < filtered.length\n const nextCursor = hasMore && tail ? encodeCursor({ updatedAt: tail.updatedAt, id: tail.id }) : undefined\n return Effect.succeed({ items: page, nextCursor })\n }\n\n const updateSession = (\n id: SessionID | string,\n patch: SessionPatch,\n ): Effect.Effect<Session.Info | undefined> => {\n const entry = store.get(id)\n if (!entry) return Effect.succeed(undefined)\n entry.info = {\n ...entry.info,\n ...(patch.title !== undefined ? { title: patch.title } : {}),\n ...(patch.metadata !== undefined ? { metadata: patch.metadata } : {}),\n updatedAt: Date.now(),\n }\n return Effect.succeed(entry.info)\n }\n\n const appendMessage = (sessionId: SessionID | string, msg: Message): Effect.Effect<void> => {\n const entry = store.get(sessionId)\n if (!entry) return Effect.void\n entry.messages.push(msg)\n entry.info = { ...entry.info, updatedAt: Date.now() }\n return Effect.void\n }\n\n const getMessages = (sessionId: SessionID | string, opts?: GetMessagesOpts): Effect.Effect<Message[]> => {\n const msgs = store.get(sessionId)?.messages ?? []\n const sliced = opts?.before ? msgs.slice(0, msgs.findIndex((m) => m.id === opts.before)) : msgs\n const limited = opts?.limit ? sliced.slice(-opts.limit) : sliced\n return Effect.succeed([...limited])\n }\n\n const deleteMessage = (\n sessionId: SessionID | string,\n messageId: MessageID | string,\n ): Effect.Effect<void> => {\n const entry = store.get(sessionId)\n if (!entry) return Effect.void\n const idx = entry.messages.findIndex((m) => m.id === messageId)\n if (idx === -1) return Effect.void\n entry.messages.splice(idx, 1)\n entry.info = { ...entry.info, updatedAt: Date.now() }\n return Effect.void\n }\n \n const updateMessage = (\n sessionId: SessionID | string,\n messageId: MessageID | string,\n msg: Message,\n ): Effect.Effect<void> => {\n const entry = store.get(sessionId)\n if (!entry) return Effect.void\n const idx = entry.messages.findIndex((m) => m.id === messageId)\n if (idx === -1) return Effect.void\n entry.messages[idx] = msg\n entry.info = { ...entry.info, updatedAt: Date.now() }\n return Effect.void\n }\n \n const deleteSession = (id: SessionID | string): Effect.Effect<void> => {\n store.delete(id)\n return Effect.void\n }\n \n return {\n createSession,\n getSession,\n upsertSession,\n listSessions,\n updateSession,\n appendMessage,\n getMessages,\n deleteMessage,\n updateMessage,\n deleteSession,\n }\n }\n"]}
|