@vellumai/assistant 0.10.4-dev.202607012040.649b529 → 0.10.4-dev.202607012136.5ef7865

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 (34) hide show
  1. package/openapi.yaml +169 -0
  2. package/package.json +1 -1
  3. package/src/__tests__/conversation-agent-loop.test.ts +38 -0
  4. package/src/__tests__/personal-memory-auth-bypass.test.ts +62 -0
  5. package/src/__tests__/resolve-trust-class.test.ts +28 -10
  6. package/src/__tests__/workspace-git-service.test.ts +1 -1
  7. package/src/cli/commands/monitoring.ts +191 -0
  8. package/src/cli/program.ts +2 -0
  9. package/src/config/schema.ts +7 -1
  10. package/src/config/schemas/monitoring.ts +61 -0
  11. package/src/daemon/conversation-agent-loop-handlers.ts +31 -89
  12. package/src/daemon/conversation-agent-loop.ts +20 -47
  13. package/src/daemon/conversation-turn-finalize.ts +211 -0
  14. package/src/daemon/lifecycle.ts +5 -0
  15. package/src/daemon/shutdown-handlers.ts +4 -0
  16. package/src/daemon/trust-context.ts +14 -6
  17. package/src/monitoring/__tests__/control.test.ts +235 -0
  18. package/src/monitoring/__tests__/sample-ring-buffer.test.ts +96 -0
  19. package/src/monitoring/control.ts +248 -0
  20. package/src/monitoring/resource-sampler.ts +258 -0
  21. package/src/monitoring/sample-ring-buffer.ts +108 -0
  22. package/src/monitoring/worker.ts +94 -0
  23. package/src/persistence/__tests__/slow-query-log.test.ts +190 -0
  24. package/src/persistence/db-connection.ts +3 -0
  25. package/src/persistence/raw-query.ts +21 -42
  26. package/src/persistence/slow-query-log.ts +261 -0
  27. package/src/runtime/routes/__tests__/monitoring-routes.test.ts +194 -0
  28. package/src/runtime/routes/identity-routes.ts +4 -87
  29. package/src/runtime/routes/index.ts +2 -0
  30. package/src/runtime/routes/monitoring-routes.ts +237 -0
  31. package/src/tools/terminal/safe-env.ts +1 -0
  32. package/src/util/cgroup-memory.ts +142 -0
  33. package/src/util/platform.ts +17 -0
  34. package/src/workspace/git-service.ts +1 -0
package/openapi.yaml CHANGED
@@ -19360,6 +19360,175 @@ paths:
19360
19360
  responses:
19361
19361
  "200":
19362
19362
  description: Successful response
