@mastra/code-sdk 1.15.0-alpha.0 → 1.15.0-alpha.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../../src/agents/workspace.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAwB,MAAM,wBAAwB,CAAC;AACxG,OAAO,KAAK,EAAa,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAyGrE,wBAAgB,eAAe,CAC7B,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,SAAe,EACtB,gBAAgB,GAAE,MAAM,EAAO,GAC9B,MAAM,EAAE,CA0BV;AAED,MAAM,WAAW,uBAAuB;IACtC,yEAAyE;IACzE,EAAE,EAAE,MAAM,CAAC;IACX,uFAAuF;IACvF,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,6EAA6E;IAC7E,YAAY,EAAE,CAAC,QAAQ,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC;CACpF;AA2BD,wBAAsB,mBAAmB,CAAC,EACxC,cAAc,EACd,MAAM,EACN,cAAc,EACd,sBAA8B,GAC/B,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,uBAAuB,CAAC;IACzC,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC,gEA0EA;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,cAAc,EACd,MAAM,GACP,EAAE;IACD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AC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAclC"}
@@ -167,6 +167,7 @@ async function getDynamicWorkspace({ requestContext, mastra, skillExtension, bac
167
167
  name: "Mastra Code Workspace",
168
168
  filesystem,
169
169
  sandbox: new LocalSandbox({
170
+ timeout: 3e4,
170
171
  workingDirectory: projectPath,
171
172
  env: buildSandboxEnv()
172
173
  }),
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings, resolveLspSetting } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\n\nimport { createMastraCodeWorkspaceTools, GOAL_JUDGE_READONLY_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n backgroundToolsEnabled = false,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n backgroundToolsEnabled?: boolean;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = createMastraCodeWorkspaceTools(backgroundToolsEnabled);\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n // LSP is opt-in. When disabled we pass `false` so core skips the dependency\n // check, the LSP manager, and the `lsp_inspect` tool entirely.\n const userLsp = resolveLspSetting(loadSettings().lsp);\n let lspConfig: LSPConfig | false = false;\n if (userLsp !== false) {\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n lspConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n }\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];\n }\n return Object.keys(readonly).length > 0 ? readonly : undefined;\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,kBAAqC;CAC5C,OAAO;EACL,GAAG,QAAQ;EAEX,aAAa;EACb,gBAAgB;EAChB,MAAM,QAAQ,IAAI,QAAQ;EAC1B,IAAI;EACJ,gBAAgB;EAChB,iBAAiB;CACnB;AACF;AAkBA,SAAS,kBAAkB,YAAsB,aAAgC;CAC/E,MAAM,QAAkB,CAAC;CACzB,MAAM,uBAAO,IAAI,IAAY;CAC7B,IAAI;CAEJ,IAAI,aACF,IAAI;EACF,kBAAkB,GAAG,aAAa,WAAW;CAC/C,QAAQ;EACN,OAAO,CAAC;CACV;CAGF,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,kBAAkB,GAAG,WAAW,SAAS;EAC/C,IAAI,mBAAmB,iBACrB,IAAI;GAEF,IAAI,CAAC,iBADiB,GAAG,aAAa,SACJ,GAAG,eAAe,GAAG;EACzD,QAAQ;GACN;EACF;EAGF,MAAM,WAAW,KAAK,QAAQ,SAAS;EACvC,IAAI,CAAC,KAAK,IAAI,QAAQ,GAAG;GACvB,KAAK,IAAI,QAAQ;GACjB,MAAM,KAAK,SAAS;EACtB;EAEA,IAAI,CAAC,iBAAiB;EAEtB,IAAI;GACF,MAAM,UAAU,GAAG,YAAY,WAAW,EAAE,eAAe,KAAK,CAAC;GACjE,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,eAAe,GACvB,IAAI;IACF,MAAM,WAAW,KAAK,KAAK,WAAW,MAAM,IAAI;IAChD,MAAM,WAAW,GAAG,aAAa,QAAQ;IACzC,IAAI,mBAAmB,CAAC,iBAAiB,UAAU,eAAe,GAAG;IAErE,IADa,GAAG,SAAS,QAClB,CAAC,CAAC,YAAY,GAAG;KACtB,MAAM,aAAa,KAAK,QAAQ,QAAQ;KACxC,IAAI,mBAAmB,CAAC,iBAAiB,YAAY,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AAa,CAAC,CAAC,GAAG;CACpD,IAAI,YAA+B;CACnC,IAAI,YAAY,OAAO;EACrB,MAAM,eAAe,KAAK,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC,GAAG,IAAI;EACvE,YAAY;GACV,gBAAgB;GAChB,GAAG;GACH,eAAe,QAAQ,iBAAiB,oBAAoB,WAAW;GACvE,aAAa,CAAC,cAAc,GAAI,QAAQ,eAAe,CAAC,CAAE;EAC5D;CACF;CAGA,MAAM,aAAa,IAAI,gBAAgB;EACrC,UAAU;EACV;CACF,CAAC;CACD,OAAO,IAAI,UAAU;EACnB,IAAI;EACJ,MAAM;EACN;EACA,SAAS,IAAI,aAAa;GACxB,kBAAkB;GAClB,KAAK,gBAAgB;EACvB,CAAC;EACD,OAAO;EACP,QAAQ;EACR,GAAI,iBAAiB,EAAE,aAAa,eAAe,aAAa,YAAY,iBAAiB,EAAE,IAAI,CAAC;EACpG,KAAK;CACP,CAAC;AACH;;;;;;;;;AAUA,eAAsB,kBAAkB,EACtC,gBACA,UAIkC;CAClC,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,oBAAoB;GAAE;GAAgB;EAAO,CAAC;CAClE,QAAQ;EACN;CACF;CAEA,MAAM,WAAW,MAAM,qBAAqB,WAAW;EAAE;EAAgB;CAAU,CAAC;CACpF,MAAM,WAAuB,CAAC;CAC9B,KAAK,MAAM,QAAQ,2BACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS;CAEhD,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,WAAW,KAAA;AACvD"}
1
+ {"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings, resolveLspSetting } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\n\nimport { createMastraCodeWorkspaceTools, GOAL_JUDGE_READONLY_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n backgroundToolsEnabled = false,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n backgroundToolsEnabled?: boolean;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = createMastraCodeWorkspaceTools(backgroundToolsEnabled);\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n // LSP is opt-in. When disabled we pass `false` so core skips the dependency\n // check, the LSP manager, and the `lsp_inspect` tool entirely.\n const userLsp = resolveLspSetting(loadSettings().lsp);\n let lspConfig: LSPConfig | false = false;\n if (userLsp !== false) {\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n lspConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n }\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n timeout: 30_000,\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];\n }\n return Object.keys(readonly).length > 0 ? readonly : undefined;\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,kBAAqC;CAC5C,OAAO;EACL,GAAG,QAAQ;EAEX,aAAa;EACb,gBAAgB;EAChB,MAAM,QAAQ,IAAI,QAAQ;EAC1B,IAAI;EACJ,gBAAgB;EAChB,iBAAiB;CACnB;AACF;AAkBA,SAAS,kBAAkB,YAAsB,aAAgC;CAC/E,MAAM,QAAkB,CAAC;CACzB,MAAM,uBAAO,IAAI,IAAY;CAC7B,IAAI;CAEJ,IAAI,aACF,IAAI;EACF,kBAAkB,GAAG,aAAa,WAAW;CAC/C,QAAQ;EACN,OAAO,CAAC;CACV;CAGF,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,kBAAkB,GAAG,WAA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Aa,YAAY,iBAAiB,EAAE,IAAI,CAAC;EACpG,KAAK;CACP,CAAC;AACH;;;;;;;;;AAUA,eAAsB,kBAAkB,EACtC,gBACA,UAIkC;CAClC,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,oBAAoB;GAAE;GAAgB;EAAO,CAAC;CAClE,QAAQ;EACN;CACF;CAEA,MAAM,WAAW,MAAM,qBAAqB,WAAW;EAAE;EAAgB;CAAU,CAAC;CACpF,MAAM,WAAuB,CAAC;CAC9B,KAAK,MAAM,QAAQ,2BACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS;CAEhD,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,WAAW,KAAA;AACvD"}
@@ -1,3 +1,4 @@
1
+ import type { Writable } from 'node:stream';
1
2
  import type { PermissionMode, RunMode, ThinkingLevel } from './types.js';
2
3
  /** Consolidated output mode (replaces the old `--format` + `--output-format`). */
3
4
  export type OutputMode = 'human' | 'json' | 'jsonl';
@@ -35,6 +36,12 @@ export declare function hasHeadlessFlag(argv: string[]): boolean;
35
36
  */
36
37
  export declare function parseHeadlessArgs(argv: string[]): HeadlessArgs;
37
38
  export declare function printHeadlessUsage(): void;
39
+ /**
40
+ * Wait until everything written to `stream` has been handed to the OS, since
41
+ * `process.exit()` drops writes a pipe has not accepted yet. Resolves `false`
42
+ * if the stream fails or closes first; never rejects or hangs on a gone reader.
43
+ */
44
+ export declare function flushWritable(stream: Writable): Promise<boolean>;
38
45
  /**
39
46
  * Headless CLI entry point: parse arguments, read stdin, initialize MastraCode,
40
47
  * run via `runMC`, render output, and exit with the mapped code.
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/headless/cli.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEzE,kFAAkF;AAClF,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,MAAM,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C,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GACzD,OAAO,CAAC,KAAK,CAAC,CAwLhB"}
@@ -3,7 +3,7 @@ import { loadSettings, resolveModelDefaults, saveSettings } from "../onboarding/
3
3
  import { releaseAllThreadLocks } from "../utils/thread-lock.js";
4
4
  import { permissionModeToPolicy } from "./policy.js";
5
5
  import { runMC } from "./run-mc.js";
6
- import { createHumanFormatState, formatHuman, formatJsonl, renderJsonResult } from "./format.js";
6
+ import { createHumanFormatState, formatHuman, formatJsonl, isJsonlEvent, renderJsonResult } from "./format.js";
7
7
  import { activateModePackInSettings, resolveModePackArg, resolvePackSelection } from "../onboarding/pack-activation.js";
8
8
  import { createProcessMemoryDiagnosticsFromEnvironment, startConfiguredProcessMemoryDiagnostics, stopProcessMemoryDiagnosticsWithTimeout } from "../process-memory-diagnostics.js";
9
9
  import { setupDebugLogging } from "../utils/debug-log.js";
@@ -104,6 +104,20 @@ Examples:
104
104
  `);
105
105
  }
106
106
  /**
107
+ * Wait until everything written to `stream` has been handed to the OS, since
108
+ * `process.exit()` drops writes a pipe has not accepted yet. Resolves `false`
109
+ * if the stream fails or closes first; never rejects or hangs on a gone reader.
110
+ */
111
+ function flushWritable(stream) {
112
+ if (stream.destroyed || stream.errored) return Promise.resolve(false);
113
+ if (stream.writableLength === 0) return Promise.resolve(true);
114
+ return new Promise((resolve) => {
115
+ stream.once("error", () => resolve(false));
116
+ stream.once("close", () => resolve(false));
117
+ stream.write("", (error) => resolve(!error));
118
+ });
119
+ }
120
+ /**
107
121
  * Headless CLI entry point: parse arguments, read stdin, initialize MastraCode,
108
122
  * run via `runMC`, render output, and exit with the mapped code.
109
123
  */
@@ -195,7 +209,7 @@ async function runMCCli(predrainedInput, options) {
195
209
  const out = formatHuman(event, humanState);
196
210
  if (out.stdout) process.stdout.write(out.stdout);
197
211
  if (out.stderr) process.stderr.write(out.stderr);
198
- } else if (args.output === "jsonl") process.stdout.write(JSON.stringify(formatJsonl(event)) + "\n");
212
+ } else if (args.output === "jsonl" && isJsonlEvent(event)) process.stdout.write(JSON.stringify(formatJsonl(event)) + "\n");
199
213
  const result = await run.result;
200
214
  exitCode = result.exitCode;
201
215
  if (args.output === "json") process.stdout.write(renderJsonResult(result));
@@ -231,9 +245,11 @@ async function runMCCli(predrainedInput, options) {
231
245
  process.stderr.write(`Warning: ${warning}\n`);
232
246
  });
