@mongodb-js/agent-engine-sdk 0.11.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.
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Canonical types for the Memory Server HTTP API.
3
+ *
4
+ * Single source of truth for result shapes returned by the memory server.
5
+ * Consumed by MemoryClient and by framework SDK adapters (e.g. sdk-langgraph).
6
+ */
7
+ import { z } from "zod";
8
+ import { DateFromStringSchema } from "../../models.js";
9
+ // =============================================================================
10
+ // Result models
11
+ //
12
+ // All response schemas use `z.looseObject` so unknown fields added by the
13
+ // server are preserved on the parsed result, rather than silently dropped.
14
+ // Request/config schemas (ContextConfigSchema) use strict object semantics.
15
+ // =============================================================================
16
+ export const WriteTurnResultSchema = z.looseObject({
17
+ id: z.string(),
18
+ session_id: z.string(),
19
+ turn_seq: z.number(),
20
+ acknowledged: z.boolean(),
21
+ });
22
+ export const CreateSemanticResultSchema = z.looseObject({
23
+ id: z.string(),
24
+ label: z.string(),
25
+ has_embedding: z.boolean(),
26
+ acknowledged: z.boolean(),
27
+ });
28
+ export const BulkCreateSemanticResultSchema = z.looseObject({
29
+ created_count: z.number(),
30
+ skipped_count: z.number(),
31
+ created_ids: z.array(z.string()),
32
+ skipped_labels: z.array(z.string()),
33
+ has_embeddings: z.boolean(),
34
+ acknowledged: z.boolean(),
35
+ });
36
+ export const CreateEpisodicResultSchema = z.looseObject({
37
+ id: z.string(),
38
+ title: z.string(),
39
+ has_embedding: z.boolean(),
40
+ acknowledged: z.boolean(),
41
+ });
42
+ export const CreateTaxonomicResultSchema = z.looseObject({
43
+ id: z.string(),
44
+ domain: z.string(),
45
+ term: z.string(),
46
+ has_embedding: z.boolean(),
47
+ acknowledged: z.boolean(),
48
+ });
49
+ export const CreateProceduralResultSchema = z.looseObject({
50
+ id: z.string(),
51
+ procedure: z.string(),
52
+ has_embedding: z.boolean(),
53
+ acknowledged: z.boolean(),
54
+ });
55
+ export const CreateUserContextResultSchema = z.looseObject({
56
+ id: z.string(),
57
+ context_key: z.string(),
58
+ acknowledged: z.boolean(),
59
+ });
60
+ export const CreateSnapshotResultSchema = z.looseObject({
61
+ id: z.string(),
62
+ session_id: z.string(),
63
+ message_count: z.number(),
64
+ has_embedding: z.boolean(),
65
+ embedding_strategy: z.string().optional(),
66
+ snapshot_reason: z.string(),
67
+ acknowledged: z.boolean(),
68
+ });
69
+ export const PromoteSnapshotResultSchema = z.looseObject({
70
+ snapshot_id: z.string().optional(),
71
+ session_id: z.string(),
72
+ promoted_count: z.number(),
73
+ reason: z.string(),
74
+ has_embedding: z.boolean().default(false),
75
+ acknowledged: z.boolean(),
76
+ });
77
+ export const DeleteResultSchema = z.looseObject({
78
+ deleted_count: z.number(),
79
+ acknowledged: z.boolean(),
80
+ });
81
+ export const InternalStateResultSchema = z.looseObject({
82
+ session_id: z.string(),
83
+ version: z.number(),
84
+ token_count: z.number(),
85
+ content_hash: z.string(),
86
+ previous_version: z.number().optional(),
87
+ was_noop: z.boolean(),
88
+ acknowledged: z.boolean(),
89
+ });
90
+ export const ISGenerationResultSchema = z.looseObject({
91
+ updated: z.boolean(),
92
+ version: z.number().optional(),
93
+ token_count: z.number().optional(),
94
+ content_hash: z.string().optional(),
95
+ previous_version: z.number().optional(),
96
+ was_noop: z.boolean(),
97
+ coalesced: z.boolean(),
98
+ skipped_reason: z.string().optional(),
99
+ next_update_at: z.string().optional(),
100
+ model_id: z.string().optional(),
101
+ events_hash: z.string().optional(),
102
+ });
103
+ export const TagScalarSchema = z.union([z.string(), z.number(), z.boolean()]);
104
+ // Deliberate deviation from the module's looseObject convention: these
105
+ // custom-type schemas stay strict so the server's internal similarity ranking
106
+ // `score` never leaks into the public result shape. The trade-off is that
107
+ // future additive server fields are dropped rather than preserved.
108
+ export const CustomMemorySaveResultSchema = z.object({
109
+ id: z.string(),
110
+ type: z.string(),
111
+ tags: z.record(z.string(), TagScalarSchema),
112
+ has_embedding: z.boolean(),
113
+ });
114
+ export const RetrievedCustomMemorySchema = z.object({
115
+ id: z.string(),
116
+ type: z.string(),
117
+ content: z.string(),
118
+ tags: z.record(z.string(), TagScalarSchema),
119
+ contextual_metadata: z.record(z.string(), z.unknown()).nullish(),
120
+ user_id: z.string().nullish(),
121
+ agent_id: z.string().nullish(),
122
+ });
123
+ export const CustomMemoryRetrieveResultSchema = z.object({
124
+ results: z.array(RetrievedCustomMemorySchema),
125
+ count: z.number(),
126
+ });
127
+ // =============================================================================
128
+ // Retrieval enums
129
+ // =============================================================================
130
+ export const MemorySourceSchema = z.enum([
131
+ "stm",
132
+ "episodic",
133
+ "semantic",
134
+ "taxonomic",
135
+ "procedural",
136
+ ]);
137
+ export const MemorySource = {
138
+ STM: "stm",
139
+ EPISODIC: "episodic",
140
+ SEMANTIC: "semantic",
141
+ TAXONOMIC: "taxonomic",
142
+ PROCEDURAL: "procedural",
143
+ };
144
+ export const FormatStyleSchema = z.enum(["openai", "claude", "jinja2"]);
145
+ export const FormatStyle = {
146
+ OPENAI: "openai",
147
+ CLAUDE: "claude",
148
+ JINJA2: "jinja2",
149
+ };
150
+ export const ModelTypeSchema = z.enum([
151
+ "openai",
152
+ "claude",
153
+ "anthropic",
154
+ "gemini",
155
+ "generic",
156
+ ]);
157
+ export const ModelType = {
158
+ OPENAI: "openai",
159
+ CLAUDE: "claude",
160
+ ANTHROPIC: "anthropic",
161
+ GEMINI: "gemini",
162
+ GENERIC: "generic",
163
+ };
164
+ // =============================================================================
165
+ // Retrieval models
166
+ // =============================================================================
167
+ /** Unified representation of a retrieved memory chunk across all memory types. */
168
+ export const MemoryChunkSchema = z.looseObject({
169
+ id: z.string(),
170
+ content: z.string(),
171
+ source: MemorySourceSchema,
172
+ timestamp: DateFromStringSchema,
173
+ embedding: z.array(z.number()).optional(),
174
+ similarity_score: z.number().optional(),
175
+ metadata: z.record(z.string(), z.unknown()).optional(),
176
+ });
177
+ const lowerCaseStrings = (v) => typeof v === "string" ? v.toLowerCase() : v;
178
+ const dedupSources = (arr) => Array.from(new Set(arr));
179
+ /** Configuration for context building requests. */
180
+ export const ContextConfigSchema = z
181
+ .object({
182
+ max_tokens: z.number().int().min(1).default(16000),
183
+ token_buffer: z.number().int().min(0).default(500),
184
+ format_style: z
185
+ .preprocess(lowerCaseStrings, FormatStyleSchema)
186
+ .default(FormatStyle.OPENAI),
187
+ model_type: z
188
+ .preprocess(lowerCaseStrings, ModelTypeSchema)
189
+ .default(ModelType.OPENAI),
190
+ similarity_threshold: z.number().min(0).max(1).default(0),
191
+ ranking_weights: z.record(z.string(), z.number()).default({}),
192
+ enabled_sources: z
193
+ .array(MemorySourceSchema)
194
+ .transform(dedupSources)
195
+ .default([MemorySource.EPISODIC, MemorySource.SEMANTIC]),
196
+ include_memories: z.boolean().default(false),
197
+ })
198
+ .refine((data) => data.enabled_sources.length > 0, {
199
+ message: "enabled_sources cannot be empty",
200
+ path: ["enabled_sources"],
201
+ });
202
+ /** Metadata about a context build response (token counts, per-source counts, timing). */
203
+ export const ContextMetadataSchema = z.looseObject({
204
+ token_count: z.number().int().min(0).default(0),
205
+ memory_counts: z.record(z.string(), z.number()).default({}),
206
+ timing: z.record(z.string(), z.number()).default({}),
207
+ });
208
+ /** Response from a context build request containing formatted context and retrieval metadata. */
209
+ export const ContextResponseSchema = z.looseObject({
210
+ formatted_context: z.union([
211
+ z.string(),
212
+ z.array(z.record(z.string(), z.unknown())),
213
+ ]),
214
+ metadata: ContextMetadataSchema,
215
+ // Mirrors Python `list[MemoryChunk] | None` (default None): the server sends
216
+ // `null` when include_memories=False (the only path any caller uses), so accept
217
+ // null as well as undefined/array.
218
+ selected_memories: z.array(MemoryChunkSchema).nullish(),
219
+ });
package/dist/app.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /** Base application class for framework-specific SDK integrations. */
2
+ import type { ToolDefinition } from "./models.js";
3
+ /**
4
+ * Abstract base class for framework-specific SDK integrations.
5
+ *
6
+ * Each framework SDK (LangGraph, CrewAI, etc.) subclasses `BaseApp`
7
+ * and implements the abstract methods using framework-native constructs.
8
+ *
9
+ * The platform runtime sets `toolWrapper` and `llmWrapper` on the
10
+ * instance before calling `entrypoint()` so that tools and LLMs are
11
+ * routed through the secure execution layer.
12
+ */
13
+ export declare abstract class BaseApp {
14
+ readonly name: string;
15
+ toolWrapper: unknown;
16
+ llmWrapper: unknown;
17
+ constructor(name: string);
18
+ /** Returns all registered tool definitions. Used by the OE to obtain tool execution information. */
19
+ abstract getToolDefinitions(): ToolDefinition[];
20
+ /** Returns a list of wrapped, framework-specific tools. */
21
+ abstract tools(): unknown[];
22
+ /** Decorator that registers a tool on this app. */
23
+ abstract tool(...args: unknown[]): unknown;
24
+ /** Decorator that registers the agent builder function. Called by runtimes to obtain a BaseAgent. */
25
+ abstract entrypoint(fn: unknown): unknown;
26
+ }
27
+ //# sourceMappingURL=app.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAElD;;;;;;;;;GASG;AACH,8BAAsB,OAAO;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,OAAO,CAAQ;IAC5B,UAAU,EAAE,OAAO,CAAQ;gBAEf,IAAI,EAAE,MAAM;IAIxB,oGAAoG;IACpG,QAAQ,CAAC,kBAAkB,IAAI,cAAc,EAAE;IAE/C,2DAA2D;IAC3D,QAAQ,CAAC,KAAK,IAAI,OAAO,EAAE;IAE3B,mDAAmD;IACnD,QAAQ,CAAC,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO;IAE1C,qGAAqG;IACrG,QAAQ,CAAC,UAAU,CAAC,EAAE,EAAE,OAAO,GAAG,OAAO;CAC1C"}
package/dist/app.js ADDED
@@ -0,0 +1,19 @@
1
+ /** Base application class for framework-specific SDK integrations. */
2
+ /**
3
+ * Abstract base class for framework-specific SDK integrations.
4
+ *
5
+ * Each framework SDK (LangGraph, CrewAI, etc.) subclasses `BaseApp`
6
+ * and implements the abstract methods using framework-native constructs.
7
+ *
8
+ * The platform runtime sets `toolWrapper` and `llmWrapper` on the
9
+ * instance before calling `entrypoint()` so that tools and LLMs are
10
+ * routed through the secure execution layer.
11
+ */
12
+ export class BaseApp {
13
+ name;
14
+ toolWrapper = null;
15
+ llmWrapper = null;
16
+ constructor(name) {
17
+ this.name = name;
18
+ }
19
+ }
@@ -0,0 +1,11 @@
1
+ /** HTTP client for the platform event API. */
2
+ import type { BranchRef, Event } from "../models.js";
3
+ export declare class EventClient {
4
+ private readonly oeUrl;
5
+ private readonly timeout;
6
+ constructor(oeUrl: string, timeout?: number);
7
+ appendEvent(sessionId: string, actorId: string, payload: Record<string, unknown>, parentEventId?: string, metadata?: Record<string, unknown>, branch?: BranchRef): Promise<Event>;
8
+ listEvents(sessionId: string, branch?: string, metadataFilters?: Record<string, string>): Promise<Event[]>;
9
+ getEvent(sessionId: string, eventId: string): Promise<Event | null>;
10
+ }
11
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/clients/events.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAE9C,OAAO,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAgBrD,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;gBAErB,KAAK,EAAE,MAAM,EAAE,OAAO,SAAK;IAKjC,WAAW,CACf,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,aAAa,CAAC,EAAE,MAAM,EACtB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,MAAM,CAAC,EAAE,SAAS,GACjB,OAAO,CAAC,KAAK,CAAC;IAmBX,UAAU,CACd,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACvC,OAAO,CAAC,KAAK,EAAE,CAAC;IAmBb,QAAQ,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC;CAW1E"}
@@ -0,0 +1,67 @@
1
+ /** HTTP client for the platform event API. */
2
+ import { EventResponseSchema, EventsResponseSchema } from "../api/events.js";
3
+ /**
4
+ * Percent-encode an id for use as a single URL path segment, refusing bare
5
+ * dot segments: encodeURIComponent leaves '.'/'..' untouched, and the URL
6
+ * parser would collapse them into a parent-path rewrite of this authenticated
7
+ * request.
8
+ */
9
+ function encodeIdSegment(id) {
10
+ if (id === "." || id === "..") {
11
+ throw new Error(`Invalid id: bare dot segment ${JSON.stringify(id)}`);
12
+ }
13
+ return encodeURIComponent(id);
14
+ }
15
+ export class EventClient {
16
+ oeUrl;
17
+ timeout;
18
+ constructor(oeUrl, timeout = 30) {
19
+ this.oeUrl = oeUrl.replace(/\/$/, "");
20
+ this.timeout = timeout;
21
+ }
22
+ async appendEvent(sessionId, actorId, payload, parentEventId, metadata, branch) {
23
+ const body = { actor_id: actorId, payload };
24
+ if (parentEventId !== undefined)
25
+ body["parent_event_id"] = parentEventId;
26
+ if (metadata !== undefined)
27
+ body["metadata"] = metadata;
28
+ if (branch !== undefined)
29
+ body["branch"] = branch;
30
+ const resp = await fetch(`${this.oeUrl}/v1/sessions/${encodeIdSegment(sessionId)}/events`, {
31
+ method: "POST",
32
+ headers: { "Content-Type": "application/json" },
33
+ body: JSON.stringify(body),
34
+ signal: AbortSignal.timeout(this.timeout * 1000),
35
+ });
36
+ if (!resp.ok)
37
+ throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
38
+ return EventResponseSchema.parse(await resp.json()).event;
39
+ }
40
+ async listEvents(sessionId, branch, metadataFilters) {
41
+ const params = new URLSearchParams();
42
+ if (branch !== undefined)
43
+ params.set("branch", branch);
44
+ if (metadataFilters !== undefined) {
45
+ for (const [key, val] of Object.entries(metadataFilters)) {
46
+ params.set(`metadata.${key}`, val);
47
+ }
48
+ }
49
+ const qs = params.size > 0 ? `?${params.toString()}` : "";
50
+ const resp = await fetch(`${this.oeUrl}/v1/sessions/${encodeIdSegment(sessionId)}/events${qs}`, {
51
+ signal: AbortSignal.timeout(this.timeout * 1000),
52
+ });
53
+ if (!resp.ok)
54
+ throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
55
+ return EventsResponseSchema.parse(await resp.json()).events;
56
+ }
57
+ async getEvent(sessionId, eventId) {
58
+ const resp = await fetch(`${this.oeUrl}/v1/sessions/${encodeIdSegment(sessionId)}/events/${encodeIdSegment(eventId)}`, {
59
+ signal: AbortSignal.timeout(this.timeout * 1000),
60
+ });
61
+ if (resp.status === 404)
62
+ return null;
63
+ if (!resp.ok)
64
+ throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
65
+ return EventResponseSchema.parse(await resp.json()).event;
66
+ }
67
+ }