@vellumai/assistant 0.10.0-dev.202606232051.e10ffb5 → 0.10.0-dev.202606232210.2d9d2d7

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.
@@ -57,6 +57,11 @@ const ALLOWED_PREFIXES = {
57
57
  // job handler directly. Depth-2 for commands/memory/ nesting.
58
58
  "../../memory/memory-retrospective-job",
59
59
  "../../../memory/memory-retrospective-job",
60
+ // Memory worker control — the `memory worker` CLI spawns/probes/stops
61
+ // the worker OS process directly (no daemon, no IPC), so it imports the
62
+ // shared PID-file control helpers. Depth-2 for commands/memory/ nesting.
63
+ "../../memory/worker-control",
64
+ "../../../memory/worker-control",
60
65
  "../logger",
61
66
  "../output",
62
67
  "../../logger",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.0-dev.202606232051.e10ffb5",
3
+ "version": "0.10.0-dev.202606232210.2d9d2d7",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
package/scripts/test.sh CHANGED
@@ -169,6 +169,7 @@ printf '%s\n' "${test_files[@]}" | xargs -P "${WORKERS}" -I {} bash -c '
169
169
 
170
170
  safe_name="$(echo "${test_file}" | tr "/" "_")"
171
171
  out_file="${results_dir}/${safe_name}.out"
172
+ base="$(basename "${test_file}")"
172
173
 
173
174
  coverage_args=""
174
175
  if [[ "${coverage_enabled}" == "true" ]]; then
@@ -185,28 +186,48 @@ printf '%s\n' "${test_files[@]}" | xargs -P "${WORKERS}" -I {} bash -c '
185
186
  timeout_cmd="gtimeout"
186
187
  fi
187
188
 
188
- start_ms=$(perl -MTime::HiRes=time -e "printf \"%d\", time*1000")
189
-
190
- if [[ -n "${timeout_cmd}" ]]; then
191
- if [[ "${exclude_exp}" == "true" ]]; then
192
- "${timeout_cmd}" -k 10 "${per_test_timeout}" bun test ${coverage_args} --test-name-pattern "^(?!.*\\[experimental\\])" "${test_file}" > "${out_file}" 2>&1
193
- else
194
- "${timeout_cmd}" -k 10 "${per_test_timeout}" bun test ${coverage_args} "${test_file}" > "${out_file}" 2>&1
195
- fi
196
- else
197
- if [[ "${exclude_exp}" == "true" ]]; then
198
- bun test ${coverage_args} --test-name-pattern "^(?!.*\\[experimental\\])" "${test_file}" > "${out_file}" 2>&1
189
+ # Run the test file in its own bun process. Wrapped in a function so a
190
+ # transient infrastructure crash can be retried without duplicating the
191
+ # four-way (timeout × experimental-filter) invocation.
192
+ run_bun_test() {
193
+ if [[ -n "${timeout_cmd}" ]]; then
194
+ if [[ "${exclude_exp}" == "true" ]]; then
195
+ "${timeout_cmd}" -k 10 "${per_test_timeout}" bun test ${coverage_args} --test-name-pattern "^(?!.*\\[experimental\\])" "${test_file}" > "${out_file}" 2>&1
196
+ else
197
+ "${timeout_cmd}" -k 10 "${per_test_timeout}" bun test ${coverage_args} "${test_file}" > "${out_file}" 2>&1
198
+ fi
199
199
  else
200
- bun test ${coverage_args} "${test_file}" > "${out_file}" 2>&1
200
+ if [[ "${exclude_exp}" == "true" ]]; then
201
+ bun test ${coverage_args} --test-name-pattern "^(?!.*\\[experimental\\])" "${test_file}" > "${out_file}" 2>&1
202
+ else
203
+ bun test ${coverage_args} "${test_file}" > "${out_file}" 2>&1
204
+ fi
201
205
  fi
202
- fi
206
+ }
207
+
208
+ start_ms=$(perl -MTime::HiRes=time -e "printf \"%d\", time*1000")
209
+
210
+ run_bun_test
203
211
  exit_code=$?
204
212
 
213
+ # Retry once on a transient bun loader/runtime crash. Bun occasionally aborts
214
+ # a worker before its tests run — e.g. "# Unhandled error between tests" with
215
+ # "error: ENOENT reading <corrupted path>" — failing the whole job even though
216
+ # the file is green on a clean process. Such a crash truncates the run before
217
+ # any assertion executes, so it prints no "(fail)" line; genuine assertion
218
+ # failures do, and are reported immediately without a retry (fast feedback, no
219
+ # masking of intermittent real failures). Timeouts (124/137) are handled by the
220
+ # hang branch below, not here.
221
+ if [[ ${exit_code} -ne 0 && ${exit_code} -ne 124 && ${exit_code} -ne 137 ]] \
222
+ && ! grep -q "^(fail)" "${out_file}" 2>/dev/null; then
223
+ echo " ↻ ${base} (transient crash, exit ${exit_code} — retrying once)"
224
+ run_bun_test
225
+ exit_code=$?
226
+ fi
227
+
205
228
  end_ms=$(perl -MTime::HiRes=time -e "printf \"%d\", time*1000")
206
229
  elapsed=$(( end_ms - start_ms ))
207
230
 
208
- base="$(basename "${test_file}")"
209
-
210
231
  # Record duration for longest-first scheduling in future runs.
211
232
  # Write the repo-relative path (not the basename) so the lookup in future
212
233
  # runs disambiguates files that share a basename across directories.
@@ -745,7 +745,11 @@ describe("loadConfig startup behavior", () => {
745
745
  );
746
746
  expect(raw.llm.profiles.frontier.provider).toBe("anthropic");
747
747
  expect(raw.llm.profiles.frontier.model).toBe("claude-opus-4-8");
748
- expect(raw.llm.profiles["cost-optimized"].provider).toBe("anthropic");
748
+ // Speed is served by DeepSeek V4 Flash on Fireworks.
749
+ expect(raw.llm.profiles["cost-optimized"].provider).toBe("fireworks");
750
+ expect(raw.llm.profiles["cost-optimized"].model).toBe(
751
+ "accounts/fireworks/models/deepseek-v4-flash",
752
+ );
749
753
  });
750
754
 