233
247
  }
248
+ const [stdoutFlushed] = await Promise.all([flushWritable(process.stdout), flushWritable(process.stderr)]);
249
+ if (!stdoutFlushed && exitCode === 0) exitCode = 1;
234
250
  process.exit(exitCode);
235
251
  }
236
252
  //#endregion
237
- export { hasHeadlessFlag, parseHeadlessArgs, printHeadlessUsage, runMCCli };
253
+ export { flushWritable, hasHeadlessFlag, parseHeadlessArgs, printHeadlessUsage, runMCCli };
238
254
 
239
255
  //# sourceMappingURL=cli.js.map
@@ -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 { activateModePackInSettings, resolveModePackArg, resolvePackSelection } from '../onboarding/pack-activation.js';\nimport { listBuiltinModePacks } from '../onboarding/packs.js';\nimport { loadSettings, resolveModelDefaults, saveSettings } from '../onboarding/settings.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 pack?: 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();\nconst STOP_NOTIFICATION_DISPATCH_TIMEOUT_MS = 2_000;\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(\n predrainedInput?: string | null,\n options?: { coAuthor?: { name?: string; email?: string } },\n): 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 // Resolve --pack up front: an unknown pack fails fast with the valid list,\n // before MastraCode boots. The selection itself is resolved inside runMC\n // after thread selection, because a resumed thread restores its persisted\n // mode — the mode that decides whether the pack has a model for this run.\n // Activation (which mirrors /models → Activate and becomes the global\n // default pack in settings) is saved via onApplied only once the pack has\n // actually been applied to the session — a rejected pack must not change\n // the persisted default on its way out.\n const settings = loadSettings(args.settings);\n let packId: string | undefined;\n if (args.pack !== undefined) {\n const resolved = resolveModePackArg(settings, args.pack);\n if ('error' in resolved) {\n process.stderr.write(`Error: ${resolved.error}\\n`);\n process.exit(1);\n }\n packId = resolved.packId;\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, coAuthor: options?.coAuthor });\n const { controller, session, mcpManager } = boot;\n\n const effectiveDefaults = resolveModelDefaults(settings, listBuiltinModePacks());\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 ...(packId\n ? {\n pack: {\n id: packId,\n resolve: (modeId: string) => resolvePackSelection(settings, packId, modeId),\n onApplied: () => {\n activateModePackInSettings(settings, packId);\n saveSettings(settings, args.settings);\n },\n },\n }\n : {}),\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. Release thread\n // claims first so a restarted process need not wait out this teardown.\n try {\n boot.releaseThreadClaims();\n } catch {\n // Best-effort — the process is exiting.\n }\n try {\n boot.stopPluginSignalProviders();\n } catch {\n // Best-effort — the process is exiting.\n }\n const { controller, mcpManager } = boot;\n // Release notification dispatch leases before the pubsub that holds them\n // closes. Headless has no shutdown deadline, so don't let a stalled\n // in-flight dispatch hold up exit.\n await Promise.race([\n boot.stopNotificationDispatch?.().catch(() => {}),\n new Promise<void>(resolve => setTimeout(resolve, STOP_NOTIFICATION_DISPATCH_TIMEOUT_MS).unref()),\n ]);\n await Promise.allSettled([\n mcpManager?.disconnect(),\n controller.getMastra()?.stopWorkers(),\n controller.stopIntervals(),\n ]);\n // The signals pubsub is Mastra's event bus, so close it after the workers\n // stop. Call close() on the object; a detached method loses `this` and\n // rejects silently, leaving socket files behind.\n const signalsPubSub = boot.signalsPubSub as { close?: () => Promise<void> | void } | undefined;\n await Promise.allSettled([signalsPubSub?.close?.()]);\n }\n await stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, warning => {\n process.stderr.write(`Warning: ${warning}\\n`);\n });\n }\n\n process.exit(exitCode);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,mBAAmB,sBAAsB;AAC/C,MAAM,wCAAwC;;;;;;;AAQ9C,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,QAA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MAAM;GAKR,IAAI;IACF,KAAK,oBAAoB;GAC3B,QAAQ,CAER;GACA,IAAI;IACF,KAAK,0BAA0B;GACjC,QAAQ,CAER;GACA,MAAM,EAAE,YAAY,eAAe;GAInC,MAAM,QAAQ,KAAK,CACjB,KAAK,2BAA2B,CAAC,CAAC,YAAY,CAAC,CAAC,GAChD,IAAI,SAAc,YAAW,WAAW,SAAS,qCAAqC,CAAC,CAAC,MAAM,CAAC,CACjG,CAAC;GACD,MAAM,QAAQ,WAAW;IACvB,YAAY,WAAW;IACvB,WAAW,UAAU,CAAC,EAAE,YAAY;IACpC,WAAW,cAAc;GAC3B,CAAC;GAID,MAAM,gBAAgB,KAAK;GAC3B,MAAM,QAAQ,WAAW,CAAC,eAAe,QAAQ,CAAC,CAAC;EACrD;EACA,MAAM,wCAAwC,2BAA0B,YAAW;GACjF,QAAQ,OAAO,MAAM,YAAY,QAAQ,GAAG;EAC9C,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 type { Writable } from 'node:stream';\nimport { parseArgs } from 'node:util';\n\nimport { createMastraCode } from '../index.js';\nimport { activateModePackInSettings, resolveModePackArg, resolvePackSelection } from '../onboarding/pack-activation.js';\nimport { listBuiltinModePacks } from '../onboarding/packs.js';\nimport { loadSettings, resolveModelDefaults, saveSettings } from '../onboarding/settings.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, isJsonlEvent, 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 pack?: 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();\nconst STOP_NOTIFICATION_DISPATCH_TIMEOUT_MS = 2_000;\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 * Wait until everything written to `stream` has been handed to the OS, since\n * `process.exit()` drops writes a pipe has not accepted yet. Resolves `false`\n * if the stream fails or closes first; never rejects or hangs on a gone reader.\n */\nexport function flushWritable(stream: Writable): Promise<boolean> {\n if (stream.destroyed || stream.errored) return Promise.resolve(false);\n if (stream.writableLength === 0) return Promise.resolve(true);\n return new Promise(resolve => {\n // Left attached: a stream can emit `error` after failing pending callbacks.\n stream.once('error', () => resolve(false));\n stream.once('close', () => resolve(false));\n stream.write('', error => resolve(!error));\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(\n predrainedInput?: string | null,\n options?: { coAuthor?: { name?: string; email?: string } },\n): 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 // Resolve --pack up front: an unknown pack fails fast with the valid list,\n // before MastraCode boots. The selection itself is resolved inside runMC\n // after thread selection, because a resumed thread restores its persisted\n // mode — the mode that decides whether the pack has a model for this run.\n // Activation (which mirrors /models → Activate and becomes the global\n // default pack in settings) is saved via onApplied only once the pack has\n // actually been applied to the session — a rejected pack must not change\n // the persisted default on its way out.\n const settings = loadSettings(args.settings);\n let packId: string | undefined;\n if (args.pack !== undefined) {\n const resolved = resolveModePackArg(settings, args.pack);\n if ('error' in resolved) {\n process.stderr.write(`Error: ${resolved.error}\\n`);\n process.exit(1);\n }\n packId = resolved.packId;\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, coAuthor: options?.coAuthor });\n const { controller, session, mcpManager } = boot;\n\n const effectiveDefaults = resolveModelDefaults(settings, listBuiltinModePacks());\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 ...(packId\n ? {\n pack: {\n id: packId,\n resolve: (modeId: string) => resolvePackSelection(settings, packId, modeId),\n onApplied: () => {\n activateModePackInSettings(settings, packId);\n saveSettings(settings, args.settings);\n },\n },\n }\n : {}),\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' && isJsonlEvent(event)) {\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. Release thread\n // claims first so a restarted process need not wait out this teardown.\n try {\n boot.releaseThreadClaims();\n } catch {\n // Best-effort — the process is exiting.\n }\n try {\n boot.stopPluginSignalProviders();\n } catch {\n // Best-effort — the process is exiting.\n }\n const { controller, mcpManager } = boot;\n // Release notification dispatch leases before the pubsub that holds them\n // closes. Headless has no shutdown deadline, so don't let a stalled\n // in-flight dispatch hold up exit.\n await Promise.race([\n boot.stopNotificationDispatch?.().catch(() => {}),\n new Promise<void>(resolve => setTimeout(resolve, STOP_NOTIFICATION_DISPATCH_TIMEOUT_MS).unref()),\n ]);\n await Promise.allSettled([\n mcpManager?.disconnect(),\n controller.getMastra()?.stopWorkers(),\n controller.stopIntervals(),\n ]);\n // The signals pubsub is Mastra's event bus, so close it after the workers\n // stop. Call close() on the object; a detached method loses `this` and\n // rejects silently, leaving socket files behind.\n const signalsPubSub = boot.signalsPubSub as { close?: () => Promise<void> | void } | undefined;\n await Promise.allSettled([signalsPubSub?.close?.()]);\n }\n await stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, warning => {\n process.stderr.write(`Warning: ${warning}\\n`);\n });\n }\n\n // Let piped output (the final result line in particular) reach the reader\n // before exiting. Output that never arrived must not count as success.\n const [stdoutFlushed] = await Promise.all([flushWritable(process.stdout), flushWritable(process.stderr)]);\n if (!stdoutFlushed && exitCode === 0) exitCode = 1;\n process.exit(exitCode);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAM,mBAAmB,sBAAsB;AAC/C,MAAM,wCAAwC;;;;;;;AAQ9C,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,IAAI,CAAC,KAAK,OAAO;EACjB,MAAM,MAAM,OAAO,KAAK;EACxB,IAAI,QAAQ,KAAA,GAAW;EAEvB,IAAI,KAAK,SAAS,WAChB,KAAK,KAAK,SAAS,QAAQ,GAAG;OACzB,IAAI,OAAO,QAAQ,UACxB,KAAK,KAAK,SAAS,KAAK,SAAS,KAAK,OAAO,GAAG,IAAI;CAExD;CAGA,IAAI,KAAK,WAAW,KAAA,KAAa,YAAY,OAAO,KAAA,GAClD,KAAK,SAAS,YAAY;CAG5B,IAAI,KAAK,aAAa,KAAK,QACzB,MAAM,IAAI,MAAM,iDAAiD;CAGnE,OAAO;AACT;AAEA,SAAgB,qBAA2B;CAC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A2F;AAC3F,wBAAgB,eAAe,IAAI,MAAM,CAmBxC"}
1
+ {"version":3,"file":"flags.d.ts","sourceRoot":"","sources":["../../src/headless/flags.ts"],"names":[],"mappings":"AAgBA,eAAO,MAAM,aAAa,qCAAsC,CAAC;AA6BjE;;;;;GAKG;AACH,MAAM,WAAW,QAAQ;IACvB,+CAA+C;IAC/C,GAAG,EAAE,MAAM,CAAC;IACZ,gEAAgE;IAChE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,IAAI,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC3B,sFAAsF;IACtF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+FAA+F;IAC/F,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC;IAClC,+DAA+D;IAC/D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gEAAgE;IAChE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;CACzB;AAED,eAAO,MAAM,KAAK,EAAE,QAAQ,EA+I3B,CAAC;AAEF,4DAA4D;AAC5D,wBAAgB,qBAAqB;UACG,QAAQ,GAAG,SAAS;YAAU,MAAM;cAAY,OAAO;GAM9F;AAED,2FAA2F;AAC3F,wBAAgB,eAAe,IAAI,MAAM,CAmBxC"}
@@ -114,7 +114,8 @@ const FLAGS = [
114
114
  "Output mode: \"human\" (default), \"json\", or \"jsonl\"",
115
115
  " human streaming text to stdout, activity to stderr",
116
116
  " json single final JSON object (text, usage, tools)",
117
- " jsonl newline-delimited JSON event stream"
117
+ " jsonl newline-delimited JSON event stream",
118
+ " (omits display_state_changed UI snapshots)"
118
119
  ]
