mixdog 0.9.149 → 0.9.151

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 (113) hide show
  1. package/README.md +28 -12
  2. package/package.json +1 -1
  3. package/src/headless-exec.mjs +40 -4
  4. package/src/headless-exec.test.mjs +116 -1
  5. package/src/rules/lead/01-general.md +3 -2
  6. package/src/rules/shared/00-general.md +1 -0
  7. package/src/rules/shared/10-tool-workflow.md +11 -12
  8. package/src/rules/shared/30-exploration.md +4 -3
  9. package/src/rules/shared/60-verification.md +4 -3
  10. package/src/runtime/agent/orchestrator/providers/openai-codex-identity.test.mjs +0 -2
  11. package/src/runtime/agent/orchestrator/providers/openai-codex-metadata.mjs +1 -4
  12. package/src/runtime/agent/orchestrator/providers/openai-codex-model.mjs +0 -18
  13. package/src/runtime/agent/orchestrator/providers/openai-oauth-http-sse.mjs +0 -3
  14. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +0 -1
  15. package/src/runtime/agent/orchestrator/providers/openai-responses-payload.mjs +4 -72
  16. package/src/runtime/agent/orchestrator/session/approval-mode.mjs +0 -8
  17. package/src/runtime/agent/orchestrator/session/compact/handoff.mjs +2 -4
  18. package/src/runtime/agent/orchestrator/session/compact/runner.mjs +18 -33
  19. package/src/runtime/agent/orchestrator/session/loop/recall-fasttrack.mjs +21 -42
  20. package/src/runtime/agent/orchestrator/session/manager/compaction-runner.mjs +20 -125
  21. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +50 -8
  22. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.test.mjs +31 -1
  23. package/src/runtime/agent/orchestrator/session/store/serialize.mjs +27 -4
  24. package/src/runtime/agent/orchestrator/session/store/serialize.test.mjs +60 -0
  25. package/src/runtime/agent/orchestrator/session/task-wait-control.mjs +78 -0
  26. package/src/runtime/agent/orchestrator/session/task-wait-control.test.mjs +78 -0
  27. package/src/runtime/agent/orchestrator/tools/builtin/absence-absorption.test.mjs +43 -0
  28. package/src/runtime/agent/orchestrator/tools/builtin/absolute-glob-expand.test.mjs +63 -0
  29. package/src/runtime/agent/orchestrator/tools/builtin/arg-guard.mjs +8 -0
  30. package/src/runtime/agent/orchestrator/tools/builtin/atomic-write.mjs +29 -10
  31. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +7 -7
  32. package/src/runtime/agent/orchestrator/tools/builtin/enoent-outside-project.test.mjs +56 -0
  33. package/src/runtime/agent/orchestrator/tools/builtin/external-tool-adapters.mjs +6 -2
  34. package/src/runtime/agent/orchestrator/tools/builtin/git-command-tool.mjs +50 -23
  35. package/src/runtime/agent/orchestrator/tools/builtin/git-command-tool.test.mjs +50 -1
  36. package/src/runtime/agent/orchestrator/tools/builtin/grep-output-budget.test.mjs +31 -0
  37. package/src/runtime/agent/orchestrator/tools/builtin/grep-single-file-rescue.test.mjs +106 -0
  38. package/src/runtime/agent/orchestrator/tools/builtin/lib/absolute-glob-expand.mjs +129 -0
  39. package/src/runtime/agent/orchestrator/tools/builtin/lib/grep-context-expander.mjs +2 -1
  40. package/src/runtime/agent/orchestrator/tools/builtin/lib/grep-single-file-rescue.mjs +218 -0
  41. package/src/runtime/agent/orchestrator/tools/builtin/lib/list-helpers.mjs +9 -2
  42. package/src/runtime/agent/orchestrator/tools/builtin/list-tool-integrity.test.mjs +6 -0
  43. package/src/runtime/agent/orchestrator/tools/builtin/list-tool.mjs +50 -2
  44. package/src/runtime/agent/orchestrator/tools/builtin/native-search-client.mjs +7 -1
  45. package/src/runtime/agent/orchestrator/tools/builtin/noise-dir-visibility.test.mjs +69 -0
  46. package/src/runtime/agent/orchestrator/tools/builtin/path-diagnostics.mjs +33 -6
  47. package/src/runtime/agent/orchestrator/tools/builtin/read-glob-survey.test.mjs +71 -0
  48. package/src/runtime/agent/orchestrator/tools/builtin/read-image-resize.mjs +6 -1
  49. package/src/runtime/agent/orchestrator/tools/builtin/read-single-tool.mjs +7 -0
  50. package/src/runtime/agent/orchestrator/tools/builtin/read-tool.mjs +54 -8
  51. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +90 -51
  52. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.test.mjs +56 -0
  53. package/src/runtime/agent/orchestrator/tools/builtin/search-builders.mjs +25 -0
  54. package/src/runtime/agent/orchestrator/tools/builtin/search-builders.test.mjs +16 -0
  55. package/src/runtime/agent/orchestrator/tools/builtin/search-glob-tool.mjs +30 -1
  56. package/src/runtime/agent/orchestrator/tools/builtin/search-grep-tool.mjs +60 -5
  57. package/src/runtime/agent/orchestrator/tools/builtin/search-path-diagnostics.mjs +54 -1
  58. package/src/runtime/agent/orchestrator/tools/builtin/task-tool.mjs +49 -24
  59. package/src/runtime/agent/orchestrator/tools/builtin/tool-output-limit.mjs +1 -0
  60. package/src/runtime/agent/orchestrator/tools/builtin/write-symlink.test.mjs +153 -0
  61. package/src/runtime/agent/orchestrator/tools/builtin.mjs +11 -1
  62. package/src/runtime/agent/orchestrator/tools/code-graph/aggregate-anchor-relocation.test.mjs +55 -0
  63. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +54 -3
  64. package/src/runtime/agent/orchestrator/tools/env-scrub.mjs +16 -0
  65. package/src/runtime/agent/orchestrator/tools/env-scrub.test.mjs +33 -1
  66. package/src/runtime/agent/orchestrator/tools/graph-manifest.json +11 -11
  67. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +9 -1
  68. package/src/runtime/agent/orchestrator/tools/patch/dispatch.mjs +44 -10
  69. package/src/runtime/agent/orchestrator/tools/patch/orchestrator.mjs +57 -5
  70. package/src/runtime/agent/orchestrator/tools/patch/patch-symlink.test.mjs +141 -0
  71. package/src/runtime/agent/orchestrator/tools/patch/v4a-convert.mjs +7 -3
  72. package/src/runtime/agent/orchestrator/tools/patch/v4a-pure-move.test.mjs +57 -0
  73. package/src/runtime/agent/orchestrator/tools/patch/v4a-section-coalesce.test.mjs +81 -0
  74. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +42 -23
  75. package/src/runtime/media/renditions.mjs +7 -1
  76. package/src/runtime/memory/index.mjs +2 -4
  77. package/src/runtime/memory/lib/pg/process.mjs +29 -2
  78. package/src/runtime/memory/lib/pg/process.test.mjs +36 -0
  79. package/src/runtime/memory/lib/pg/supervisor.mjs +5 -1
  80. package/src/runtime/memory/lib/query-handlers.mjs +13 -19
  81. package/src/runtime/memory/lib/recall-format.mjs +13 -31
  82. package/src/runtime/memory/tool-defs.mjs +2 -2
  83. package/src/runtime/shared/memory-snapshot.mjs +57 -4
  84. package/src/runtime/shared/pristine-execution-contract.json +3 -0
  85. package/src/runtime/shared/pristine-execution.mjs +6 -3
  86. package/src/runtime/shared/tool-surface.mjs +6 -0
  87. package/src/runtime/shared/tool-surface.test.mjs +8 -0
  88. package/src/session-runtime/lifecycle-api.mjs +1 -0
  89. package/src/session-runtime/session-turn-api.mjs +5 -0
  90. package/src/standalone/agent-dispatch-broker.mjs +25 -80
  91. package/src/standalone/channel-worker-heartbeat.test.mjs +30 -0
  92. package/src/standalone/channel-worker.mjs +31 -1
  93. package/src/standalone/daemon.mjs +9 -9
  94. package/src/standalone/memory-runtime-proxy.mjs +5 -2
  95. package/src/standalone/session-client.mjs +23 -3
  96. package/src/standalone/session-runtime-host-health.test.mjs +36 -0
  97. package/src/standalone/session-runtime-host.mjs +26 -76
  98. package/src/standalone/session-runtime-worker.mjs +97 -0
  99. package/src/tui/App.jsx +3 -2
  100. package/src/tui/app/use-global-key-input.mjs +9 -0
  101. package/src/tui/app/use-mouse-input.mjs +77 -14
  102. package/src/tui/components/Spinner.jsx +1 -1
  103. package/src/tui/dist/index.mjs +83 -23
  104. package/src/tui/lib/voice-setup.mjs +3 -2
  105. package/src/tui/session/completion-card-restore.test.mjs +18 -0
  106. package/src/tui/session/session-api-ext.mjs +2 -1
  107. package/src/tui/session/session-api.mjs +8 -1
  108. package/src/tui/session/task-wait-submit.test.mjs +80 -0
  109. package/src/tui/session/turn.mjs +58 -6
  110. package/src/tui/spinner-verbs.mjs +1 -0
  111. package/src/workflows/default/WORKFLOW.md +12 -19
  112. package/src/workflows/headless/WORKFLOW.md +11 -0
  113. package/src/workflows/solo/WORKFLOW.md +6 -11
