@mastra/code-sdk 1.3.0 → 1.4.0-alpha.1

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # @mastra/code-sdk
2
2
 
3
+ ## 1.4.0-alpha.1
4
+
5
+ ### Minor Changes
6
+
7
+ - Fixed credential failures that told every interface to run `/login`, a command only the terminal UI has. A provider fetch without a usable credential now throws `ProviderAuthRequiredError`, which states the fact and leaves the remedy to the host running the agent. ([#21860](https://github.com/mastra-ai/mastra/pull/21860))
8
+
9
+ ```ts
10
+ import { ProviderAuthRequiredError } from '@mastra/code-sdk/auth/provider-auth-error';
11
+
12
+ try {
13
+ await run();
14
+ } catch (error) {
15
+ // Before: the message hardcoded "Run /login first."
16
+ // Now: match the error and point the user at whatever sign-in path your host offers.
17
+ if (error instanceof ProviderAuthRequiredError) showSignIn();
18
+ }
19
+ ```
20
+
21
+ The error name is stable across serialization, so a client that only receives `{ name, message }` over the wire can match it too.
22
+
23
+ - Added opt-in process memory diagnostics for SDK process adapters. The service records process and V8 heap-space samples, naturally occurring garbage collection events, and periodic allocation profiles without forcing garbage collection or writing heap snapshots. ([#21821](https://github.com/mastra-ai/mastra/pull/21821))
24
+
25
+ Start diagnostics before creating Mastra Code, then await the final capture after work-producing services stop:
26
+
27
+ ```ts
28
+ import {
29
+ createProcessMemoryDiagnosticsFromEnvironment,
30
+ startConfiguredProcessMemoryDiagnostics,
31
+ } from '@mastra/code-sdk/process-memory-diagnostics';
32
+
33
+ const setup = createProcessMemoryDiagnosticsFromEnvironment(process.env);
34
+ const diagnostics = await startConfiguredProcessMemoryDiagnostics(setup, console.warn);
35
+
36
+ try {
37
+ // Create and run the process adapter.
38
+ } finally {
39
+ await diagnostics.stop();
40
+ }
41
+ ```
42
+
43
+ Allocation profiles remain local and may contain prompts, credentials, file contents, and tool arguments. Keep them private and delete them after analysis.
44
+
45
+ ### Patch Changes
46
+
47
+ - Updated dependencies [[`d23e75d`](https://github.com/mastra-ai/mastra/commit/d23e75d57cc7cf5b9bfdbee896bf5a6a2484fed7), [`c8faa4e`](https://github.com/mastra-ai/mastra/commit/c8faa4e1cfebaec56b65e754e90b9fe46d153359), [`f2031a4`](https://github.com/mastra-ai/mastra/commit/f2031a47445e8f67a89ba1309036816f97ab7a65), [`8e529d4`](https://github.com/mastra-ai/mastra/commit/8e529d4ac754efef04b225841349e0da9edf89a6)]:
48
+ - @mastra/core@1.61.0-alpha.1
49
+
50
+ ## 1.3.1-alpha.0
51
+
52
+ ### Patch Changes
53
+
54
+ - Updated dependencies [[`88d14ca`](https://github.com/mastra-ai/mastra/commit/88d14cac008582a618fecc3d5c7fd3bdf4f6ddc3), [`84a5b69`](https://github.com/mastra-ai/mastra/commit/84a5b699f84d6bae0a34efe5a970d891090b9f41), [`84a5b69`](https://github.com/mastra-ai/mastra/commit/84a5b699f84d6bae0a34efe5a970d891090b9f41), [`64cd7ac`](https://github.com/mastra-ai/mastra/commit/64cd7ac22c2c7a6e6b533a4b3a9ede432700f1fb), [`84a5b69`](https://github.com/mastra-ai/mastra/commit/84a5b699f84d6bae0a34efe5a970d891090b9f41), [`038b7b4`](https://github.com/mastra-ai/mastra/commit/038b7b405cb4ac25ab3f3031334111b1f87ac112), [`4132d61`](https://github.com/mastra-ai/mastra/commit/4132d61f8367077120ee9e6420d3224dffd93c93)]:
55
+ - @mastra/core@1.60.1-alpha.0
56
+ - @mastra/libsql@1.21.1-alpha.0
57
+ - @mastra/pg@1.21.1-alpha.0
58
+ - @mastra/mcp@1.17.1-alpha.0
59
+
3
60
  ## 1.3.0
4
61
 
5
62
  ### Minor Changes
package/README.md CHANGED
@@ -57,6 +57,65 @@ const prepared = await prepareAgentControllerMount({
57
57
 
58
58
  Configured processors run before Mastra Code's built-in input processors. Keep processor instances stateless because the mounted agent shares them across sessions and runs.
59
59
 
60
+ ## Process memory diagnostics
61
+
62
+ Use `ProcessMemoryDiagnostics` to collect low-perturbation memory evidence from a long-running Node.js process. The service records process memory, V8 heap-space statistics, naturally occurring garbage collection (GC) events, and sampled allocation profiles. It doesn't force GC or write heap snapshots.
63
+
64
+ > **Warning:** Allocation profiles can contain prompts, credentials, file contents, and tool arguments. Store them in a restricted location, don't upload them as telemetry, and delete them when you finish the investigation.
65
+
66
+ The environment factory applies the supported defaults and validation rules:
67
+
68
+ ```ts
69
+ import {
70
+ createProcessMemoryDiagnosticsFromEnvironment,
71
+ startConfiguredProcessMemoryDiagnostics,
72
+ } from '@mastra/code-sdk/process-memory-diagnostics';
73
+
74
+ const setup = createProcessMemoryDiagnosticsFromEnvironment(process.env);
75
+ const diagnostics = await startConfiguredProcessMemoryDiagnostics(setup, warning => {
76
+ console.warn(warning);
77
+ });
78
+
79
+ try {
80
+ // Create and run your Mastra Code process adapter.
81
+ } finally {
82
+ await diagnostics.stop();
83
+ }
84
+ ```
85
+
86
+ Construct and start diagnostics before creating Mastra Code. Stop work-producing services first during shutdown, then await `diagnostics.stop()` to write the final process sample and allocation profile.
87
+
88
+ ### Configuration
89
+
90
+ | Environment variable | Default | Minimum | Description |
91
+ | ---------------------------------------------- | --------------------------------- | ------- | ----------------------------------------------------------- |
92
+ | `MASTRACODE_PROFILE` | Disabled | N/A | Enables startup profiling for `1`, `true`, `yes`, or `on` |
93
+ | `MASTRACODE_PROFILE_DIR` | `<Mastra Code app-data>/profiles` | N/A | Parent directory for private, unique run directories |
94
+ | `MASTRACODE_PROFILE_SAMPLE_INTERVAL_MS` | `10000` | `1000` | Process and V8 sample interval in milliseconds |
95
+ | `MASTRACODE_PROFILE_CAPTURE_INTERVAL_MS` | `300000` | `10000` | Durable allocation-profile capture interval in milliseconds |
96
+ | `MASTRACODE_PROFILE_ALLOCATION_INTERVAL_BYTES` | `524288` | `32768` | V8 allocation-sampling interval in bytes |
97
+
98
+ Truthy values are case-insensitive and may contain surrounding whitespace. Other values leave startup profiling disabled. Invalid numeric values produce an actionable error instead of starting a higher-overhead profiler.
99
+
100
+ ### Artifacts
101
+
102
+ Each run directory contains:
103
+
104
+ - `metadata.json`: Immutable runtime and configuration metadata
105
+ - `process-samples.jsonl`: Append-only RSS, JavaScript heap, external memory, ArrayBuffer memory, resource usage, and V8 heap-space samples
106
+ - `gc-events.jsonl`: Append-only GC kind, flags, duration, and nearby memory values when V8 emits GC performance entries. A run can contain zero events.
107
+ - `allocation-<sequence>-<timestamp>.heapprofile`: Atomic Chrome allocation-sampling profiles. Each capture closes one sampling epoch and immediately starts the next.
108
+
109
+ The service requests mode `0700` for run directories and `0600` for files on POSIX systems. Other platforms may apply permissions differently.
110
+
111
+ Compare JavaScript heap growth with resident set size (RSS). Rising heap-space usage points to retained JavaScript objects. Rising RSS with a stable JavaScript heap can point to external buffers, ArrayBuffers, native libraries, memory-mapped files, or allocator behavior. Allocation profiles include objects collected by major and minor GC, which helps distinguish sustained retention from transient allocation pressure.
112
+
113
+ Sampling and periodic writes add overhead. Larger allocation intervals and longer capture intervals reduce it. A manual or periodic capture rotates allocation sampling without triggering a heap snapshot or forced GC.
114
+
115
+ Atomically completed captures survive later `SIGINT`, `SIGTERM`, `SIGHUP`, `SIGKILL`, or native crashes. Awaited shutdown can write a final capture for graceful signals and application errors. JavaScript can't guarantee a final capture after immediate `SIGKILL`, a native crash, or power loss, so use periodic captures for those cases.
116
+
117
+ Delete a run after analysis with your platform's file-removal tools. Never commit captured profiles.
118
+
60
119
  ## Dynamic workflows
61
120
 
62
121
  The local controller registers the Workflow Builder before workers start. In build mode, users can ask the code agent to create a workflow in natural language. The builder discovers registered agents, tools, and workflows, validates a complete definition, then persists and registers it immediately.
@@ -2,6 +2,7 @@
2
2
  * OAuth credential management for AI providers.
3
3
  */
4
4
  export * from './types.js';
5
+ export * from './provider-auth-error.js';
5
6
  export * from './storage.js';
6
7
  export { anthropicOAuthProvider } from './providers/anthropic.js';
7
8
  export { githubCopilotOAuthProvider } from './providers/github-copilot.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC;AACzC,cAAc,cAAc,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -3,4 +3,5 @@ import { githubCopilotOAuthProvider } from "./providers/github-copilot.js";
3
3
  import { openaiCodexOAuthProvider } from "./providers/openai-codex.js";
4
4
  import { xaiOAuthProvider } from "./providers/xai.js";
5
5
  import { AuthStorage, PROVIDER_DEFAULT_MODELS, getOAuthProvider, getOAuthProviders } from "./storage.js";
6
- export { AuthStorage, PROVIDER_DEFAULT_MODELS, anthropicOAuthProvider, getOAuthProvider, getOAuthProviders, githubCopilotOAuthProvider, openaiCodexOAuthProvider, xaiOAuthProvider };
6
+ import { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError } from "./provider-auth-error.js";
7
+ export { AuthStorage, PROVIDER_AUTH_REQUIRED_ERROR, PROVIDER_DEFAULT_MODELS, ProviderAuthRequiredError, anthropicOAuthProvider, getOAuthProvider, getOAuthProviders, githubCopilotOAuthProvider, openaiCodexOAuthProvider, xaiOAuthProvider };
@@ -0,0 +1,12 @@
1
+ /** Wire-stable `Error.name`: the server flattens errors to `{ name, message }`, so hosts match on this. */
2
+ export declare const PROVIDER_AUTH_REQUIRED_ERROR = "ProviderAuthRequiredError";
3
+ /**
4
+ * A provider credential is missing or no longer usable. The message states the
5
+ * fact only — how the user re-authenticates is the host's call (`/login` in the
6
+ * TUI, Settings → Models in the factory web UI), so no host advertises a
7
+ * command another host doesn't have.
8
+ */
9
+ export declare class ProviderAuthRequiredError extends Error {
10
+ readonly name = "ProviderAuthRequiredError";
11
+ }
12
+ //# sourceMappingURL=provider-auth-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-auth-error.d.ts","sourceRoot":"","sources":["../../src/auth/provider-auth-error.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,eAAO,MAAM,4BAA4B,8BAA8B,CAAC;AAExE;;;;;GAKG;AACH,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,QAAQ,CAAC,IAAI,+BAAgC;CAC9C"}
@@ -0,0 +1,16 @@
1
+ //#region src/auth/provider-auth-error.ts
2
+ /** Wire-stable `Error.name`: the server flattens errors to `{ name, message }`, so hosts match on this. */
3
+ const PROVIDER_AUTH_REQUIRED_ERROR = "ProviderAuthRequiredError";
4
+ /**
5
+ * A provider credential is missing or no longer usable. The message states the
6
+ * fact only — how the user re-authenticates is the host's call (`/login` in the
7
+ * TUI, Settings → Models in the factory web UI), so no host advertises a
8
+ * command another host doesn't have.
9
+ */
10
+ var ProviderAuthRequiredError = class extends Error {
11
+ name = PROVIDER_AUTH_REQUIRED_ERROR;
12
+ };
13
+ //#endregion
14
+ export { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError };
15
+
16
+ //# sourceMappingURL=provider-auth-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-auth-error.js","names":[],"sources":["../../src/auth/provider-auth-error.ts"],"sourcesContent":["/** Wire-stable `Error.name`: the server flattens errors to `{ name, message }`, so hosts match on this. */\nexport const PROVIDER_AUTH_REQUIRED_ERROR = 'ProviderAuthRequiredError';\n\n/**\n * A provider credential is missing or no longer usable. The message states the\n * fact only — how the user re-authenticates is the host's call (`/login` in the\n * TUI, Settings → Models in the factory web UI), so no host advertises a\n * command another host doesn't have.\n */\nexport class ProviderAuthRequiredError extends Error {\n readonly name = PROVIDER_AUTH_REQUIRED_ERROR;\n}\n"],"mappings":";;AACA,MAAa,+BAA+B;;;;;;;AAQ5C,IAAa,4BAAb,cAA+C,MAAM;CACnD,OAAgB;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/headless/cli.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEzE,kFAAkF;AAClF,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,CAAC;AAEpD,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,UAAU,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,OAAO,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gFAAgF;IAChF,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC;AAID;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,IAAI,EA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,YAAY,CAsC9D;AAED,wBAAgB,kBAAkB,IAAI,IAAI,CA+BzC;AAED;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAmI9E"}
@@ -2,6 +2,7 @@ import { releaseAllThreadLocks } from "../utils/thread-lock.js";
2
2
  import { permissionModeToPolicy } from "./policy.js";
3
3
  import { runMC } from "./run-mc.js";
4
4
  import { createHumanFormatState, formatHuman, formatJsonl, renderJsonResult } from "./format.js";
5
+ import { createProcessMemoryDiagnosticsFromEnvironment, startConfiguredProcessMemoryDiagnostics, stopProcessMemoryDiagnosticsWithTimeout } from "../process-memory-diagnostics.js";
5
6
  import { setupDebugLogging } from "../utils/debug-log.js";
6
7
  import { FLAGS, buildParseArgsOptions, renderFlagUsage } from "./flags.js";
7
8
  import { createMastraCode } from "../index.js";
@@ -130,16 +131,20 @@ async function runMCCli(predrainedInput) {
130
131
  process.stderr.write(`Error: Settings file not found: ${args.settings}\n`);
131
132
  process.exit(1);
132
133
  }
133
- const boot = await createMastraCode({ settingsPath: args.settings });
134
- const { controller, session, mcpManager, effectiveDefaults } = boot;
135
- if (mcpManager?.hasServers()) try {
136
- await mcpManager.initInBackground();
137
- } catch (err) {
138
- process.stderr.write(`Warning: MCP server initialization failed: ${err.message ?? err}\n`);
139
- }
140
- setupDebugLogging();
134
+ const processMemoryDiagnostics = await startConfiguredProcessMemoryDiagnostics(createProcessMemoryDiagnosticsFromEnvironment(process.env), (warning) => {
135
+ process.stderr.write(`Warning: ${warning}\n`);
136
+ });
137
+ let boot;
141
138
  let exitCode = 1;
142
139
  try {
140
+ boot = await createMastraCode({ settingsPath: args.settings });
141
+ const { controller, session, mcpManager, effectiveDefaults } = boot;
142
+ if (mcpManager?.hasServers()) try {
143
+ await mcpManager.initInBackground();
144
+ } catch (err) {
145
+ process.stderr.write(`Warning: MCP server initialization failed: ${err.message ?? err}\n`);
146
+ }
147
+ setupDebugLogging();
143
148
  const humanState = createHumanFormatState();
144
149
  const run = runMC({
145
150
  controller,
@@ -179,16 +184,22 @@ async function runMCCli(predrainedInput) {
179
184
  exitCode = 1;
180
185
  } finally {
181
186
  releaseAllThreadLocks();
182
- try {
183
- boot.stopPluginSignalProviders();
184
- } catch {}
185
- const closeSignalsPubSub = boot.signalsPubSub?.close;
186
- await Promise.allSettled([
187
- mcpManager?.disconnect(),
188
- controller.getMastra()?.stopWorkers(),
189
- controller?.stopIntervals(),
190
- closeSignalsPubSub?.()
191
- ]);
187
+ if (boot) {
188
+ try {
189
+ boot.stopPluginSignalProviders();
190
+ } catch {}
191
+ const { controller, mcpManager } = boot;
192
+ const closeSignalsPubSub = boot.signalsPubSub?.close;
193
+ await Promise.allSettled([
194
+ mcpManager?.disconnect(),
195
+ controller.getMastra()?.stopWorkers(),
196
+ controller.stopIntervals(),
197
+ closeSignalsPubSub?.()
198
+ ]);
199
+ }
200
+ await stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, (warning) => {
201
+ process.stderr.write(`Warning: ${warning}\n`);
202
+ });
192
203
  }
193
204
  process.exit(exitCode);
194
205
  }
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../../src/headless/cli.ts"],"sourcesContent":["/**\n * CLI adapter for headless MastraCode runs.\n *\n * This is the only headless layer that touches the process: it parses argv,\n * reads stdin, bootstraps MastraCode via `createMastraCode`, drives `runMC`,\n * renders events/results to stdout/stderr through the pure formatters, maps the\n * result to an exit code, and owns teardown + `process.exit`.\n */\nimport { existsSync } from 'node:fs';\nimport { parseArgs } from 'node:util';\n\nimport { createMastraCode } from '../index.js';\nimport { setupDebugLogging } from '../utils/debug-log.js';\nimport { releaseAllThreadLocks } from '../utils/thread-lock.js';\n\nimport { buildParseArgsOptions, FLAGS, renderFlagUsage } from './flags.js';\nimport { createHumanFormatState, formatHuman, formatJsonl, renderJsonResult } from './format.js';\nimport { permissionModeToPolicy } from './policy.js';\nimport { runMC } from './run-mc.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\n\n/** Consolidated output mode (replaces the old `--format` + `--output-format`). */\nexport type OutputMode = 'human' | 'json' | 'jsonl';\n\nexport interface HeadlessArgs {\n prompt?: string;\n /** Timeout in seconds (CLI surface); converted to ms before `runMC`. */\n timeout?: number;\n output: OutputMode;\n continue_: boolean;\n model?: string;\n mode?: RunMode;\n thinkingLevel?: ThinkingLevel;\n settings?: string;\n thread?: string;\n title?: string;\n cloneThread: boolean;\n resourceId?: string;\n /** Max agentic turns before the run aborts with exit code 1. */\n maxTurns?: number;\n /** Named permission mode resolving to a built-in policy. Defaults to `auto`. */\n permissionMode?: PermissionMode;\n}\n\nconst parseArgsOptions = buildParseArgsOptions();\n\n/**\n * Returns true if `argv` selects headless mode. This must agree with what\n * {@link parseHeadlessArgs} (and `runMCCli`) accept as a prompt: `--prompt`/`-p`\n * or a bare positional prompt (e.g. `mastracode \"Fix the bug\"`). Note that a\n * prompt piped via stdin without a flag is handled separately by the caller.\n */\nexport function hasHeadlessFlag(argv: string[]): boolean {\n if (argv.some(a => a === '--prompt' || a === '-p')) return true;\n try {\n const { values, positionals } = parseArgs({\n args: argv.slice(2),\n options: parseArgsOptions,\n strict: false,\n allowPositionals: true,\n });\n // A positional prompt only counts when not asking for help.\n return positionals.length > 0 && !values.help;\n } catch {\n return false;\n }\n}\n\n/**\n * Parse CLI arguments for headless mode. The flag table in `flags.ts` is the\n * single source of truth: each flag carries its own coercion/validation, so this\n * function just walks {@link FLAGS} and assembles the typed {@link HeadlessArgs}.\n */\nexport function parseHeadlessArgs(argv: string[]): HeadlessArgs {\n const { values, positionals } = parseArgs({\n args: argv.slice(2),\n options: parseArgsOptions,\n strict: false,\n allowPositionals: true,\n });\n\n // Seed defaults; per-flag values below override these.\n const args: HeadlessArgs = {\n output: 'human',\n continue_: false,\n cloneThread: false,\n };\n const sink = args as unknown as Record<string, unknown>;\n\n for (const flag of FLAGS) {\n if (!flag.field) continue; // e.g. --help, handled by the caller\n const raw = values[flag.key];\n if (raw === undefined) continue;\n\n if (flag.type === 'boolean') {\n sink[flag.field] = Boolean(raw);\n } else if (typeof raw === 'string') {\n sink[flag.field] = flag.coerce ? flag.coerce(raw) : raw;\n }\n }\n\n // A bare positional acts as the prompt when --prompt/-p is absent.\n if (args.prompt === undefined && positionals[0] !== undefined) {\n args.prompt = positionals[0];\n }\n\n if (args.continue_ && args.thread) {\n throw new Error('--continue and --thread cannot be used together');\n }\n\n return args;\n}\n\nexport function printHeadlessUsage(): void {\n process.stdout.write(`\nUsage: mastracode --prompt <text> [options]\n\nHeadless (non-interactive) mode options:\n${renderFlagUsage()}\n\nThread behavior:\n By default, a new thread is created for each run.\n Use --continue to resume the most recent thread, or --thread to target a specific one.\n Use --clone-thread to branch off a copy before running.\n\nSettings file:\n Uses the same settings.json as the interactive TUI. Pass --settings to use\n a custom settings file (e.g., settings-ci.json for CI). All model, pack,\n subagent, and OM configuration is resolved from settings at startup.\n\nExit codes:\n 0 Agent completed successfully\n 1 Error, aborted, or max turns reached\n 2 Timeout\n\nExamples:\n mastracode --prompt \"Fix the bug in auth.ts\"\n mastracode --prompt \"Add tests\" --timeout 300 --output json\n mastracode --prompt \"Refactor\" --output jsonl\n mastracode --prompt \"Review this PR\" --permission-mode deny --max-turns 10\n mastracode --settings ./settings-ci.json --prompt \"Run tests\"\n mastracode -c --prompt \"Continue where you left off\"\n echo \"Summarize the repo\" | mastracode --prompt -\n`);\n}\n\n/**\n * Headless CLI entry point: parse arguments, read stdin, initialize MastraCode,\n * run via `runMC`, render output, and exit with the mapped code.\n */\nexport async function runMCCli(predrainedInput?: string | null): Promise<never> {\n if (process.argv.includes('--help') || process.argv.includes('-h')) {\n printHeadlessUsage();\n process.exit(0);\n }\n\n let args: HeadlessArgs;\n try {\n args = parseHeadlessArgs(process.argv);\n } catch (e) {\n process.stderr.write(`Error: ${(e as Error).message}\\n`);\n process.exit(1);\n }\n\n let prompt = args.prompt;\n if (predrainedInput !== undefined) {\n prompt = predrainedInput ?? '';\n } else if (prompt === '-' || (!prompt && !process.stdin.isTTY)) {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n prompt = Buffer.concat(chunks).toString('utf-8').trim();\n }\n\n if (!prompt) {\n printHeadlessUsage();\n process.stderr.write('Error: --prompt is required (or pipe via stdin)\\n');\n process.exit(1);\n }\n\n if (args.settings && !existsSync(args.settings)) {\n process.stderr.write(`Error: Settings file not found: ${args.settings}\\n`);\n process.exit(1);\n }\n\n const boot = await createMastraCode({ settingsPath: args.settings });\n const { controller, session, mcpManager, effectiveDefaults } = boot;\n\n if (mcpManager?.hasServers()) {\n try {\n await mcpManager.initInBackground();\n } catch (err) {\n process.stderr.write(`Warning: MCP server initialization failed: ${(err as Error).message ?? err}\\n`);\n }\n }\n\n setupDebugLogging();\n\n // Default to a non-zero exit so an unexpected throw before the run resolves\n // still surfaces as a failure to the caller / CI.\n let exitCode = 1;\n try {\n const humanState = createHumanFormatState();\n const run = runMC({\n controller,\n session,\n prompt,\n model: args.model,\n mode: args.mode,\n modeDefaults: effectiveDefaults,\n thinkingLevel: args.thinkingLevel,\n thread: { id: args.thread, continueLatest: args.continue_, clone: args.cloneThread },\n resourceId: args.resourceId,\n title: args.title,\n timeoutMs: args.timeout ? args.timeout * 1000 : undefined,\n maxTurns: args.maxTurns,\n policy: args.permissionMode ? permissionModeToPolicy(args.permissionMode) : undefined,\n });\n\n // Stream live events for human + jsonl modes. (json mode prints only the final object.)\n for await (const event of run) {\n if (args.output === 'human') {\n const out = formatHuman(event, humanState);\n if (out.stdout) process.stdout.write(out.stdout);\n if (out.stderr) process.stderr.write(out.stderr);\n } else if (args.output === 'jsonl') {\n process.stdout.write(JSON.stringify(formatJsonl(event)) + '\\n');\n }\n }\n\n const result = await run.result;\n exitCode = result.exitCode;\n\n if (args.output === 'json') {\n process.stdout.write(renderJsonResult(result));\n } else if (args.output === 'jsonl') {\n process.stdout.write(JSON.stringify({ type: 'result', ...result }) + '\\n');\n }\n\n if (result.status === 'timeout') {\n process.stderr.write(`\\nTimeout elapsed. Aborted.\\n`);\n } else if (result.error && args.output === 'human') {\n process.stderr.write(`Error: ${result.error.message}\\n`);\n }\n } catch (err) {\n process.stderr.write(`Error: ${(err as Error).message ?? err}\\n`);\n exitCode = 1;\n } finally {\n // --- Teardown (always runs, even on a thrown error) ---\n releaseAllThreadLocks();\n // Stop plugin-contributed signal providers (and the plugin reload listener)\n // before quiescing workers: a provider that keeps polling past this point\n // could dispatch into a controller that is shutting down.\n try {\n boot.stopPluginSignalProviders();\n } catch {\n // Best-effort — the process is exiting.\n }\n const closeSignalsPubSub = (boot.signalsPubSub as { close?: () => Promise<void> | void } | undefined)?.close;\n await Promise.allSettled([\n mcpManager?.disconnect(),\n controller.getMastra()?.stopWorkers(),\n controller?.stopIntervals(),\n closeSignalsPubSub?.(),\n ]);\n }\n\n process.exit(exitCode);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4CA,MAAM,mBAAmB,sBAAsB;;;;;;;AAQ/C,SAAgB,gBAAgB,MAAyB;CACvD,IAAI,KAAK,MAAK,MAAK,MAAM,cAAc,MAAM,IAAI,GAAG,OAAO;CAC3D,IAAI;EACF,MAAM,EAAE,QAAQ,gBAAgB,UAAU;GACxC,MAAM,KAAK,MAAM,CAAC;GAClB,SAAS;GACT,QAAQ;GACR,kBAAkB;EACpB,CAAC;EAED,OAAO,YAAY,SAAS,KAAK,CAAC,OAAO;CAC3C,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AAOA,SAAgB,kBAAkB,MAA8B;CAC9D,MAAM,EAAE,QAAQ,gBAAgB,UAAU;EACxC,MAAM,KAAK,MAAM,CAAC;EAClB,SAAS;EACT,QAAQ;EACR,kBAAkB;CACpB,CAAC;CAGD,MAAM,OAAqB;EACzB,QAAQ;EACR,WAAW;EACX,aAAa;CACf;CACA,MAAM,OAAO;CAEb,KAAK,MAAM,QAAQ,OAAO;EACxB,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ACxC,IAAI,KAAK,WAAW,SACzB,QAAQ,OAAO,MAAM,KAAK,UAAU;GAAE,MAAM;GAAU,GAAG;EAAO,CAAC,IAAI,IAAI;EAG3E,IAAI,OAAO,WAAW,WACpB,QAAQ,OAAO,MAAM,+BAA+B;OAC/C,IAAI,OAAO,SAAS,KAAK,WAAW,SACzC,QAAQ,OAAO,MAAM,UAAU,OAAO,MAAM,QAAQ,GAAG;CAE3D,SAAS,KAAK;EACZ,QAAQ,OAAO,MAAM,UAAW,IAAc,WAAW,IAAI,GAAG;EAChE,WAAW;CACb,UAAU;EAER,sBAAsB;EAItB,IAAI;GACF,KAAK,0BAA0B;EACjC,QAAQ,CAER;EACA,MAAM,qBAAsB,KAAK,eAAsE;EACvG,MAAM,QAAQ,WAAW;GACvB,YAAY,WAAW;GACvB,WAAW,UAAU,CAAC,EAAE,YAAY;GACpC,YAAY,cAAc;GAC1B,qBAAqB;EACvB,CAAC;CACH;CAEA,QAAQ,KAAK,QAAQ;AACvB"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../../src/headless/cli.ts"],"sourcesContent":["/**\n * CLI adapter for headless MastraCode runs.\n *\n * This is the only headless layer that touches the process: it parses argv,\n * reads stdin, bootstraps MastraCode via `createMastraCode`, drives `runMC`,\n * renders events/results to stdout/stderr through the pure formatters, maps the\n * result to an exit code, and owns teardown + `process.exit`.\n */\nimport { existsSync } from 'node:fs';\nimport { parseArgs } from 'node:util';\n\nimport { createMastraCode } from '../index.js';\nimport {\n createProcessMemoryDiagnosticsFromEnvironment,\n startConfiguredProcessMemoryDiagnostics,\n stopProcessMemoryDiagnosticsWithTimeout,\n} from '../process-memory-diagnostics.js';\nimport { setupDebugLogging } from '../utils/debug-log.js';\nimport { releaseAllThreadLocks } from '../utils/thread-lock.js';\n\nimport { buildParseArgsOptions, FLAGS, renderFlagUsage } from './flags.js';\nimport { createHumanFormatState, formatHuman, formatJsonl, renderJsonResult } from './format.js';\nimport { permissionModeToPolicy } from './policy.js';\nimport { runMC } from './run-mc.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\n\n/** Consolidated output mode (replaces the old `--format` + `--output-format`). */\nexport type OutputMode = 'human' | 'json' | 'jsonl';\n\nexport interface HeadlessArgs {\n prompt?: string;\n /** Timeout in seconds (CLI surface); converted to ms before `runMC`. */\n timeout?: number;\n output: OutputMode;\n continue_: boolean;\n model?: string;\n mode?: RunMode;\n thinkingLevel?: ThinkingLevel;\n settings?: string;\n thread?: string;\n title?: string;\n cloneThread: boolean;\n resourceId?: string;\n /** Max agentic turns before the run aborts with exit code 1. */\n maxTurns?: number;\n /** Named permission mode resolving to a built-in policy. Defaults to `auto`. */\n permissionMode?: PermissionMode;\n}\n\nconst parseArgsOptions = buildParseArgsOptions();\n\n/**\n * Returns true if `argv` selects headless mode. This must agree with what\n * {@link parseHeadlessArgs} (and `runMCCli`) accept as a prompt: `--prompt`/`-p`\n * or a bare positional prompt (e.g. `mastracode \"Fix the bug\"`). Note that a\n * prompt piped via stdin without a flag is handled separately by the caller.\n */\nexport function hasHeadlessFlag(argv: string[]): boolean {\n if (argv.some(a => a === '--prompt' || a === '-p')) return true;\n try {\n const { values, positionals } = parseArgs({\n args: argv.slice(2),\n options: parseArgsOptions,\n strict: false,\n allowPositionals: true,\n });\n // A positional prompt only counts when not asking for help.\n return positionals.length > 0 && !values.help;\n } catch {\n return false;\n }\n}\n\n/**\n * Parse CLI arguments for headless mode. The flag table in `flags.ts` is the\n * single source of truth: each flag carries its own coercion/validation, so this\n * function just walks {@link FLAGS} and assembles the typed {@link HeadlessArgs}.\n */\nexport function parseHeadlessArgs(argv: string[]): HeadlessArgs {\n const { values, positionals } = parseArgs({\n args: argv.slice(2),\n options: parseArgsOptions,\n strict: false,\n allowPositionals: true,\n });\n\n // Seed defaults; per-flag values below override these.\n const args: HeadlessArgs = {\n output: 'human',\n continue_: false,\n cloneThread: false,\n };\n const sink = args as unknown as Record<string, unknown>;\n\n for (const flag of FLAGS) {\n if (!flag.field) continue; // e.g. --help, handled by the caller\n const raw = values[flag.key];\n if (raw === undefined) continue;\n\n if (flag.type === 'boolean') {\n sink[flag.field] = Boolean(raw);\n } else if (typeof raw === 'string') {\n sink[flag.field] = flag.coerce ? flag.coerce(raw) : raw;\n }\n }\n\n // A bare positional acts as the prompt when --prompt/-p is absent.\n if (args.prompt === undefined && positionals[0] !== undefined) {\n args.prompt = positionals[0];\n }\n\n if (args.continue_ && args.thread) {\n throw new Error('--continue and --thread cannot be used together');\n }\n\n return args;\n}\n\nexport function printHeadlessUsage(): void {\n process.stdout.write(`\nUsage: mastracode --prompt <text> [options]\n\nHeadless (non-interactive) mode options:\n${renderFlagUsage()}\n\nThread behavior:\n By default, a new thread is created for each run.\n Use --continue to resume the most recent thread, or --thread to target a specific one.\n Use --clone-thread to branch off a copy before running.\n\nSettings file:\n Uses the same settings.json as the interactive TUI. Pass --settings to use\n a custom settings file (e.g., settings-ci.json for CI). All model, pack,\n subagent, and OM configuration is resolved from settings at startup.\n\nExit codes:\n 0 Agent completed successfully\n 1 Error, aborted, or max turns reached\n 2 Timeout\n\nExamples:\n mastracode --prompt \"Fix the bug in auth.ts\"\n mastracode --prompt \"Add tests\" --timeout 300 --output json\n mastracode --prompt \"Refactor\" --output jsonl\n mastracode --prompt \"Review this PR\" --permission-mode deny --max-turns 10\n mastracode --settings ./settings-ci.json --prompt \"Run tests\"\n mastracode -c --prompt \"Continue where you left off\"\n echo \"Summarize the repo\" | mastracode --prompt -\n`);\n}\n\n/**\n * Headless CLI entry point: parse arguments, read stdin, initialize MastraCode,\n * run via `runMC`, render output, and exit with the mapped code.\n */\nexport async function runMCCli(predrainedInput?: string | null): Promise<never> {\n if (process.argv.includes('--help') || process.argv.includes('-h')) {\n printHeadlessUsage();\n process.exit(0);\n }\n\n let args: HeadlessArgs;\n try {\n args = parseHeadlessArgs(process.argv);\n } catch (e) {\n process.stderr.write(`Error: ${(e as Error).message}\\n`);\n process.exit(1);\n }\n\n let prompt = args.prompt;\n if (predrainedInput !== undefined) {\n prompt = predrainedInput ?? '';\n } else if (prompt === '-' || (!prompt && !process.stdin.isTTY)) {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n prompt = Buffer.concat(chunks).toString('utf-8').trim();\n }\n\n if (!prompt) {\n printHeadlessUsage();\n process.stderr.write('Error: --prompt is required (or pipe via stdin)\\n');\n process.exit(1);\n }\n\n if (args.settings && !existsSync(args.settings)) {\n process.stderr.write(`Error: Settings file not found: ${args.settings}\\n`);\n process.exit(1);\n }\n\n const diagnosticsSetup = createProcessMemoryDiagnosticsFromEnvironment(process.env);\n const processMemoryDiagnostics = await startConfiguredProcessMemoryDiagnostics(diagnosticsSetup, warning => {\n process.stderr.write(`Warning: ${warning}\\n`);\n });\n\n let boot: Awaited<ReturnType<typeof createMastraCode>> | undefined;\n // Default to a non-zero exit so an unexpected throw before the run resolves\n // still surfaces as a failure to the caller / CI.\n let exitCode = 1;\n try {\n boot = await createMastraCode({ settingsPath: args.settings });\n const { controller, session, mcpManager, effectiveDefaults } = boot;\n\n if (mcpManager?.hasServers()) {\n try {\n await mcpManager.initInBackground();\n } catch (err) {\n process.stderr.write(`Warning: MCP server initialization failed: ${(err as Error).message ?? err}\\n`);\n }\n }\n\n setupDebugLogging();\n\n const humanState = createHumanFormatState();\n const run = runMC({\n controller,\n session,\n prompt,\n model: args.model,\n mode: args.mode,\n modeDefaults: effectiveDefaults,\n thinkingLevel: args.thinkingLevel,\n thread: { id: args.thread, continueLatest: args.continue_, clone: args.cloneThread },\n resourceId: args.resourceId,\n title: args.title,\n timeoutMs: args.timeout ? args.timeout * 1000 : undefined,\n maxTurns: args.maxTurns,\n policy: args.permissionMode ? permissionModeToPolicy(args.permissionMode) : undefined,\n });\n\n // Stream live events for human + jsonl modes. (json mode prints only the final object.)\n for await (const event of run) {\n if (args.output === 'human') {\n const out = formatHuman(event, humanState);\n if (out.stdout) process.stdout.write(out.stdout);\n if (out.stderr) process.stderr.write(out.stderr);\n } else if (args.output === 'jsonl') {\n process.stdout.write(JSON.stringify(formatJsonl(event)) + '\\n');\n }\n }\n\n const result = await run.result;\n exitCode = result.exitCode;\n\n if (args.output === 'json') {\n process.stdout.write(renderJsonResult(result));\n } else if (args.output === 'jsonl') {\n process.stdout.write(JSON.stringify({ type: 'result', ...result }) + '\\n');\n }\n\n if (result.status === 'timeout') {\n process.stderr.write(`\\nTimeout elapsed. Aborted.\\n`);\n } else if (result.error && args.output === 'human') {\n process.stderr.write(`Error: ${result.error.message}\\n`);\n }\n } catch (err) {\n process.stderr.write(`Error: ${(err as Error).message ?? err}\\n`);\n exitCode = 1;\n } finally {\n // --- Teardown (always runs, even on a thrown error) ---\n releaseAllThreadLocks();\n if (boot) {\n // Stop plugin-contributed signal providers (and the plugin reload listener)\n // before quiescing workers: a provider that keeps polling past this point\n // could dispatch into a controller that is shutting down.\n try {\n boot.stopPluginSignalProviders();\n } catch {\n // Best-effort — the process is exiting.\n }\n const { controller, mcpManager } = boot;\n const closeSignalsPubSub = (boot.signalsPubSub as { close?: () => Promise<void> | void } | undefined)?.close;\n await Promise.allSettled([\n mcpManager?.disconnect(),\n controller.getMastra()?.stopWorkers(),\n controller.stopIntervals(),\n closeSignalsPubSub?.(),\n ]);\n }\n await stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, warning => {\n process.stderr.write(`Warning: ${warning}\\n`);\n });\n }\n\n process.exit(exitCode);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiDA,MAAM,mBAAmB,sBAAsB;;;;;;;AAQ/C,SAAgB,gBAAgB,MAAyB;CACvD,IAAI,KAAK,MAAK,MAAK,MAAM,cAAc,MAAM,IAAI,GAAG,OAAO;CAC3D,IAAI;EACF,MAAM,EAAE,QAAQ,gBAAgB,UAAU;GACxC,MAAM,KAAK,MAAM,CAAC;GAClB,SAAS;GACT,QAAQ;GACR,kBAAkB;EACpB,CAAC;EAED,OAAO,YAAY,SAAS,KAAK,CAAC,OAA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ver, type PerformanceEntry } from 'node:perf_hooks';
2
+ import { getHeapSpaceStatistics, getHeapStatistics } from 'node:v8';
3
+ export declare const PROCESS_MEMORY_DIAGNOSTICS_DEFAULTS: {
4
+ readonly sampleIntervalMs: 10000;
5
+ readonly captureIntervalMs: 300000;
6
+ readonly allocationIntervalBytes: 524288;
7
+ };
8
+ export declare const PROCESS_MEMORY_DIAGNOSTICS_MINIMUMS: {
9
+ readonly sampleIntervalMs: 1000;
10
+ readonly captureIntervalMs: 10000;
11
+ readonly allocationIntervalBytes: 32768;
12
+ };
13
+ export interface ProcessMemoryDiagnosticsConfig {
14
+ parentDirectory: string;
15
+ sampleIntervalMs: number;
16
+ captureIntervalMs: number;
17
+ allocationIntervalBytes: number;
18
+ }
19
+ export interface ProcessMemoryDiagnosticsEnvironment {
20
+ MASTRACODE_PROFILE?: string;
21
+ MASTRACODE_PROFILE_DIR?: string;
22
+ MASTRACODE_PROFILE_SAMPLE_INTERVAL_MS?: string;
23
+ MASTRACODE_PROFILE_CAPTURE_INTERVAL_MS?: string;
24
+ MASTRACODE_PROFILE_ALLOCATION_INTERVAL_BYTES?: string;
25
+ }
26
+ export interface ProcessMemoryDiagnosticsMemorySample {
27
+ timestamp: string;
28
+ sequence: number;
29
+ elapsedMs: number;
30
+ memory: ReturnType<typeof process.memoryUsage>;
31
+ resourceUsage: ReturnType<typeof process.resourceUsage>;
32
+ heap: ReturnType<typeof getHeapStatistics>;
33
+ heapSpaces: ReturnType<typeof getHeapSpaceStatistics>;
34
+ }
35
+ export interface ProcessMemoryDiagnosticsStatus {
36
+ state: 'inactive' | 'starting' | 'active' | 'stopping' | 'error';
37
+ outputDirectory: string | null;
38
+ config: ProcessMemoryDiagnosticsConfig;
39
+ sampleCount: number;
40
+ captureCount: number;
41
+ gcEventCount: number;
42
+ latestSample: ProcessMemoryDiagnosticsMemorySample | null;
43
+ latestCapturePath: string | null;
44
+ error: string | null;
45
+ }
46
+ export interface ProcessMemoryDiagnosticsCapture {
47
+ path: string;
48
+ sequence: number;
49
+ timestamp: string;
50
+ reason: 'manual' | 'periodic' | 'stop';
51
+ }
52
+ interface InspectorSessionAdapter {
53
+ connect(): void;
54
+ disconnect(): void;
55
+ post(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
56
+ }
57
+ interface PerformanceObserverAdapter {
58
+ observe(options: Parameters<PerformanceObserver['observe']>[0]): void;
59
+ disconnect(): void;
60
+ }
61
+ interface ProcessMemoryDiagnosticsDependencies {
62
+ createInspectorSession?: () => InspectorSessionAdapter;
63
+ createPerformanceObserver?: (callback: (entries: PerformanceEntry[]) => void) => PerformanceObserverAdapter;
64
+ now?: () => Date;
65
+ randomId?: () => string;
66
+ }
67
+ export interface ProcessMemoryDiagnosticsSetup {
68
+ diagnostics: ProcessMemoryDiagnostics;
69
+ enabled: boolean;
70
+ error: string | null;
71
+ }
72
+ export declare class ProcessMemoryDiagnosticsConfigError extends Error {
73
+ constructor(message: string);
74
+ }
75
+ export declare function parseProcessMemoryDiagnosticsEnvironment(env?: ProcessMemoryDiagnosticsEnvironment): {
76
+ enabled: boolean;
77
+ config: ProcessMemoryDiagnosticsConfig;
78
+ };
79
+ export declare function createProcessMemoryDiagnosticsFromEnvironment(env?: ProcessMemoryDiagnosticsEnvironment, dependencies?: ProcessMemoryDiagnosticsDependencies): ProcessMemoryDiagnosticsSetup;
80
+ export declare function startConfiguredProcessMemoryDiagnostics(setup: ProcessMemoryDiagnosticsSetup, warn: (message: string) => void): Promise<ProcessMemoryDiagnostics>;
81
+ export declare function stopProcessMemoryDiagnosticsWithTimeout(diagnostics: ProcessMemoryDiagnostics, warn: (message: string) => void, timeoutMs?: number): Promise<void>;
82
+ export declare class ProcessMemoryDiagnostics {
83
+ readonly config: ProcessMemoryDiagnosticsConfig;
84
+ private state;
85
+ private outputDirectory;
86
+ private inspector;
87
+ private observer;
88
+ private sampleTimer;
89
+ private captureTimer;
90
+ private startedAt;
91
+ private sampleCount;
92
+ private captureCount;
93
+ private gcEventCount;
94
+ private latestSample;
95
+ private latestCapturePath;
96
+ private latestError;
97
+ private samplingActive;
98
+ private stopRequested;
99
+ private startingPromise;
100
+ private stoppingPromise;
101
+ private restartAfterStopPromise;
102
+ private restartRequested;
103
+ private pendingGcEvents;
104
+ private gcEventBufferOverflowed;
105
+ private artifactWriteFailed;
106
+ private captureQueue;
107
+ private writeQueue;
108
+ private readonly configError;
109
+ private readonly createInspectorSession;
110
+ private readonly createPerformanceObserver;
111
+ private readonly now;
112
+ private readonly randomId;
113
+ constructor(config: ProcessMemoryDiagnosticsConfig, dependencies?: ProcessMemoryDiagnosticsDependencies, initialError?: string | null);
114
+ getStatus(): ProcessMemoryDiagnosticsStatus;
115
+ start(): Promise<ProcessMemoryDiagnosticsStatus>;
116
+ private startRun;
117
+ private abortStartIfRequested;
118
+ capture(reason?: 'manual' | 'periodic'): Promise<ProcessMemoryDiagnosticsCapture>;
119
+ stop(): Promise<ProcessMemoryDiagnosticsStatus>;
120
+ private createArtifacts;
121
+ private observeGc;
122
+ private startSampling;
123
+ private takeSample;
124
+ private enqueueWrite;
125
+ private enqueueWriteBatch;
126
+ private enqueueCapture;
127
+ private captureEpoch;
128
+ private restartSamplingAfterFailure;
129
+ private recordError;
130
+ private clearTimersAndObserver;
131
+ private disconnectInspector;
132
+ private cleanupAfterStartFailure;
133
+ }
134
+ export {};
135
+ //# sourceMappingURL=process-memory-diagnostics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-memory-diagnostics.d.ts","sourceRoot":"","sources":["../src/process-memory-diagnostics.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,KAAK,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAE7E,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEpE,eAAO,MAAM,mCAAmC;;;;CAItC,CAAC;AAEX,eAAO,MAAM,mCAAmC;;;;CAItC,CAAC;AAKX,MAAM,WAAW,8BAA8B;IAC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