119
120
  },
120
121
  {
@@ -1 +1 @@
1
- {"version":3,"file":"flags.js","names":[],"sources":["../../src/headless/flags.ts"],"sourcesContent":["/**\n * Declarative flag specification for the headless CLI.\n *\n * A single table is the source of truth for three things that previously drifted\n * apart in `cli.ts`:\n * 1. the `node:util` `parseArgs` option config,\n * 2. per-flag value coercion + validation, and\n * 3. the `--help` usage text.\n *\n * Adding a flag means adding one row here; parsing, validation, and the usage\n * listing all follow automatically.\n */\nimport type { OutputMode } from './cli.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\nimport { VALID_MODES, VALID_PERMISSION_MODES, VALID_THINKING_LEVELS } from './types.js';\n\nexport const VALID_OUTPUTS = ['human', 'json', 'jsonl'] as const;\n\n/** Reusable validators. Each throws a descriptive Error or returns the typed value. */\nconst validate = {\n /** Restrict to a fixed set of string literals. */\n enum<T extends string>(flag: string, allowed: readonly T[]) {\n return (raw: string): T => {\n if (!(allowed as readonly string[]).includes(raw)) {\n throw new Error(`${flag} must be one of: ${allowed.join(', ')}`);\n }\n return raw as T;\n };\n },\n /** Require a positive (>0) integer. */\n positiveInt(flag: string) {\n return (raw: string): number => {\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${flag} must be a positive integer`);\n }\n return parsed;\n };\n },\n /** Pass a string through unchanged. */\n string(raw: string): string {\n return raw;\n },\n};\n\n/**\n * One CLI flag. `key` is the long name (e.g. `output`); `field` is the\n * {@link import('./cli.js').HeadlessArgs} property it populates. `coerce`\n * converts the raw string and validates it. Boolean flags omit `coerce` and set\n * `field` to `true` when present.\n */\nexport interface FlagSpec {\n /** Long flag name without the leading `--`. */\n key: string;\n /** Single-character alias (without the leading `-`), if any. */\n short?: string;\n /** Whether the flag takes a value (`string`) or is a switch (`boolean`). */\n type: 'string' | 'boolean';\n /** Target field on `HeadlessArgs`. Omit for flags handled out-of-band (e.g. help). */\n field?: string;\n /** Coerce/validate a string value. Required for `type: 'string'` flags that map to a field. */\n coerce?: (raw: string) => unknown;\n /** `<...>` value placeholder shown in usage, e.g. `<text>`. */\n placeholder?: string;\n /** One-line (or multi-line) help description shown in usage. */\n help: string | string[];\n}\n\nexport const FLAGS: FlagSpec[] = [\n {\n key: 'prompt',\n short: 'p',\n type: 'string',\n field: 'prompt',\n coerce: validate.string,\n placeholder: '<text>',\n help: 'The task to execute (required, or pipe via stdin)',\n },\n {\n key: 'continue',\n short: 'c',\n type: 'boolean',\n field: 'continue_',\n help: 'Resume the most recent thread instead of creating a new one',\n },\n {\n key: 'thread',\n short: 't',\n type: 'string',\n field: 'thread',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Resume a specific thread by ID',\n },\n {\n key: 'title',\n type: 'string',\n field: 'title',\n coerce: validate.string,\n placeholder: '<title>',\n help: 'Set or rename the thread title',\n },\n {\n key: 'clone-thread',\n type: 'boolean',\n field: 'cloneThread',\n help: 'Clone the current thread before running (work on a copy)',\n },\n {\n key: 'resource-id',\n type: 'string',\n field: 'resourceId',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Set the resource ID for thread scoping',\n },\n {\n key: 'timeout',\n type: 'string',\n field: 'timeout',\n coerce: validate.positiveInt('--timeout'),\n placeholder: '<seconds>',\n help: 'Exit with code 2 if not complete within timeout',\n },\n {\n key: 'max-turns',\n type: 'string',\n field: 'maxTurns',\n coerce: validate.positiveInt('--max-turns'),\n placeholder: '<n>',\n help: 'Abort after N agentic turns (exit code 1)',\n },\n {\n key: 'permission-mode',\n type: 'string',\n field: 'permissionMode',\n coerce: validate.enum<PermissionMode>('--permission-mode', VALID_PERMISSION_MODES),\n placeholder: '<mode>',\n help: [\n 'How tool approvals/suspensions resolve:',\n ' auto approve everything (default)',\n ' deny refuse approvals, abort on suspension',\n ],\n },\n {\n key: 'output',\n short: 'o',\n type: 'string',\n field: 'output',\n coerce: validate.enum<OutputMode>('--output', VALID_OUTPUTS),\n placeholder: '<mode>',\n help: [\n 'Output mode: \"human\" (default), \"json\", or \"jsonl\"',\n ' human streaming text to stdout, activity to stderr',\n ' json single final JSON object (text, usage, tools)',\n ' jsonl newline-delimited JSON event stream',\n ],\n },\n {\n key: 'model',\n short: 'm',\n type: 'string',\n field: 'model',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Model override (e.g., a provider/model id); wins over --pack for the active mode',\n },\n {\n key: 'pack',\n type: 'string',\n field: 'pack',\n coerce: validate.string,\n placeholder: '<id>',\n help: [\n 'Model pack to activate (like /models → Activate): a builtin pack id',\n '(anthropic, openai, github-copilot) or a saved custom pack, by',\n '\"custom:<name>\" or its bare name. Sets the pack for every mode and',\n 'becomes the global default pack. --model overrides it for the active mode.',\n ],\n },\n {\n key: 'mode',\n type: 'string',\n field: 'mode',\n coerce: validate.enum<RunMode>('--mode', VALID_MODES),\n placeholder: '{build|plan|fast}',\n help: 'Execution mode — defaults to \"build\" if omitted',\n },\n {\n key: 'thinking-level',\n type: 'string',\n field: 'thinkingLevel',\n coerce: validate.enum<ThinkingLevel>('--thinking-level', VALID_THINKING_LEVELS),\n placeholder: '<level>',\n help: 'Thinking level: off, low, medium, high, xhigh, max',\n },\n {\n key: 'settings',\n type: 'string',\n field: 'settings',\n coerce: validate.string,\n placeholder: '<path>',\n help: 'Path to settings.json file (default: global settings)',\n },\n {\n key: 'help',\n short: 'h',\n type: 'boolean',\n help: 'Show this help and exit',\n },\n];\n\n/** `parseArgs` option config derived from {@link FLAGS}. */\nexport function buildParseArgsOptions() {\n const options: Record<string, { type: 'string' | 'boolean'; short?: string; default?: boolean }> = {};\n for (const flag of FLAGS) {\n options[flag.key] = flag.type === 'boolean' ? { type: 'boolean', default: false } : { type: 'string' };\n if (flag.short) options[flag.key]!.short = flag.short;\n }\n return options;\n}\n\n/** Render the aligned `--flag description` block of the usage text from {@link FLAGS}. */\nexport function renderFlagUsage(): string {\n const left = (flag: FlagSpec): string => {\n const long = `--${flag.key}`;\n const short = flag.short ? `, -${flag.short}` : '';\n const value = flag.placeholder ? ` ${flag.placeholder}` : '';\n return ` ${long}${short}${value}`;\n };\n\n const rows = FLAGS.map(flag => ({ flag, label: left(flag) }));\n const width = Math.max(...rows.map(r => r.label.length)) + 2;\n\n return rows\n .map(({ flag, label }) => {\n const lines = Array.isArray(flag.help) ? flag.help : [flag.help];\n const first = `${label.padEnd(width)}${lines[0]}`;\n const rest = lines.slice(1).map(line => `${' '.repeat(width)}${line}`);\n return [first, ...rest].join('\\n');\n })\n .join('\\n');\n}\n"],"mappings":";;AAgBA,MAAa,gBAAgB;CAAC;CAAS;CAAQ;AAAO;;AAGtD,MAAM,WAAW;;CAEf,KAAuB,MAAc,SAAuB;EAC1D,QAAQ,QAAmB;GACzB,IAAI,CAAE,QAA8B,SAAS,GAAG,GAC9C,MAAM,IAAI,MAAM,GAAG,KAAK,mBAAmB,QAAQ,KAAK,IAAI,GAAG;GAEjE,OAAO;EACT;CACF;;CAEA,YAAY,MAAc;EACxB,QAAQ,QAAwB;GAC9B,MAAM,SAAS,OAAO,GAAG;GACzB,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU,GACzC,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;GAEtD,OAAO;EACT;CACF;;CAEA,OAAO,KAAqB;EAC1B,OAAO;CACT;AACF;AAyBA,MAAa,QAAoB;CAC/B;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS,YAAY,WAAW;EACxC,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS,YAAY,aAAa;EAC1C,aAA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,IAAI,KAAK,gBAAgB;CAE5D;CAEA,MAAM,OAAO,MAAM,KAAI,UAAS;EAAE;EAAM,OAAO,KAAK,IAAI;CAAE,EAAE;CAC5D,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,KAAI,MAAK,EAAE,MAAM,MAAM,CAAC,IAAI;CAE3D,OAAO,KACJ,KAAK,EAAE,MAAM,YAAY;EACxB,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;EAG/D,OAAO,CAAC,GAFS,MAAM,OAAO,KAAK,IAAI,MAAM,MAE9B,GADF,MAAM,MAAM,CAAC,CAAC,CAAC,KAAI,SAAQ,GAAG,IAAI,OAAO,KAAK,IAAI,MAC1C,CAAC,CAAC,CAAC,KAAK,IAAI;CACnC,CAAC,CAAC,CACD,KAAK,IAAI;AACd"}
1
+ {"version":3,"file":"flags.js","names":[],"sources":["../../src/headless/flags.ts"],"sourcesContent":["/**\n * Declarative flag specification for the headless CLI.\n *\n * A single table is the source of truth for three things that previously drifted\n * apart in `cli.ts`:\n * 1. the `node:util` `parseArgs` option config,\n * 2. per-flag value coercion + validation, and\n * 3. the `--help` usage text.\n *\n * Adding a flag means adding one row here; parsing, validation, and the usage\n * listing all follow automatically.\n */\nimport type { OutputMode } from './cli.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\nimport { VALID_MODES, VALID_PERMISSION_MODES, VALID_THINKING_LEVELS } from './types.js';\n\nexport const VALID_OUTPUTS = ['human', 'json', 'jsonl'] as const;\n\n/** Reusable validators. Each throws a descriptive Error or returns the typed value. */\nconst validate = {\n /** Restrict to a fixed set of string literals. */\n enum<T extends string>(flag: string, allowed: readonly T[]) {\n return (raw: string): T => {\n if (!(allowed as readonly string[]).includes(raw)) {\n throw new Error(`${flag} must be one of: ${allowed.join(', ')}`);\n }\n return raw as T;\n };\n },\n /** Require a positive (>0) integer. */\n positiveInt(flag: string) {\n return (raw: string): number => {\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${flag} must be a positive integer`);\n }\n return parsed;\n };\n },\n /** Pass a string through unchanged. */\n string(raw: string): string {\n return raw;\n },\n};\n\n/**\n * One CLI flag. `key` is the long name (e.g. `output`); `field` is the\n * {@link import('./cli.js').HeadlessArgs} property it populates. `coerce`\n * converts the raw string and validates it. Boolean flags omit `coerce` and set\n * `field` to `true` when present.\n */\nexport interface FlagSpec {\n /** Long flag name without the leading `--`. */\n key: string;\n /** Single-character alias (without the leading `-`), if any. */\n short?: string;\n /** Whether the flag takes a value (`string`) or is a switch (`boolean`). */\n type: 'string' | 'boolean';\n /** Target field on `HeadlessArgs`. Omit for flags handled out-of-band (e.g. help). */\n field?: string;\n /** Coerce/validate a string value. Required for `type: 'string'` flags that map to a field. */\n coerce?: (raw: string) => unknown;\n /** `<...>` value placeholder shown in usage, e.g. `<text>`. */\n placeholder?: string;\n /** One-line (or multi-line) help description shown in usage. */\n help: string | string[];\n}\n\nexport const FLAGS: FlagSpec[] = [\n {\n key: 'prompt',\n short: 'p',\n type: 'string',\n field: 'prompt',\n coerce: validate.string,\n placeholder: '<text>',\n help: 'The task to execute (required, or pipe via stdin)',\n },\n {\n key: 'continue',\n short: 'c',\n type: 'boolean',\n field: 'continue_',\n help: 'Resume the most recent thread instead of creating a new one',\n },\n {\n key: 'thread',\n short: 't',\n type: 'string',\n field: 'thread',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Resume a specific thread by ID',\n },\n {\n key: 'title',\n type: 'string',\n field: 'title',\n coerce: validate.string,\n placeholder: '<title>',\n help: 'Set or rename the thread title',\n },\n {\n key: 'clone-thread',\n type: 'boolean',\n field: 'cloneThread',\n help: 'Clone the current thread before running (work on a copy)',\n },\n {\n key: 'resource-id',\n type: 'string',\n field: 'resourceId',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Set the resource ID for thread scoping',\n },\n {\n key: 'timeout',\n type: 'string',\n field: 'timeout',\n coerce: validate.positiveInt('--timeout'),\n placeholder: '<seconds>',\n help: 'Exit with code 2 if not complete within timeout',\n },\n {\n key: 'max-turns',\n type: 'string',\n field: 'maxTurns',\n coerce: validate.positiveInt('--max-turns'),\n placeholder: '<n>',\n help: 'Abort after N agentic turns (exit code 1)',\n },\n {\n key: 'permission-mode',\n type: 'string',\n field: 'permissionMode',\n coerce: validate.enum<PermissionMode>('--permission-mode', VALID_PERMISSION_MODES),\n placeholder: '<mode>',\n help: [\n 'How tool approvals/suspensions resolve:',\n ' auto approve everything (default)',\n ' deny refuse approvals, abort on suspension',\n ],\n },\n {\n key: 'output',\n short: 'o',\n type: 'string',\n field: 'output',\n coerce: validate.enum<OutputMode>('--output', VALID_OUTPUTS),\n placeholder: '<mode>',\n help: [\n 'Output mode: \"human\" (default), \"json\", or \"jsonl\"',\n ' human streaming text to stdout, activity to stderr',\n ' json single final JSON object (text, usage, tools)',\n ' jsonl newline-delimited JSON event stream',\n ' (omits display_state_changed UI snapshots)',\n ],\n },\n {\n key: 'model',\n short: 'm',\n type: 'string',\n field: 'model',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Model override (e.g., a provider/model id); wins over --pack for the active mode',\n },\n {\n key: 'pack',\n type: 'string',\n field: 'pack',\n coerce: validate.string,\n placeholder: '<id>',\n help: [\n 'Model pack to activate (like /models → Activate): a builtin pack id',\n '(anthropic, openai, github-copilot) or a saved custom pack, by',\n '\"custom:<name>\" or its bare name. Sets the pack for every mode and',\n 'becomes the global default pack. --model overrides it for the active mode.',\n ],\n },\n {\n key: 'mode',\n type: 'string',\n field: 'mode',\n coerce: validate.enum<RunMode>('--mode', VALID_MODES),\n placeholder: '{build|plan|fast}',\n help: 'Execution mode — defaults to \"build\" if omitted',\n },\n {\n key: 'thinking-level',\n type: 'string',\n field: 'thinkingLevel',\n coerce: validate.enum<ThinkingLevel>('--thinking-level', VALID_THINKING_LEVELS),\n placeholder: '<level>',\n help: 'Thinking level: off, low, medium, high, xhigh, max',\n },\n {\n key: 'settings',\n type: 'string',\n field: 'settings',\n coerce: validate.string,\n placeholder: '<path>',\n help: 'Path to settings.json file (default: global settings)',\n },\n {\n key: 'help',\n short: 'h',\n type: 'boolean',\n help: 'Show this help and exit',\n },\n];\n\n/** `parseArgs` option config derived from {@link FLAGS}. */\nexport function buildParseArgsOptions() {\n const options: Record<string, { type: 'string' | 'boolean'; short?: string; default?: boolean }> = {};\n for (const flag of FLAGS) {\n options[flag.key] = flag.type === 'boolean' ? { type: 'boolean', default: false } : { type: 'string' };\n if (flag.short) options[flag.key]!.short = flag.short;\n }\n return options;\n}\n\n/** Render the aligned `--flag description` block of the usage text from {@link FLAGS}. */\nexport function renderFlagUsage(): string {\n const left = (flag: FlagSpec): string => {\n const long = `--${flag.key}`;\n const short = flag.short ? `, -${flag.short}` : '';\n const value = flag.placeholder ? ` ${flag.placeholder}` : '';\n return ` ${long}${short}${value}`;\n };\n\n const rows = FLAGS.map(flag => ({ flag, label: left(flag) }));\n const width = Math.max(...rows.map(r => r.label.length)) + 2;\n\n return rows\n .map(({ flag, label }) => {\n const lines = Array.isArray(flag.help) ? flag.help : [flag.help];\n const first = `${label.padEnd(width)}${lines[0]}`;\n const rest = lines.slice(1).map(line => `${' '.repeat(width)}${line}`);\n return [first, ...rest].join('\\n');\n })\n .join('\\n');\n}\n"],"mappings":";;AAgBA,MAAa,gBAAgB;CAAC;CAAS;CAAQ;AAAO;;AAGtD,MAAM,WAAW;;CAEf,KAAuB,MAAc,SAAuB;EAC1D,QAAQ,QAAmB;GACzB,IAAI,CAAE,QAA8B,SAAS,GAAG,GAC9C,MAAM,IAAI,MAAM,GAAG,KAAK,mBAAmB,QAAQ,KAAK,IAAI,GAAG;GAEjE,OAAO;EACT;CACF;;CAEA,YAAY,MAAc;EACxB,QAAQ,QAAwB;GAC9B,MAAM,SAAS,OAAO,GAAG;GACzB,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU,GACzC,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;GA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ACnC,CAAC,CAAC,CACD,KAAK,IAAI;AACd"}
@@ -25,6 +25,8 @@ export interface FormattedOutput {
25
25
  * newly-appended text.
26
26
  */
27
27
  export declare function formatHuman(event: AgentControllerEvent, state: HumanFormatState): FormattedOutput;
28
+ /** Whether `--output jsonl` writes this event. Only `display_state_changed` is skipped. */
29
+ export declare function isJsonlEvent(event: AgentControllerEvent): boolean;
28
30
  /**
29
31
  * JSONL (stream-json) formatter — returns a plain object to be `JSON.stringify`'d
30
32
  * as one line per event by the sink. `Error` instances are normalized so their
@@ -1 +1 @@
1
- {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../src/headless/format.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,2EAA2E;AAC3E,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAEvD;AAED,sFAAsF;AACtF,MAAM,WAAW,gBAAgB;IAC/B,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,wBAAgB,sBAAsB,IAAI,gBAAgB,CAEzD;AAED,qEAAqE;AACrE,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,oBAAoB,EAAE,KAAK,EAAE,gBAAgB,GAAG,eAAe,CAuCjG;AAOD;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,oBAAoB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMhF;AAED,uFAAuF;AACvF,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAE5D;AAED,oEAAoE;AACpE,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAc5D"}
1
+ {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../src/headless/format.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,2EAA2E;AAC3E,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAEvD;AAED,sFAAsF;AACtF,MAAM,WAAW,gBAAgB;IAC/B,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,wBAAgB,sBAAsB,IAAI,gBAAgB,CAEzD;AAED,qEAAqE;AACrE,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,oBAAoB,EAAE,KAAK,EAAE,gBAAgB,GAAG,eAAe,CAuCjG;AAgBD,2FAA2F;AAC3F,wBAAgB,YAAY,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAEjE;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,oBAAoB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMhF;AAED,uFAAuF;AACvF,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAE5D;AAED,oEAAoE;AACpE,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAc5D"}
@@ -51,6 +51,18 @@ function serializeError(err) {
51
51
  };
52
52
  }
53
53
  /**
54
+ * Event types left out of `--output jsonl`. `display_state_changed` carries a
55
+ * full snapshot of the session's UI state and is re-sent after almost every
56
+ * other event, so each line repeats the whole conversation, including large
57
+ * tool results and shell output. A long run writes gigabytes of these lines,
58
+ * and the stream's other events already carry everything they contain.
59
+ */
60
+ const JSONL_EXCLUDED_EVENT_TYPES = /* @__PURE__ */ new Set(["display_state_changed"]);
61
+ /** Whether `--output jsonl` writes this event. Only `display_state_changed` is skipped. */
62
+ function isJsonlEvent(event) {
63
+ return !JSONL_EXCLUDED_EVENT_TYPES.has(event.type);
64
+ }
65
+ /**
54
66
  * JSONL (stream-json) formatter — returns a plain object to be `JSON.stringify`'d
55
67
  * as one line per event by the sink. `Error` instances are normalized so their
56
68
  * `name`/`message`/`stack` survive serialization (`JSON.stringify` turns a raw
@@ -80,6 +92,6 @@ function renderJsonResult(result) {
80
92
  }) + "\n";
81
93
  }
82
94
  //#endregion
83
- export { createHumanFormatState, formatHuman, formatJsonl, renderJsonResult, renderTextResult, truncate };
95
+ export { createHumanFormatState, formatHuman, formatJsonl, isJsonlEvent, renderJsonResult, renderTextResult, truncate };
84
96
 
85
97
  //# sourceMappingURL=format.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"format.js","names":[],"sources":["../../src/headless/format.ts"],"sourcesContent":["/**\n * Output formatters for headless runs. All functions here are pure — they take\n * an event (or a final result) and return strings / plain objects. They never\n * touch `process.*`; the CLI adapter owns the sinks.\n */\nimport type { AgentControllerEvent } from '@mastra/core/agent-controller';\n\nimport type { RunMCResult } from './types.js';\n\n/** Truncate a string to `max` characters, appending \"...\" if truncated. */\nexport function truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max) + '...' : s;\n}\n\n/** Mutable per-stream cursor used by {@link formatHuman} to stream assistant text. */\nexport interface HumanFormatState {\n activeAssistantMessageId?: string;\n lastTextLength: number;\n}\n\nexport function createHumanFormatState(): HumanFormatState {\n return { lastTextLength: 0 };\n}\n\n/** A chunk of formatted output destined for stdout and/or stderr. */\nexport interface FormattedOutput {\n stdout?: string;\n stderr?: string;\n}\n\n/**\n * Human-readable streaming formatter (the historical default). Assistant text\n * streams to stdout; tool/subagent/shell/error activity goes to stderr. The\n * `state` cursor is mutated so repeated `message_update` events only emit the\n * newly-appended text.\n */\nexport function formatHuman(event: AgentControllerEvent, state: HumanFormatState): FormattedOutput {\n switch (event.type) {\n case 'agent_start':\n state.lastTextLength = 0;\n return {};\n case 'message_start':\n if (event.message.role === 'assistant') {\n state.activeAssistantMessageId = event.message.id;\n state.lastTextLength = 0;\n }\n return {};\n case 'message_update':\n if (event.event.type !== 'text-delta' || event.id !== state.activeAssistantMessageId || !event.event.delta)\n return {};\n state.lastTextLength += event.event.delta.length;\n return { stdout: event.event.delta };\n case 'message_end':\n if (event.id !== state.activeAssistantMessageId) return {};\n state.activeAssistantMessageId = undefined;\n if (state.lastTextLength === 0) return {};\n state.lastTextLength = 0;\n return { stdout: '\\n' };\n case 'tool_start':\n return { stderr: `[tool] ${event.toolName}\\n` };\n case 'tool_end':\n return event.isError ? { stderr: `[tool error] ${truncate(String(event.result), 200)}\\n` } : {};\n case 'shell_output':\n return { stderr: event.output };\n case 'subagent_start':\n return {\n stderr: `[subagent:${event.forked ? 'forked:' : ''}${event.agentType}] ${truncate(event.task, 100)}\\n`,\n };\n case 'subagent_end':\n return event.isError ? { stderr: `[subagent error] ${truncate(event.result, 200)}\\n` } : {};\n case 'error':\n return { stderr: `[error] ${event.error.message}\\n` };\n default:\n return {};\n }\n}\n\n/** Convert an `Error` instance into a JSON-serializable plain object. */\nfunction serializeError(err: Error): { name: string; message: string; stack?: string } {\n return { name: err.name, message: err.message, stack: err.stack };\n}\n\n/**\n * JSONL (stream-json) formatter — returns a plain object to be `JSON.stringify`'d\n * as one line per event by the sink. `Error` instances are normalized so their\n * `name`/`message`/`stack` survive serialization (`JSON.stringify` turns a raw\n * `Error` into `{}`).\n */\nexport function formatJsonl(event: AgentControllerEvent): Record<string, unknown> {\n const out: Record<string, unknown> = { ...event };\n if ('error' in event && event.error instanceof Error) {\n out.error = serializeError(event.error);\n }\n return out;\n}\n\n/** Render the final result for `--output text`: assistant text, newline-terminated. */\nexport function renderTextResult(result: RunMCResult): string {\n return result.text.endsWith('\\n') ? result.text : result.text + '\\n';\n}\n\n/** Render the final result for `--output json`: one JSON object. */\nexport function renderJsonResult(result: RunMCResult): string {\n return (\n JSON.stringify({\n status: result.status,\n text: result.text,\n finishReason: result.finishReason,\n usage: result.usage,\n toolCalls: result.toolCalls,\n toolResults: result.toolResults,\n error: result.error,\n threadId: result.threadId,\n exitCode: result.exitCode,\n }) + '\\n'\n );\n}\n"],"mappings":";;AAUA,SAAgB,SAAS,GAAW,KAAqB;CACvD,OAAO,EAAE,SAAS,MAAM,EAAE,MAAM,GAAG,GAAG,IAAI,QAAQ;AACpD;AAQA,SAAgB,yBAA2C;CACzD,OAAO,EAAE,gBAAgB,EAAE;AAC7B;;;;;;;AAcA,SAAgB,YAAY,OAA6B,OAA0C;CACjG,QAAQ,MAAM,MAAd;EACE,KAAK;GACH,MAAM,iBAAiB;GACvB,OAAO,CAAC;EACV,KAAK;GACH,IAAI,MAAM,QAAQ,SAAS,aAAa;IACtC,MAAM,2BAA2B,MAAM,QAAQ;IAC/C,MAAM,iBAAiB;GACzB;GACA,OAAO,CAAC;EACV,KAAK;GACH,IAAI,MAAM,MAAM,SAAS,gBAAgB,MAAM,OAAO,MAAM,4BAA4B,CAAC,MAAM,MAAM,OACnG,OAAO,CAAC;GACV,MAAM,kBAAkB,MAAM,MAAM,MAAM;GAC1C,OAAO,EAAE,QAAQ,MAAM,MAAM,MAAM;EACrC,KAAK;GACH,IAAI,MAAM,OAAO,MAAM,0BAA0B,OAAO,CAAC;GACzD,MAAM,2BAA2B,KAAA;GACjC,IAAI,MAAM,mBAAmB,GAAG,OAAO,CAAC;GACxC,MAAM,iBAAiB;GACvB,OAAO,EAAE,QAAQ,KAAK;EACxB,KAAK,cACH,OAAO,EAAE,QAAQ,UAAU,MAAM,SAAS,IAAI;EAChD,KAAK,YACH,OAAO,MAAM,UAAU,EAAE,QAAQ,gBAAgB,SAAS,OAAO,MAAM,MAAM,GAAG,GAAG,EAAE,IAAI,IAAI,CAAC;EAChG,KAAK,gBACH,OAAO,EAAE,QAAQ,MAAM,OAAO;EAChC,KAAK,kBACH,OAAO,EACL,QAAQ,aAAa,MAAM,SAAS,YAAY,KAAK,MAAM,UAAU,IAAI,SAAS,MAAM,MAAM,GAAG,EAAE,IACrG;EACF,KAAK,gBACH,OAAO,MAAM,UAAU,EAAE,QAAQ,oBAAoB,SAAS,MAAM,QAAQ,GAAG,EAAE,IAAI,IAAI,CAAC;EAC5F,KAAK,SACH,OAAO,EAAE,QAAQ,WAAW,MAAM,MAAM,QAAQ,IAAI;EACtD,SACE,OAAO,CAAC;CACZ;AACF;;AAGA,SAAS,eAAe,KAA+D;CACrF,OAAO;EAAE,MAAM,IAAI;EAAM,SAAS,IAAI;EAAS,OAAO,IAAI;CAAM;AAClE;;;;;;;AAQA,SAAgB,YAAY,OAAsD;CAChF,MAAM,MAA+B,EAAE,GAAG,MAAM;CAChD,IAAI,WAAW,SAAS,MAAM,iBAAiB,OAC7C,IAAI,QAAQ,eAAe,MAAM,KAAK;CAExC,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAA6B;CAC5D,OAAO,OAAO,KAAK,SAAS,IAAI,IAAI,OAAO,OAAO,OAAO,OAAO;AAClE;;AAGA,SAAgB,iBAAiB,QAA6B;CAC5D,OACE,KAAK,UAAU;EACb,QAAQ,OAAO;EACf,MAAM,OAAO;EACb,cAAc,OAAO;EACrB,OAAO,OAAO;EACd,WAAW,OAAO;EAClB,aAAa,OAAO;EACpB,OAAO,OAAO;EACd,UAAU,OAAO;EACjB,UAAU,OAAO;CACnB,CAAC,IAAI;AAET"}