751
755
  test("off-platform managed profiles are overwritten on every boot", () => {
@@ -1555,6 +1555,84 @@ describe("resolveCallSiteConfig sampling-param provenance (temperature / top_p)"
1555
1555
  expect(resolved.model).toBe("claude-opus-4-7");
1556
1556
  expect(resolved.topP).toBeNull();
1557
1557
  });
1558
+
1559
+ test("forceOverrideProfile: an explicit call-site temperature survives a forced profile silent on sampling", () => {
1560
+ const llm = LLMSchema.parse({
1561
+ default: fullDefault,
1562
+ profiles: {
1563
+ active: { verbosity: "low" },
1564
+ sitep: { provider: "anthropic", model: "claude-haiku-4-5-20251001" },
1565
+ forced: { model: "claude-opus-4-7", effort: "high" },
1566
+ },
1567
+ callSites: {
1568
+ memoryExtraction: {
1569
+ profile: "sitep",
1570
+ temperature: 0.7,
1571
+ maxTokens: 1000,
1572
+ },
1573
+ },
1574
+ activeProfile: "active",
1575
+ });
1576
+ const resolved = resolveCallSiteConfig("memoryExtraction", llm, {
1577
+ overrideProfile: "forced",
1578
+ forceOverrideProfile: true,
1579
+ });
1580
+ // The forced profile floats to the top for fields it sets.
1581
+ expect(resolved.model).toBe("claude-opus-4-7");
1582
+ expect(resolved.effort).toBe("high");
1583
+ // It is silent on temperature, so the deliberate call-site value survives —
1584
+ // consistent with sibling call-site fields like maxTokens (which flow
1585
+ // through the deep-merge).
1586
+ expect(resolved.temperature).toBe(0.7);
1587
+ expect(resolved.maxTokens).toBe(1000);
1588
+ });
1589
+
1590
+ test("forceOverrideProfile: a forced profile that sets temperature wins over the call-site override", () => {
1591
+ const llm = LLMSchema.parse({
1592
+ default: fullDefault,
1593
+ profiles: {
1594
+ sitep: { provider: "anthropic", model: "claude-haiku-4-5-20251001" },
1595
+ forced: { model: "claude-opus-4-7", temperature: 0.1 },
1596
+ },
1597
+ callSites: {
1598
+ memoryExtraction: { profile: "sitep", temperature: 0.7 },
1599
+ },
1600
+ });
1601
+ const resolved = resolveCallSiteConfig("memoryExtraction", llm, {
1602
+ overrideProfile: "forced",
1603
+ forceOverrideProfile: true,
1604
+ });
1605
+ // The forced profile explicitly sets temperature, so it floats above the
1606
+ // call-site override.
1607
+ expect(resolved.temperature).toBe(0.1);
1608
+ });
1609
+
1610
+ test("mainAgent: an explicit call-site temperature survives an active profile silent on sampling", () => {
1611
+ const llm = LLMSchema.parse({
1612
+ default: fullDefault,
1613
+ profiles: { active: { model: "claude-sonnet-4-7" } },
1614
+ callSites: { mainAgent: { temperature: 0.5 } },
1615
+ activeProfile: "active",
1616
+ });
1617
+ const resolved = resolveCallSiteConfig("mainAgent", llm);
1618
+ // The active profile floats above the call-site for mainAgent but is silent
1619
+ // on temperature, so the deliberate call-site value survives.
1620
+ expect(resolved.model).toBe("claude-sonnet-4-7");
1621
+ expect(resolved.temperature).toBe(0.5);
1622
+ });
1623
+
1624
+ test("mainAgent: the active profile's explicit temperature wins over a call-site temperature", () => {
1625
+ const llm = LLMSchema.parse({
1626
+ default: fullDefault,
1627
+ profiles: { active: { model: "claude-sonnet-4-7", temperature: 0.2 } },
1628
+ callSites: { mainAgent: { temperature: 0.5 } },
1629
+ activeProfile: "active",
1630
+ });
1631
+ const resolved = resolveCallSiteConfig("mainAgent", llm);
1632
+ // For mainAgent the active profile floats above the call-site override, so
1633
+ // its explicit temperature wins.
1634
+ expect(resolved.temperature).toBe(0.2);
1635
+ });
1558
1636
  });
1559
1637
 
