@nirmos/sdk 0.3.1 → 0.3.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.
Files changed (91) hide show
  1. package/README.md +264 -16
  2. package/dist/cjs/client.js +1 -9
  3. package/dist/cjs/client.js.map +1 -1
  4. package/dist/cjs/core/transport.js +16 -3
  5. package/dist/cjs/core/transport.js.map +1 -1
  6. package/dist/cjs/core/version.js +6 -0
  7. package/dist/cjs/core/version.js.map +1 -0
  8. package/dist/cjs/gateway/chat-stream.js +10 -0
  9. package/dist/cjs/gateway/chat-stream.js.map +1 -1
  10. package/dist/cjs/gateway/chat.js +1 -0
  11. package/dist/cjs/gateway/chat.js.map +1 -1
  12. package/dist/cjs/gateway/embeddings.js +1 -0
  13. package/dist/cjs/gateway/embeddings.js.map +1 -1
  14. package/dist/cjs/gateway/mappers.js +39 -2
  15. package/dist/cjs/gateway/mappers.js.map +1 -1
  16. package/dist/cjs/index.js +8 -1
  17. package/dist/cjs/index.js.map +1 -1
  18. package/dist/cjs/management/manifest.js +16 -0
  19. package/dist/cjs/management/manifest.js.map +1 -1
  20. package/dist/cjs/management/resources.js +3 -1
  21. package/dist/cjs/management/resources.js.map +1 -1
  22. package/dist/cjs/prompts/render.js +12 -4
  23. package/dist/cjs/prompts/render.js.map +1 -1
  24. package/dist/cjs/prompts/variables.js +117 -0
  25. package/dist/cjs/prompts/variables.js.map +1 -0
  26. package/dist/esm/client.d.ts +6 -20
  27. package/dist/esm/client.d.ts.map +1 -1
  28. package/dist/esm/client.js +1 -9
  29. package/dist/esm/client.js.map +1 -1
  30. package/dist/esm/core/transport.js +15 -2
  31. package/dist/esm/core/transport.js.map +1 -1
  32. package/dist/esm/core/version.d.ts +2 -0
  33. package/dist/esm/core/version.d.ts.map +1 -0
  34. package/dist/esm/core/version.js +3 -0
  35. package/dist/esm/core/version.js.map +1 -0
  36. package/dist/esm/gateway/chat-stream.d.ts.map +1 -1
  37. package/dist/esm/gateway/chat-stream.js +11 -1
  38. package/dist/esm/gateway/chat-stream.js.map +1 -1
  39. package/dist/esm/gateway/chat.d.ts.map +1 -1
  40. package/dist/esm/gateway/chat.js +1 -0
  41. package/dist/esm/gateway/chat.js.map +1 -1
  42. package/dist/esm/gateway/embeddings.d.ts.map +1 -1
  43. package/dist/esm/gateway/embeddings.js +1 -0
  44. package/dist/esm/gateway/embeddings.js.map +1 -1
  45. package/dist/esm/gateway/mappers.d.ts +2 -0
  46. package/dist/esm/gateway/mappers.d.ts.map +1 -1
  47. package/dist/esm/gateway/mappers.js +38 -2
  48. package/dist/esm/gateway/mappers.js.map +1 -1
  49. package/dist/esm/gateway/types.d.ts +8 -0
  50. package/dist/esm/gateway/types.d.ts.map +1 -1
  51. package/dist/esm/index.d.ts +2 -1
  52. package/dist/esm/index.d.ts.map +1 -1
  53. package/dist/esm/index.js +1 -0
  54. package/dist/esm/index.js.map +1 -1
  55. package/dist/esm/management/contracts.d.ts +18194 -6741
  56. package/dist/esm/management/contracts.d.ts.map +1 -1
  57. package/dist/esm/management/manifest.d.ts +14 -0
  58. package/dist/esm/management/manifest.d.ts.map +1 -1
  59. package/dist/esm/management/manifest.js +16 -0
  60. package/dist/esm/management/manifest.js.map +1 -1
  61. package/dist/esm/management/resources.d.ts +2 -0
  62. package/dist/esm/management/resources.d.ts.map +1 -1
  63. package/dist/esm/management/resources.js +3 -1
  64. package/dist/esm/management/resources.js.map +1 -1
  65. package/dist/esm/memory/types.d.ts +14 -5
  66. package/dist/esm/memory/types.d.ts.map +1 -1
  67. package/dist/esm/prompts/render.js +11 -3
  68. package/dist/esm/prompts/render.js.map +1 -1
  69. package/dist/esm/prompts/variables.d.ts +29 -0
  70. package/dist/esm/prompts/variables.d.ts.map +1 -0
  71. package/dist/esm/prompts/variables.js +108 -0
  72. package/dist/esm/prompts/variables.js.map +1 -0
  73. package/examples/memory-quickstart.mjs +199 -0
  74. package/examples/memory-quickstart.ts +240 -0
  75. package/examples/tsconfig.json +5 -0
  76. package/package.json +5 -4
  77. package/src/client.ts +10 -30
  78. package/src/core/transport.ts +14 -2
  79. package/src/core/version.ts +2 -0
  80. package/src/gateway/chat-stream.ts +12 -1
  81. package/src/gateway/chat.ts +1 -0
  82. package/src/gateway/embeddings.ts +1 -0
  83. package/src/gateway/mappers.ts +55 -2
  84. package/src/gateway/types.ts +8 -0
  85. package/src/index.ts +13 -0
  86. package/src/management/contracts.ts +226 -131
  87. package/src/management/manifest.ts +16 -0
  88. package/src/management/resources.ts +3 -1
  89. package/src/memory/types.ts +15 -4
  90. package/src/prompts/render.ts +9 -4
  91. package/src/prompts/variables.ts +156 -0