19363
+ /v1/monitoring/start:
19364
+ post:
19365
+ operationId: monitoring_start_post
19366
+ summary: Start the resource monitor
19367
+ description: Spawns (or reuses) the resource monitor process as a child of the daemon and enables monitoring.enabled.
19368
+ tags:
19369
+ - system
19370
+ responses:
19371
+ "200":
19372
+ description: Successful response
19373
+ content:
19374
+ application/json:
19375
+ schema:
19376
+ type: object
19377
+ properties:
19378
+ pid:
19379
+ type: number
19380
+ alreadyRunning:
19381
+ type: boolean
19382
+ monitoringEnabled:
19383
+ type: boolean
19384
+ const: true
19385
+ pidPath:
19386
+ type: string
19387
+ required:
19388
+ - pid
19389
+ - alreadyRunning
19390
+ - monitoringEnabled
19391
+ - pidPath
19392
+ additionalProperties: false
19393
+ /v1/monitoring/status:
19394
+ get:
19395
+ operationId: monitoring_status_get
19396
+ summary: Resource monitor status
19397
+ description:
19398
+ Reports the resource monitor process state, monitoring.enabled, the forensics data directory, and the most
19399
+ recent persisted memory/disk sample.
19400
+ tags:
19401
+ - system
19402
+ responses:
19403
+ "200":
19404
+ description: Successful response
19405
+ content:
19406
+ application/json:
19407
+ schema:
19408
+ type: object
19409
+ properties:
19410
+ status:
19411
+ type: string
19412
+ enum:
19413
+ - running
19414
+ - not_running
19415
+ pid:
19416
+ type: number
19417
+ monitoringEnabled:
19418
+ type: boolean
19419
+ dataDir:
19420
+ type: string
19421
+ latestSample:
19422
+ anyOf:
19423
+ - type: object
19424
+ properties:
19425
+ ts:
19426
+ type: number
19427
+ memory:
19428
+ anyOf:
19429
+ - type: object
19430
+ properties:
19431
+ currentBytes:
19432
+ type: number
19433
+ limitBytes:
19434
+ anyOf:
19435
+ - type: number
19436
+ - type: "null"
19437
+ peakBytes:
19438
+ anyOf:
19439
+ - type: number
19440
+ - type: "null"
19441
+ ratio:
19442
+ anyOf:
19443
+ - type: number
19444
+ - type: "null"
19445
+ required:
19446
+ - currentBytes
19447
+ - limitBytes
19448
+ - peakBytes
19449
+ - ratio
19450
+ additionalProperties: false
19451
+ - type: "null"
19452
+ events:
19453
+ anyOf:
19454
+ - type: object
19455
+ properties:
19456
+ low:
19457
+ type: number
19458
+ high:
19459
+ type: number
19460
+ max:
19461
+ type: number
19462
+ oom:
19463
+ type: number
19464
+ oomKill:
19465
+ type: number
19466
+ required:
19467
+ - low
19468
+ - high
19469
+ - max
19470
+ - oom
19471
+ - oomKill
19472
+ additionalProperties: false
19473
+ - type: "null"
19474
+ disk:
19475
+ anyOf:
19476
+ - type: object
19477
+ properties:
19478
+ path:
19479
+ type: string
19480
+ usedMb:
19481
+ type: number
19482
+ totalMb:
19483
+ type: number
19484
+ freeMb:
19485
+ type: number
19486
+ required:
19487
+ - path
19488
+ - usedMb
19489
+ - totalMb
19490
+ - freeMb
19491
+ additionalProperties: false
19492
+ - type: "null"
19493
+ required:
19494
+ - ts
19495
+ - memory
19496
+ - events
19497
+ - disk
19498
+ additionalProperties: false
19499
+ - type: "null"
19500
+ required:
19501
+ - status
19502
+ - monitoringEnabled
19503
+ - dataDir
19504
+ - latestSample
19505
+ additionalProperties: false
19506
+ /v1/monitoring/stop:
19507
+ post:
19508
+ operationId: monitoring_stop_post
19509
+ summary: Stop the resource monitor
19510
+ description: Disables monitoring.enabled and SIGTERMs the resource monitor process if it is running.
19511
+ tags:
19512
+ - system
19513
+ responses:
19514
+ "200":
19515
+ description: Successful response
19516
+ content:
19517
+ application/json:
19518
+ schema:
19519
+ type: object
19520
+ properties:
19521
+ monitoringWasRunning:
19522
+ type: boolean
19523
+ pid:
19524
+ type: number
19525
+ monitoringEnabled:
19526
+ type: boolean
19527
+ const: false
19528
+ required:
19529
+ - monitoringWasRunning
19530
+ - monitoringEnabled
19531
+ additionalProperties: false
19363
19532
  /v1/notification-intent-result:
19364
19533
  post:
19365
19534
  operationId: notificationintentresult_post
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.4-dev.202607012040.649b529",
3
+ "version": "0.10.4-dev.202607012136.5ef7865",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -2409,6 +2409,44 @@ describe("session-agent-loop", () => {
2409
2409
  expect(metadataPublishes).toHaveLength(1);
2410
2410
  });
2411
2411
 
