@agent-dreamer/sdk 0.0.3

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/README.md ADDED
@@ -0,0 +1,235 @@
1
+ # @agent-dreamer/sdk
2
+
3
+ Agent Memory TypeScript SDK 用于让 Node.js / TypeScript Agent 接入外部记忆服务。它封装了 session、memory event、记忆查询、短记忆生成和长记忆整理接口,并提供轻量的 `AgentMemorySession` 接入层。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ npm install @agent-dreamer/sdk
9
+ ```
10
+
11
+ 本地开发时可以从源码安装依赖:
12
+
13
+ ```bash
14
+ cd sdk/typescript
15
+ npm install
16
+ npm run build
17
+ ```
18
+
19
+ ## 创建 Client
20
+
21
+ ```ts
22
+ import { AgentMemoryClient } from "@agent-dreamer/sdk";
23
+
24
+ const client = new AgentMemoryClient({
25
+ baseUrl: process.env.AGENT_MEMORY_BASE_URL!,
26
+ apiKey: process.env.AGENT_MEMORY_API_KEY!,
27
+ });
28
+ ```
29
+
30
+ 常用环境变量:
31
+
32
+ ```bash
33
+ export AGENT_MEMORY_BASE_URL='http://localhost:8080'
34
+ export AGENT_MEMORY_API_KEY='<workspace api key>'
35
+ export AGENT_MEMORY_AGENT_INSTANCE_ID='<agent_instance_id>'
36
+ ```
37
+
38
+ ## 创建或复用 Session
39
+
40
+ 每个 Agent 会话开始时先创建或复用 session。`external_session_id` 是调用方自己的会话 ID,同一个 Agent 下重复传入会复用同一个服务端 session。
41
+
42
+ ```ts
43
+ const session = await client.createSession({
44
+ agent_instance_id: process.env.AGENT_MEMORY_AGENT_INSTANCE_ID!,
45
+ external_session_id: "typescript-task-20260616-001",
46
+ metadata: {
47
+ source: "typescript-agent",
48
+ },
49
+ });
50
+
51
+ console.log("session_id:", session.session_id);
52
+ ```
53
+
54
+ ## 写入 Memory Event
55
+
56
+ Agent 每轮推理和工具执行过程都应该写入 memory event。事件是记忆生成的事实来源。
57
+
58
+ ```ts
59
+ const event = await client.recordEvent({
60
+ session_id: session.session_id,
61
+ external_thread_id: "main",
62
+ event_id: "evt-user-001",
63
+ event_type: "message",
64
+ actor: "user",
65
+ status: "success",
66
+ summary: "用户要求继续 SDK 接入任务。",
67
+ payload: {
68
+ text: "请继续 SDK 接入任务",
69
+ },
70
+ });
71
+
72
+ console.log("thread_id:", event.thread_id);
73
+ ```
74
+
75
+ 常用事件类型:
76
+
77
+ | event_type | 适合场景 |
78
+ | --- | --- |
79
+ | `message` | 用户消息、Agent 回复 |
80
+ | `tool_call` | 调用工具前记录工具名和参数摘要 |
81
+ | `tool_result` | 工具执行完成后记录结果、状态、错误码 |
82
+ | `planner_update` | 计划、待办、阶段性决策变化 |
83
+ | `task_state` | 任务开始、暂停、完成、失败、阻塞 |
84
+ | `artifact_change` | 文件、代码、文档、报告等产物变化 |
85
+ | `correction_signal` | 用户纠错或要求修正此前信息 |
86
+
87
+ 工具失败事件建议填写 `status`、`error_code` 和 `retryable`。
88
+
89
+ ```ts
90
+ await client.recordEvent({
91
+ session_id: session.session_id,
92
+ event_id: "evt-tool-result-001",
93
+ event_type: "tool_result",
94
+ actor: "tool",
95
+ status: "error",
96
+ tool_name: "npm test",
97
+ error_code: "TEST_FAILED",
98
+ retryable: true,
99
+ summary: "npm test 执行失败。",
100
+ payload: {
101
+ command: "npm test",
102
+ exit_code: 1,
103
+ },
104
+ });
105
+ ```
106
+
107
+ ## 查询记忆
108
+
109
+ 每轮 Agent 推理前建议调用一次记忆查询,获取少量可注入上下文。
110
+
111
+ ```ts
112
+ import { formatMemoryContext } from "@agent-dreamer/sdk";
113
+
114
+ const response = await client.queryMemories({
115
+ session_id: session.session_id,
116
+ thread_id: event.thread_id,
117
+ query_text: "继续 SDK 接入任务,需要恢复当前进展和注意事项",
118
+ query_intent: "execution_help",
119
+ desired_memory_types: [
120
+ "task_whiteboard",
121
+ "tool_digest",
122
+ "failure_digest",
123
+ "procedure",
124
+ ],
125
+ limit: 8,
126
+ event_limit: 3,
127
+ });
128
+
129
+ const promptContext = formatMemoryContext(response);
130
+ console.log(promptContext);
131
+ ```
132
+
133
+ 常用查询意图:
134
+
135
+ | query_intent | 适合场景 |
136
+ | --- | --- |
137
+ | `execution_help` | 继续任务、写代码、调用工具、排错 |
138
+ | `policy_lookup` | 查询规则、约束、团队规范 |
139
+ | `preference_lookup` | 查询用户偏好、输出风格 |
140
+ | `factual_lookup` | 查询稳定事实、项目背景 |
141
+ | `broad_context` | 不确定意图时综合召回 |
142
+
143
+ ## 触发短记忆生成
144
+
145
+ 短记忆用于整理当前 session/thread 的近期上下文,例如任务白板、工具结果摘要、失败摘要。
146
+
147
+ 适合触发时机:
148
+
149
+ - 用户消息写入后,尤其是用户给出新目标或新约束。
150
+ - 工具调用或工具结果写入后。
151
+ - 一个阶段性步骤完成后。
152
+ - 出现错误、超时、取消、用户纠错后。
153
+
154
+ ```ts
155
+ const run = await client.generateShortMemory({
156
+ session_id: session.session_id,
157
+ thread_id: event.thread_id,
158
+ trigger_source: "thread_end",
159
+ hints: {
160
+ reason: "阶段完成后刷新任务白板",
161
+ },
162
+ });
163
+
164
+ console.log("short memory queued:", run.run_ids);
165
+ ```
166
+
167
+ `status=queued` 表示任务已入队。需要 worker 消费完成后,新的短记忆才会出现在查询结果中。
168
+
169
+ ## 触发长记忆整理
170
+
171
+ 长记忆用于沉淀跨会话可复用的信息,例如事实、偏好、流程和规则。
172
+
173
+ 适合触发时机:
174
+
175
+ - 会话结束时。
176
+ - 一个完整任务完成后。
177
+ - 用户明确表达稳定偏好时。
178
+ - 形成可复用流程、项目事实、团队规则时。
179
+ - 不建议对临时、未经确认、明显只对当前轮有效的信息触发长期整理。
180
+
181
+ ```ts
182
+ const run = await client.consolidateLongMemory({
183
+ session_id: session.session_id,
184
+ trigger_source: "session_end",
185
+ hints: {
186
+ reason: "会话结束后沉淀长期记忆",
187
+ },
188
+ });
189
+
190
+ console.log("long memory queued:", run.run_ids);
191
+ ```
192
+
193
+ ## 使用 AgentMemorySession 简化接入
194
+
195
+ `AgentMemorySession` 会自动创建 session、写标准事件,并缓存服务端返回的 `thread_id`,后续查询和生成会自动带上线程上下文。
196
+
197
+ ```ts
198
+ import { AgentMemoryClient, AgentMemorySession } from "@agent-dreamer/sdk";
199
+
200
+ const client = new AgentMemoryClient({
201
+ baseUrl: process.env.AGENT_MEMORY_BASE_URL!,
202
+ apiKey: process.env.AGENT_MEMORY_API_KEY!,
203
+ });
204
+
205
+ const agentMemory = new AgentMemorySession(client, {
206
+ agentInstanceId: process.env.AGENT_MEMORY_AGENT_INSTANCE_ID!,
207
+ externalSessionId: "typescript-task-20260616-001",
208
+ externalThreadId: "main",
209
+ });
210
+
211
+ await agentMemory.recordUserMessage("请继续 SDK 接入任务。");
212
+
213
+ const shortRun = await agentMemory.generateShortMemory("thread_end");
214
+ console.log("short memory queued:", shortRun.run_ids);
215
+
216
+ const memoryContext = await agentMemory.queryContext({
217
+ queryText: "继续 SDK 接入任务",
218
+ queryIntent: "execution_help",
219
+ desiredMemoryTypes: ["task_whiteboard", "tool_digest", "procedure"],
220
+ limit: 6,
221
+ eventLimit: 3,
222
+ });
223
+
224
+ console.log(memoryContext.text);
225
+ ```
226
+
227
+ ## 查看示例
228
+
229
+ ```bash
230
+ cd sdk/typescript
231
+ npm install
232
+ npm run build
233
+ npx tsx examples/basic.ts
234
+ npx tsx examples/agent_loop.ts
235
+ ```
@@ -0,0 +1,48 @@
1
+ import { AgentMemoryClient } from "./client.js";
2
+ import { GenerateMemoryResp, MemoryEventItem, MemoryItem, MemoryQueryResp, RecordEventResp } from "./types.js";
3
+ export interface AgentSessionConfig {
4
+ agentInstanceId: string;
5
+ externalSessionId: string;
6
+ sessionId?: string;
7
+ threadId?: string;
8
+ externalThreadId?: string;
9
+ metadata?: unknown;
10
+ threadMetadata?: unknown;
11
+ }
12
+ export interface QueryContextReq {
13
+ queryText: string;
14
+ queryIntent?: string;
15
+ desiredMemoryTypes?: string[];
16
+ limit?: number;
17
+ eventLimit?: number;
18
+ includeArchived?: boolean;
19
+ }
20
+ export interface MemoryContext {
21
+ text: string;
22
+ response: MemoryQueryResp;
23
+ items: MemoryItem[];
24
+ memoryEvents: MemoryEventItem[];
25
+ }
26
+ export declare class AgentMemorySession {
27
+ private client;
28
+ private config;
29
+ constructor(client: AgentMemoryClient, config: AgentSessionConfig);
30
+ ensureSession(): Promise<string>;
31
+ recordUserMessage(content: string): Promise<RecordEventResp>;
32
+ recordAssistantMessage(content: string): Promise<RecordEventResp>;
33
+ recordToolCall(toolName: string, summary: string, payload: unknown): Promise<RecordEventResp>;
34
+ recordToolResult(toolName: string, status: string, summary: string, payload: unknown, options?: {
35
+ errorCode?: string;
36
+ retryable?: boolean;
37
+ }): Promise<RecordEventResp>;
38
+ recordPlannerUpdate(summary: string, payload: unknown): Promise<RecordEventResp>;
39
+ recordTaskState(summary: string, payload: unknown): Promise<RecordEventResp>;
40
+ recordArtifactChange(summary: string, payload: unknown): Promise<RecordEventResp>;
41
+ recordCorrectionSignal(summary: string, payload: unknown): Promise<RecordEventResp>;
42
+ queryContext(req: QueryContextReq): Promise<MemoryContext>;
43
+ generateShortMemory(triggerSource?: string): Promise<GenerateMemoryResp>;
44
+ consolidateLongMemory(triggerSource?: string): Promise<GenerateMemoryResp>;
45
+ private record;
46
+ private captureThreadId;
47
+ }
48
+ export declare function formatMemoryContext(response: MemoryQueryResp): string;
@@ -0,0 +1,165 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { EVENT_ACTOR_ASSISTANT, EVENT_ACTOR_SYSTEM, EVENT_ACTOR_TOOL, EVENT_ACTOR_USER, EVENT_STATUS_SUCCESS, MEMORY_TYPE_FACT, MEMORY_TYPE_POLICY, MEMORY_TYPE_PREFERENCE, MEMORY_TYPE_PROCEDURE, TRIGGER_SOURCE_MANUAL, } from "./types.js";
3
+ export class AgentMemorySession {
4
+ client;
5
+ config;
6
+ constructor(client, config) {
7
+ this.client = client;
8
+ this.config = config;
9
+ }
10
+ async ensureSession() {
11
+ if (this.config.sessionId)
12
+ return this.config.sessionId;
13
+ const resp = await this.client.createSession({
14
+ agent_instance_id: this.config.agentInstanceId,
15
+ external_session_id: this.config.externalSessionId,
16
+ metadata: this.config.metadata,
17
+ });
18
+ this.config.sessionId = resp.session_id;
19
+ return resp.session_id;
20
+ }
21
+ recordUserMessage(content) {
22
+ return this.record("message", EVENT_ACTOR_USER, content, { text: content });
23
+ }
24
+ recordAssistantMessage(content) {
25
+ return this.record("message", EVENT_ACTOR_ASSISTANT, content, { text: content });
26
+ }
27
+ recordToolCall(toolName, summary, payload) {
28
+ return this.record("tool_call", EVENT_ACTOR_TOOL, summary, payload, toolName);
29
+ }
30
+ async recordToolResult(toolName, status, summary, payload, options = {}) {
31
+ const sessionId = await this.ensureSession();
32
+ const result = await this.client.recordEvent({
33
+ session_id: sessionId,
34
+ external_thread_id: this.config.externalThreadId,
35
+ thread_metadata: this.config.threadMetadata,
36
+ event_id: newEventId("tool-result"),
37
+ event_type: "tool_result",
38
+ actor: EVENT_ACTOR_TOOL,
39
+ summary,
40
+ status,
41
+ tool_name: toolName,
42
+ error_code: options.errorCode,
43
+ retryable: options.retryable,
44
+ payload,
45
+ });
46
+ this.captureThreadId(result.thread_id);
47
+ return result;
48
+ }
49
+ recordPlannerUpdate(summary, payload) {
50
+ return this.record("planner_update", EVENT_ACTOR_SYSTEM, summary, payload);
51
+ }
52
+ recordTaskState(summary, payload) {
53
+ return this.record("task_state", EVENT_ACTOR_SYSTEM, summary, payload);
54
+ }
55
+ recordArtifactChange(summary, payload) {
56
+ return this.record("artifact_change", EVENT_ACTOR_SYSTEM, summary, payload);
57
+ }
58
+ recordCorrectionSignal(summary, payload) {
59
+ return this.record("correction_signal", EVENT_ACTOR_USER, summary, payload);
60
+ }
61
+ async queryContext(req) {
62
+ const sessionId = await this.ensureSession();
63
+ const response = await this.client.queryMemories({
64
+ session_id: sessionId,
65
+ thread_id: this.config.threadId,
66
+ query_text: req.queryText,
67
+ query_intent: req.queryIntent,
68
+ desired_memory_types: req.desiredMemoryTypes,
69
+ include_archived: req.includeArchived,
70
+ limit: req.limit,
71
+ event_limit: req.eventLimit,
72
+ });
73
+ return {
74
+ text: formatMemoryContext(response),
75
+ response,
76
+ items: response.result.items,
77
+ memoryEvents: response.result.memory_events,
78
+ };
79
+ }
80
+ async generateShortMemory(triggerSource = TRIGGER_SOURCE_MANUAL) {
81
+ return this.client.generateShortMemory({
82
+ session_id: await this.ensureSession(),
83
+ thread_id: this.config.threadId,
84
+ trigger_source: triggerSource,
85
+ });
86
+ }
87
+ async consolidateLongMemory(triggerSource = TRIGGER_SOURCE_MANUAL) {
88
+ return this.client.consolidateLongMemory({
89
+ session_id: await this.ensureSession(),
90
+ thread_id: this.config.threadId,
91
+ trigger_source: triggerSource,
92
+ });
93
+ }
94
+ async record(eventType, actor, summary, payload, toolName) {
95
+ const sessionId = await this.ensureSession();
96
+ const result = await this.client.recordEvent({
97
+ session_id: sessionId,
98
+ external_thread_id: this.config.externalThreadId,
99
+ thread_metadata: this.config.threadMetadata,
100
+ event_id: newEventId(eventType),
101
+ event_type: eventType,
102
+ actor,
103
+ summary,
104
+ status: EVENT_STATUS_SUCCESS,
105
+ tool_name: toolName,
106
+ payload,
107
+ });
108
+ this.captureThreadId(result.thread_id);
109
+ return result;
110
+ }
111
+ captureThreadId(threadId) {
112
+ if (threadId)
113
+ this.config.threadId = threadId;
114
+ }
115
+ }
116
+ export function formatMemoryContext(response) {
117
+ const lines = [];
118
+ const used = new Set();
119
+ const groups = [
120
+ ["Policy memories", (item) => item.memory_type === MEMORY_TYPE_POLICY],
121
+ ["Procedure memories", (item) => item.memory_type === MEMORY_TYPE_PROCEDURE],
122
+ ["Preference memories", (item) => item.memory_type === MEMORY_TYPE_PREFERENCE],
123
+ ["Fact memories", (item) => item.memory_type === MEMORY_TYPE_FACT],
124
+ ["Short memories", (item) => item.kind === "short"],
125
+ ];
126
+ for (const [title, predicate] of groups) {
127
+ const selected = response.result.items.filter((item) => !used.has(item.id) && predicate(item));
128
+ if (!selected.length)
129
+ continue;
130
+ appendSection(lines, title);
131
+ for (const item of selected) {
132
+ used.add(item.id);
133
+ lines.push(formatItem(item));
134
+ }
135
+ }
136
+ const other = response.result.items.filter((item) => !used.has(item.id));
137
+ if (other.length) {
138
+ appendSection(lines, "Other memories");
139
+ lines.push(...other.map(formatItem));
140
+ }
141
+ if (response.result.memory_events.length) {
142
+ appendSection(lines, "Recent raw events");
143
+ lines.push(...response.result.memory_events.map((event) => `- [${event.event_type}/${event.actor || ""}] ${event.summary || ""}`));
144
+ }
145
+ return lines.join("\n").trim();
146
+ }
147
+ function appendSection(lines, title) {
148
+ if (lines.length)
149
+ lines.push("");
150
+ lines.push(`## ${title}`);
151
+ }
152
+ function formatItem(item) {
153
+ const markers = [];
154
+ if (item.conflict_state && item.conflict_state !== "none")
155
+ markers.push(`conflict=${item.conflict_state}`);
156
+ if (item.archived_at)
157
+ markers.push("archived");
158
+ if (item.confidence > 0 && item.confidence < 0.5)
159
+ markers.push("low_confidence");
160
+ const marker = markers.length ? ` [${markers.join(",")}]` : "";
161
+ return `- (${item.scope}/${item.memory_type} confidence=${item.confidence.toFixed(2)}${marker}) ${item.content}`;
162
+ }
163
+ function newEventId(prefix) {
164
+ return `${prefix}-${randomBytes(8).toString("hex")}`;
165
+ }
@@ -0,0 +1,25 @@
1
+ import { AgentMemoryClientConfig, CreateSessionReq, CreateSessionResp, GenerateMemoryReq, GenerateMemoryResp, ListRunsReq, MemoryQueryReq, MemoryQueryResp, RecordEventReq, RecordEventResp } from "./types.js";
2
+ export declare class AgentMemoryApiError extends Error {
3
+ statusCode: number;
4
+ traceId?: string;
5
+ responseBody: string;
6
+ constructor(statusCode: number, message: string, traceId?: string, responseBody?: string);
7
+ }
8
+ export declare class AgentMemoryClient {
9
+ private baseUrl;
10
+ private apiKey;
11
+ private apiKeyHeader;
12
+ private timeoutMs;
13
+ private maxRetries;
14
+ private fetchImpl;
15
+ constructor(config: AgentMemoryClientConfig);
16
+ createSession(req: CreateSessionReq): Promise<CreateSessionResp>;
17
+ recordEvent(req: RecordEventReq): Promise<RecordEventResp>;
18
+ queryMemories(req: MemoryQueryReq): Promise<MemoryQueryResp>;
19
+ generateShortMemory(req: GenerateMemoryReq): Promise<GenerateMemoryResp>;
20
+ consolidateLongMemory(req: GenerateMemoryReq): Promise<GenerateMemoryResp>;
21
+ listMemoryGenerationRuns(req?: ListRunsReq): Promise<Record<string, unknown>>;
22
+ getMemoryGenerationRun(id: string): Promise<Record<string, unknown>>;
23
+ private request;
24
+ private requestOnce;
25
+ }
package/dist/client.js ADDED
@@ -0,0 +1,142 @@
1
+ import { TRIGGER_SOURCE_MANUAL, } from "./types.js";
2
+ const DEFAULT_API_KEY_HEADER = "X-API-Key";
3
+ export class AgentMemoryApiError extends Error {
4
+ statusCode;
5
+ traceId;
6
+ responseBody;
7
+ constructor(statusCode, message, traceId, responseBody = "") {
8
+ super(message);
9
+ this.name = "AgentMemoryApiError";
10
+ this.statusCode = statusCode;
11
+ this.traceId = traceId;
12
+ this.responseBody = responseBody;
13
+ }
14
+ }
15
+ export class AgentMemoryClient {
16
+ baseUrl;
17
+ apiKey;
18
+ apiKeyHeader;
19
+ timeoutMs;
20
+ maxRetries;
21
+ fetchImpl;
22
+ constructor(config) {
23
+ if (!config.baseUrl)
24
+ throw new Error("baseUrl is required");
25
+ if (!config.apiKey)
26
+ throw new Error("apiKey is required");
27
+ this.baseUrl = config.baseUrl.replace(/\/+$/, "");
28
+ this.apiKey = config.apiKey;
29
+ this.apiKeyHeader = config.apiKeyHeader || DEFAULT_API_KEY_HEADER;
30
+ this.timeoutMs = config.timeoutMs || 10_000;
31
+ this.maxRetries = config.maxRetries ?? 3;
32
+ this.fetchImpl = config.fetchImpl || fetch;
33
+ }
34
+ createSession(req) {
35
+ return this.request("POST", "/v1/sessions", req);
36
+ }
37
+ recordEvent(req) {
38
+ return this.request("POST", "/v1/events", req);
39
+ }
40
+ queryMemories(req) {
41
+ return this.request("POST", "/v1/memory/query", req);
42
+ }
43
+ generateShortMemory(req) {
44
+ return this.request("POST", "/v1/memory/short/generate", normalizeGenerateReq(req));
45
+ }
46
+ consolidateLongMemory(req) {
47
+ return this.request("POST", "/v1/memory/long/consolidate", normalizeGenerateReq(req));
48
+ }
49
+ listMemoryGenerationRuns(req = {}) {
50
+ const query = new URLSearchParams();
51
+ for (const [key, value] of Object.entries(req)) {
52
+ if (value !== undefined && value !== null && value !== "")
53
+ query.set(key, String(value));
54
+ }
55
+ const suffix = query.size ? `?${query.toString()}` : "";
56
+ return this.request("GET", `/v1/memory/runs${suffix}`);
57
+ }
58
+ getMemoryGenerationRun(id) {
59
+ return this.request("GET", `/v1/memory/runs/${encodeURIComponent(id)}`);
60
+ }
61
+ async request(method, path, body) {
62
+ const payload = body === undefined ? undefined : JSON.stringify(compact(body));
63
+ let lastError;
64
+ for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
65
+ if (attempt > 0)
66
+ await sleep(retryDelay(attempt));
67
+ try {
68
+ return await this.requestOnce(method, path, payload);
69
+ }
70
+ catch (error) {
71
+ lastError = error;
72
+ if (!(error instanceof AgentMemoryApiError) || !shouldRetry(error.statusCode))
73
+ throw error;
74
+ }
75
+ }
76
+ throw lastError;
77
+ }
78
+ async requestOnce(method, path, payload) {
79
+ const controller = new AbortController();
80
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
81
+ try {
82
+ const response = await this.fetchImpl(this.baseUrl + path, {
83
+ method,
84
+ body: payload,
85
+ signal: controller.signal,
86
+ headers: {
87
+ [this.apiKeyHeader]: this.apiKey,
88
+ Accept: "application/json",
89
+ ...(payload ? { "Content-Type": "application/json" } : {}),
90
+ },
91
+ });
92
+ const raw = await response.text();
93
+ if (!response.ok) {
94
+ throw parseApiError(response.status, response.headers.get("X-Trace-Id") || undefined, raw);
95
+ }
96
+ return raw ? JSON.parse(raw) : undefined;
97
+ }
98
+ catch (error) {
99
+ if (error instanceof AgentMemoryApiError)
100
+ throw error;
101
+ throw new AgentMemoryApiError(0, error instanceof Error ? error.message : String(error));
102
+ }
103
+ finally {
104
+ clearTimeout(timeout);
105
+ }
106
+ }
107
+ }
108
+ function normalizeGenerateReq(req) {
109
+ return { ...req, trigger_source: req.trigger_source || TRIGGER_SOURCE_MANUAL };
110
+ }
111
+ function parseApiError(statusCode, traceId, raw) {
112
+ let message = raw.trim();
113
+ try {
114
+ const parsed = JSON.parse(raw);
115
+ if (parsed.error)
116
+ message = parsed.error;
117
+ }
118
+ catch {
119
+ // 保留原始响应文本作为错误信息。
120
+ }
121
+ return new AgentMemoryApiError(statusCode, message, traceId, raw);
122
+ }
123
+ function shouldRetry(statusCode) {
124
+ return statusCode === 0 || statusCode === 408 || statusCode === 429 || statusCode >= 500;
125
+ }
126
+ function retryDelay(attempt) {
127
+ const base = 100 * 2 ** Math.min(attempt - 1, 5);
128
+ return base + Math.random() * (base / 2);
129
+ }
130
+ function sleep(ms) {
131
+ return new Promise((resolve) => setTimeout(resolve, ms));
132
+ }
133
+ function compact(value) {
134
+ if (Array.isArray(value))
135
+ return value.map(compact);
136
+ if (value && typeof value === "object") {
137
+ return Object.fromEntries(Object.entries(value)
138
+ .filter(([, nested]) => nested !== undefined && nested !== null)
139
+ .map(([key, nested]) => [key, compact(nested)]));
140
+ }
141
+ return value;
142
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./adapter.js";
2
+ export * from "./client.js";
3
+ export * from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./adapter.js";
2
+ export * from "./client.js";
3
+ export * from "./types.js";
@@ -0,0 +1,141 @@
1
+ export declare const MEMORY_TYPE_TIMELINE = "timeline";
2
+ export declare const MEMORY_TYPE_TASK_WHITEBOARD = "task_whiteboard";
3
+ export declare const MEMORY_TYPE_FAILURE_DIGEST = "failure_digest";
4
+ export declare const MEMORY_TYPE_TOOL_DIGEST = "tool_digest";
5
+ export declare const MEMORY_TYPE_FACT = "fact";
6
+ export declare const MEMORY_TYPE_PREFERENCE = "preference";
7
+ export declare const MEMORY_TYPE_PROCEDURE = "procedure";
8
+ export declare const MEMORY_TYPE_POLICY = "policy";
9
+ export declare const QUERY_INTENT_EXECUTION_HELP = "execution_help";
10
+ export declare const QUERY_INTENT_BROAD_CONTEXT = "broad_context";
11
+ export declare const EVENT_ACTOR_USER = "user";
12
+ export declare const EVENT_ACTOR_ASSISTANT = "assistant";
13
+ export declare const EVENT_ACTOR_TOOL = "tool";
14
+ export declare const EVENT_ACTOR_SYSTEM = "system";
15
+ export declare const EVENT_STATUS_SUCCESS = "success";
16
+ export declare const EVENT_STATUS_ERROR = "error";
17
+ export declare const EVENT_STATUS_TIMEOUT = "timeout";
18
+ export declare const EVENT_STATUS_CANCELLED = "cancelled";
19
+ export declare const TRIGGER_SOURCE_MANUAL = "manual";
20
+ export declare const TRIGGER_SOURCE_SESSION_END = "session_end";
21
+ export declare const TRIGGER_SOURCE_THREAD_END = "thread_end";
22
+ export interface AgentMemoryClientConfig {
23
+ baseUrl: string;
24
+ apiKey: string;
25
+ apiKeyHeader?: string;
26
+ timeoutMs?: number;
27
+ maxRetries?: number;
28
+ fetchImpl?: typeof fetch;
29
+ }
30
+ export interface CreateSessionReq {
31
+ agent_instance_id: string;
32
+ external_session_id: string;
33
+ metadata?: unknown;
34
+ }
35
+ export interface CreateSessionResp {
36
+ session_id: string;
37
+ agent_instance_id: string;
38
+ external_session_id: string;
39
+ started_at: string;
40
+ }
41
+ export interface RecordEventReq {
42
+ session_id: string;
43
+ event_id: string;
44
+ event_type: string;
45
+ payload: unknown;
46
+ external_thread_id?: string;
47
+ thread_metadata?: unknown;
48
+ actor?: string;
49
+ summary?: string;
50
+ status?: string;
51
+ tool_name?: string;
52
+ error_code?: string;
53
+ retryable?: boolean;
54
+ occurred_at?: string;
55
+ }
56
+ export interface RecordEventResp {
57
+ inserted: boolean;
58
+ thread_id?: string;
59
+ }
60
+ export interface GenerateMemoryReq {
61
+ session_id: string;
62
+ thread_id?: string;
63
+ strategy_pack_key?: string;
64
+ trigger_source?: string;
65
+ hints?: unknown;
66
+ }
67
+ export interface GenerateMemoryResp {
68
+ run_ids: string[];
69
+ strategy_ids: string[];
70
+ strategy_pack_key?: string;
71
+ trigger_source: string;
72
+ status: string;
73
+ }
74
+ export interface MemoryQueryReq {
75
+ session_id: string;
76
+ query_text: string;
77
+ thread_id?: string;
78
+ query_intent?: string;
79
+ desired_memory_types?: string[];
80
+ include_archived?: boolean;
81
+ limit?: number;
82
+ event_limit?: number;
83
+ }
84
+ export interface MemoryQueryResp {
85
+ scope_policy: {
86
+ order: string[];
87
+ };
88
+ query_profile: {
89
+ intent: string;
90
+ memory_type_priority: string[];
91
+ include_archived?: boolean;
92
+ rerank_weights?: Record<string, unknown>;
93
+ };
94
+ result: {
95
+ items: MemoryItem[];
96
+ memory_events: MemoryEventItem[];
97
+ };
98
+ }
99
+ export interface MemoryItem {
100
+ id: string;
101
+ kind: string;
102
+ scope: string;
103
+ memory_type: string;
104
+ title?: string | null;
105
+ content: string;
106
+ confidence: number;
107
+ quality_score?: number;
108
+ human_verified?: boolean;
109
+ conflict_state?: string;
110
+ strategy_id?: string;
111
+ created_at?: string;
112
+ updated_at?: string | null;
113
+ archived_at?: string | null;
114
+ score?: number;
115
+ reason_tags?: string[];
116
+ }
117
+ export interface MemoryEventItem {
118
+ id: number;
119
+ agent_instance_id: string;
120
+ session_id: string;
121
+ thread_id?: string | null;
122
+ event_id: string;
123
+ event_type: string;
124
+ actor?: string;
125
+ summary?: string;
126
+ status?: string;
127
+ tool_name?: string;
128
+ error_code?: string;
129
+ retryable?: boolean | null;
130
+ payload?: unknown;
131
+ occurred_at: string;
132
+ ingested_at: string;
133
+ }
134
+ export interface ListRunsReq {
135
+ kind?: string;
136
+ status?: string;
137
+ session_id?: string;
138
+ thread_id?: string;
139
+ limit?: number;
140
+ offset?: number;
141
+ }
package/dist/types.js ADDED
@@ -0,0 +1,21 @@
1
+ export const MEMORY_TYPE_TIMELINE = "timeline";
2
+ export const MEMORY_TYPE_TASK_WHITEBOARD = "task_whiteboard";
3
+ export const MEMORY_TYPE_FAILURE_DIGEST = "failure_digest";
4
+ export const MEMORY_TYPE_TOOL_DIGEST = "tool_digest";
5
+ export const MEMORY_TYPE_FACT = "fact";
6
+ export const MEMORY_TYPE_PREFERENCE = "preference";
7
+ export const MEMORY_TYPE_PROCEDURE = "procedure";
8
+ export const MEMORY_TYPE_POLICY = "policy";
9
+ export const QUERY_INTENT_EXECUTION_HELP = "execution_help";
10
+ export const QUERY_INTENT_BROAD_CONTEXT = "broad_context";
11
+ export const EVENT_ACTOR_USER = "user";
12
+ export const EVENT_ACTOR_ASSISTANT = "assistant";
13
+ export const EVENT_ACTOR_TOOL = "tool";
14
+ export const EVENT_ACTOR_SYSTEM = "system";
15
+ export const EVENT_STATUS_SUCCESS = "success";
16
+ export const EVENT_STATUS_ERROR = "error";
17
+ export const EVENT_STATUS_TIMEOUT = "timeout";
18
+ export const EVENT_STATUS_CANCELLED = "cancelled";
19
+ export const TRIGGER_SOURCE_MANUAL = "manual";
20
+ export const TRIGGER_SOURCE_SESSION_END = "session_end";
21
+ export const TRIGGER_SOURCE_THREAD_END = "thread_end";
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@agent-dreamer/sdk",
3
+ "version": "0.0.3",
4
+ "description": "Agent Memory HTTP SDK and lightweight Agent adapter",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "README.md"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "scripts": {
16
+ "build": "tsc -p tsconfig.json",
17
+ "test": "npm run build && node --test test/*.test.mjs"
18
+ },
19
+ "keywords": [
20
+ "agent",
21
+ "memory",
22
+ "sdk"
23
+ ],
24
+ "license": "MIT",
25
+ "devDependencies": {
26
+ "@types/node": "^18.19.0",
27
+ "typescript": "^5.6.0"
28
+ }
29
+ }