@@ -0,0 +1,108 @@
1
+ /** Shared placeholder semantics for managed prompts, the dashboard and execution. */
2
+ export const PROMPT_VARIABLE_PATTERN = /\{\{\s*([a-zA-Z][a-zA-Z0-9_.-]*)\s*\}\}/g;
3
+ export function extractPromptVariableNames(...values) {
4
+ return [
5
+ ...new Set(values.flatMap((value) => [...(value ?? "").matchAll(PROMPT_VARIABLE_PATTERN)].map((match) => match[1]))),
6
+ ];
7
+ }
8
+ export function promptVariableValue(values, name) {
9
+ if (Object.hasOwn(values, name))
10
+ return values[name];
11
+ let current = values;
12
+ for (const key of name.split(".")) {
13
+ if (["__proto__", "prototype", "constructor"].includes(key) ||
14
+ !current ||
15
+ typeof current !== "object" ||
16
+ !Object.hasOwn(current, key))
17
+ return undefined;
18
+ current = current[key];
19
+ }
20
+ return current;
21
+ }
22
+ export function interpolatePromptVariables(text, values) {
23
+ return text.replace(PROMPT_VARIABLE_PATTERN, (token, name) => {
24
+ const value = promptVariableValue(values, name);
25
+ return value === undefined
26
+ ? token
27
+ : typeof value === "string"
28
+ ? value
29
+ : JSON.stringify(value);
30
+ });
31
+ }
32
+ export function validatePromptTemplate(text) {
33
+ const remaining = text.replace(PROMPT_VARIABLE_PATTERN, "");
34
+ return /\{\{|\{%/.test(remaining)
35
+ ? [
36
+ "Unsupported variable syntax. Use {{name}}, {{ spaced }}, or {{user.name}}. Expressions, filters and template blocks cannot run as managed prompt variables.",
37
+ ]
38
+ : [];
39
+ }
40
+ export function validatePromptVariableValues(definitions, values) {
41
+ const errors = {};
42
+ for (const definition of definitions) {
43
+ const supplied = promptVariableValue(values, definition.name);
44
+ const value = supplied === undefined ? definition.default : supplied;
45
+ let error = "";
46
+ if (value === undefined || value === "") {
47
+ if (definition.required)
48
+ error = "A value is required.";
49
+ }
50
+ else {
51
+ const type = definition.type;
52
+ if (type === "number" &&
53
+ (typeof value !== "number" || !Number.isFinite(value)))
54
+ error = "Enter a valid number.";
55
+ if (type === "boolean" && typeof value !== "boolean")
56
+ error = "Choose true or false.";
57
+ if (type === "string" && typeof value !== "string")
58
+ error = "Enter text.";
59
+ if (type === "enum" &&
60
+ !(definition.enum ?? definition.values)?.includes(String(value)))
61
+ error = "Choose one of the allowed values.";
62
+ if (type === "array" && !Array.isArray(value))
63
+ error = "Enter a valid array.";
64
+ if (typeof value === "number" &&
65
+ ((definition.min !== undefined && value < definition.min) ||
66
+ (definition.max !== undefined && value > definition.max)))
67
+ error = `Enter a number between ${definition.min ?? "−∞"} and ${definition.max ?? "∞"}.`;
68
+ const minLength = definition.minLength ?? definition.min_length;
69
+ const maxLength = definition.maxLength ?? definition.max_length;
70
+ if (typeof value === "string" &&
71
+ ((minLength !== undefined && value.length < minLength) ||
72
+ (maxLength !== undefined && value.length > maxLength)))
73
+ error = `Use ${minLength ?? 0} to ${maxLength ?? "any number of"} characters.`;
74
+ const itemType = definition.itemType ?? definition.item_type;
75
+ if (Array.isArray(value) &&
76
+ itemType &&
77
+ value.some((item) => itemType === "array"
78
+ ? !Array.isArray(item)
79
+ : itemType !== "enum" && typeof item !== itemType))
80
+ error = `Every item must be ${itemType}.`;
81
+ }
82
+ if (error)
83
+ errors[definition.name] = error;
84
+ }
85
+ return errors;
86
+ }
87
+ export function validatePromptSettings(settings) {
88
+ const errors = {};
89
+ for (const [field, label, min, max] of [
90
+ ["temperature", "Temperature", 0, 2],
91
+ ["topP", "Top P", 0, 1],
92
+ ["maxTokens", "Max tokens", 1, 200000],
93
+ ]) {
94
+ const raw = settings[field];
95
+ const value = Number(raw);
96
+ if (raw === "" ||
97
+ raw === null ||
98
+ raw === undefined ||
99
+ !Number.isFinite(value) ||
100
+ value < min ||
101
+ value > max ||
102
+ (field === "maxTokens" && !Number.isInteger(value)))
103
+ errors[field] =
104
+ `${label} must be ${field === "maxTokens" ? "a whole number" : "a number"} between ${min} and ${max}.`;
105
+ }
106
+ return errors;
107
+ }
108
+ //# sourceMappingURL=variables.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"variables.js","sourceRoot":"","sources":["../../../src/prompts/variables.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,MAAM,CAAC,MAAM,uBAAuB,GAClC,0CAA0C,CAAC;AAC7C,MAAM,UAAU,0BAA0B,CACxC,GAAG,MAAwC;IAE3C,OAAO;QACL,GAAG,IAAI,GAAG,CACR,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CACvB,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,uBAAuB,CAAC,CAAC,CAAC,GAAG,CACtD,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAE,CACrB,CACF,CACF;KACF,CAAC;AACJ,CAAC;AACD,MAAM,UAAU,mBAAmB,CACjC,MAA+B,EAC/B,IAAY;IAEZ,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC;QAAE,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC;IACrD,IAAI,OAAO,GAAY,MAAM,CAAC;IAC9B,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QAClC,IACE,CAAC,WAAW,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC;YACvD,CAAC,OAAO;YACR,OAAO,OAAO,KAAK,QAAQ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C9B,EAAE,CAAC;QACX,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;QAC5B,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1B,IACE,GAAG,KAAK,EAAE;YACV,GAAG,KAAK,IAAI;YACZ,GAAG,KAAK,SAAS;YACjB,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;YACvB,KAAK,GAAG,GAAG;YACX,KAAK,GAAG,GAAG;YACX,CAAC,KAAK,KAAK,WAAW,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;YAEnD,MAAM,CAAC,KAAK,CAAC;gBACX,GAAG,KAAK,YAAY,KAAK,KAAK,WAAW,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,UAAU,YAAY,GAAG,QAAQ,GAAG,GAAG,CAAC;IAC7G,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,199 @@
1
+ // Generated from memory-quickstart.ts. Do not edit.
2
+ import { APIError, Nirmos, } from "@nirmos/sdk";
3
+ async function all(load) {
4
+ const items = [];
5
+ let cursor;
6
+ do {
7
+ const page = await load(cursor);
8
+ items.push(...page.items);
9
+ cursor = page.nextCursor ?? undefined;
10
+ } while (cursor);
11
+ return items;
12
+ }
13
+ /** Server-side only. Persist eventKey with the source event before first ingestion. */
14
+ export async function memoryQuickstart(client, options) {
15
+ const pause = () => new Promise((resolve) => setTimeout(resolve, options.paceMs ?? 20000));
16
+ const provider = (await all((cursor) => client.providers.list({ cursor, limit: 100 }))).find((p) => p.slug === "google");
17
+ if (!provider)
18
+ throw new Error("Google provider missing from this deployment's catalog.");
19
+ // Optional SDK setup; dashboard Gateway Credentials → Add credential → Google is equivalent.
20
+ if (options.googleApiKey)
21
+ await client.providerCredentials.create({
22
+ name: "Memory quickstart Google",
23
+ providerId: provider.id,
24
+ credentialType: "api_key",
25
+ secretData: { apiKey: options.googleApiKey },
26
+ isDefault: true,
27
+ });
28
+ const models = await all((cursor) => client.models.list({ providerId: provider.id, limit: 100, cursor }));
29
+ const text = models.find((m) => m.slug === "google-gemini-2-5-flash-lite" && m.availability);
30
+ const embedding = models.find((m) => m.slug === "google-gemini-embedding-001" && m.availability);
31
+ if (!text || !embedding)
32
+ throw new Error("Configure an active Google credential and verify both models in models.list(). Availability does not guarantee provider quota.");
33
+ if (!embedding.knowledgeSupportedDimensions?.includes(768))
34
+ throw new Error("Selected embedding model does not support 768 dimensions in this deployment.");
35
+ const textModel = `${provider.slug}/${text.id}`;
36
+ const policyInput = {
37
+ policyKey: `${options.eventKey}-policy`,
38
+ name: "Memory quickstart",
39
+ version: 1,
40
+ status: "active",
41
+ captureTypes: [
42
+ "preference",
43
+ "fact",
44
+ "project_fact",
45
+ "decision",
46
+ "constraint",
47
+ "commitment",
48
+ "event",
49
+ "temporary_state",
50
+ ],
51
+ allowInferredMemories: false,
52
+ minimumConfidence: 0.7,
53
+ minimumFutureUtility: 0.5,
54
+ defaultMemoryTTLSeconds: 86400,
55
+ extractionConfig: {
56
+ model: textModel,
57
+ reconciliationModel: textModel,
58
+ profileModel: textModel,
59
+ observationModel: textModel,
60
+ indexing: {
61
+ model: `${provider.slug}/${embedding.id}`,
62
+ dimensions: 768,
63
+ distanceMetric: "cosine",
64
+ },
65
+ },
66
+ privacyConfig: {
67
+ allowPII: false,
68
+ allowedSensitivities: ["unclassified", "public", "internal"],
69
+ },
70
+ retentionConfig: {
71
+ episodeContent: "full",
72
+ evidenceExcerpts: true,
73
+ candidateContent: false,
74
+ },
75
+ };
76
+ const existing = await client.memory.policies.list({
77
+ policyKey: policyInput.policyKey,
78
+ limit: 100,
79
+ });
80
+ const policy = existing.items.find((p) => p.version === 1) ??
81
+ (await client.memory.policies.create(policyInput));
82
+ const spaceKey = `${options.eventKey}/customer-123`;
83
+ const spaces = await all((cursor) => client.memory.spaces.list({
84
+ externalSubjectId: "customer-123",
85
+ cursor,
86
+ limit: 100,
87
+ }));
88
+ const space = spaces.find((s) => s.spaceKey === spaceKey) ??
89
+ (await client.memory.spaces.create({
90
+ spaceKey,
91
+ name: "Disposable customer memory",
92
+ scopeType: "user",
93
+ scopeId: "customer-123",
94
+ externalSubjectId: "customer-123",
95
+ policyId: policy.id,
96
+ }));
97
+ const input = {
98
+ memorySpaceId: space.id,
99
+ conversationId: options.eventKey,
100
+ idempotencyKey: options.eventKey,
101
+ messages: [
102
+ {
103
+ id: `${options.eventKey}-message`,
104
+ role: "user",
105
+ content: "I prefer important notifications through email rather than WhatsApp.",
106
+ },
107
+ ],
108
+ };
109
+ let result;
110
+ try {
111
+ result = await client.memory.ingest(input, {
112
+ idempotencyKey: options.eventKey,
113
+ maxRetries: 0,
114
+ });
115
+ }
116
+ catch (error) {
117
+ if (error instanceof APIError) {
118
+ // Safe identifiers/categories only; never print secrets, prompts or memory content.
119
+ console.error({
120
+ code: error.code,
121
+ status: error.status,
122
+ retryable: error.retryable,
123
+ retryAfterMs: error.retryAfterMs,
124
+ requestId: error.requestId,
125
+ diagnostics: error.details,
126
+ });
127
+ }
128
+ // After correcting configuration/quota, call ingest(input) with the SAME event identity.
129
+ // Do not blindly retry, mutate the input, or generate a fresh key.
130
+ throw error;
131
+ }
132
+ console.log({
133
+ runId: result.memoryRunId,
134
+ accepted: result.acceptedCount,
135
+ rejected: result.rejectedCount,
136
+ indexing: result.indexing,
137
+ });
138
+ const run = await client.memory.runs.get(result.memoryRunId);
139
+ if (result.indexing.failed)
140
+ throw new Error(`Indexing incomplete for run ${run.id}; inspect diagnostics and repair through memory.reindex().`);
141
+ // A completed event replays without model execution or another memory write.
142
+ const replay = await client.memory.ingest(input, {
143
+ idempotencyKey: options.eventKey,
144
+ maxRetries: 0,
145
+ });
146
+ if (replay.memoryRunId !== result.memoryRunId || !replay.replayed)
147
+ throw new Error("Expected the original completed event to replay.");
148
+ console.log({ replayed: replay.replayed, runId: replay.memoryRunId });
149
+ await pause();
150
+ const search = await client.memory.search({
151
+ memorySpaceId: space.id,
152
+ query: "How should I send important notifications?",
153
+ relevance: "relevant",
154
+ });
155
+ console.log({ relevantMatches: search.memories.length });
156
+ await pause();
157
+ const context = await client.memory.context({
158
+ memorySpaceId: space.id,
159
+ messages: [{ role: "user", content: "How should you notify me?" }],
160
+ });
161
+ console.log({ contextMemories: context.memories.length });
162
+ await pause();
163
+ await client.memory.profiles.generate({ memorySpaceId: space.id });
164
+ const profile = await client.memory.profiles.get(space.id);
165
+ const items = await client.memory.items.list({
166
+ memorySpaceId: space.id,
167
+ limit: 25,
168
+ });
169
+ const first = items.items[0];
170
+ if (first) {
171
+ await client.memory.items.update(first.id, { importance: 0.8 });
172
+ await client.memory.items.evidence(first.id, { limit: 25 });
173
+ // Explicit cleanup only for this disposable example's space.
174
+ if (options.cleanup)
175
+ await client.memory.items.delete(first.id);
176
+ }
177
+ if (options.cleanup) {
178
+ await client.memory.spaces.delete(space.id);
179
+ await client.memory.erase(space.id);
180
+ await client.memory.policies.delete(policy.id);
181
+ }
182
+ return { space, policy, result, search, context, profile };
183
+ }
184
+ if (process.env.NIRMOS_RUN_MEMORY_EXAMPLE === "1") {
185
+ const token = process.env.NIRMOS_API_KEY;
186
+ const eventKey = process.env.MEMORY_EVENT_KEY;
187
+ if (!token || !eventKey)
188
+ throw new Error("Set NIRMOS_API_KEY and a persisted MEMORY_EVENT_KEY.");
189
+ await memoryQuickstart(new Nirmos({
190
+ auth: { type: "api-key", key: token },
191
+ apiBaseUrl: process.env.NIRMOS_API_BASE_URL ?? "http://localhost:4001",
192
+ runtimeBaseUrl: process.env.NIRMOS_RUNTIME_BASE_URL ?? "http://localhost:4000",
193
+ maxRetries: 0,
194
+ }), {
195
+ eventKey,
196
+ googleApiKey: process.env.GOOGLE_API_KEY,
197
+ cleanup: process.env.MEMORY_CLEANUP === "1",
198
+ });
199
+ }
@@ -0,0 +1,240 @@
1
+ import {
2
+ APIError,
3
+ Nirmos,
4
+ type MemoryIngestRequest,
5
+ type MemoryPolicyCreate,
6
+ } from "@nirmos/sdk";
7
+
8
+ declare const process: { env: Record<string, string | undefined> };
9
+
10
+ async function all<T>(
11
+ load: (cursor?: string) => Promise<{ items: T[]; nextCursor: string | null }>,
12
+ ): Promise<T[]> {
13
+ const items: T[] = [];
14
+ let cursor: string | undefined;
15
+ do {
16
+ const page = await load(cursor);
17
+ items.push(...page.items);
18
+ cursor = page.nextCursor ?? undefined;
19
+ } while (cursor);
20
+ return items;
21
+ }
22
+
23
+ /** Server-side only. Persist eventKey with the source event before first ingestion. */
24
+ export async function memoryQuickstart(
25
+ client: Nirmos,
26
+ options: {
27
+ eventKey: string;
28
+ googleApiKey?: string;
29
+ cleanup?: boolean;
30
+ paceMs?: number;
31
+ },
32
+ ) {
33
+ const pause = () =>
34
+ new Promise((resolve) => setTimeout(resolve, options.paceMs ?? 20000));
35
+ const provider = (
36
+ await all((cursor) => client.providers.list({ cursor, limit: 100 }))
37
+ ).find((p) => p.slug === "google");
38
+ if (!provider)
39
+ throw new Error("Google provider missing from this deployment's catalog.");
40
+ // Optional SDK setup; dashboard Gateway Credentials → Add credential → Google is equivalent.
41
+ if (options.googleApiKey)
42
+ await client.providerCredentials.create({
43
+ name: "Memory quickstart Google",
44
+ providerId: provider.id,
45
+ credentialType: "api_key",
46
+ secretData: { apiKey: options.googleApiKey },
47
+ isDefault: true,
48
+ });
49
+ const models = await all((cursor) =>
50
+ client.models.list({ providerId: provider.id, limit: 100, cursor }),
51
+ );
52
+ const text = models.find(
53
+ (m) => m.slug === "google-gemini-2-5-flash-lite" && m.availability,
54
+ );
55
+ const embedding = models.find(
56
+ (m) => m.slug === "google-gemini-embedding-001" && m.availability,
57
+ );
58
+ if (!text || !embedding)
59
+ throw new Error(
60
+ "Configure an active Google credential and verify both models in models.list(). Availability does not guarantee provider quota.",
61
+ );
62
+ if (!embedding.knowledgeSupportedDimensions?.includes(768))
63
+ throw new Error(
64
+ "Selected embedding model does not support 768 dimensions in this deployment.",
65
+ );
66
+ const textModel = `${provider.slug}/${text.id}`;
67
+ const policyInput: MemoryPolicyCreate = {
68
+ policyKey: `${options.eventKey}-policy`,
69
+ name: "Memory quickstart",
70
+ version: 1,
71
+ status: "active",
72
+ captureTypes: [
73
+ "preference",
74
+ "fact",
75
+ "project_fact",
76
+ "decision",
77
+ "constraint",
78
+ "commitment",
79
+ "event",
80
+ "temporary_state",
81
+ ],
82
+ allowInferredMemories: false,
83
+ minimumConfidence: 0.7,
84
+ minimumFutureUtility: 0.5,
85
+ defaultMemoryTTLSeconds: 86400,
86
+ extractionConfig: {
87
+ model: textModel,
88
+ reconciliationModel: textModel,
89
+ profileModel: textModel,
90
+ observationModel: textModel,
91
+ indexing: {
92
+ model: `${provider.slug}/${embedding.id}`,
93
+ dimensions: 768,
94
+ distanceMetric: "cosine",
95
+ },
96
+ },
97
+ privacyConfig: {
98
+ allowPII: false,
99
+ allowedSensitivities: ["unclassified", "public", "internal"],
100
+ },
101
+ retentionConfig: {
102
+ episodeContent: "full",
103
+ evidenceExcerpts: true,
104
+ candidateContent: false,
105
+ },
106
+ };
107
+ const existing = await client.memory.policies.list({
108
+ policyKey: policyInput.policyKey,
109
+ limit: 100,
110
+ });
111
+ const policy =
112
+ existing.items.find((p) => p.version === 1) ??
113
+ (await client.memory.policies.create(policyInput));
114
+ const spaceKey = `${options.eventKey}/customer-123`;
115
+ const spaces = await all((cursor) =>
116
+ client.memory.spaces.list({
117
+ externalSubjectId: "customer-123",
118
+ cursor,
119
+ limit: 100,
120
+ }),
121
+ );
122
+ const space =
123
+ spaces.find((s) => s.spaceKey === spaceKey) ??
124
+ (await client.memory.spaces.create({
125
+ spaceKey,
126
+ name: "Disposable customer memory",
127
+ scopeType: "user",
128
+ scopeId: "customer-123",
129
+ externalSubjectId: "customer-123",
130
+ policyId: policy.id,
131
+ }));
132
+ const input: MemoryIngestRequest = {
133
+ memorySpaceId: space.id,
134
+ conversationId: options.eventKey,
135
+ idempotencyKey: options.eventKey,
136
+ messages: [
137
+ {
138
+ id: `${options.eventKey}-message`,
139
+ role: "user",
140
+ content:
141
+ "I prefer important notifications through email rather than WhatsApp.",
142
+ },
143
+ ],
144
+ };
145
+ let result;
146
+ try {
147
+ result = await client.memory.ingest(input, {
148
+ idempotencyKey: options.eventKey,
149
+ maxRetries: 0,
150
+ });
151
+ } catch (error) {
152
+ if (error instanceof APIError) {
153
+ // Safe identifiers/categories only; never print secrets, prompts or memory content.
154
+ console.error({
155
+ code: error.code,
156
+ status: error.status,
157
+ retryable: error.retryable,
158
+ retryAfterMs: error.retryAfterMs,
159
+ requestId: error.requestId,
160
+ diagnostics: error.details,
161
+ });
162
+ }
163
+ // After correcting configuration/quota, call ingest(input) with the SAME event identity.
164
+ // Do not blindly retry, mutate the input, or generate a fresh key.
165
+ throw error;
166
+ }
167
+ console.log({
168
+ runId: result.memoryRunId,
169
+ accepted: result.acceptedCount,
170
+ rejected: result.rejectedCount,
171
+ indexing: result.indexing,
172
+ });
173
+ const run = await client.memory.runs.get(result.memoryRunId);
174
+ if (result.indexing.failed)
175
+ throw new Error(
176
+ `Indexing incomplete for run ${run.id}; inspect diagnostics and repair through memory.reindex().`,
177
+ );
178
+ // A completed event replays without model execution or another memory write.
179
+ const replay = await client.memory.ingest(input, {
180
+ idempotencyKey: options.eventKey,
181
+ maxRetries: 0,
182
+ });
183
+ if (replay.memoryRunId !== result.memoryRunId || !replay.replayed)
184
+ throw new Error("Expected the original completed event to replay.");
185
+ console.log({ replayed: replay.replayed, runId: replay.memoryRunId });
186
+ await pause();
187
+ const search = await client.memory.search({
188
+ memorySpaceId: space.id,
189
+ query: "How should I send important notifications?",
190
+ relevance: "relevant",
191
+ });
192
+ console.log({ relevantMatches: search.memories.length });
193
+ await pause();
194
+ const context = await client.memory.context({
195
+ memorySpaceId: space.id,
196
+ messages: [{ role: "user", content: "How should you notify me?" }],
197
+ });
198
+ console.log({ contextMemories: context.memories.length });
199
+ await pause();
200
+ await client.memory.profiles.generate({ memorySpaceId: space.id });
201
+ const profile = await client.memory.profiles.get(space.id);
202
+ const items = await client.memory.items.list({
203
+ memorySpaceId: space.id,
204
+ limit: 25,
205
+ });
206
+ const first = items.items[0];
207
+ if (first) {
208
+ await client.memory.items.update(first.id, { importance: 0.8 });
209
+ await client.memory.items.evidence(first.id, { limit: 25 });
210
+ // Explicit cleanup only for this disposable example's space.
211
+ if (options.cleanup) await client.memory.items.delete(first.id);
212
+ }
213
+ if (options.cleanup) {
214
+ await client.memory.spaces.delete(space.id);
215
+ await client.memory.erase(space.id);
216
+ await client.memory.policies.delete(policy.id);
217
+ }
218
+ return { space, policy, result, search, context, profile };
219
+ }
220
+
221
+ if (process.env.NIRMOS_RUN_MEMORY_EXAMPLE === "1") {
222
+ const token = process.env.NIRMOS_API_KEY;
223
+ const eventKey = process.env.MEMORY_EVENT_KEY;
224
+ if (!token || !eventKey)
225
+ throw new Error("Set NIRMOS_API_KEY and a persisted MEMORY_EVENT_KEY.");
226
+ await memoryQuickstart(
227
+ new Nirmos({
228
+ auth: { type: "api-key", key: token },
229
+ apiBaseUrl: process.env.NIRMOS_API_BASE_URL ?? "http://localhost:4001",
230
+ runtimeBaseUrl:
231
+ process.env.NIRMOS_RUNTIME_BASE_URL ?? "http://localhost:4000",
232
+ maxRetries: 0,
233
+ }),
234
+ {
235
+ eventKey,
236
+ googleApiKey: process.env.GOOGLE_API_KEY,
237
+ cleanup: process.env.MEMORY_CLEANUP === "1",
238
+ },
239
+ );
240
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": "../tsconfig.json",
3
+ "compilerOptions": { "noEmit": true, "rootDir": ".." },
4
+ "include": ["memory-quickstart.ts"]
5
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nirmos/sdk",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Official TypeScript SDK for the Nirmos AI platform.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -8,7 +8,8 @@
8
8
  "files": [
9
9
  "dist",
10
10
  "src",
11
- "README.md"
11
+ "README.md",
12
+ "examples"
12
13
  ],
13
14
  "main": "./dist/cjs/index.js",
14
15
  "module": "./dist/esm/index.js",
@@ -21,11 +22,11 @@
21
22
  }
22
23
  },
23
24
  "scripts": {
24
- "build": "node ./scripts/clean.mjs && tsc -p tsconfig.build.json && tsc -p tsconfig.cjs.json && node ./scripts/write-cjs-package.mjs",
25
+ "build": "node ./scripts/generate-version.mjs && node ./scripts/clean.mjs && tsc -p tsconfig.build.json && tsc -p tsconfig.cjs.json && node ./scripts/write-cjs-package.mjs && node ./scripts/generate-examples.mjs",
25
26
  "check-types": "tsc --noEmit",
26
27
  "lint": "eslint src tests --max-warnings 0",
27
28
  "prepack": "pnpm build",
28
- "test": "node ./scripts/ensure-built.mjs && tsc -p tests/tsconfig.json && node --test tests/*.test.mjs"
29
+ "test": "node ./scripts/ensure-built.mjs && tsc -p examples/tsconfig.json && tsc -p tests/tsconfig.json && node --test tests/*.test.mjs"
29
30
  },
30
31
  "engines": {
31
32
  "node": ">=18"
package/src/client.ts CHANGED
@@ -72,18 +72,7 @@ export class Nirmos {
72
72
  ) => Promise<EndpointExecution>;
73
73
  };
74
74
  readonly memory: Memory;
75
- readonly knowledge: ManagementResources["knowledge"] & {
76
- search: (
77
- id: string,
78
- body: {
79
- query: string;
80
- topK?: number;
81
- minScore?: number;
82
- filters?: Record<string, string | number | boolean>;
83
- },
84
- options?: RequestOptions,
85
- ) => Promise<KnowledgeMatch[]>;
86
- };
75
+ readonly knowledge: ManagementResources["knowledge"];
87
76
  readonly evaluations: Omit<ManagementResources["evaluations"], "runs"> & {
88
77
  runs: ManagementResources["evaluations"]["runs"] & {
89
78
  create: (
@@ -193,16 +182,7 @@ export class Nirmos {
193
182
  })
194
183
  ).data,
195
184
  };
196
- this.knowledge = {
197
- ...resources.knowledge,
198
- search: (id, body, options) =>
199
- runtime.data<KnowledgeMatch[]>({
200
- method: "POST",
201
- path: `/v1/knowledge-bases/${encodeURIComponent(id)}/search`,
202
- body,
203
- options,
204
- }),
205
- };
185
+ this.knowledge = resources.knowledge;
206
186
  const runPath = (id: string) =>
207
187
  `/v1/evaluations/runs/${encodeURIComponent(id)}`;
208
188
  const command = async (
@@ -260,14 +240,14 @@ export class Nirmos {
260
240
  }
261
241
  }
262
242
 
263
- export interface KnowledgeMatch {
264
- chunkId: string;
265
- documentId: string;
266
- content: string;
267
- score: number;
268
- metadata: Record<string, string | number | boolean> | null;
269
- source: { title: string; uri: string | null; type: string };
270
- }
243
+ export type KnowledgeSearchRequest =
244
+ import("./management/contracts.js").Requests["searchKnowledgeBase"];
245
+ export type KnowledgeSearchResponse =
246
+ import("./management/contracts.js").Responses["searchKnowledgeBase"];
247
+ export type KnowledgeSearchMode = KnowledgeSearchResponse["mode"];
248
+ export type KnowledgeMatch = KnowledgeSearchResponse["items"][number];
249
+ export type KnowledgeSearchStatus =
250
+ import("./management/contracts.js").Responses["getKnowledgeSearchStatus"];
271
251
  export interface EndpointExecution {
272
252
  success: boolean;
273
253
  data: {