1560
1638
  describe("resolveCallSiteConfig — workflowLeaf default", () => {
@@ -88,8 +88,15 @@ mock.module("../../../util/logger.js", () => ({
88
88
  }));
89
89
 
90
90
  mock.module("../../lib/cache-fs.js", () => ({
91
- readFileSync: (path: string, encoding?: BufferEncoding) => {
91
+ readFileSync: (path: string | number, encoding?: BufferEncoding) => {
92
+ // Stdin must be read via fd 0, not by reopening "/dev/stdin": a spawned
93
+ // subprocess whose stdin is a pipe (Bun.spawn stdin:"pipe") cannot reopen
94
+ // its read-end by path — open("/dev/stdin") fails ENXIO. Throwing here on
95
+ // the path makes any regression to path-based reading fail loudly.
92
96
  if (path === "/dev/stdin") {
97
+ throw new Error("ENXIO: no such device or address, open '/dev/stdin'");
98
+ }
99
+ if (path === 0) {
93
100
  if (mockStdinContent === null) {
94
101
  throw new Error("EAGAIN: resource temporarily unavailable");
95
102
  }
@@ -17,6 +17,9 @@ import { log } from "../logger.js";
17
17
  /** Warn (stderr) when a raw payload exceeds this byte count. */
18
18
  const MAX_PAYLOAD_BYTES = 1_000_000; // 1 MB
19
19
 
20
+ /** Standard input file descriptor. */
21
+ const STDIN_FD = 0;
22
+
20
23
  // ── TTL parsing ───────────────────────────────────────────────────────
21
24
 
22
25
  const TTL_PATTERN = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/;
@@ -99,6 +102,11 @@ function parseJsonPayload(raw: string, source: string): unknown {
99
102
  * Read JSON payload from stdin when piped. Throws when stdin is a TTY
100
103
  * (no piped input) or when the input is empty/invalid JSON, so the CLI
101
104
  * can surface actionable parse errors.
105
+ *
106
+ * Reads file descriptor 0 directly rather than reopening the `/dev/stdin`
107
+ * path. When the caller is a spawned subprocess whose stdin is a pipe (e.g.
108
+ * `Bun.spawn(..., { stdin: "pipe" })`), `open("/dev/stdin")` fails with ENXIO
109
+ * because a pipe read-end cannot be reopened by path; the fd is readable.
102
110
  */
103
111
  function readPayloadFromStdin(): unknown {
104
112
  if (process.stdin.isTTY) {
@@ -111,7 +119,7 @@ function readPayloadFromStdin(): unknown {
111
119
 
112
120
  let raw: string;
113
121
  try {
114
- raw = readFileSync("/dev/stdin", "utf-8");
122
+ raw = readFileSync(STDIN_FD, "utf-8");
115
123
  } catch (err) {
116
124
  throw new Error(
117
125
  `Failed to read stdin: ${err instanceof Error ? err.message : String(err)}.\n` +
@@ -173,10 +181,9 @@ export function registerCacheCommand(program: Command): void {
173
181
  transport: "ipc",
174
182
  description: "Interact with the assistant's in-memory key/value cache",
175
183
  build: (cache) => {
176
-
177
- cache.addHelpText(
178
- "after",
179
- `
184
+ cache.addHelpText(
185
+ "after",
186
+ `
180
187
  The cache is a TTL-aware, LRU-evicting in-memory store managed by the
181
188
  running assistant. Data is scoped to the assistant process lifetime and
182
189
  is not persisted across restarts.
@@ -190,33 +197,33 @@ Examples:
190
197
  $ echo '{"result": [1,2,3]}' | assistant cache set --ttl 5m
191
198
  $ assistant cache get my-key
192
199
  $ assistant cache delete my-key`,
193
- );
194
-
195
- // ── set ───────────────────────────────────────────────────────────
196
-
197
- cache
198
- .command("set")
199
- .description("Store a JSON value in the cache")
200
- .option(
201
- "--key <key>",
202
- "Cache key for idempotent upsert. Omit to auto-generate.",
203
- )
204
- .option(
205
- "--ttl <duration>",
206
- "Time-to-live (minimum 1s). Units: ms, s, m, h (e.g. 1000ms, 30s, 5m, 2h). Defaults to 30m if omitted.",
207
- )
208
- .option(
209
- "--value <json>",
210
- "JSON payload to store. Alternative to piping via stdin.",
211
- )
212
- .option(
213
- "--file <path>",
214
- "Path to a file containing the JSON payload. Alternative to piping via stdin.",
215
- )
216
- .option("--json", "Output result as machine-readable JSON.")
217
- .addHelpText(
218
- "after",
219
- `
200
+ );
201
+
202
+ // ── set ───────────────────────────────────────────────────────────
203
+
204
+ cache
205
+ .command("set")
206
+ .description("Store a JSON value in the cache")
207
+ .option(
208
+ "--key <key>",
209
+ "Cache key for idempotent upsert. Omit to auto-generate.",
210
+ )
211
+ .option(
212
+ "--ttl <duration>",
213
+ "Time-to-live (minimum 1s). Units: ms, s, m, h (e.g. 1000ms, 30s, 5m, 2h). Defaults to 30m if omitted.",
214
+ )
215
+ .option(
216
+ "--value <json>",
217
+ "JSON payload to store. Alternative to piping via stdin.",
218
+ )
219
+ .option(
220
+ "--file <path>",
221
+ "Path to a file containing the JSON payload. Alternative to piping via stdin.",
222
+ )
223
+ .option("--json", "Output result as machine-readable JSON.")
224
+ .addHelpText(
225
+ "after",
226
+ `
220
227
  Stores a JSON payload in the cache and prints the assigned key. The payload
221
228
  can be provided via --value, --file, or piped through stdin. If --key is
222
229
  provided, the entry is upserted (created or replaced). If omitted, a new
@@ -240,86 +247,86 @@ Examples:
240
247
  $ assistant cache set --file /tmp/payload.json --key scores --ttl 10m
241
248
  $ echo '{"scores":[98,85,72]}' | assistant cache set
242
249
  $ echo '"simple string"' | assistant cache set --ttl 1h --json`,
243
- )
244
- .action(
245
- async (opts: {
246
- key?: string;
247
- ttl?: string;
248
- value?: string;
249
- file?: string;
250
- json?: boolean;
251
- }) => {
252
- let data: unknown;
253
- try {
254
- data = resolvePayload(opts);
255
- } catch (err) {
256
- const msg = err instanceof Error ? err.message : String(err);
257
- if (opts.json) {
258
- process.stdout.write(
259
- JSON.stringify({ ok: false, error: msg }) + "\n",
260
- );
261
- } else {
262
- log.error(msg);
263
- }
264
- process.exitCode = 1;
265
- return;
266
- }
267
-
268
- let ttl_ms: number | undefined;
269
- try {
270
- ttl_ms = parseTtl(opts.ttl);
271
- } catch (err) {
272
- const msg = err instanceof Error ? err.message : String(err);
273
- if (opts.json) {
274
- process.stdout.write(
275
- JSON.stringify({ ok: false, error: msg }) + "\n",
276
- );
277
- } else {
278
- log.error(msg);
279
- }
280
- process.exitCode = 1;
281
- return;
282
- }
283
-
284
- const params: Record<string, unknown> = { data };
285
- if (ttl_ms !== undefined) params.ttl_ms = ttl_ms;
286
- if (opts.key) params.key = opts.key;
287
-
288
- const result = await cliIpcCall<{ key: string }>("cache_set", {
289
- body: params,
290
- });
291
-
292
- if (!result.ok) {
293
- if (opts.json) {
294
- process.stdout.write(
295
- JSON.stringify({ ok: false, error: result.error }) + "\n",
296
- );
297
- } else {
298
- log.error(`Error: ${result.error}`);
299
- }
300
- process.exitCode = 1;
301
- return;
302
- }
303
-
304
- if (opts.json) {
305
- process.stdout.write(
306
- JSON.stringify({ ok: true, key: result.result!.key }) + "\n",
307
- );
308
- } else {
309
- log.info(`Cached with key: ${result.result!.key}`);
310
- }
311
- },
312
- );
250
+ )
251
+ .action(
252
+ async (opts: {
253
+ key?: string;
254
+ ttl?: string;
255
+ value?: string;
256
+ file?: string;
257
+ json?: boolean;
258
+ }) => {
259
+ let data: unknown;
260
+ try {
261
+ data = resolvePayload(opts);
262
+ } catch (err) {
263
+ const msg = err instanceof Error ? err.message : String(err);
264
+ if (opts.json) {
265
+ process.stdout.write(
266
+ JSON.stringify({ ok: false, error: msg }) + "\n",
267
+ );
268
+ } else {
269
+ log.error(msg);
270
+ }
271
+ process.exitCode = 1;
272
+ return;
273
+ }
274
+
275
+ let ttl_ms: number | undefined;
276
+ try {
277
+ ttl_ms = parseTtl(opts.ttl);
278
+ } catch (err) {
279
+ const msg = err instanceof Error ? err.message : String(err);
280
+ if (opts.json) {
281
+ process.stdout.write(
282
+ JSON.stringify({ ok: false, error: msg }) + "\n",
283
+ );
284
+ } else {
285
+ log.error(msg);
286
+ }
287
+ process.exitCode = 1;
288
+ return;
289
+ }
290
+
291
+ const params: Record<string, unknown> = { data };
292
+ if (ttl_ms !== undefined) params.ttl_ms = ttl_ms;
293
+ if (opts.key) params.key = opts.key;
294
+
295
+ const result = await cliIpcCall<{ key: string }>("cache_set", {
296
+ body: params,
297
+ });
298
+
299
+ if (!result.ok) {
300
+ if (opts.json) {
301
+ process.stdout.write(
302
+ JSON.stringify({ ok: false, error: result.error }) + "\n",
303
+ );
304
+ } else {
305
+ log.error(`Error: ${result.error}`);
306
+ }
307
+ process.exitCode = 1;
308
+ return;
309
+ }
310
+
311
+ if (opts.json) {
312
+ process.stdout.write(
313
+ JSON.stringify({ ok: true, key: result.result!.key }) + "\n",
314
+ );
315
+ } else {
316
+ log.info(`Cached with key: ${result.result!.key}`);
317
+ }
318
+ },
319
+ );
313
320
 
314
- // ── get ───────────────────────────────────────────────────────────
321
+ // ── get ───────────────────────────────────────────────────────────
315
322
 
316
- cache
317
- .command("get <key>")
318
- .description("Retrieve a cached value by key")
319
- .option("--json", "Output result as machine-readable JSON.")
320
- .addHelpText(
321
- "after",
322
- `
323
+ cache
324
+ .command("get <key>")
325
+ .description("Retrieve a cached value by key")
326
+ .option("--json", "Output result as machine-readable JSON.")
327
+ .addHelpText(
328
+ "after",
329
+ `
323
330
  Arguments:
324
331
  key The cache key to look up. Run 'assistant cache set' to store a
325
332
  value and receive its key.
@@ -331,49 +338,52 @@ exist or has expired, reports not-found. In --json mode, a miss returns
331
338
  Examples:
332
339
  $ assistant cache get my-key
333
340
  $ assistant cache get my-key --json`,
334
- )
335
- .action(async (key: string, opts: { json?: boolean }) => {
336
- const result = await cliIpcCall<{ data: unknown } | null>("cache_get", {
337
- body: { key },
338
- });
339
-
340
- if (!result.ok) {
341
- if (opts.json) {
342
- process.stdout.write(
343
- JSON.stringify({ ok: false, error: result.error }) + "\n",
341
+ )
342
+ .action(async (key: string, opts: { json?: boolean }) => {
343
+ const result = await cliIpcCall<{ data: unknown } | null>(
344
+ "cache_get",
345
+ {
346
+ body: { key },
347
+ },
344
348
  );
345
- } else {
346
- log.error(`Error: ${result.error}`);
347
- }
348
- process.exitCode = 1;
349
- return;
350
- }
351
-
352
- if (opts.json) {
353
- process.stdout.write(
354
- JSON.stringify({
355
- ok: true,
356
- data: result.result ? result.result.data : null,
357
- }) + "\n",
358
- );
359
- } else {
360
- if (result.result == null) {
361
- log.info(`No cache entry found for key "${key}".`);
362
- } else {
363
- log.info(JSON.stringify(result.result.data, null, 2));
364
- }
365
- }
366
- });
367
-
368
- // ── delete ────────────────────────────────────────────────────────
369
-
370
- cache
371
- .command("delete <key>")
372
- .description("Remove a cached entry by key")
373
- .option("--json", "Output result as machine-readable JSON.")
374
- .addHelpText(
375
- "after",
376
- `
349
+
350
+ if (!result.ok) {
351
+ if (opts.json) {
352
+ process.stdout.write(
353
+ JSON.stringify({ ok: false, error: result.error }) + "\n",
354
+ );
355
+ } else {
356
+ log.error(`Error: ${result.error}`);
357
+ }
358
+ process.exitCode = 1;
359
+ return;
360
+ }
361
+
362
+ if (opts.json) {
363
+ process.stdout.write(
364
+ JSON.stringify({
365
+ ok: true,
366
+ data: result.result ? result.result.data : null,
367
+ }) + "\n",
368
+ );
369
+ } else {
370
+ if (result.result == null) {
371
+ log.info(`No cache entry found for key "${key}".`);
372
+ } else {
373
+ log.info(JSON.stringify(result.result.data, null, 2));
374
+ }
375
+ }
376
+ });
377
+
378
+ // ── delete ────────────────────────────────────────────────────────
379
+
380
+ cache
381
+ .command("delete <key>")
382
+ .description("Remove a cached entry by key")
383
+ .option("--json", "Output result as machine-readable JSON.")
384
+ .addHelpText(
385
+ "after",
386
+ `
377
387
  Arguments:
378
388
  key The cache key to remove. Run 'assistant cache get <key>' to
379
389
  verify a key exists before deleting.
@@ -384,36 +394,39 @@ existed or not, but reports whether an entry was actually removed.
384
394
  Examples:
385
395
  $ assistant cache delete my-key
386
396
  $ assistant cache delete my-key --json`,
387
- )
388
- .action(async (key: string, opts: { json?: boolean }) => {
389
- const result = await cliIpcCall<{ deleted: boolean }>("cache_delete", {
390
- body: { key },
391
- });
392
-
393
- if (!result.ok) {
394
- if (opts.json) {
395
- process.stdout.write(
396
- JSON.stringify({ ok: false, error: result.error }) + "\n",
397
+ )
398
+ .action(async (key: string, opts: { json?: boolean }) => {
399
+ const result = await cliIpcCall<{ deleted: boolean }>(
400
+ "cache_delete",
401
+ {
402
+ body: { key },
403
+ },
397
404
  );
398
- } else {
399
- log.error(`Error: ${result.error}`);
400
- }
401
- process.exitCode = 1;
402
- return;
403
- }
404
-
405
- const deleted = result.result!.deleted;
406
-
407
- if (opts.json) {
408
- process.stdout.write(JSON.stringify({ ok: true, deleted }) + "\n");
409
- } else {
410
- if (deleted) {
411
- log.info(`Deleted cache entry "${key}".`);
412
- } else {
413
- log.info(`No cache entry "${key}" (nothing to delete).`);
414
- }
415
- }
416
- });
405
+
406
+ if (!result.ok) {
407
+ if (opts.json) {
408
+ process.stdout.write(
409
+ JSON.stringify({ ok: false, error: result.error }) + "\n",
410
+ );
411
+ } else {
412
+ log.error(`Error: ${result.error}`);
413
+ }
414
+ process.exitCode = 1;
415
+ return;
416
+ }
417
+
418
+ const deleted = result.result!.deleted;
419
+
420
+ if (opts.json) {
421
+ process.stdout.write(JSON.stringify({ ok: true, deleted }) + "\n");
422
+ } else {
423
+ if (deleted) {
424
+ log.info(`Deleted cache entry "${key}".`);
425
+ } else {
426
+ log.info(`No cache entry "${key}" (nothing to delete).`);
427
+ }
428
+ }
429
+ });
417
430
  },
418
431
  });
419
432
  }
@@ -15,54 +15,17 @@
15
15
  * round-trip to the daemon.
16
16
  */
17
17
 
18
- import { existsSync, readFileSync, unlinkSync } from "node:fs";
19
-
20
18
  import type { Command } from "commander";
21
19
 
20
+ import {
21
+ probeMemoryWorker,
22
+ spawnMemoryWorkerProcess,
23
+ } from "../../../memory/worker-control.js";
22
24
  import { getMemoryWorkerPidPath } from "../../../util/platform.js";
23
25
  import { registerCommand } from "../../lib/register-command.js";
24
26
  import { log } from "../../logger.js";
25
27
  import { shouldOutputJson, writeOutput } from "../../output.js";
26
28
 
27
- // ---------------------------------------------------------------------------
28
- // PID file helpers
29
- // ---------------------------------------------------------------------------
30
-
31
- interface PidStatus {
32
- status: "running" | "not_running";
33
- pid?: number;
34
- }
35
-
36
- function probeWorker(): PidStatus {
37
- const pidPath = getMemoryWorkerPidPath();
38
- if (!existsSync(pidPath)) return { status: "not_running" };
39
-
40
- const raw = readFileSync(pidPath, "utf-8").trim();
41
- const pid = parseInt(raw, 10);
42
- if (!Number.isFinite(pid) || pid <= 0) return { status: "not_running" };
43
-
44
- try {
45
- process.kill(pid, 0);
46
- return { status: "running", pid };
47
- } catch (err: unknown) {
48
- if (
49
- err &&
50
- typeof err === "object" &&
51
- "code" in err &&
52
- err.code === "ESRCH"
53
- ) {
54
- // Stale PID file — clean it up.
55
- try {
56
- unlinkSync(pidPath);
57
- } catch {
58
- // best-effort
59
- }
60
- return { status: "not_running" };
61
- }
62
- throw err;
63
- }
64
- }
65
-
66
29
  // ---------------------------------------------------------------------------
67
30
  // `start`
68
31
  // ---------------------------------------------------------------------------
@@ -71,11 +34,13 @@ async function startWorker(
71
34
  opts: { json?: boolean },
72
35
  cmd: Command,
73
36
  ): Promise<void> {
74
- const current = probeWorker();
75
- if (current.status === "running") {
76
- const msg = `Memory worker is already running (PID ${current.pid})`;
37
+ let result: { pid: number; alreadyRunning: boolean };
38
+ try {
39
+ result = await spawnMemoryWorkerProcess();
40
+ } catch (err) {
41
+ const msg = err instanceof Error ? err.message : String(err);
77
42
  if (shouldOutputJson(cmd)) {
78
- writeOutput(cmd, { ok: false, error: msg, pid: current.pid });
43
+ writeOutput(cmd, { ok: false, error: msg });
79
44
  } else {
80
45
  log.error(msg);
81
46
  }
@@ -83,34 +48,10 @@ async function startWorker(
83
48
  return;
84
49
  }
85
50
 
86
- const pidPath = getMemoryWorkerPidPath();
87
- const entry = new URL("../../../memory/worker-process.ts", import.meta.url);
88
-
89
- // Spawn detached so the worker survives the CLI process exiting.
90
- const child = Bun.spawn({
91
- cmd: ["bun", "run", entry.pathname],
92
- stdio: ["ignore", "ignore", "ignore"],
93
- detached: true,
94
- });
95
-
96
- // Unreference so the CLI process doesn't wait for the child.
97
- child.unref();
98
-
99
- // Wait briefly for the PID file to appear (the worker writes it on startup).
100
- let pidWritten = false;
101
- for (let i = 0; i < 10; i++) {
102
- await Bun.sleep(100);
103
- if (existsSync(pidPath)) {
104
- pidWritten = true;
105
- break;
106
- }
107
- }
108
-
109
- if (!pidWritten) {
110
- const msg =
111
- "Memory worker was spawned but PID file did not appear within 1s";
51
+ if (result.alreadyRunning) {
52
+ const msg = `Memory worker is already running (PID ${result.pid})`;
112
53
  if (shouldOutputJson(cmd)) {
113
- writeOutput(cmd, { ok: false, error: msg });
54
+ writeOutput(cmd, { ok: false, error: msg, pid: result.pid });
114
55
  } else {
115
56
  log.error(msg);
116
57
  }
@@ -118,11 +59,14 @@ async function startWorker(
118
59
  return;
119
60
  }
120
61
 
121
- const pid = parseInt(readFileSync(pidPath, "utf-8").trim(), 10);
122
62
  if (shouldOutputJson(cmd)) {
123
- writeOutput(cmd, { ok: true, pid, pidPath });
63
+ writeOutput(cmd, {
64
+ ok: true,
65
+ pid: result.pid,
66
+ pidPath: getMemoryWorkerPidPath(),
67
+ });
124
68
  } else {
125
- log.info(`Memory worker started (PID ${pid})`);
69
+ log.info(`Memory worker started (PID ${result.pid})`);
126
70
  }
127
71
  }
128
72
 
@@ -131,7 +75,7 @@ async function startWorker(
131
75
  // ---------------------------------------------------------------------------
132
76
 
133
77
  function stopWorker(opts: { json?: boolean }, cmd: Command): void {
134
- const current = probeWorker();
78
+ const current = probeMemoryWorker();
135
79
  if (current.status !== "running" || current.pid == null) {
136
80
  const msg = "Memory worker is not running";
137
81
  if (shouldOutputJson(cmd)) {
@@ -169,7 +113,7 @@ function stopWorker(opts: { json?: boolean }, cmd: Command): void {
169
113
  // ---------------------------------------------------------------------------
170
114
 
171
115
  function statusWorker(opts: { json?: boolean }, cmd: Command): void {
172
- const result = probeWorker();
116
+ const result = probeMemoryWorker();
173
117
  if (shouldOutputJson(cmd)) {
174
118
  writeOutput(cmd, result);
175
119
  } else {
@@ -125,11 +125,16 @@ export function resolveCallSiteConfig(
125
125
 
126
126
  // Effective sampling params, tracked outside the deep-merge for the same
127
127
  // reason as `logitBias`: `temperature`/`top_p` are provider-coupled, so only
128
- // the winning profile may contribute them. Each profile fully determines the
129
- // pair (REPLACE — a profile that omits a param clears what a lower-precedence
130
- // profile set), while an explicit call-site override COALESCES on top (see
131
- // `appendProfileLayer` / `appendCallSiteLayers`).
132
- const samplingRef: SamplingRef = { temperature: undefined, topP: undefined };
128
+ // the winning profile may contribute them. A profile clears what a lower
129
+ // PROFILE set where it is silent (so a shadowed profile's sampling can't
130
+ // leak), while an explicit call-site override is sticky and survives a later
131
+ // silent profile (see `applyProfileSampling` / `appendCallSiteLayers`).
132
+ const samplingRef: SamplingRef = {
133
+ temperature: undefined,
134
+ topP: undefined,
135
+ temperatureFromCallSite: false,
136
+ topPFromCallSite: false,
137
+ };
133
138
 
134
139
  const activeFragment = resolveProfileFragment(llm.activeProfile, llm, opts);
135
140
  const overrideFragment = resolveProfileFragment(
@@ -224,6 +229,13 @@ type LogitBiasRef = { preset: ProfileEntry["logitBias"] };
224
229
  type SamplingRef = {
225
230
  temperature: ProfileEntry["temperature"];
226
231
  topP: ProfileEntry["topP"];
232
+ // Provenance of the current pair: `true` when a field came from an explicit
233
+ // call-site override (deliberate, sticky), `false` when it came from a profile
234
+ // (clearable by a higher-precedence profile that determines the model). Lets a
235
+ // silent higher profile clear a lower profile's sampling without discarding a
236
+ // deliberate call-site override.
237
+ temperatureFromCallSite: boolean;
238
+ topPFromCallSite: boolean;
227
239
  };
228
240
 
229
241
  // ---------------------------------------------------------------------------
@@ -383,6 +395,32 @@ function withImpliedProviderForKnownModel(source: Mergeable): Mergeable {
383
395
  };
384
396
  }
385
397
 
398
+ /**
399
+ * Fold a profile's sampling into `samplingRef`. A profile determines
400
+ * provider/model, so its pair supersedes any LOWER PROFILE's: set each field the
401
+ * profile specifies, and clear a lower profile's value where the profile is
402
+ * silent. A deliberate call-site override is NOT a profile and outranks a silent
403
+ * profile — it survives until a profile EXPLICITLY sets the field. (The mirror
404
+ * COALESCE for call-site overrides lives in `appendCallSiteLayers`.)
405
+ */
406
+ function applyProfileSampling(
407
+ samplingRef: SamplingRef,
408
+ profile: ProfileEntry,
409
+ ): void {
410
+ if (profile.temperature !== undefined) {
411
+ samplingRef.temperature = profile.temperature;
412
+ samplingRef.temperatureFromCallSite = false;
413
+ } else if (!samplingRef.temperatureFromCallSite) {
414
+ samplingRef.temperature = undefined;
415
+ }
416
+ if (profile.topP !== undefined) {
417
+ samplingRef.topP = profile.topP;
418
+ samplingRef.topPFromCallSite = false;
419
+ } else if (!samplingRef.topPFromCallSite) {
420
+ samplingRef.topP = undefined;
421
+ }
422
+ }
423
+
386
424
  function appendProfileLayer(
387
425
  layers: Mergeable[],
388
426
  profile: ProfileEntry | undefined,
@@ -391,11 +429,7 @@ function appendProfileLayer(
391
429
  ): void {
392
430
  if (profile != null) {
393
431
  biasRef.preset = profile.logitBias;
394
- // Each profile fully determines the sampling pair: a profile that omits
395
- // `temperature`/`topP` clears what a lower-precedence profile set, so the
396
- // winning (last-appended) profile is the sole profile source.
397
- samplingRef.temperature = profile.temperature;
398
- samplingRef.topP = profile.topP;
432
+ applyProfileSampling(samplingRef, profile);
399
433
  layers.push(profileConfigFragment(profile));
400
434
  }
401
435
  }
@@ -422,24 +456,29 @@ function appendCallSiteLayers(
422
456
  );
423
457
  }
424
458
  biasRef.preset = profileFragment.logitBias;
425
- samplingRef.temperature = profileFragment.temperature;
426
- samplingRef.topP = profileFragment.topP;
459
+ applyProfileSampling(samplingRef, profileFragment);
427
460
  layers.push(profileConfigFragment(profileFragment));
428
461
  }
429
462
  // Strip the `profile` discriminator (not a `LLMConfigBase` field) and the
430
463
  // sampling params before merging. An explicit call-site `temperature` /
431
464
  // `topP` is a deliberate per-site choice, so it COALESCES over the winning
432
- // profile's pair (only overriding the fields it sets) — routed through
433
- // `samplingRef` so it never inherits a shadowed profile's value via merge.
465
+ // profile's pair (only overriding the fields it sets) and is marked sticky
466
+ // so a later silent profile can't clear it — routed through `samplingRef` so
467
+ // it never inherits a shadowed profile's value via merge.
434
468
  const {
435
469
  profile: _profile,
436
470
  temperature: siteTemperature,
437
471
  topP: siteTopP,
438
472
  ...siteFragment
439
473
  } = site;
440
- if (siteTemperature !== undefined)
474
+ if (siteTemperature !== undefined) {
441
475
  samplingRef.temperature = siteTemperature;
442
- if (siteTopP !== undefined) samplingRef.topP = siteTopP;
476
+ samplingRef.temperatureFromCallSite = true;
477
+ }
478
+ if (siteTopP !== undefined) {
479
+ samplingRef.topP = siteTopP;
480
+ samplingRef.topPFromCallSite = true;
481
+ }
443
482
  layers.push(siteFragment as Mergeable);
444
483
  }
445
484
  }
@@ -78,6 +78,17 @@ export const MemoryJobsConfigSchema = MemoryJobsConfigInputSchema.transform(
78
78
  },
79
79
  ).describe("Memory background job processing configuration");
80
80
 
81
+ export const MemoryWorkerConfigSchema = z
82
+ .object({
83
+ enabled: z
84
+ .boolean({ error: "memory.worker.enabled must be a boolean" })
85
+ .default(false)
86
+ .describe(
87
+ "Whether the memory jobs worker runs as a separate OS process spawned at daemon startup (the `assistant memory worker` implementation) instead of on the daemon's main event loop. Only affects daemon startup; shutdown stops whichever worker is actually running.",
88
+ ),
89
+ })
90
+ .describe("Memory jobs worker process configuration");
91
+
81
92
  export const MemoryRetentionConfigSchema = z
82
93
  .object({
83
94
  keepRawForever: z
@@ -185,6 +196,7 @@ export const MemoryMaintenanceConfigSchema = z
185
196
  );
186
197
 
187
198
  export type MemoryJobsConfig = z.infer<typeof MemoryJobsConfigSchema>;
199
+ export type MemoryWorkerConfig = z.infer<typeof MemoryWorkerConfigSchema>;
188
200
  export type MemoryRetentionConfig = z.infer<typeof MemoryRetentionConfigSchema>;
189
201
  export type MemoryCleanupConfig = z.infer<typeof MemoryCleanupConfigSchema>;
190
202
  export type MemoryMaintenanceConfig = z.infer<
@@ -5,6 +5,7 @@ import {
5
5
  MemoryJobsConfigSchema,
6
6
  MemoryMaintenanceConfigSchema,
7
7
  MemoryRetentionConfigSchema,
8
+ MemoryWorkerConfigSchema,
8
9
  } from "./memory-lifecycle.js";
9
10
  import {
10
11
  MemoryExtractionConfigSchema,
@@ -39,6 +40,9 @@ export const MemoryConfigSchema = z
39
40
  MemorySegmentationConfigSchema.parse({}),
40
41
  ),
41
42
  jobs: MemoryJobsConfigSchema.default(MemoryJobsConfigSchema.parse({})),
43
+ worker: MemoryWorkerConfigSchema.default(
44
+ MemoryWorkerConfigSchema.parse({}),
45
+ ),
42
46
  retention: MemoryRetentionConfigSchema.default(
43
47
  MemoryRetentionConfigSchema.parse({}),
44
48
  ),
@@ -88,15 +88,24 @@ const MANAGED_PROFILE_TEMPLATES: Record<string, ManagedProfileTemplate> = {
88
88
  // profile there's nothing stronger to consult, so the advisor defaults off.
89
89
  advisorEnabled: false,
90
90
  },
91
+ // Served by DeepSeek V4 Flash on Fireworks via managed platform inference: a
92
+ // fast, low-cost open model. `model` is pinned explicitly rather than
93
+ // resolved via the `latency-optimized` intent (which still maps to Kimi K2.5
94
+ // on Fireworks and Anthropic Haiku elsewhere).
95
+ //
96
+ // `effort: "none"` (not "low") because Fireworks is not thinking-aware: the
97
+ // disabled `thinking` config is stripped before the request, so a non-"none"
98
+ // effort would be sent as `reasoning_effort` and make this profile pay for
99
+ // reasoning despite thinking being off. "none" keeps Speed non-reasoning.
91
100
  "cost-optimized": {
92
- intent: "latency-optimized",
93
- provider: "anthropic",
94
- connectionName: "anthropic-managed",
101
+ model: "accounts/fireworks/models/deepseek-v4-flash",
102
+ provider: "fireworks",
103
+ connectionName: "fireworks-managed",
95
104
  source: "managed",
96
105
  label: "Speed",
97
- description: "Fastest responses at lower cost",
106
+ description: "Fastest responses at lower cost (DeepSeek V4 Flash)",
98
107
  maxTokens: 8192,
99
- effort: "low",
108
+ effort: "none",
100
109
  thinking: { enabled: false, streamThinking: false },
101
110
  contextWindow: { maxInputTokens: DEFAULT_CONTEXT_WINDOW_MAX_INPUT_TOKENS },
102
111
  },
@@ -58,6 +58,7 @@ import { initQdrantClient, resolveQdrantUrl } from "../memory/qdrant-client.js";
58
58
  import { QdrantManager } from "../memory/qdrant-manager.js";
59
59
  import { rotateToolInvocations } from "../memory/tool-usage-store.js";
60
60
  import { sweepConceptPageFrontmatter } from "../memory/v2/frontmatter-sweep.js";
61
+ import { spawnMemoryWorkerProcess } from "../memory/worker-control.js";
61
62
  import { emitNotificationSignal } from "../notifications/emit-signal.js";
62
63
  import { backfillManualTokenConnections } from "../oauth/manual-token-connection.js";
63
64
  import { seedOAuthProviders } from "../oauth/seed-providers.js";
@@ -966,8 +967,33 @@ export async function runDaemon(): Promise<void> {
966
967
  }
967
968
  }
968
969
 
969
- log.info("Daemon startup: starting memory worker");
970
- bgRefs.memoryWorker = startMemoryJobsWorker();
970
+ // `memory.worker.enabled` selects which worker implementation the daemon
971
+ // starts: the out-of-process worker (spawned like `assistant memory
972
+ // worker start`) or the in-process worker on the daemon's event loop.
973
+ // This flag only affects startup — shutdown stops whichever worker is
974
+ // actually running (see shutdown-handlers.ts).
975
+ if (config.memory.worker.enabled) {
976
+ log.info(
977
+ "Daemon startup: starting memory worker as a separate process",
978
+ );
979
+ try {
980
+ const { pid, alreadyRunning } = await spawnMemoryWorkerProcess();
981
+ log.info(
982
+ { pid, alreadyRunning },
983
+ alreadyRunning
984
+ ? "Memory worker process already running — reusing it"
985
+ : "Memory worker process started",
986
+ );
987
+ } catch (err) {
988
+ log.warn(
989
+ { err },
990
+ "Failed to start memory worker process — memory jobs will not be processed",
991
+ );
992
+ }
993
+ } else {
994
+ log.info("Daemon startup: starting memory worker");
995
+ bgRefs.memoryWorker = startMemoryJobsWorker();
996
+ }
971
997
 
972
998
  // Seed capability graph nodes (new memory graph system)
973
999
  try {
@@ -5,6 +5,7 @@ import type { HeartbeatService } from "../heartbeat/heartbeat-service.js";
5
5
  import type { McpServerManager } from "../mcp/manager.js";
6
6
  import { getSqlite, resetDb } from "../memory/db-connection.js";
7
7
  import type { QdrantManager } from "../memory/qdrant-manager.js";
8
+ import { stopMemoryWorkerProcess } from "../memory/worker-control.js";
8
9
  import type { RuntimeHttpServer } from "../runtime/http-server.js";
9
10
  import { browserManager } from "../tools/browser/browser-manager.js";
10
11
  import { cleanupShellOutputTempFiles } from "../tools/shared/shell-output.js";
@@ -117,8 +118,27 @@ export function installShutdownHandlers(deps: ShutdownDeps): void {
117
118
  await browserManager.closeAllPages();
118
119
  cleanupShellOutputTempFiles();
119
120
  deps.scheduler.stop();
121
+
122
+ // Stop the in-process memory worker if one was started on the daemon's
123
+ // event loop (memory.worker.enabled = false).
120
124
  deps.getMemoryWorker()?.stop();
121
125
 
126
+ // Stop the out-of-process memory worker if it's actually running. This is
127
+ // keyed off live state rather than config: the worker may have been
128
+ // spawned at startup (memory.worker.enabled = true) or out of band via
129
+ // `assistant memory worker start`, so we stop whatever is actually there.
130
+ try {
131
+ const workerStatus = stopMemoryWorkerProcess();
132
+ if (workerStatus.status === "running") {
133
+ log.info(
134
+ { pid: workerStatus.pid },
135
+ "Sent SIGTERM to memory worker process",
136
+ );
137
+ }
138
+ } catch (err) {
139
+ log.warn({ err }, "Failed to stop memory worker process (non-fatal)");
140
+ }
141
+
122
142
  if (deps.mcpManager) {
123
143
  try {
124
144
  await deps.mcpManager.stop();
@@ -40,7 +40,7 @@ export class GeminiEmbeddingBackend implements EmbeddingBackend {
40
40
  this.taskType = options?.taskType;
41
41
  this.dimensions = options?.dimensions;
42
42
  this.managedBaseUrl = options?.managedBaseUrl;
43
- this.interCallDelayMs = options?.interCallDelayMs ?? 5000;
43
+ this.interCallDelayMs = options?.interCallDelayMs ?? 100;
44
44
  }
45
45
 
46
46
  /** True when requests route through the managed platform proxy. */
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Shared control surface for the memory jobs worker *process* — the detached
3
+ * OS process whose entry point is `worker-process.ts`.
4
+ *
5
+ * Both the `assistant memory worker` CLI and the daemon lifecycle (when
6
+ * `memory.worker.enabled` is set) need to probe, spawn, and stop this process,
7
+ * so the PID-file bookkeeping lives here in one place.
8
+ */
9
+
10
+ import { existsSync, readFileSync, unlinkSync } from "node:fs";
11
+
12
+ import { getMemoryWorkerPidPath } from "../util/platform.js";
13
+
14
+ export interface MemoryWorkerStatus {
15
+ status: "running" | "not_running";
16
+ pid?: number;
17
+ }
18
+
19
+ /**
20
+ * Inspect the PID file to determine whether the worker process is alive.
21
+ * A stale PID file (pointing at a dead process) is cleaned up and reported
22
+ * as not_running.
23
+ */
24
+ export function probeMemoryWorker(): MemoryWorkerStatus {
25
+ const pidPath = getMemoryWorkerPidPath();
26
+ if (!existsSync(pidPath)) return { status: "not_running" };
27
+
28
+ const raw = readFileSync(pidPath, "utf-8").trim();
29
+ const pid = parseInt(raw, 10);
30
+ if (!Number.isFinite(pid) || pid <= 0) return { status: "not_running" };
31
+
32
+ try {
33
+ process.kill(pid, 0);
34
+ return { status: "running", pid };
35
+ } catch (err: unknown) {
36
+ if (
37
+ err &&
38
+ typeof err === "object" &&
39
+ "code" in err &&
40
+ err.code === "ESRCH"
41
+ ) {
42
+ // Stale PID file — clean it up.
43
+ try {
44
+ unlinkSync(pidPath);
45
+ } catch {
46
+ // best-effort
47
+ }
48
+ return { status: "not_running" };
49
+ }
50
+ throw err;
51
+ }
52
+ }
53
+
54
+ export class MemoryWorkerSpawnError extends Error {}
55
+
56
+ /**
57
+ * Spawn the memory worker as a detached background process.
58
+ *
59
+ * If a worker is already running, returns its PID with `alreadyRunning: true`
60
+ * rather than spawning a second one. Throws {@link MemoryWorkerSpawnError} if
61
+ * the child is spawned but never writes its PID file (i.e. failed to start).
62
+ */
63
+ export async function spawnMemoryWorkerProcess(): Promise<{
64
+ pid: number;
65
+ alreadyRunning: boolean;
66
+ }> {
67
+ const current = probeMemoryWorker();
68
+ if (current.status === "running" && current.pid != null) {
69
+ return { pid: current.pid, alreadyRunning: true };
70
+ }
71
+
72
+ const pidPath = getMemoryWorkerPidPath();
73
+ const entry = new URL("./worker-process.ts", import.meta.url);
74
+
75
+ // Spawn detached so the worker survives the spawning process exiting.
76
+ const child = Bun.spawn({
77
+ cmd: ["bun", "run", entry.pathname],
78
+ stdio: ["ignore", "ignore", "ignore"],
79
+ detached: true,
80
+ });
81
+
82
+ // Unreference so the spawning process doesn't wait for the child.
83
+ child.unref();
84
+
85
+ // Wait briefly for the PID file to appear (the worker writes it on startup).
86
+ let pidWritten = false;
87
+ for (let i = 0; i < 10; i++) {
88
+ await Bun.sleep(100);
89
+ if (existsSync(pidPath)) {
90
+ pidWritten = true;
91
+ break;
92
+ }
93
+ }
94
+
95
+ if (!pidWritten) {
96
+ throw new MemoryWorkerSpawnError(
97
+ "Memory worker was spawned but PID file did not appear within 1s",
98
+ );
99
+ }
100
+
101
+ const pid = parseInt(readFileSync(pidPath, "utf-8").trim(), 10);
102
+ return { pid, alreadyRunning: false };
103
+ }
104
+
105
+ /**
106
+ * Send SIGTERM to the worker process if it is actually running.
107
+ *
108
+ * Returns the status observed before signalling, so callers can report
109
+ * whether anything was stopped. Only throws if `process.kill` itself fails
110
+ * (e.g. EPERM) — a not-running worker is a no-op.
111
+ */
112
+ export function stopMemoryWorkerProcess(): MemoryWorkerStatus {
113
+ const current = probeMemoryWorker();
114
+ if (current.status === "running" && current.pid != null) {
115
+ process.kill(current.pid, "SIGTERM");
116
+ }
117
+ return current;
118
+ }
@@ -864,13 +864,20 @@ export class AnthropicProvider implements Provider {
864
864
  (restConfig as Record<string, unknown>).model?.toString() ?? this.model;
865
865
  const isHaiku = effectiveModel.includes("haiku");
866
866
  const supportsEffort = !isHaiku;
867
- // opus-4-7 / opus-4-8 reject `temperature` and `top_p` with a 400
868
- // "`temperature`/`top_p` is deprecated for this model" — model-wide, not
867
+ // opus-4-7 / opus-4-8 reject `temperature`, `top_p`, and `top_k` with a
868
+ // 400 "`<param>` is deprecated for this model" — model-wide, not
869
869
  // effort-conditional (verified 2026-06-23). opus-4-6 / sonnet-4-6 /
870
870
  // haiku-4-5 still accept them. fable-5 is included conservatively (a
871
871
  // frontier model that could not be verified directly but follows the same
872
872
  // deprecation direction). Stripping the params here keeps callers that set
873
873
  // them (e.g. the memory-v3 L2 selector's `temperature: 0`) from 400ing.
874
+ //
875
+ // This dash-form predicate targets the direct Anthropic API. The
876
+ // OpenRouter delegation reuses this provider with dotted catalog IDs
877
+ // (`anthropic/claude-opus-4.8`), which it deliberately does not match:
878
+ // OpenRouter's Messages endpoint accepts these params for the same models
879
+ // (verified 2026-06-23, 200), so stripping there would alter sampling on a
880
+ // working path rather than avert a 400.
874
881
  const deprecatesSamplingParams =
875
882
  /claude-opus-4-[78]\b/.test(effectiveModel) ||
876
883
  effectiveModel.startsWith("claude-fable-");
@@ -760,6 +760,22 @@ const RAW_PROVIDER_CATALOG: ProviderCatalogEntry[] = [
760
760
  maxEffort: "max",
761
761
  pricing: { inputPer1mTokens: 1.74, outputPer1mTokens: 3.48 },
762
762
  },
763
+ {
764
+ id: "accounts/fireworks/models/deepseek-v4-flash",
765
+ displayName: "DeepSeek V4 Flash",
766
+ contextWindowTokens: 1040000,
767
+ maxOutputTokens: 131072,
768
+ supportsThinking: true,
769
+ supportsCaching: true,
770
+ supportsVision: false,
771
+ supportsToolUse: true,
772
+ maxEffort: "max",
773
+ pricing: {
774
+ inputPer1mTokens: 0.14,
775
+ outputPer1mTokens: 0.28,
776
+ cacheReadPer1mTokens: 0.03,
777
+ },
778
+ },
763
779
  ],
764
780
  defaultModel: "accounts/fireworks/models/kimi-k2p5",
765
781
  apiKeyUrl: "https://fireworks.ai/account/api-keys",