@vellumai/assistant 0.5.4 → 0.5.6

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 (151) hide show
  1. package/Dockerfile +17 -27
  2. package/node_modules/@vellumai/ces-contracts/src/index.ts +1 -0
  3. package/node_modules/@vellumai/ces-contracts/src/trust-rules.ts +42 -0
  4. package/package.json +1 -1
  5. package/src/__tests__/actor-token-service.test.ts +113 -0
  6. package/src/__tests__/config-schema.test.ts +2 -2
  7. package/src/__tests__/context-window-manager.test.ts +78 -0
  8. package/src/__tests__/conversation-title-service.test.ts +30 -1
  9. package/src/__tests__/credential-security-invariants.test.ts +2 -0
  10. package/src/__tests__/docker-signing-key-bootstrap.test.ts +207 -0
  11. package/src/__tests__/memory-regressions.test.ts +8 -30
  12. package/src/__tests__/openai-whisper.test.ts +93 -0
  13. package/src/__tests__/require-fresh-approval.test.ts +4 -0
  14. package/src/__tests__/slack-messaging-token-resolution.test.ts +319 -0
  15. package/src/__tests__/tool-executor-lifecycle-events.test.ts +4 -0
  16. package/src/__tests__/tool-executor.test.ts +4 -0
  17. package/src/__tests__/volume-security-guard.test.ts +155 -0
  18. package/src/cli/commands/conversations.ts +0 -18
  19. package/src/config/bundled-skills/messaging/tools/shared.ts +1 -0
  20. package/src/config/bundled-skills/transcribe/tools/transcribe-media.ts +16 -37
  21. package/src/config/env-registry.ts +9 -0
  22. package/src/config/env.ts +8 -2
  23. package/src/config/feature-flag-registry.json +8 -8
  24. package/src/config/schema.ts +0 -12
  25. package/src/config/schemas/memory.ts +0 -4
  26. package/src/config/schemas/platform.ts +1 -1
  27. package/src/config/schemas/security.ts +4 -0
  28. package/src/context/window-manager.ts +53 -2
  29. package/src/credential-execution/managed-catalog.ts +5 -15
  30. package/src/daemon/conversation-agent-loop.ts +0 -60
  31. package/src/daemon/conversation-memory.ts +0 -117
  32. package/src/daemon/conversation-runtime-assembly.ts +0 -2
  33. package/src/daemon/daemon-control.ts +7 -0
  34. package/src/daemon/handlers/conversations.ts +0 -11
  35. package/src/daemon/lifecycle.ts +10 -47
  36. package/src/daemon/providers-setup.ts +2 -1
  37. package/src/followups/followup-store.ts +5 -2
  38. package/src/hooks/manager.ts +7 -0
  39. package/src/instrument.ts +33 -1
  40. package/src/memory/conversation-crud.ts +0 -236
  41. package/src/memory/conversation-title-service.ts +26 -10
  42. package/src/memory/db-init.ts +5 -13
  43. package/src/memory/embedding-local.ts +11 -5
  44. package/src/memory/indexer.ts +15 -106
  45. package/src/memory/job-handlers/conversation-starters.ts +24 -36
  46. package/src/memory/job-handlers/embedding.ts +0 -79
  47. package/src/memory/job-utils.ts +1 -1
  48. package/src/memory/jobs-store.ts +0 -8
  49. package/src/memory/jobs-worker.ts +0 -20
  50. package/src/memory/migrations/189-drop-simplified-memory.ts +42 -0
  51. package/src/memory/migrations/index.ts +1 -3
  52. package/src/memory/qdrant-client.ts +4 -6
  53. package/src/memory/schema/conversations.ts +0 -3
  54. package/src/memory/schema/index.ts +0 -2
  55. package/src/messaging/draft-store.ts +2 -2
  56. package/src/messaging/provider.ts +9 -0
  57. package/src/messaging/providers/slack/adapter.ts +29 -2
  58. package/src/oauth/connection-resolver.test.ts +22 -18
  59. package/src/oauth/connection-resolver.ts +92 -7
  60. package/src/oauth/platform-connection.test.ts +78 -69
  61. package/src/oauth/platform-connection.ts +12 -19
  62. package/src/permissions/defaults.ts +3 -3
  63. package/src/permissions/trust-client.ts +332 -0
  64. package/src/permissions/trust-store-interface.ts +105 -0
  65. package/src/permissions/trust-store.ts +531 -39
  66. package/src/platform/client.test.ts +148 -0
  67. package/src/platform/client.ts +71 -0
  68. package/src/providers/speech-to-text/openai-whisper.test.ts +190 -0
  69. package/src/providers/speech-to-text/openai-whisper.ts +68 -0
  70. package/src/providers/speech-to-text/resolve.ts +9 -0
  71. package/src/providers/speech-to-text/types.ts +17 -0
  72. package/src/runtime/auth/route-policy.ts +14 -0
  73. package/src/runtime/auth/token-service.ts +133 -0
  74. package/src/runtime/http-server.ts +4 -2
  75. package/src/runtime/routes/conversation-management-routes.ts +0 -36
  76. package/src/runtime/routes/conversation-query-routes.ts +44 -2
  77. package/src/runtime/routes/conversation-routes.ts +2 -1
  78. package/src/runtime/routes/inbound-message-handler.ts +27 -3
  79. package/src/runtime/routes/inbound-stages/acl-enforcement.ts +16 -1
  80. package/src/runtime/routes/inbound-stages/transcribe-audio.test.ts +287 -0
  81. package/src/runtime/routes/inbound-stages/transcribe-audio.ts +122 -0
  82. package/src/runtime/routes/log-export-routes.ts +1 -0
  83. package/src/runtime/routes/memory-item-routes.test.ts +221 -3
  84. package/src/runtime/routes/memory-item-routes.ts +124 -2
  85. package/src/runtime/routes/secret-routes.ts +4 -1
  86. package/src/runtime/routes/upgrade-broadcast-routes.ts +151 -0
  87. package/src/schedule/schedule-store.ts +0 -21
  88. package/src/security/ces-credential-client.ts +173 -0
  89. package/src/security/secure-keys.ts +65 -22
  90. package/src/signals/bash.ts +3 -0
  91. package/src/signals/cancel.ts +3 -0
  92. package/src/signals/confirm.ts +3 -0
  93. package/src/signals/conversation-undo.ts +3 -0
  94. package/src/signals/event-stream.ts +7 -0
  95. package/src/signals/shotgun.ts +3 -0
  96. package/src/signals/trust-rule.ts +3 -0
  97. package/src/skills/inline-command-render.ts +5 -1
  98. package/src/skills/inline-command-runner.ts +30 -2
  99. package/src/telemetry/usage-telemetry-reporter.test.ts +23 -36
  100. package/src/telemetry/usage-telemetry-reporter.ts +21 -19
  101. package/src/tools/memory/handlers.ts +1 -129
  102. package/src/tools/permission-checker.ts +18 -0
  103. package/src/tools/skills/load.ts +9 -2
  104. package/src/util/device-id.ts +70 -7
  105. package/src/util/logger.ts +35 -9
  106. package/src/util/platform.ts +29 -5
  107. package/src/util/xml.ts +8 -0
  108. package/src/workspace/heartbeat-service.ts +5 -24
  109. package/src/workspace/migrations/migrate-to-workspace-volume.ts +113 -0
  110. package/src/workspace/migrations/registry.ts +2 -0
  111. package/src/__tests__/archive-recall.test.ts +0 -560
  112. package/src/__tests__/conversation-memory-dirty-tail.test.ts +0 -150
  113. package/src/__tests__/conversation-switch-memory-reduction.test.ts +0 -474
  114. package/src/__tests__/db-memory-archive-migration.test.ts +0 -372
  115. package/src/__tests__/db-memory-brief-state-migration.test.ts +0 -213
  116. package/src/__tests__/db-memory-reducer-checkpoints.test.ts +0 -273
  117. package/src/__tests__/memory-brief-open-loops.test.ts +0 -530
  118. package/src/__tests__/memory-brief-time.test.ts +0 -285
  119. package/src/__tests__/memory-brief-wrapper.test.ts +0 -311
  120. package/src/__tests__/memory-chunk-archive.test.ts +0 -400
  121. package/src/__tests__/memory-chunk-dual-write.test.ts +0 -453
  122. package/src/__tests__/memory-episode-archive.test.ts +0 -370
  123. package/src/__tests__/memory-episode-dual-write.test.ts +0 -626
  124. package/src/__tests__/memory-observation-archive.test.ts +0 -375
  125. package/src/__tests__/memory-observation-dual-write.test.ts +0 -318
  126. package/src/__tests__/memory-reducer-job.test.ts +0 -538
  127. package/src/__tests__/memory-reducer-scheduling.test.ts +0 -473
  128. package/src/__tests__/memory-reducer-store.test.ts +0 -728
  129. package/src/__tests__/memory-reducer-types.test.ts +0 -707
  130. package/src/__tests__/memory-reducer.test.ts +0 -704
  131. package/src/__tests__/memory-simplified-config.test.ts +0 -281
  132. package/src/__tests__/simplified-memory-e2e.test.ts +0 -666
  133. package/src/__tests__/simplified-memory-runtime.test.ts +0 -616
  134. package/src/config/schemas/memory-simplified.ts +0 -101
  135. package/src/memory/archive-recall.ts +0 -516
  136. package/src/memory/archive-store.ts +0 -400
  137. package/src/memory/brief-formatting.ts +0 -33
  138. package/src/memory/brief-open-loops.ts +0 -266
  139. package/src/memory/brief-time.ts +0 -162
  140. package/src/memory/brief.ts +0 -75
  141. package/src/memory/job-handlers/backfill-simplified-memory.ts +0 -462
  142. package/src/memory/job-handlers/reduce-conversation-memory.ts +0 -229
  143. package/src/memory/migrations/185-memory-brief-state.ts +0 -52
  144. package/src/memory/migrations/186-memory-archive.ts +0 -109
  145. package/src/memory/migrations/187-memory-reducer-checkpoints.ts +0 -19
  146. package/src/memory/reducer-scheduler.ts +0 -242
  147. package/src/memory/reducer-store.ts +0 -271
  148. package/src/memory/reducer-types.ts +0 -106
  149. package/src/memory/reducer.ts +0 -467
  150. package/src/memory/schema/memory-archive.ts +0 -121
  151. package/src/memory/schema/memory-brief.ts +0 -55