@@ -28,42 +28,26 @@ function dispatchSignature(agent, params) {
28
28
  } catch { return null; }
29
29
  }
30
30
 
31
- function awaitSharedPreparation(promise, signal) {
32
- if (!signal) return promise;
33
- if (signal.aborted) return Promise.reject(abortError(signal));
34
- let listener = null;
35
- const aborted = new Promise((_, reject) => {
36
- listener = () => reject(abortError(signal));
37
- signal.addEventListener('abort', listener, { once: true });
38
- });
39
- return Promise.race([promise, aborted]).finally(() => {
40
- if (listener) {
41
- try { signal.removeEventListener('abort', listener); } catch {}
42
- }
43
- });
44
- }
45
-
46
31
  /**
47
32
  * Process-singleton memory LLM broker.
48
33
  *
49
- * The daemon owns one provider/session/memory graph. Memory
50
- * process keeps PG, embeddings, and recall, and forwards only cycle LLM calls
51
- * here. A singleton is NOT a serial lane: every call gets its own dispatch
52
- * session + AbortController and the fair scheduler starts calls in parallel
53
- * unless an operator explicitly configures a finite active limit.
34
+ * The memory process keeps PG, embeddings, and recall, and forwards only
35
+ * cycle LLM calls here. The broker owns admission (fair scheduler), callId
36
+ * idempotency, and cancellation; actual agent execution is delegated through
37
+ * dispatchAgent to the recyclable session runtime worker so orchestrator and
38
+ * provider churn never accumulates in the permanent daemon process. A
39
+ * singleton is NOT a serial lane: every call gets its own AbortController and
40
+ * the fair scheduler starts calls in parallel unless an operator explicitly
41
+ * configures a finite active limit.
54
42
  */