1
+ {"version":3,"file":"format.js","names":[],"sources":["../../src/headless/format.ts"],"sourcesContent":["/**\n * Output formatters for headless runs. All functions here are pure — they take\n * an event (or a final result) and return strings / plain objects. They never\n * touch `process.*`; the CLI adapter owns the sinks.\n */\nimport type { AgentControllerEvent } from '@mastra/core/agent-controller';\n\nimport type { RunMCResult } from './types.js';\n\n/** Truncate a string to `max` characters, appending \"...\" if truncated. */\nexport function truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max) + '...' : s;\n}\n\n/** Mutable per-stream cursor used by {@link formatHuman} to stream assistant text. */\nexport interface HumanFormatState {\n activeAssistantMessageId?: string;\n lastTextLength: number;\n}\n\nexport function createHumanFormatState(): HumanFormatState {\n return { lastTextLength: 0 };\n}\n\n/** A chunk of formatted output destined for stdout and/or stderr. */\nexport interface FormattedOutput {\n stdout?: string;\n stderr?: string;\n}\n\n/**\n * Human-readable streaming formatter (the historical default). Assistant text\n * streams to stdout; tool/subagent/shell/error activity goes to stderr. The\n * `state` cursor is mutated so repeated `message_update` events only emit the\n * newly-appended text.\n */\nexport function formatHuman(event: AgentControllerEvent, state: HumanFormatState): FormattedOutput {\n switch (event.type) {\n case 'agent_start':\n state.lastTextLength = 0;\n return {};\n case 'message_start':\n if (event.message.role === 'assistant') {\n state.activeAssistantMessageId = event.message.id;\n state.lastTextLength = 0;\n }\n return {};\n case 'message_update':\n if (event.event.type !== 'text-delta' || event.id !== state.activeAssistantMessageId || !event.event.delta)\n return {};\n state.lastTextLength += event.event.delta.length;\n return { stdout: event.event.delta };\n case 'message_end':\n if (event.id !== state.activeAssistantMessageId) return {};\n state.activeAssistantMessageId = undefined;\n if (state.lastTextLength === 0) return {};\n state.lastTextLength = 0;\n return { stdout: '\\n' };\n case 'tool_start':\n return { stderr: `[tool] ${event.toolName}\\n` };\n case 'tool_end':\n return event.isError ? { stderr: `[tool error] ${truncate(String(event.result), 200)}\\n` } : {};\n case 'shell_output':\n return { stderr: event.output };\n case 'subagent_start':\n return {\n stderr: `[subagent:${event.forked ? 'forked:' : ''}${event.agentType}] ${truncate(event.task, 100)}\\n`,\n };\n case 'subagent_end':\n return event.isError ? { stderr: `[subagent error] ${truncate(event.result, 200)}\\n` } : {};\n case 'error':\n return { stderr: `[error] ${event.error.message}\\n` };\n default:\n return {};\n }\n}\n\n/** Convert an `Error` instance into a JSON-serializable plain object. */\nfunction serializeError(err: Error): { name: string; message: string; stack?: string } {\n return { name: err.name, message: err.message, stack: err.stack };\n}\n\n/**\n * Event types left out of `--output jsonl`. `display_state_changed` carries a\n * full snapshot of the session's UI state and is re-sent after almost every\n * other event, so each line repeats the whole conversation, including large\n * tool results and shell output. A long run writes gigabytes of these lines,\n * and the stream's other events already carry everything they contain.\n */\nconst JSONL_EXCLUDED_EVENT_TYPES = new Set<AgentControllerEvent['type']>(['display_state_changed']);\n\n/** Whether `--output jsonl` writes this event. Only `display_state_changed` is skipped. */\nexport function isJsonlEvent(event: AgentControllerEvent): boolean {\n return !JSONL_EXCLUDED_EVENT_TYPES.has(event.type);\n}\n\n/**\n * JSONL (stream-json) formatter — returns a plain object to be `JSON.stringify`'d\n * as one line per event by the sink. `Error` instances are normalized so their\n * `name`/`message`/`stack` survive serialization (`JSON.stringify` turns a raw\n * `Error` into `{}`).\n */\nexport function formatJsonl(event: AgentControllerEvent): Record<string, unknown> {\n const out: Record<string, unknown> = { ...event };\n if ('error' in event && event.error instanceof Error) {\n out.error = serializeError(event.error);\n }\n return out;\n}\n\n/** Render the final result for `--output text`: assistant text, newline-terminated. */\nexport function renderTextResult(result: RunMCResult): string {\n return result.text.endsWith('\\n') ? result.text : result.text + '\\n';\n}\n\n/** Render the final result for `--output json`: one JSON object. */\nexport function renderJsonResult(result: RunMCResult): string {\n return (\n JSON.stringify({\n status: result.status,\n text: result.text,\n finishReason: result.finishReason,\n usage: result.usage,\n toolCalls: result.toolCalls,\n toolResults: result.toolResults,\n error: result.error,\n threadId: result.threadId,\n exitCode: result.exitCode,\n }) + '\\n'\n );\n}\n"],"mappings":";;AAUA,SAAgB,SAAS,GAAW,KAAqB;CACvD,OAAO,EAAE,SAAS,MAAM,EAAE,MAAM,GAAG,GAAG,IAAI,QAAQ;AACpD;AAQA,SAAgB,yBAA2C;CACzD,OAAO,EAAE,gBAAgB,EAAE;AAC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AAM,SAAS,IAAI;EAAS,OAAO,IAAI;CAAM;AAClE;;;;;;;;AASA,MAAM,6CAA6B,IAAI,IAAkC,CAAC,uBAAuB,CAAC;;AAGlG,SAAgB,aAAa,OAAsC;CACjE,OAAO,CAAC,2BAA2B,IAAI,MAAM,IAAI;AACnD;;;;;;;AAQA,SAAgB,YAAY,OAAsD;CAChF,MAAM,MAA+B,EAAE,GAAG,MAAM;CAChD,IAAI,WAAW,SAAS,MAAM,iBAAiB,OAC7C,IAAI,QAAQ,eAAe,MAAM,KAAK;CAExC,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAA6B;CAC5D,OAAO,OAAO,KAAK,SAAS,IAAI,IAAI,OAAO,OAAO,OAAO,OAAO;AAClE;;AAGA,SAAgB,iBAAiB,QAA6B;CAC5D,OACE,KAAK,UAAU;EACb,QAAQ,OAAO;EACf,MAAM,OAAO;EACb,cAAc,OAAO;EACrB,OAAO,OAAO;EACd,WAAW,OAAO;EAClB,aAAa,OAAO;EACpB,OAAO,OAAO;EACd,UAAU,OAAO;EACjB,UAAU,OAAO;CACnB,CAAC,IAAI;AAET"}
@@ -1 +1 @@
1
- {"version":3,"file":"run-mc.d.ts","sourceRoot":"","sources":["../../src/headless/run-mc.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,KAAK,EAAoB,YAAY,EAA4B,MAAM,YAAY,CAAC;AA2IlG;;;GAGG;AACH,wBAAgB,KAAK,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,MAAM,CAAC,GAAG,KAAK,CA+WlG"}
1
+ {"version":3,"file":"run-mc.d.ts","sourceRoot":"","sources":["../../src/headless/run-mc.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,KAAK,EAAoB,YAAY,EAA4B,MAAM,YAAY,CAAC;AA2IlG;;;GAGG;AACH,wBAAgB,KAAK,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,MAAM,CAAC,GAAG,KAAK,CAmZlG"}
@@ -149,6 +149,7 @@ function runMC(options) {
149
149
  let assistantTurns = 0;
150
150
  let activeAssistantMessageId;
151
151
  let settled = false;
152
+ let agentStarts = 0;
152
153
  let unsubscribe;
153
154
  let resolveResult;
154
155
  const result = new Promise((resolve) => {
@@ -180,6 +181,48 @@ function runMC(options) {
180
181
  };
181
182
  finish("error");
182
183
  }
184
+ function failUnresolvedSuspension(toolName) {
185
+ fail(`Run ended with an unresolved ${toolName ? `${toolName} suspension` : "tool suspension"}.`);
186
+ }
187
+ /**
188
+ * Ask the policy for the next parked tool. The session starts a fresh
189
+ * run for it, so this run stays open until that run ends. Returns false when
190
+ * nothing is left to resume.
191
+ */
192
+ function resumeNextSuspension() {
193
+ const next = session.displayState.get().pendingSuspensions.values().next();
194
+ if (next.done) return false;
195
+ const { toolCallId, toolName } = next.value;
196
+ let outcome;
197
+ try {
198
+ outcome = policy.onSuspension({
199
+ type: "tool_suspended",
200
+ ...next.value
201
+ });
202
+ } catch (err) {
203
+ fail(`Resolution policy failed: ${err.message}`);
204
+ return true;
205
+ }
206
+ if ("abort" in outcome) {
207
+ abort();
208
+ finish("aborted");
209
+ return true;
210
+ }
211
+ const { resumeData } = outcome;
212
+ setTimeout(() => {
213
+ if (settled) return;
214
+ if (timedOut) return finish("timeout");
215
+ if (aborted) return finish("aborted");
216
+ const startsBeforeResume = agentStarts;
217
+ session.respondToToolSuspension({
218
+ toolCallId,
219
+ resumeData
220
+ }).then(() => {
221
+ if (!settled && agentStarts === startsBeforeResume) failUnresolvedSuspension(toolName);
222
+ }, (err) => fail(`Failed to resume ${toolName}: ${err.message}`));
223
+ }, 0);
224
+ return true;
225
+ }
183
226
  function abort() {
184
227
  if (settled) return;
185
228
  aborted = true;
@@ -200,6 +243,7 @@ function runMC(options) {
200
243
  armTimeout();
201
244
  unsubscribe = session.subscribe((event) => {
202
245
  if (settled) return;
246
+ if (event.type === "agent_start") agentStarts += 1;
203
247
  if (goal) armTimeout();
204
248
  if (event.type === "tool_approval_required") {
205
249
  let decision;
@@ -216,26 +260,6 @@ function runMC(options) {
216
260
  queue.push(event);
217
261
  return;
218
262
  }
219
- if (event.type === "tool_suspended") {
220
- let outcome;
221
- try {
222
- outcome = policy.onSuspension(event);
223
- } catch (err) {
224
- fail(`Resolution policy failed: ${err.message}`);
225
- return;
226
- }
227
- if ("abort" in outcome) {
228
- queue.push(event);
229
- abort();
230
- return;
231
- }
232
- session.respondToToolSuspension({
233
- toolCallId: event.toolCallId,
234
- resumeData: outcome.resumeData
235
- });
236
- queue.push(event);
237
- return;
238
- }
239
263
  if (event.type === "message_start" && event.message.role === "assistant") activeAssistantMessageId = event.message.id;
240
264
  aggregate(event, acc);
241
265
  queue.push(event);
@@ -263,6 +287,10 @@ function runMC(options) {
263
287
  }
264
288
  if (event.type === "agent_end") {
265
289
  acc.finishReason = event.reason;
290
+ if (event.reason === "suspended" && !timedOut && !aborted) {
291
+ if (!resumeNextSuspension()) failUnresolvedSuspension();
292
+ return;
293
+ }
266
294
  if (goal) return;
267
295
  if (timedOut) finish("timeout");
268
296
  else if (event.reason === "error") finish("error");