@@ -1,467 +0,0 @@
1
- /**
2
- * Simplified memory reducer — provider-backed conversation turn processor.
3
- *
4
- * This module owns:
5
- * 1. ReducerPromptInput — structured input for the provider call
6
- * 2. runReducer — send the transcript span to the LLM and return a typed result
7
- * 3. parseReducerOutput — raw string -> validated ReducerResult
8
- * 4. Fallback to EMPTY_REDUCER_RESULT on unparseable output (parse failures only)
9
- *
10
- * The reducer is intentionally side-effect-free: it never writes to the
11
- * database. Callers are responsible for applying the returned ReducerResult.
12
- */
13
-
14
- import {
15
- createTimeout,
16
- extractText,
17
- getConfiguredProvider,
18
- } from "../providers/provider-send-message.js";
19
- import { getLogger } from "../util/logger.js";
20
- import {
21
- type ArchiveEpisodeCandidate,
22
- type ArchiveObservationCandidate,
23
- EMPTY_REDUCER_RESULT,
24
- type OpenLoopCreate,
25
- type OpenLoopOp,
26
- type OpenLoopUpdate,
27
- type ReducerResult,
28
- type TimeContextOp,
29
- type TimeContextUpdate,
30
- } from "./reducer-types.js";
31
-
32
- const log = getLogger("memory-reducer");
33
-
34
- /** Timeout for the reducer provider call (ms). */
35
- const REDUCER_TIMEOUT_MS = 30_000;
36
-
37
- // ── Prompt input type ──────────────────────────────────────────────────
38
-
39
- /** The structured input that will be fed to the reducer provider call. */
40
- export interface ReducerPromptInput {
41
- /** Conversation ID being reduced. */
42
- conversationId: string;
43
- /** New messages since the last reduction checkpoint (role + content). */
44
- newMessages: Array<{ role: string; content: string }>;
45
- /** Current time-context rows the model can reference for updates. */
46
- existingTimeContexts: Array<{ id: string; summary: string }>;
47
- /** Current open-loop rows the model can reference for updates. */
48
- existingOpenLoops: Array<{ id: string; summary: string; status: string }>;
49
- /** Current time as epoch ms — injected for deterministic tests. */
50
- nowMs: number;
51
- /** Memory scope identifier (e.g. assistant instance ID). */
52
- scopeId: string;
53
- }
54
-
55
- // ── System prompt ─────────────────────────────────────────────────────
56
-
57
- /**
58
- * Build the reducer system prompt. Extracted as a named function so tests can
59
- * assert on prompt content without coupling to string literals.
60
- */
61
- export function buildReducerSystemPrompt(): string {
62
- return [
63
- "You are a memory reducer for a personal assistant. Your job is to analyze",
64
- "a span of new conversation messages and produce structured JSON output that",
65
- "captures important information for the assistant's long-term memory.",
66
- "",
67
- "You output a single JSON object with four optional arrays:",
68
- "",
69
- "1. `timeContexts` — time-bounded situational context (e.g. 'user traveling next week').",
70
- " Each entry has: action ('create'|'update'|'resolve'), and fields depending on the action.",
71
- " - create: summary (string), source (string), activeFrom (epoch ms), activeUntil (epoch ms)",
72
- " - update: id (string), and at least one of: summary, activeFrom, activeUntil",
73
- " - resolve: id (string)",
74
- "",
75
- "2. `openLoops` — unresolved items to track (e.g. 'waiting for Bob's reply').",
76
- " Each entry has: action ('create'|'update'|'resolve'), and fields depending on the action.",
77
- " - create: summary (string), source (string), optional dueAt (epoch ms)",
78
- " - update: id (string), and at least one of: summary, dueAt",
79
- " - resolve: id (string), status ('resolved'|'expired')",
80
- "",
81
- "3. `archiveObservations` — factual statements extracted from the conversation.",
82
- " Each entry has: content (string), role (string), optional modality (string), optional source (string)",
83
- "",
84
- "4. `archiveEpisodes` — coherent narrative summaries of interaction spans.",
85
- " Each entry has: title (string), summary (string), optional source (string)",
86
- "",
87
- "Rules:",
88
- "- Output ONLY valid JSON. No markdown, no explanation, no wrapping.",
89
- "- Omit arrays that would be empty rather than including empty arrays.",
90
- "- For updates and resolves, reference existing IDs from the provided context.",
91
- "- Be selective: only extract genuinely important or actionable information.",
92
- "- Timestamps are in epoch milliseconds.",
93
- "- If there is nothing meaningful to extract, output: {}",
94
- ].join("\n");
95
- }
96
-
97
- /**
98
- * Build the user-message content for the reducer prompt from the structured input.
99
- */
100
- export function buildReducerUserMessage(input: ReducerPromptInput): string {
101
- const parts: string[] = [];
102
-
103
- parts.push(
104
- `Current time: ${new Date(input.nowMs).toISOString()} (${input.nowMs}ms)`,
105
- );
106
- parts.push(`Conversation: ${input.conversationId}`);
107
- parts.push(`Scope: ${input.scopeId}`);
108
- parts.push("");
109
-
110
- // Existing state the model can reference for updates/resolves
111
- if (input.existingTimeContexts.length > 0) {
112
- parts.push("## Active time contexts");
113
- for (const tc of input.existingTimeContexts) {
114
- parts.push(`- [${tc.id}] ${tc.summary}`);
115
- }
116
- parts.push("");
117
- }
118
-
119
- if (input.existingOpenLoops.length > 0) {
120
- parts.push("## Active open loops");
121
- for (const ol of input.existingOpenLoops) {
122
- parts.push(`- [${ol.id}] (${ol.status}) ${ol.summary}`);
123
- }
124
- parts.push("");
125
- }
126
-
127
- // The unreduced transcript span
128
- parts.push("## New messages to process");
129
- for (const msg of input.newMessages) {
130
- parts.push(`[${msg.role}]: ${msg.content}`);
131
- }
132
-
133
- return parts.join("\n");
134
- }
135
-
136
- // ── Provider-backed reducer call ──────────────────────────────────────
137
-
138
- /**
139
- * Run the memory reducer against a transcript span.
140
- *
141
- * Sends the unreduced messages, active time contexts, active open loops,
142
- * current time, and scope metadata to the configured LLM provider. Parses
143
- * the response into a typed {@link ReducerResult}.
144
- *
145
- * This function is **side-effect-free**: it never writes to the database.
146
- * The caller is responsible for applying the returned result.
147
- *
148
- * Returns {@link EMPTY_REDUCER_RESULT} when:
149
- * - No provider is configured/available
150
- * - The provider call fails or times out
151
- * - The model output is unparseable
152
- *
153
- * @param input Structured reducer input
154
- * @param signal Optional external abort signal
155
- */
156
- export async function runReducer(
157
- input: ReducerPromptInput,
158
- signal?: AbortSignal,
159
- ): Promise<ReducerResult> {
160
- const provider = await getConfiguredProvider();
161
- if (!provider) {
162
- log.warn(
163
- "No provider available for memory reducer — returning empty result",
164
- );
165
- return EMPTY_REDUCER_RESULT;
166
- }
167
-
168
- const systemPrompt = buildReducerSystemPrompt();
169
- const userText = buildReducerUserMessage(input);
170
-
171
- const { signal: timeoutSignal, cleanup } = createTimeout(REDUCER_TIMEOUT_MS);
172
- const combinedSignal = signal
173
- ? AbortSignal.any([signal, timeoutSignal])
174
- : timeoutSignal;
175
-
176
- try {
177
- const response = await provider.sendMessage(
178
- [{ role: "user", content: [{ type: "text", text: userText }] }],
179
- undefined,
180
- systemPrompt,
181
- {
182
- signal: combinedSignal,
183
- config: {
184
- modelIntent: "latency-optimized" as const,
185
- max_tokens: 4096,
186
- },
187
- },
188
- );
189
-
190
- const rawText = extractText(response);
191
- if (!rawText) {
192
- log.warn("Reducer provider returned empty text — returning empty result");
193
- return EMPTY_REDUCER_RESULT;
194
- }
195
-
196
- return parseReducerOutput(rawText);
197
- } catch (err) {
198
- if (combinedSignal.aborted) {
199
- log.warn("Memory reducer provider call timed out or was aborted");
200
- } else {
201
- log.warn({ err }, "Memory reducer provider call failed");
202
- }
203
- return EMPTY_REDUCER_RESULT;
204
- } finally {
205
- cleanup();
206
- }
207
- }
208
-
209
- // ── Validation helpers ─────────────────────────────────────────────────
210
-
211
- const VALID_TIME_CONTEXT_ACTIONS = new Set(["create", "update", "resolve"]);
212
- const VALID_OPEN_LOOP_ACTIONS = new Set(["create", "update", "resolve"]);
213
- const VALID_OPEN_LOOP_RESOLVE_STATUSES = new Set(["resolved", "expired"]);
214
-
215
- function isNonEmptyString(v: unknown): v is string {
216
- return typeof v === "string" && v.length > 0;
217
- }
218
-
219
- function isPositiveNumber(v: unknown): v is number {
220
- return typeof v === "number" && Number.isFinite(v) && v > 0;
221
- }
222
-
223
- function isNonNegativeNumber(v: unknown): v is number {
224
- return typeof v === "number" && Number.isFinite(v) && v >= 0;
225
- }
226
-
227
- function validateTimeContextOp(raw: unknown): TimeContextOp | null {
228
- if (raw == null || typeof raw !== "object") return null;
229
- const obj = raw as Record<string, unknown>;
230
- const action = obj.action;
231
-
232
- if (!isNonEmptyString(action) || !VALID_TIME_CONTEXT_ACTIONS.has(action)) {
233
- return null;
234
- }
235
-
236
- if (action === "create") {
237
- if (
238
- !isNonEmptyString(obj.summary) ||
239
- !isNonEmptyString(obj.source) ||
240
- !isNonNegativeNumber(obj.activeFrom) ||
241
- !isPositiveNumber(obj.activeUntil)
242
- ) {
243
- return null;
244
- }
245
- return {
246
- action: "create",
247
- summary: obj.summary,
248
- source: obj.source,
249
- activeFrom: obj.activeFrom,
250
- activeUntil: obj.activeUntil,
251
- };
252
- }
253
-
254
- if (action === "update") {
255
- if (!isNonEmptyString(obj.id)) return null;
256
- // Extract and narrow optional fields
257
- const summary = isNonEmptyString(obj.summary) ? obj.summary : undefined;
258
- const activeFrom = isNonNegativeNumber(obj.activeFrom)
259
- ? obj.activeFrom
260
- : undefined;
261
- const activeUntil = isPositiveNumber(obj.activeUntil)
262
- ? obj.activeUntil
263
- : undefined;
264
- // At least one field must be provided for the update to be meaningful
265
- if (
266
- summary === undefined &&
267
- activeFrom === undefined &&
268
- activeUntil === undefined
269
- ) {
270
- return null;
271
- }
272
- const result: TimeContextUpdate = {
273
- action: "update",
274
- id: obj.id,
275
- };
276
- if (summary !== undefined) result.summary = summary;
277
- if (activeFrom !== undefined) result.activeFrom = activeFrom;
278
- if (activeUntil !== undefined) result.activeUntil = activeUntil;
279
- return result;
280
- }
281
-
282
- // resolve
283
- if (!isNonEmptyString(obj.id)) return null;
284
- return { action: "resolve", id: obj.id };
285
- }
286
-
287
- function validateOpenLoopOp(raw: unknown): OpenLoopOp | null {
288
- if (raw == null || typeof raw !== "object") return null;
289
- const obj = raw as Record<string, unknown>;
290
- const action = obj.action;
291
-
292
- if (!isNonEmptyString(action) || !VALID_OPEN_LOOP_ACTIONS.has(action)) {
293
- return null;
294
- }
295
-
296
- if (action === "create") {
297
- if (!isNonEmptyString(obj.summary) || !isNonEmptyString(obj.source)) {
298
- return null;
299
- }
300
- const result: OpenLoopCreate = {
301
- action: "create",
302
- summary: obj.summary,
303
- source: obj.source,
304
- };
305
- const dueAt = isNonNegativeNumber(obj.dueAt) ? obj.dueAt : undefined;
306
- if (dueAt !== undefined) result.dueAt = dueAt;
307
- return result;
308
- }
309
-
310
- if (action === "update") {
311
- if (!isNonEmptyString(obj.id)) return null;
312
- const summary = isNonEmptyString(obj.summary) ? obj.summary : undefined;
313
- const dueAt = isNonNegativeNumber(obj.dueAt) ? obj.dueAt : undefined;
314
- if (summary === undefined && dueAt === undefined) return null;
315
-
316
- const result: OpenLoopUpdate = {
317
- action: "update",
318
- id: obj.id,
319
- };
320
- if (summary !== undefined) result.summary = summary;
321
- if (dueAt !== undefined) result.dueAt = dueAt;
322
- return result;
323
- }
324
-
325
- // resolve
326
- if (!isNonEmptyString(obj.id)) return null;
327
- if (
328
- !isNonEmptyString(obj.status) ||
329
- !VALID_OPEN_LOOP_RESOLVE_STATUSES.has(obj.status)
330
- ) {
331
- return null;
332
- }
333
- return {
334
- action: "resolve",
335
- id: obj.id,
336
- status: obj.status as "resolved" | "expired",
337
- };
338
- }
339
-
340
- function validateArchiveObservation(
341
- raw: unknown,
342
- ): ArchiveObservationCandidate | null {
343
- if (raw == null || typeof raw !== "object") return null;
344
- const obj = raw as Record<string, unknown>;
345
- if (!isNonEmptyString(obj.content) || !isNonEmptyString(obj.role)) {
346
- return null;
347
- }
348
- const result: ArchiveObservationCandidate = {
349
- content: obj.content,
350
- role: obj.role,
351
- };
352
- if (isNonEmptyString(obj.modality)) result.modality = obj.modality;
353
- if (isNonEmptyString(obj.source)) result.source = obj.source;
354
- return result;
355
- }
356
-
357
- function validateArchiveEpisode(raw: unknown): ArchiveEpisodeCandidate | null {
358
- if (raw == null || typeof raw !== "object") return null;
359
- const obj = raw as Record<string, unknown>;
360
- if (!isNonEmptyString(obj.title) || !isNonEmptyString(obj.summary)) {
361
- return null;
362
- }
363
- const result: ArchiveEpisodeCandidate = {
364
- title: obj.title,
365
- summary: obj.summary,
366
- };
367
- if (isNonEmptyString(obj.source)) result.source = obj.source;
368
- return result;
369
- }
370
-
371
- // ── Public API ─────────────────────────────────────────────────────────
372
-
373
- /**
374
- * Parse raw model output into a validated ReducerResult.
375
- *
376
- * On any structural error (non-JSON, not a JSON object) the function returns
377
- * {@link EMPTY_REDUCER_RESULT} rather than throwing — callers use identity
378
- * comparison (`=== EMPTY_REDUCER_RESULT`) to detect true parse failures and
379
- * skip checkpoint advancement.
380
- *
381
- * A valid JSON object with no recognized top-level arrays (e.g. `{}`) is
382
- * treated as a **valid-but-empty** response — the model simply had nothing
383
- * to extract. In this case a normal `ReducerResult` with all empty arrays
384
- * is returned so that callers advance the checkpoint and clear the dirty
385
- * tail, avoiding an infinite retry loop.
386
- *
387
- * Individual invalid operations within an otherwise valid structure are
388
- * silently dropped to preserve the rest of the result.
389
- */
390
- export function parseReducerOutput(raw: string): ReducerResult {
391
- let parsed: unknown;
392
- try {
393
- parsed = JSON.parse(raw);
394
- } catch {
395
- log.warn("reducer output is not valid JSON — falling back to empty result");
396
- return EMPTY_REDUCER_RESULT;
397
- }
398
-
399
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
400
- log.warn(
401
- "reducer output is not a JSON object — falling back to empty result",
402
- );
403
- return EMPTY_REDUCER_RESULT;
404
- }
405
-
406
- const obj = parsed as Record<string, unknown>;
407
-
408
- // Check which top-level array keys are present
409
- const hasTimeContexts = Array.isArray(obj.timeContexts);
410
- const hasOpenLoops = Array.isArray(obj.openLoops);
411
- const hasArchiveObservations = Array.isArray(obj.archiveObservations);
412
- const hasArchiveEpisodes = Array.isArray(obj.archiveEpisodes);
413
-
414
- // A valid JSON object with no recognized arrays (e.g. `{}`) means the
415
- // model had nothing to extract — return a normal (non-sentinel) empty
416
- // result so the checkpoint advances.
417
- if (
418
- !hasTimeContexts &&
419
- !hasOpenLoops &&
420
- !hasArchiveObservations &&
421
- !hasArchiveEpisodes
422
- ) {
423
- log.debug(
424
- "reducer output is valid JSON with no extractions — advancing with empty result",
425
- );
426
- return {
427
- timeContexts: [],
428
- openLoops: [],
429
- archiveObservations: [],
430
- archiveEpisodes: [],
431
- };
432
- }
433
-
434
- const timeContexts: TimeContextOp[] = [];
435
- if (hasTimeContexts) {
436
- for (const item of obj.timeContexts as unknown[]) {
437
- const validated = validateTimeContextOp(item);
438
- if (validated) timeContexts.push(validated);
439
- }
440
- }
441
-
442
- const openLoops: OpenLoopOp[] = [];
443
- if (hasOpenLoops) {
444
- for (const item of obj.openLoops as unknown[]) {
445
- const validated = validateOpenLoopOp(item);
446
- if (validated) openLoops.push(validated);
447
- }
448
- }
449
-
450
- const archiveObservations: ArchiveObservationCandidate[] = [];
451
- if (hasArchiveObservations) {
452
- for (const item of obj.archiveObservations as unknown[]) {
453
- const validated = validateArchiveObservation(item);
454
- if (validated) archiveObservations.push(validated);
455
- }
456
- }
457
-
458
- const archiveEpisodes: ArchiveEpisodeCandidate[] = [];
459
- if (hasArchiveEpisodes) {
460
- for (const item of obj.archiveEpisodes as unknown[]) {
461
- const validated = validateArchiveEpisode(item);
462
- if (validated) archiveEpisodes.push(validated);
463
- }
464
- }
465
-
466
- return { timeContexts, openLoops, archiveObservations, archiveEpisodes };
467
- }
@@ -1,121 +0,0 @@
1
- import {
2
- index,
3
- integer,
4
- sqliteTable,
5
- text,
6
- uniqueIndex,
7
- } from "drizzle-orm/sqlite-core";
8
-
9
- import { conversations, messages } from "./conversations.js";
10
-
11
- /**
12
- * Raw observation records captured from conversation turns. Each observation
13
- * is a single factual statement extracted from user or assistant messages,
14
- * annotated with modality and source metadata for downstream recall.
15
- */
16
- export const memoryObservations = sqliteTable(
17
- "memory_observations",
18
- {
19
- id: text("id").primaryKey(),
20
- scopeId: text("scope_id").notNull().default("default"),
21
- conversationId: text("conversation_id")
22
- .notNull()
23
- .references(() => conversations.id, { onDelete: "cascade" }),
24
- messageId: text("message_id").references(() => messages.id, {
25
- onDelete: "set null",
26
- }),
27
- /** The role that produced the observation (e.g. "user", "assistant"). */
28
- role: text("role").notNull(),
29
- /** Free-text statement capturing the observed fact. */
30
- content: text("content").notNull(),
31
- /**
32
- * Modality of the source material: "text", "voice", "image", etc.
33
- * Enables downstream filters for recall relevance.
34
- */
35
- modality: text("modality").notNull().default("text"),
36
- /**
37
- * Source channel or interface that produced the observation
38
- * (e.g. "vellum", "telegram", "phone").
39
- */
40
- source: text("source"),
41
- createdAt: integer("created_at").notNull(),
42
- },
43
- (table) => [
44
- index("idx_memory_observations_scope_id").on(table.scopeId),
45
- index("idx_memory_observations_conversation_id").on(table.conversationId),
46
- index("idx_memory_observations_created_at").on(table.createdAt),
47
- ],
48
- );
49
-
50
- /**
51
- * Deduplicated content chunks derived from observations. Chunks are the unit
52
- * of embedding and recall — each chunk carries a contentHash for idempotent
53
- * dual-write safety so the same content is never stored twice.
54
- */
55
- export const memoryChunks = sqliteTable(
56
- "memory_chunks",
57
- {
58
- id: text("id").primaryKey(),
59
- scopeId: text("scope_id").notNull().default("default"),
60
- observationId: text("observation_id")
61
- .notNull()
62
- .references(() => memoryObservations.id, { onDelete: "cascade" }),
63
- /** The chunk text used for embedding and recall. */
64
- content: text("content").notNull(),
65
- /** Token count estimate for context-window budgeting. */
66
- tokenEstimate: integer("token_estimate").notNull(),
67
- /**
68
- * SHA-256 hash of the normalized content, used to skip duplicate inserts
69
- * during dual-write windows.
70
- */
71
- contentHash: text("content_hash").notNull(),
72
- createdAt: integer("created_at").notNull(),
73
- },
74
- (table) => [
75
- index("idx_memory_chunks_scope_id").on(table.scopeId),
76
- index("idx_memory_chunks_observation_id").on(table.observationId),
77
- uniqueIndex("idx_memory_chunks_content_hash").on(
78
- table.scopeId,
79
- table.contentHash,
80
- ),
81
- index("idx_memory_chunks_created_at").on(table.createdAt),
82
- ],
83
- );
84
-
85
- /**
86
- * Episode records that group related observations into coherent narrative
87
- * units. An episode represents a meaningful interaction or topic span,
88
- * with source-link metadata for provenance tracking.
89
- */
90
- export const memoryEpisodes = sqliteTable(
91
- "memory_episodes",
92
- {
93
- id: text("id").primaryKey(),
94
- scopeId: text("scope_id").notNull().default("default"),
95
- conversationId: text("conversation_id")
96
- .notNull()
97
- .references(() => conversations.id, { onDelete: "cascade" }),
98
- /** Human-readable title summarizing the episode. */
99
- title: text("title").notNull(),
100
- /** Longer narrative summary of the episode content. */
101
- summary: text("summary").notNull(),
102
- /** Token count estimate for the summary. */
103
- tokenEstimate: integer("token_estimate").notNull(),
104
- /**
105
- * Source channel or interface that produced the episode
106
- * (mirrors observation.source for episode-level filtering).
107
- */
108
- source: text("source"),
109
- /** Epoch-ms timestamp of the earliest observation in the episode. */
110
- startAt: integer("start_at").notNull(),
111
- /** Epoch-ms timestamp of the latest observation in the episode. */
112
- endAt: integer("end_at").notNull(),
113
- createdAt: integer("created_at").notNull(),
114
- updatedAt: integer("updated_at").notNull(),
115
- },
116
- (table) => [
117
- index("idx_memory_episodes_scope_id").on(table.scopeId),
118
- index("idx_memory_episodes_conversation_id").on(table.conversationId),
119
- index("idx_memory_episodes_created_at").on(table.createdAt),
120
- ],
121
- );
@@ -1,55 +0,0 @@
1
- import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
2
-
3
- /**
4
- * Time contexts represent bounded temporal windows that are relevant to the
5
- * assistant's current awareness — e.g. "user is traveling next week",
6
- * "quarterly planning period ends Friday". Each row captures one window
7
- * with an activation range and a human-readable summary the brief can surface.
8
- */
9
- export const timeContexts = sqliteTable(
10
- "time_contexts",
11
- {
12
- id: text("id").primaryKey(),
13
- scopeId: text("scope_id").notNull(),
14
- summary: text("summary").notNull(),
15
- source: text("source").notNull(), // e.g. 'conversation', 'schedule', 'manual'
16
- activeFrom: integer("active_from").notNull(), // epoch ms — window start
17
- activeUntil: integer("active_until").notNull(), // epoch ms — window end
18
- createdAt: integer("created_at").notNull(),
19
- updatedAt: integer("updated_at").notNull(),
20
- },
21
- (table) => [
22
- index("idx_time_contexts_scope_active_until").on(
23
- table.scopeId,
24
- table.activeUntil,
25
- ),
26
- ],
27
- );
28
-
29
- /**
30
- * Open loops track unresolved items the assistant should follow up on —
31
- * e.g. "waiting for Bob's reply", "need to file taxes before April 15".
32
- * Each row carries a status and an optional due date so the brief can
33
- * prioritise which loops to surface.
34
- */
35
- export const openLoops = sqliteTable(
36
- "open_loops",
37
- {
38
- id: text("id").primaryKey(),
39
- scopeId: text("scope_id").notNull(),
40
- summary: text("summary").notNull(),
41
- status: text("status").notNull().default("open"), // 'open' | 'resolved' | 'expired'
42
- source: text("source").notNull(), // e.g. 'conversation', 'followup', 'manual'
43
- dueAt: integer("due_at"), // epoch ms — optional deadline
44
- surfacedAt: integer("surfaced_at"), // epoch ms — last time shown in brief
45
- createdAt: integer("created_at").notNull(),
46
- updatedAt: integer("updated_at").notNull(),
47
- },
48
- (table) => [
49
- index("idx_open_loops_scope_status_due").on(
50
- table.scopeId,
51
- table.status,
52
- table.dueAt,
53
- ),
54
- ],
55
- );