2412
+ test("terminal message_complete is emitted before the deferred indexer runs (LUM-2654)", async () => {
2413
+ // Regression guard for LUM-2654 ("long delay between last streaming token
2414
+ // and send-button becoming available"). The terminal `message_complete`
2415
+ // SSE — which the client uses to flip stop→send — is emitted before the
2416
+ // non-critical finalize side-effects (memory segment indexing, lexical
2417
+ // indexing, attention projection), which the orchestrator drains from its
2418
+ // end-of-turn tail. The tail runs within the turn, so the indexer still
2419
+ // fires exactly once; this test pins the ordering by asserting
2420
+ // `message_complete` is already in the client stream when it does.
2421
+ mockMessageById = {
2422
+ id: "msg-reserve",
2423
+ conversationId: "test-conv",
2424
+ createdAt: 1234567,
2425
+ role: "assistant",
2426
+ content: "[]",
2427
+ metadata: null,
2428
+ };
2429
+
2430
+ const events: ServerMessage[] = [];
2431
+ let messageCompleteSeenWhenIndexed: boolean | undefined;
2432
+ indexMessageNowMock.mockImplementationOnce(async () => {
2433
+ messageCompleteSeenWhenIndexed = events.some(
2434
+ (event) => event.type === "message_complete",
2435
+ );
2436
+ return { indexedSegments: 0, enqueuedJobs: 0 };
2437
+ });
2438
+
2439
+ const ctx = makeCtx({
2440
+ providerResponses: [textResponse("indexed reply")],
2441
+ });
2442
+ await runAgentLoopImpl(ctx, "hi", "msg-1", (msg) => events.push(msg));
2443
+
2444
+ // The deferred indexer runs exactly once, within the turn…
2445
+ expect(indexMessageNowMock).toHaveBeenCalledTimes(1);
2446
+ // …and only after the terminal SSE that re-enables the composer.
2447
+ expect(messageCompleteSeenWhenIndexed).toBe(true);
2448
+ });
2449
+
2412
2450
  test("handleMessageComplete skips sync invalidation when attention state unchanged", async () => {
2413
2451
  // Mirror of the previous test but with the default projector return
2414
2452
  // (`false`). The projection still runs every turn, but the sync
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Security regression test for the personal-memory trust gate under
3
+ * DISABLE_HTTP_AUTH.
4
+ *
5
+ * `isPersonalMemoryAllowed` derives trust from `resolveTrustClass`, which only
6
+ * elevates an *unresolved* actor to guardian under DISABLE_HTTP_AUTH (the
7
+ * standing config in platform-managed deployments). A resolved non-guardian
8
+ * channel actor must therefore be denied personal memory even with auth
9
+ * disabled — otherwise the guardian's memory leaks to Slack/phone contacts in
10
+ * the cloud. See LUM-2669. These cases fail on the pre-fix behavior.
11
+ *
12
+ * Uses process.env directly (not a module mock) since isHttpAuthDisabled()
13
+ * reads DISABLE_HTTP_AUTH live.
14
+ */
15
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
16
+
17
+ import {
18
+ isPersonalMemoryAllowed,
19
+ type TrustContext,
20
+ } from "../daemon/trust-context.js";
21
+ import type { TrustClass } from "../runtime/actor-trust-resolver.js";
22
+
23
+ function slack(trustClass: TrustClass): TrustContext {
24
+ return { sourceChannel: "slack", trustClass };
25
+ }
26
+
27
+ let prior: string | undefined;
28
+
29
+ beforeEach(() => {
30
+ // Platform-managed / dev-bypass posture: the flag is on process-wide.
31
+ prior = process.env.DISABLE_HTTP_AUTH;
32
+ process.env.DISABLE_HTTP_AUTH = "true";
33
+ });
34
+
35
+ afterEach(() => {
36
+ if (prior === undefined) {
37
+ delete process.env.DISABLE_HTTP_AUTH;
38
+ } else {
39
+ process.env.DISABLE_HTTP_AUTH = prior;
40
+ }
41
+ });
42
+
43
+ describe("isPersonalMemoryAllowed — no exposure to non-guardian channel actors under DISABLE_HTTP_AUTH", () => {
44
+ test("blocks personal memory for a non-guardian Slack actor even with auth disabled", () => {
45
+ expect(isPersonalMemoryAllowed(slack("trusted_contact"))).toBe(false);
46
+ expect(isPersonalMemoryAllowed(slack("unknown"))).toBe(false);
47
+ expect(isPersonalMemoryAllowed(slack("unverified_contact"))).toBe(false);
48
+ });
49
+
50
+ test("allows personal memory for the guardian and for local / internal turns", () => {
51
+ expect(isPersonalMemoryAllowed(slack("guardian"))).toBe(true);
52
+ // Local/native turn — no resolved actor.
53
+ expect(isPersonalMemoryAllowed(undefined)).toBe(true);
54
+ // Internal vellum-channel flow.
55
+ expect(
56
+ isPersonalMemoryAllowed({
57
+ sourceChannel: "vellum",
58
+ trustClass: "unknown",
59
+ }),
60
+ ).toBe(true);
61
+ });
62
+ });
@@ -12,6 +12,7 @@ mock.module("../config/env.js", () => ({
12
12
  // ── Real imports (after mocks) ───────────────────────────────────────
13
13
 
14
14
  import {
15
+ FALLBACK_TURN_TRUST,
15
16
  resolveTrustClass,
16
17
  type TrustContext,
17
18
  } from "../daemon/trust-context.js";
@@ -38,19 +39,36 @@ describe("resolveTrustClass", () => {
38
39
  expect(resolveTrustClass(undefined)).toBe("unknown");
39
40
  });
40
41
 
41
- test("forces guardian when HTTP auth is disabled, regardless of context trust class", () => {
42
+ test("does not elevate a resolved non-guardian actor when HTTP auth is disabled", () => {
43
+ // DISABLE_HTTP_AUTH is the standing config in platform-managed deployments,
44
+ // so a resolved channel actor's class must survive it — otherwise a
45
+ // non-guardian Slack/phone contact would be treated as the guardian
46
+ // (LUM-2669). Only an unresolved (local/native) turn is elevated; see below.
42
47
  fakeHttpAuthDisabled = true;
43
- const ctx: Pick<TrustContext, "trustClass"> = {
44
- trustClass: "trusted_contact",
45
- };
46
- expect(resolveTrustClass(ctx as TrustContext)).toBe("guardian");
48
+ expect(
49
+ resolveTrustClass({ trustClass: "trusted_contact" } as TrustContext),
50
+ ).toBe("trusted_contact");
51
+ expect(resolveTrustClass({ trustClass: "unknown" } as TrustContext)).toBe(
52
+ "unknown",
53
+ );
47
54
  });
48
55
 
49
- test("forces guardian for unknown trust class when HTTP auth is disabled", () => {
56
+ test("treats an unresolved (local/native) turn as guardian when HTTP auth is disabled", () => {
57
+ // Local/native turns reach the daemon without a channel-resolved
58
+ // trustContext; in an auth-disabled (local) deployment that actor is the
59
+ // guardian, so control-plane gates don't block local development.
50
60
  fakeHttpAuthDisabled = true;
51
- const ctx: Pick<TrustContext, "trustClass"> = {
52
- trustClass: "unknown",
53
- };
54
- expect(resolveTrustClass(ctx as TrustContext)).toBe("guardian");
61
+ expect(resolveTrustClass(undefined)).toBe("guardian");
62
+ });
63
+
64
+ test("does not elevate the FALLBACK_TURN_TRUST snapshot to guardian when HTTP auth is disabled", () => {
65
+ // conversation-tool-setup substitutes FALLBACK_TURN_TRUST (a *present*,
66
+ // unknown-class context) when no per-turn snapshot has been captured. Because
67
+ // it is a resolved context -- not `undefined` -- the dev-bypass must not
68
+ // elevate it: the fallback's documented bias-to-unknown has to survive
69
+ // DISABLE_HTTP_AUTH so a missing snapshot can't grant guardian trust. This is
70
+ // the fail-safe sibling to LUM-2665; see LUM-2669.
71
+ fakeHttpAuthDisabled = true;
72
+ expect(resolveTrustClass(FALLBACK_TURN_TRUST)).toBe("unknown");
55
73
  });
56
74
  });
@@ -830,7 +830,7 @@ describe("WorkspaceGitService", () => {
830
830
  cwd: testDir,
831
831
  });
832
832
  const gitignoreContent =
833
- "# Runtime state - excluded from git tracking\ndata/db/\ndata/qdrant/\nplugins/*/node_modules/\nlogs/\n*.log\n*.sock\n*.pid\n*.sqlite\n*.sqlite-journal\n*.sqlite-wal\n*.sqlite-shm\n*.db\n*.db-journal\n*.db-wal\n*.db-shm\nvellum.pid\nsession-token\n";
833
+ "# Runtime state - excluded from git tracking\ndata/db/\ndata/qdrant/\ndata/monitoring/\nplugins/*/node_modules/\nlogs/\n*.log\n*.sock\n*.pid\n*.sqlite\n*.sqlite-journal\n*.sqlite-wal\n*.sqlite-shm\n*.db\n*.db-journal\n*.db-wal\n*.db-shm\nvellum.pid\nsession-token\n";
834
834
  writeFileSync(join(testDir, ".gitignore"), gitignoreContent);
835
835
  writeFileSync(join(testDir, "file.txt"), "content");
836
836
  execFileSync("git", ["add", "-A"], { cwd: testDir });
@@ -0,0 +1,191 @@
1
+ /**
2
+ * `assistant monitoring` CLI command.
3
+ *
4
+ * Manages the resource monitor as its own OS process — separate from the
5
+ * assistant's main event loop — so it keeps sampling memory/disk during a
6
+ * main-thread freeze and its samples survive an OOM SIGKILL.
7
+ *
8
+ * Subcommands:
9
+ *
10
+ * - `start` — spawn the monitor process and enable `monitoring.enabled`.
11
+ * - `stop` — SIGTERM the monitor process and disable `monitoring.enabled`.
12
+ * - `status` — report the monitor process state, `monitoring.enabled`,
13
+ * and the most recent memory/disk sample.
14
+ *
15
+ * All three are thin IPC wrappers (transport: "ipc"): the daemon owns the
16
+ * monitor process so it is spawned as a *child of the daemon* — which is what
17
+ * makes it appear in `assistant ps` and lets the daemon tear it down on
18
+ * shutdown. Mirrors `assistant memory worker`.
19
+ */
20
+
21
+ import type { Command } from "commander";
22
+
23
+ import { cliIpcCall, exitFromIpcResult } from "../../ipc/cli-client.js";
24
+ import { registerCommand } from "../lib/register-command.js";
25
+ import { log } from "../logger.js";
26
+ import { shouldOutputJson, writeOutput } from "../output.js";
27
+
28
+ interface LatestSample {
29
+ ts: number;
30
+ memory: {
31
+ currentBytes: number;
32
+ limitBytes: number | null;
33
+ peakBytes: number | null;
34
+ ratio: number | null;
35
+ } | null;
36
+ disk: {
37
+ path: string;
38
+ usedMb: number;
39
+ totalMb: number;
40
+ freeMb: number;
41
+ } | null;
42
+ }
43
+
44
+ interface StartResponse {
45
+ pid: number;
46
+ alreadyRunning: boolean;
47
+ monitoringEnabled: true;
48
+ pidPath: string;
49
+ }
50
+
51
+ interface StopResponse {
52
+ monitoringWasRunning: boolean;
53
+ pid?: number;
54
+ monitoringEnabled: false;
55
+ }
56
+
57
+ interface StatusResponse {
58
+ status: "running" | "not_running";
59
+ pid?: number;
60
+ monitoringEnabled: boolean;
61
+ dataDir: string;
62
+ latestSample: LatestSample | null;
63
+ }
64
+
65
+ function formatMib(bytes: number): string {
66
+ return `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MiB`;
67
+ }
68
+
69
+ export function registerMonitoringCommand(program: Command): void {
70
+ registerCommand(program, {
71
+ name: "monitoring",
72
+ transport: "ipc",
73
+ description: "Manage the resource monitor process (start/stop/status)",
74
+ build: (monitor) => {
75
+ monitor.addHelpText(
76
+ "after",
77
+ `
78
+ The resource monitor samples the container's own cgroup memory + workspace disk
79
+ in a separate OS process, off the assistant's main event loop, so it keeps
80
+ recording during a main-thread freeze and its samples survive an OOM SIGKILL.
81
+ The daemon owns the process, so it is spawned as a child of the daemon and shows
82
+ up in \`assistant ps\`.
83
+
84
+ \`start\` enables monitoring.enabled (so it is respawned on the next boot)
85
+ and \`stop\` disables it. Samples and high-memory snapshots are written under the
86
+ data directory reported by \`status\`.
87
+
88
+ Examples:
89
+ $ assistant monitoring start
90
+ $ assistant monitoring status
91
+ $ assistant monitoring stop`,
92
+ );
93
+
94
+ monitor
95
+ .command("start")
96
+ .description(
97
+ "Start the resource monitor process and enable monitoring.enabled",
98
+ )
99
+ .option("--json", "Emit raw JSON instead of a formatted summary")
100
+ .action(async (_opts: { json?: boolean }, cmd: Command) => {
101
+ const r = await cliIpcCall<StartResponse>("monitoring_start");
102
+ if (!r.ok) return exitFromIpcResult(r);
103
+ const res = r.result!;
104
+
105
+ if (shouldOutputJson(cmd)) {
106
+ writeOutput(cmd, res);
107
+ return;
108
+ }
109
+ log.info(
110
+ res.alreadyRunning
111
+ ? `Resource monitor is already running (PID ${res.pid})`
112
+ : `Resource monitor started (PID ${res.pid})`,
113
+ );
114
+ log.info(
115
+ "Enabled monitoring.enabled; it will be respawned on the next assistant start",
116
+ );
117
+ });
118
+
119
+ monitor
120
+ .command("stop")
121
+ .description(
122
+ "Stop the resource monitor process and disable monitoring.enabled",
123
+ )
124
+ .option("--json", "Emit raw JSON instead of a formatted summary")
125
+ .action(async (_opts: { json?: boolean }, cmd: Command) => {
126
+ const r = await cliIpcCall<StopResponse>("monitoring_stop");
127
+ if (!r.ok) return exitFromIpcResult(r);
128
+ const res = r.result!;
129
+
130
+ if (shouldOutputJson(cmd)) {
131
+ writeOutput(cmd, res);
132
+ return;
133
+ }
134
+ if (res.monitoringWasRunning) {
135
+ log.info(`Resource monitor stop signal sent (PID ${res.pid})`);
136
+ } else {
137
+ log.info("Resource monitor process was not running");
138
+ }
139
+ log.info("Disabled monitoring.enabled");
140
+ });
141
+
142
+ monitor
143
+ .command("status")
144
+ .description(
145
+ "Report the monitor process state, monitoring.enabled, and the latest sample",
146
+ )
147
+ .option("--json", "Emit raw JSON instead of a formatted summary")
148
+ .action(async (_opts: { json?: boolean }, cmd: Command) => {
149
+ const r = await cliIpcCall<StatusResponse>("monitoring_status");
150
+ if (!r.ok) return exitFromIpcResult(r);
151
+ const res = r.result!;
152
+
153
+ if (shouldOutputJson(cmd)) {
154
+ writeOutput(cmd, res);
155
+ return;
156
+ }
157
+ if (res.status === "running") {
158
+ log.info(`Resource monitor process is running (PID ${res.pid})`);
159
+ } else {
160
+ log.info("Resource monitor process is not running");
161
+ }
162
+ log.info(`monitoring.enabled: ${res.monitoringEnabled}`);
163
+ log.info(`Data directory: ${res.dataDir}`);
164
+
165
+ const sample = res.latestSample;
166
+ if (!sample) {
167
+ log.info("No samples recorded yet");
168
+ return;
169
+ }
170
+ const age = Math.max(0, Math.round((Date.now() - sample.ts) / 1000));
171
+ log.info(`Latest sample: ${age}s ago`);
172
+ if (sample.memory) {
173
+ const { currentBytes, limitBytes, peakBytes, ratio } =
174
+ sample.memory;
175
+ const pct = ratio != null ? ` (${Math.round(ratio * 100)}%)` : "";
176
+ const limit =
177
+ limitBytes != null ? formatMib(limitBytes) : "unknown";
178
+ const peak = peakBytes != null ? formatMib(peakBytes) : "unknown";
179
+ log.info(
180
+ ` Memory: ${formatMib(currentBytes)} / ${limit}${pct}, peak ${peak}`,
181
+ );
182
+ }
183
+ if (sample.disk) {
184
+ log.info(
185
+ ` Disk (${sample.disk.path}): ${sample.disk.usedMb} / ${sample.disk.totalMb} MiB used`,
186
+ );
187
+ }
188
+ });
189
+ },
190
+ });
191
+ }
@@ -33,6 +33,7 @@ import { registerInferenceCommand } from "./commands/inference.js";
33
33
  import { registerKeysCommand } from "./commands/keys.js";
34
34
  import { registerMcpCommand } from "./commands/mcp.js";
35
35
  import { registerMemoryCommand } from "./commands/memory/index.js";
36
+ import { registerMonitoringCommand } from "./commands/monitoring.js";
36
37
  import { registerNotificationsCommand } from "./commands/notifications.js";
37
38
  import { registerOAuthCommand } from "./commands/oauth/index.js";
38
39
  import { registerPendingCommand } from "./commands/pending.js";
@@ -133,6 +134,7 @@ Examples:
133
134
  registerPendingCommand(program);
134
135
  registerPlatformCommand(program);
135
136
  registerPluginsCommand(program);
137
+ registerMonitoringCommand(program);
136
138
  registerPsCommand(program);
137
139
  registerRoutesCommand(program);
138
140
  registerSchedulesCommand(program);
@@ -43,6 +43,7 @@ import {
43
43
  import { McpConfigSchema } from "./schemas/mcp.js";
44
44
  import { MemoryConfigSchema } from "./schemas/memory.js";
45
45
  import { MigrationsConfigSchema } from "./schemas/migrations.js";
46
+ import { MonitoringConfigSchema } from "./schemas/monitoring.js";
46
47
  import { NotificationsConfigSchema } from "./schemas/notifications.js";
47
48
  import {
48
49
  DaemonConfigSchema,
@@ -64,7 +65,12 @@ export const AssistantConfigSchema = z
64
65
  .object({
65
66
  services: ServicesSchema.default(ServicesSchema.parse({})),
66
67
  memory: MemoryConfigSchema.default(MemoryConfigSchema.parse({})),
67
- migrations: MigrationsConfigSchema.default(MigrationsConfigSchema.parse({})),
68
+ monitoring: MonitoringConfigSchema.default(
69
+ MonitoringConfigSchema.parse({}),
70
+ ),
71
+ migrations: MigrationsConfigSchema.default(
72
+ MigrationsConfigSchema.parse({}),
73
+ ),
68
74
  dataDir: z
69
75
  .string({ error: "dataDir must be a string" })
70
76
  .default(getDataDir())
@@ -0,0 +1,61 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Resource monitor configuration.
5
+ *
6
+ * The resource monitor runs as a separate OS process (a child of the assistant)
7
+ * that samples the container's own cgroup memory + workspace disk off the main
8
+ * event loop, so it keeps recording during a main-thread freeze and its samples
9
+ * survive an OOM SIGKILL. `assistant monitoring start`/`stop` flip
10
+ * `enabled` (and spawn/stop the process) to switch it on or off at runtime
11
+ * without a restart; when `enabled` is set the assistant also spawns it at
12
+ * startup.
13
+ */
14
+ export const MonitoringConfigSchema = z
15
+ .object({
16
+ enabled: z
17
+ .boolean({ error: "monitoring.enabled must be a boolean" })
18
+ .default(false)
19
+ .describe(
20
+ "Whether the resource monitor process runs. When set, the assistant spawns it at startup and it samples cgroup memory + workspace disk into a ring buffer on the workspace volume. `assistant monitoring start`/`stop` flip this flag at runtime.",
21
+ ),
22
+ sampleIntervalMs: z
23
+ .number({ error: "monitoring.sampleIntervalMs must be a number" })
24
+ .int("monitoring.sampleIntervalMs must be an integer")
25
+ .min(50, "monitoring.sampleIntervalMs must be at least 50ms")
26
+ .max(10_000, "monitoring.sampleIntervalMs must be <= 10000ms")
27
+ .default(250)
28
+ .describe(
29
+ "How often the monitor samples memory + disk, in milliseconds. Fast (default 250ms) so vertical memory spikes are caught before an OOM kill.",
30
+ ),
31
+ ringBufferSize: z
32
+ .number({ error: "monitoring.ringBufferSize must be a number" })
33
+ .int("monitoring.ringBufferSize must be an integer")
34
+ .min(100, "monitoring.ringBufferSize must be at least 100")
35
+ .max(100_000, "monitoring.ringBufferSize must be <= 100000")
36
+ .default(4000)
37
+ .describe(
38
+ "How many recent samples the on-disk ring buffer retains. At the default 250ms interval, 4000 samples is ~16 minutes of history preserved across a crash.",
39
+ ),
40
+ highMemThresholdRatio: z
41
+ .number({
42
+ error: "monitoring.highMemThresholdRatio must be a number",
43
+ })
44
+ .min(0.1, "monitoring.highMemThresholdRatio must be >= 0.1")
45
+ .max(1, "monitoring.highMemThresholdRatio must be <= 1")
46
+ .default(0.75)
47
+ .describe(
48
+ "Fraction of the container memory limit at which a high-memory snapshot (cgroup stats + process tree) is captured to the workspace volume. Default 0.75 (e.g. ~6 GiB of an 8 GiB limit).",
49
+ ),
50
+ snapshotCooldownMs: z
51
+ .number({ error: "monitoring.snapshotCooldownMs must be a number" })
52
+ .int("monitoring.snapshotCooldownMs must be an integer")
53
+ .min(0, "monitoring.snapshotCooldownMs must be non-negative")
54
+ .default(30_000)
55
+ .describe(
56
+ "Minimum interval between high-memory snapshots, in milliseconds, so a sustained spike does not write a snapshot on every sample.",
57
+ ),
58
+ })
59
+ .describe("Resource monitor process configuration");
60
+
61
+ export type MonitoringConfig = z.infer<typeof MonitoringConfigSchema>;