55
43
  export function createAgentDispatchBroker({
56
- loadConfig,
57
- initProviders,
58
- makeAgentDispatch,
44
+ dispatchAgent,
59
45
  log = () => {},
60
46
  activeMax = Infinity,
61
47
  queueMax = 256,
62
48
  onActivityChanged = null,
63
49
  } = {}) {
64
- if (typeof loadConfig !== 'function') throw new TypeError('loadConfig is required');
65
- if (typeof initProviders !== 'function') throw new TypeError('initProviders is required');
66
- if (typeof makeAgentDispatch !== 'function') throw new TypeError('makeAgentDispatch is required');
50
+ if (typeof dispatchAgent !== 'function') throw new TypeError('dispatchAgent is required');
67
51
 
68
52
  const scheduler = createFairCallScheduler({
69
53
  name: 'memory agent dispatch',
@@ -72,51 +56,8 @@ export function createAgentDispatchBroker({
72
56
  minOwnerQueue: Math.max(8, Math.floor(queueMax / 16)),
73
57
  });
74
58
  const inFlight = new Map();
75
- const dispatchers = new Map(MEMORY_AGENTS.map((agent) => [
76
- agent,
77
- makeAgentDispatch({
78
- agent,
79
- taskType: 'maintenance',
80
- sourceType: 'memory-cycle',
81
- brief: false,
82
- }),
83
- ]));
84
59
  let nextCallId = 0;
85
60
  let closed = false;
86
- let preparedProviderSignature = null;
87
- let providerPreparePromise = null;
88
-
89
- async function prepareProviders(signal = null) {
90
- const config = loadConfig();
91
- const providers = config?.providers || {};
92
- let signature = null;
93
- try { signature = JSON.stringify(providers); } catch {}
94
- if (signature !== null && preparedProviderSignature === signature) return;
95
- if (providerPreparePromise) {
96
- await awaitSharedPreparation(providerPreparePromise, signal);
97
- if (signature !== null && preparedProviderSignature === signature) return;
98
- return prepareProviders(signal);
99
- }
100
- const pending = Promise.resolve()
101
- // Process-global preparation is shared by every request. One caller's
102
- // cancellation may stop waiting but must never abort initialization
103
- // underneath independent calls.
104
- .then(() => initProviders(providers))
105
- .then(() => {
106
- preparedProviderSignature = signature;
107
- });
108
- const tracked = pending.finally(() => {
109
- if (providerPreparePromise === tracked) providerPreparePromise = null;
110
- });
111
- providerPreparePromise = tracked;
112
- await awaitSharedPreparation(tracked, signal);
113
- }
114
-
115
- async function warmup() {
116
- if (closed) throw new Error('memory agent dispatch broker is closed');
117
- await prepareProviders();
118
- return true;
119
- }
120
61
 
121
62
  function dispatch(params = {}, { callId = null, signal = null } = {}) {
122
63
  if (closed) return Promise.reject(new Error('memory agent dispatch broker is closed'));
@@ -156,17 +97,23 @@ export function createAgentDispatchBroker({
156
97
  else signal?.addEventListener?.('abort', abortFromCaller, { once: true });
157
98
 
158
99
  const run = async () => {
159
- if (controller.signal.aborted) throw abortError(controller.signal);
160
- await prepareProviders(controller.signal);
161
100
  if (controller.signal.aborted) throw abortError(controller.signal);
162
101
  const timeout = Number(params.timeout);
163
- return dispatchers.get(agent)({
164
- prompt,
165
- preset: params.preset || undefined,
166
- cwd: typeof params.cwd === 'string' && params.cwd ? params.cwd : undefined,
167
- parentSignal: controller.signal,
168
- ...(Number.isFinite(timeout) && timeout > 0 ? { idleTimeoutMs: timeout } : {}),
169
- });
102
+ // Execution happens in the recyclable session runtime worker, not in
103
+ // this permanent daemon process: provider/orchestrator churn from
104
+ // memory-cycle agents returns to the OS at the worker's next memory
105
+ // recycle instead of accumulating in daemon commit forever.
106
+ return dispatchAgent({
107
+ dispatchId: id,
108
+ agent,
109
+ options: { taskType: 'maintenance', sourceType: 'memory-cycle', brief: false },
110
+ params: {
111
+ prompt,
112
+ preset: params.preset || undefined,
113
+ cwd: typeof params.cwd === 'string' && params.cwd ? params.cwd : undefined,
114
+ ...(Number.isFinite(timeout) && timeout > 0 ? { idleTimeoutMs: timeout } : {}),
115
+ },
116
+ }, { signal: controller.signal });
170
117
  };
171
118
  const promise = scheduler.enqueue(`memory:${agent}`, run, {
172
119
  signal: controller.signal,
@@ -204,7 +151,6 @@ export function createAgentDispatchBroker({
204
151
  return {
205
152
  ...scheduler.snapshot(),
206
153
  inFlight: inFlight.size,
207
- dispatchers: dispatchers.size,
208
154
  };
209
155
  }
210
156
 
@@ -219,7 +165,6 @@ export function createAgentDispatchBroker({
219
165
  }
220
166
 
221
167
  return {
222
- warmup,
223
168
  dispatch,
224
169
  cancel,
225
170
  cancelAndWait,
@@ -0,0 +1,30 @@
1
+ import assert from 'node:assert/strict';
2
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import test from 'node:test';
6
+
7
+ import { pruneStaleChannelClientHeartbeats } from './channel-worker.mjs';
8
+
9
+ test('channel heartbeat sweep removes dead and expired rows only', () => {
10
+ const root = mkdtempSync(join(tmpdir(), 'mixdog-channel-heartbeat-test-'));
11
+ const now = 100_000;
12
+ try {
13
+ writeFileSync(join(root, '1.json'), JSON.stringify({ pid: 1, updatedAt: now - 1_000 }));
14
+ writeFileSync(join(root, '2.json'), JSON.stringify({ pid: 2, updatedAt: now - 60_000 }));
15
+ writeFileSync(join(root, '3.json'), JSON.stringify({ pid: 3, updatedAt: now - 1_000 }));
16
+
17
+ const removed = pruneStaleChannelClientHeartbeats(root, {
18
+ now,
19
+ maxAgeMs: 30_000,
20
+ pidAlive: (pid) => pid !== 3,
21
+ });
22
+
23
+ assert.equal(removed, 2);
24
+ assert.equal(existsSync(join(root, '1.json')), true);
25
+ assert.equal(existsSync(join(root, '2.json')), false);
26
+ assert.equal(existsSync(join(root, '3.json')), false);
27
+ } finally {
28
+ rmSync(root, { recursive: true, force: true });
29
+ }
30
+ });
@@ -1,9 +1,10 @@
1
1
  import { fork } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { mkdirSync, rmSync, writeFile } from 'node:fs';
3
+ import { mkdirSync, readFileSync, readdirSync, rmSync, writeFile } from 'node:fs';
4
4
  import { dirname, join, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { appendBuffered } from '../runtime/shared/buffered-appender.mjs';
7
+ import { isPidAlive } from '../runtime/shared/pid-liveness.mjs';
7
8
  import { ensurePrivateRuntimeRoot, resolveRuntimeRoot } from '../runtime/shared/runtime-root.mjs';
8
9
  import { detachedSpawnOpts } from '../runtime/shared/spawn-flags.mjs';
9
10
  import { scrubLoaderVars } from '../runtime/agent/orchestrator/tools/env-scrub.mjs';
@@ -34,6 +35,34 @@ function logLine(path, line) {
34
35
  const CHANNEL_WORKER_EXIT_CLEANUPS = new Set();
35
36
  let channelWorkerExitHookInstalled = false;
36
37
 
38
+ export function pruneStaleChannelClientHeartbeats(clientDir, {
39
+ now = Date.now(),
40
+ maxAgeMs = 30_000,
41
+ pidAlive = isPidAlive,
42
+ } = {}) {
43
+ let removed = 0;
44
+ try {
45
+ for (const name of readdirSync(clientDir)) {
46
+ if (!/^\d+\.json$/.test(name)) continue;
47
+ const target = join(clientDir, name);
48
+ let row = null;
49
+ try { row = JSON.parse(readFileSync(target, 'utf8')); } catch {}
50
+ const pid = Number(row?.pid);
51
+ const updatedAt = Number(row?.updatedAt);
52
+ const stale = !Number.isInteger(pid) || pid <= 0
53
+ || !Number.isFinite(updatedAt)
54
+ || now - updatedAt > Math.max(5_000, Number(maxAgeMs) || 30_000)
55
+ || !pidAlive(pid);
56
+ if (!stale) continue;
57
+ try {
58
+ rmSync(target, { force: true });
59
+ removed += 1;
60
+ } catch {}
61
+ }
62
+ } catch {}
63
+ return removed;
64
+ }
65
+
37
66
  function registerChannelWorkerExitCleanup(cleanup) {
38
67
  if (typeof cleanup !== 'function') return () => {};
39
68
  CHANNEL_WORKER_EXIT_CLEANUPS.add(cleanup);
@@ -82,6 +111,7 @@ export function createStandaloneChannelWorker({
82
111
  try {
83
112
  if (!clientDirReady) {
84
113
  mkdirSync(clientDir, { recursive: true });
114
+ pruneStaleChannelClientHeartbeats(clientDir);
85
115
  clientDirReady = true;
86
116
  }
87
117
  writeFile(clientPath, JSON.stringify({
@@ -49,10 +49,6 @@ import { resourceAdmission } from '../runtime/shared/resource-admission.mjs';
49
49
  import { snapshot as childSpawnSnapshot } from '../runtime/shared/child-spawn-gate.mjs';
50
50
  import { toolWorkloadSnapshot } from '../runtime/shared/tool-workload-gates.mjs';
51
51
  import { providerAdmissionScheduler } from '../runtime/agent/orchestrator/providers/admission-scheduler.mjs';
52
- import { getMcpAdmissionSnapshot } from '../runtime/agent/orchestrator/mcp/client.mjs';
53
- import { loadConfig as loadAgentConfig } from '../runtime/agent/orchestrator/config.mjs';
54
- import { initProviders } from '../runtime/agent/orchestrator/providers/registry.mjs';
55
- import { makeAgentDispatch } from '../runtime/agent/orchestrator/agent-runtime/agent-dispatch.mjs';
56
52
  import {
57
53
  closeProviderStreamJsonPool,
58
54
  providerStreamJsonSnapshot,
@@ -420,9 +416,13 @@ async function main() {
420
416
  process.on('exit', () => { try { releaseSingletonOwner(OWNER_PATH, process.pid); } catch {} });
421
417
  startMemoryRuntimeEarly();
422
418
  agentDispatchBroker = createAgentDispatchBroker({
423
- loadConfig: loadAgentConfig,
424
- initProviders,
425
- makeAgentDispatch,
419
+ // Memory-cycle agents execute inside the recyclable session runtime
420
+ // worker: this permanent daemon never loads the orchestrator graph for
421
+ // them, so its commit stays flat across cycles.
422
+ dispatchAgent: (payload, options) => {
423
+ if (!sessionRuntimeHost) throw new Error('session runtime host is not ready');
424
+ return sessionRuntimeHost.agentDispatch(payload, options);
425
+ },
426
426
  log,
427
427
  onActivityChanged: () => { maybeSelfShutdown('memory agent activity changed'); },
428
428
  });
@@ -583,7 +583,6 @@ async function main() {
583
583
  sessionRuntimeHost = createSessionRuntimeHost({
584
584
  cwd: CWD,
585
585
  log,
586
- canRecycle: () => (sessionService?.busyCount ?? 1) === 0,
587
586
  });
588
587
  function prewarmSessionRuntime() {
589
588
  if (sessionRuntimePrewarmPromise) return sessionRuntimePrewarmPromise;
@@ -651,7 +650,8 @@ async function main() {
651
650
  resources: resourceAdmission.snapshot(),
652
651
  childSpawns: childSpawnSnapshot(),
653
652
  toolIo: toolWorkloadSnapshot(),
654
- mcp: getMcpAdmissionSnapshot(),
653
+ // MCP runs in session/agent workers, never in this daemon process.
654
+ mcp: {},
655
655
  providers: providerAdmissionScheduler.snapshot(),
656
656
  streamParsing: providerStreamJsonSnapshot(),
657
657
  },
@@ -650,9 +650,12 @@ export function createStandaloneMemoryRuntime({
650
650
  const ownedChild = child;
651
651
  const childExit = waitForExit && ownedChild && ownedChild.exitCode == null
652
652
  ? new Promise((resolveExit, rejectExit) => {
653
- const onExit = () => {
653
+ const onExit = (code, signal) => {
654
654
  clearTimeout(timer);
655
- resolveExit(true);
655
+ if (code === 0) resolveExit(true);
656
+ else rejectExit(new Error(
657
+ `memory runtime exited unsuccessfully (${signal || code || 'unknown'})`,
658
+ ));
656
659
  };
657
660
  const timer = setTimeout(() => {
658
661
  ownedChild.off('exit', onExit);
@@ -677,15 +677,35 @@ export async function attachSession({
677
677
 
678
678
  /** Ask a live daemon to exit. Used by dev/test teardown; normal clients just
679
679
  * detach and let the client-grace shutdown fire. */
680
- export async function shutdownDaemon(discovery = readSessionDiscovery()) {
680
+ export async function shutdownDaemon(discovery = readSessionDiscovery(), {
681
+ waitForExit = false,
682
+ timeoutMs = 15_000,
683
+ } = {}) {
681
684
  if (!discovery?.port) return false;
685
+ const daemonPid = Number(discovery.pid);
682
686
  try {
683
687
  await request({
684
688
  port: discovery.port, token: discovery.token, method: 'POST',
685
689
  path: '/shutdown', body: {}, timeoutMs: 3000, control: true,
686
690
  });
687
- return true;
688
- } catch { return false; }
691
+ } catch {
692
+ return Number.isInteger(daemonPid) && daemonPid > 0 && !isPidAlive(daemonPid);
693
+ }
694
+ if (!waitForExit || !Number.isInteger(daemonPid) || daemonPid <= 0) return true;
695
+ const deadline = Date.now() + Math.max(1, Number(timeoutMs) || 15_000);
696
+ while (isPidAlive(daemonPid) && Date.now() < deadline) await delay(50);
697
+ if (isPidAlive(daemonPid)) {
698
+ throw new Error(`session daemon pid=${daemonPid} did not exit within ${timeoutMs}ms`);
699
+ }
700
+ return true;
701
+ }
702
+
703
+ export async function shutdownDaemonForRuntimeRoot(root, options = {}) {
704
+ const runtimeRoot = String(root || '').trim();
705
+ if (!runtimeRoot) return false;
706
+ const discovery = readSessionDiscovery(path.join(path.resolve(runtimeRoot), 'daemon.json'));
707
+ if (!discovery) return false;
708
+ return shutdownDaemon(discovery, options);
689
709
  }
690
710
 
691
711
  // ── Shared per-process attachment ────────────────────────────────────────────
@@ -34,6 +34,14 @@ process.on('message', (message) => {
34
34
  respond(requestId, { published: true });
35
35
  return;
36
36
  }
37
+ if (message.type === 'workload') {
38
+ respond(requestId, {
39
+ runtimes: revisions.size,
40
+ memory: { rssBytes: 1024 * 1024 * 1024 },
41
+ resources: { active: {} },
42
+ });
43
+ return;
44
+ }
37
45
  if (message.type === 'call') {
38
46
  if (message.method === 'resume') {
39
47
  respond(requestId, true);
@@ -117,3 +125,31 @@ test('omitted trailing arguments stay omitted across the runtime wire', async ()
117
125
  await rm(dir, { recursive: true, force: true });
118
126
  }
119
127
  });
128
+
129
+ test('RSS telemetry never schedules a destructive runtime recycle', async () => {
130
+ const dir = await mkdtemp(join(tmpdir(), 'mixdog-runtime-rss-'));
131
+ const workerEntry = join(dir, 'worker.mjs');
132
+ await writeFile(workerEntry, WORKER_STUB, 'utf8');
133
+
134
+ const host = createSessionRuntimeHost({
135
+ workerEntry,
136
+ cwd: dir,
137
+ env: {
138
+ ...process.env,
139
+ MIXDOG_SESSION_WORKER_RECYCLE_RSS_MB: '1',
140
+ MIXDOG_SESSION_WORKER_RECYCLE_INTERVAL_MS: '1',
141
+ },
142
+ log: () => {},
143
+ });
144
+ try {
145
+ const runtime = await host.create({ sessionId: 'session-rss' });
146
+ const originalPid = host.status.worker.pid;
147
+ await host.refreshRuntimeWorkload();
148
+ assert.equal(host.status.memoryRecycle, undefined);
149
+ assert.equal((await runtime.submitAsync('healthy')).pid, originalPid);
150
+ assert.equal(host.status.worker.pid, originalPid);
151
+ } finally {
152
+ await host.close('test complete');
153
+ await rm(dir, { recursive: true, force: true });
154
+ }
155
+ });
@@ -30,24 +30,6 @@ const RUNTIME_METHODS = new Set([
30
30
  'dispose',
31
31
  ]);
32
32
 
33
- export function shouldRecycleSessionRuntimeWorker({
34
- rssBytes = 0,
35
- thresholdBytes = 0,
36
- daemonBusy = 0,
37
- pending = 0,
38
- activeResources = 0,
39
- now = Date.now(),
40
- lastRecycleAt = 0,
41
- cooldownMs = 0,
42
- } = {}) {
43
- return Number(thresholdBytes) > 0
44
- && Number(rssBytes) >= Number(thresholdBytes)
45
- && Number(daemonBusy) === 0
46
- && Number(pending) === 0
47
- && Number(activeResources) === 0
48
- && Number(now) - Number(lastRecycleAt) >= Math.max(0, Number(cooldownMs) || 0);
49
- }
50
-
51
33
  export function applyRuntimeStateFrame(previous, frame) {
52
34
  if (frame?.full && typeof frame.full === 'object') return frame.full;
53
35
  const patch = frame?.patch;
@@ -244,12 +226,6 @@ class SessionRuntimeWorker {
244
226
  void this.recycleChild(child, `unhealthy: ${reason}`);
245
227
  }
246
228
 
247
- recycleForMemory(rssBytes) {
248
- const rssMb = Math.round(Number(rssBytes) / 1024 / 1024);
249
- return this.recycleChild(this.child, `idle memory reclaim (${rssMb} MB RSS)`)
250
- || Promise.resolve(false);
251
- }
252
-
253
229
  requestRaw(type, payload = {}, timeoutMs = 10 * 60_000) {
254
230
  const child = this.ensureChild();
255
231
  const requestId = `runtime-${process.pid}-${++this.sequence}`;
@@ -515,7 +491,6 @@ export function createSessionRuntimeHost({
515
491
  cwd = process.cwd(),
516
492
  env = process.env,
517
493
  log = () => {},
518
- canRecycle = () => true,
519
494
  } = {}) {
520
495
  const worker = new SessionRuntimeWorker({
521
496
  workerEntry,
@@ -531,23 +506,8 @@ export function createSessionRuntimeHost({
531
506
 
532
507
  // Runtime workload telemetry is refreshed lazily with a short TTL.
533
508
  const WORKLOAD_TTL_MS = 2_000;
534
- const configuredRecycleMb = Number(env.MIXDOG_SESSION_WORKER_RECYCLE_RSS_MB);
535
- const MEMORY_RECYCLE_THRESHOLD_BYTES = (
536
- Number.isFinite(configuredRecycleMb) && configuredRecycleMb >= 0
537
- ? configuredRecycleMb
538
- : 384
539
- ) * 1024 * 1024;
540
- const MEMORY_RECYCLE_INTERVAL_MS = Math.max(
541
- 5_000,
542
- Number(env.MIXDOG_SESSION_WORKER_RECYCLE_INTERVAL_MS) || 60_000,
543
- );
544
- const MEMORY_RECYCLE_COOLDOWN_MS = Math.max(
545
- 60_000,
546
- Number(env.MIXDOG_SESSION_WORKER_RECYCLE_COOLDOWN_MS) || 15 * 60_000,
547
- );
548
509
  let workloadCache = { refreshedAt: 0, worker: null };
549
510
  let workloadRefresh = null;
550
- let lastMemoryRecycleAt = Date.now();
551
511
  function refreshRuntimeWorkload() {
552
512
  if (workloadRefresh) return workloadRefresh;
553
513
  if (!worker.child || worker.child.killed) {
@@ -571,36 +531,6 @@ export function createSessionRuntimeHost({
571
531
  return workloadRefresh;
572
532
  }
573
533
 
574
- async function maybeRecycleWorkerMemory() {
575
- if (closed || !worker.child || worker.child.killed || worker.recycling || worker.recovery) return;
576
- let daemonBusy = 1;
577
- try { daemonBusy = Number(canRecycle()) === 1 ? 0 : 1; } catch {}
578
- if (daemonBusy !== 0) return;
579
- await refreshRuntimeWorkload();
580
- const snapshot = workloadCache.worker;
581
- const active = snapshot?.resources?.active || {};
582
- const activeResources = Object.values(active)
583
- .reduce((sum, value) => sum + Math.max(0, Number(value) || 0), 0);
584
- const now = Date.now();
585
- if (!shouldRecycleSessionRuntimeWorker({
586
- rssBytes: snapshot?.memory?.rssBytes,
587
- thresholdBytes: MEMORY_RECYCLE_THRESHOLD_BYTES,
588
- daemonBusy,
589
- pending: worker.pending.size,
590
- activeResources,
591
- now,
592
- lastRecycleAt: lastMemoryRecycleAt,
593
- cooldownMs: MEMORY_RECYCLE_COOLDOWN_MS,
594
- })) return;
595
- lastMemoryRecycleAt = now;
596
- await worker.recycleForMemory(snapshot.memory.rssBytes);
597
- workloadCache = { refreshedAt: Date.now(), worker: null };
598
- }
599
- const memoryRecycleTimer = MEMORY_RECYCLE_THRESHOLD_BYTES > 0
600
- ? setInterval(() => { void maybeRecycleWorkerMemory(); }, MEMORY_RECYCLE_INTERVAL_MS)
601
- : null;
602
- memoryRecycleTimer?.unref?.();
603
-
604
534
  return {
605
535
  async create(options = {}) {
606
536
  if (closed) throw new Error('session runtime host is closed');
@@ -609,6 +539,32 @@ export function createSessionRuntimeHost({
609
539
  prewarm() {
610
540
  return worker.request('prewarm', {}, 120_000);
611
541
  },
542
+ // Agent execution rides the runtime worker instead of accumulating
543
+ // provider/orchestrator churn in the daemon.
544
+ async agentDispatch(payload = {}, { signal = null, timeoutMs = 60 * 60_000 } = {}) {
545
+ if (closed) throw new Error('session runtime host is closed');
546
+ const dispatchId = String(payload?.dispatchId || '');
547
+ if (!dispatchId) throw new Error('agent dispatch id is required');
548
+ const cancel = (reason) => {
549
+ void worker.request('agent-dispatch-cancel', {
550
+ dispatchId,
551
+ reason: String(reason || 'agent dispatch canceled'),
552
+ }, 10_000).catch(() => {});
553
+ };
554
+ if (signal?.aborted) throw new Error('agent dispatch canceled before start');
555
+ const onAbort = () => cancel(signal?.reason?.message || signal?.reason);
556
+ signal?.addEventListener?.('abort', onAbort, { once: true });
557
+ try {
558
+ const result = await worker.request('agent-dispatch', payload, timeoutMs);
559
+ return result?.value;
560
+ } catch (error) {
561
+ // The worker keeps running after a host-side timeout; tell it to stop.
562
+ if (/timed out/.test(String(error?.message || ''))) cancel('agent dispatch timed out');
563
+ throw error;
564
+ } finally {
565
+ signal?.removeEventListener?.('abort', onAbort);
566
+ }
567
+ },
612
568
  refreshRuntimeWorkload,
613
569
  get workloads() {
614
570
  if (!closed && Date.now() - workloadCache.refreshedAt > WORKLOAD_TTL_MS) {
@@ -623,7 +579,6 @@ export function createSessionRuntimeHost({
623
579
  async close(reason = 'session runtime host closed') {
624
580
  if (closed) return;
625
581
  closed = true;
626
- if (memoryRecycleTimer) clearInterval(memoryRecycleTimer);
627
582
  await worker.close(reason);
628
583
  },
629
584
  get status() {
@@ -631,11 +586,6 @@ export function createSessionRuntimeHost({
631
586
  return {
632
587
  active: Boolean(status.pid),
633
588
  worker: status,
634
- memoryRecycle: {
635
- thresholdBytes: MEMORY_RECYCLE_THRESHOLD_BYTES,
636
- cooldownMs: MEMORY_RECYCLE_COOLDOWN_MS,
637
- lastRecycleAt: lastMemoryRecycleAt,
638
- },
639
589
  };
640
590
  },
641
591
  };
@@ -133,6 +133,98 @@ async function callRuntime(message) {
133
133
  return sanitizeForWire(value);
134
134
  }
135
135
 
136
+ // ── Memory-cycle agent dispatch ────────────────────────────────────────────
137
+ // Cycle agents (LLM maintenance calls brokered by the daemon) execute in THIS
138
+ // worker: the daemon process is permanent and allocator churn there is
139
+ // unreclaimable, while this worker already recycles above its RSS threshold
140
+ // once fully idle. The orchestrator graph and providers load lazily on the
141
+ // first dispatch; an in-flight dispatch holds an 'agent' admission lease, so
142
+ // the host's recycle guard (activeResources) never interrupts one.
143
+ let agentGraphPromise = null;
144
+ function agentGraph() {
145
+ agentGraphPromise ??= Promise.all([
146
+ import('../runtime/agent/orchestrator/config.mjs'),
147
+ import('../runtime/agent/orchestrator/providers/registry.mjs'),
148
+ import('../runtime/agent/orchestrator/agent-runtime/agent-dispatch.mjs'),
149
+ ]).then(
150
+ ([config, registry, dispatch]) => ({ config, registry, dispatch }),
151
+ (error) => {
152
+ agentGraphPromise = null;
153
+ throw error;
154
+ },
155
+ );
156
+ return agentGraphPromise;
157
+ }
158
+ const agentDispatchers = new Map();
159
+ const agentDispatchRuns = new Map(); // dispatchId -> AbortController
160
+ let preparedProviderSignature = null;
161
+ let providerPreparePromise = null;
162
+
163
+ async function prepareAgentProviders() {
164
+ const { config, registry } = await agentGraph();
165
+ const providers = config.loadConfig()?.providers || {};
166
+ let signature = null;
167
+ try { signature = JSON.stringify(providers); } catch { /* re-prepare each call */ }
168
+ if (signature !== null && preparedProviderSignature === signature) return;
169
+ if (providerPreparePromise) {
170
+ await providerPreparePromise;
171
+ if (signature !== null && preparedProviderSignature === signature) return;
172
+ return prepareAgentProviders();
173
+ }
174
+ const pending = Promise.resolve()
175
+ .then(() => registry.initProviders(providers))
176
+ .then(() => { preparedProviderSignature = signature; });
177
+ const tracked = pending.finally(() => {
178
+ if (providerPreparePromise === tracked) providerPreparePromise = null;
179
+ });
180
+ providerPreparePromise = tracked;
181
+ await tracked;
182
+ }
183
+
184
+ async function runAgentDispatch(message) {
185
+ const dispatchId = String(message.dispatchId || '');
186
+ if (!dispatchId) throw new Error('agent dispatch id is required');
187
+ if (agentDispatchRuns.has(dispatchId)) {
188
+ throw new Error(`agent dispatch ${dispatchId} is already running`);
189
+ }
190
+ const agent = String(message.agent || '');
191
+ const { dispatch } = await agentGraph();
192
+ await prepareAgentProviders();
193
+ let dispatcher = agentDispatchers.get(agent);
194
+ if (!dispatcher) {
195
+ dispatcher = dispatch.makeAgentDispatch({
196
+ agent,
197
+ ...(message.options && typeof message.options === 'object' ? message.options : {}),
198
+ });
199
+ agentDispatchers.set(agent, dispatcher);
200
+ }
201
+ const controller = new AbortController();
202
+ agentDispatchRuns.set(dispatchId, controller);
203
+ try {
204
+ const params = message.params && typeof message.params === 'object' ? message.params : {};
205
+ const value = await dispatcher({
206
+ prompt: String(params.prompt ?? ''),
207
+ preset: params.preset || undefined,
208
+ cwd: typeof params.cwd === 'string' && params.cwd ? params.cwd : undefined,
209
+ parentSignal: controller.signal,
210
+ ...(Number.isFinite(Number(params.idleTimeoutMs)) && Number(params.idleTimeoutMs) > 0
211
+ ? { idleTimeoutMs: Number(params.idleTimeoutMs) }
212
+ : {}),
213
+ });
214
+ return { value: sanitizeForWire(value) ?? null };
215
+ } finally {
216
+ agentDispatchRuns.delete(dispatchId);
217
+ }
218
+ }
219
+
220
+ function cancelAgentDispatch(message) {
221
+ const controller = agentDispatchRuns.get(String(message.dispatchId || ''));
222
+ if (!controller) return { cancelled: false };
223
+ const reason = new Error(String(message.reason || 'agent dispatch canceled'));
224
+ try { controller.abort(reason); } catch { try { controller.abort(); } catch { /* settled */ } }
225
+ return { cancelled: true };
226
+ }
227
+
136
228
  async function prewarm() {
137
229
  const module = await sessionModule();
138
230
  await Promise.allSettled([
@@ -192,6 +284,9 @@ async function exitAfterPendingWrites(code = 0) {
192
284
  async function stopAll(reason = 'session runtime worker shutdown') {
193
285
  if (stopping) return;
194
286
  stopping = true;
287
+ for (const controller of agentDispatchRuns.values()) {
288
+ try { controller.abort(new Error(reason)); } catch { /* settled */ }
289
+ }
195
290
  for (const record of [...records.values()]) {
196
291
  try {
197
292
  await disposeSessionRuntimeRecord(
@@ -220,6 +315,8 @@ process.on('message', (message) => {
220
315
  }
221
316
  if (message.type === 'prewarm') return prewarm();
222
317
  if (message.type === 'workload') return workloadSnapshot();
318
+ if (message.type === 'agent-dispatch') return runAgentDispatch(message);
319
+ if (message.type === 'agent-dispatch-cancel') return cancelAgentDispatch(message);
223
320
  if (message.type === 'shutdown') {
224
321
  await stopAll(message.reason);
225
322
  return { stopped: true };