@mastra/code-sdk 0.0.0-knowledge-studio-20261029065150 → 0.0.0-knowledge-alpha-studio-20261030162625
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp/agent.d.ts.map +1 -1
- package/dist/acp/agent.js +1 -2
- package/dist/acp/errors.js +1 -2
- package/dist/acp/event-mapper.js +1 -2
- package/dist/acp/index.js +1 -2
- package/dist/acp/runtime.d.ts.map +1 -1
- package/dist/acp/runtime.js +5 -4
- package/dist/acp/runtime.js.map +1 -1
- package/dist/acp/server.js +1 -2
- package/dist/acp/skills.js +1 -2
- package/dist/agent-connections/messaging-processor.d.ts.map +1 -1
- package/dist/agent-connections/messaging-processor.js +1 -2
- package/dist/agent-connections/ownership.js +1 -2
- package/dist/agent-connections/registry.d.ts.map +1 -1
- package/dist/agent-connections/registry.js +1 -2
- package/dist/agent-connections/session-advertisement.js +1 -2
- package/dist/agent-connections/signal-provider.d.ts +21 -21
- package/dist/agent-connections/signal-provider.d.ts.map +1 -1
- package/dist/agent-connections/signal-provider.js +1 -2
- package/dist/agent-connections/state-processor.d.ts.map +1 -1
- package/dist/agent-connections/state-processor.js +1 -2
- package/dist/agent-connections/thread-state.js +1 -2
- package/dist/agent-connections/tools.d.ts +21 -21
- package/dist/agent-connections/tools.d.ts.map +1 -1
- package/dist/agent-connections/tools.js +1 -2
- package/dist/agent-connections/types.js +1 -2
- package/dist/agent-connections/untrusted-text.js +1 -2
- package/dist/agents/background-completion-events.js +1 -2
- package/dist/agents/background-completion.js +1 -2
- package/dist/agents/context-audit.js +1 -2
- package/dist/agents/credential-resolver.d.ts.map +1 -1
- package/dist/agents/credential-resolver.js +1 -2
- package/dist/agents/custom-provider-source.js +1 -2
- package/dist/agents/instructions.d.ts +2 -10
- package/dist/agents/instructions.d.ts.map +1 -1
- package/dist/agents/instructions.js +3 -6
- package/dist/agents/instructions.js.map +1 -1
- package/dist/agents/mastracode-gateway.d.ts.map +1 -1
- package/dist/agents/mastracode-gateway.js +6 -5
- package/dist/agents/mastracode-gateway.js.map +1 -1
- package/dist/agents/memory.d.ts +1 -24
- package/dist/agents/memory.d.ts.map +1 -1
- package/dist/agents/memory.js +11 -68
- package/dist/agents/memory.js.map +1 -1
- package/dist/agents/model.js +1 -2
- package/dist/agents/modes/build.js +1 -2
- package/dist/agents/modes/explore.js +1 -2
- package/dist/agents/modes/plan.js +1 -2
- package/dist/agents/prompts/agent-instructions.js +1 -2
- package/dist/agents/prompts/build.js +1 -2
- package/dist/agents/prompts/fast.js +1 -2
- package/dist/agents/prompts/index.d.ts +0 -2
- package/dist/agents/prompts/index.d.ts.map +1 -1
- package/dist/agents/prompts/index.js +1 -3
- package/dist/agents/prompts/index.js.map +1 -1
- package/dist/agents/prompts/model.d.ts.map +1 -1
- package/dist/agents/prompts/model.js +1 -2
- package/dist/agents/prompts/plan.js +1 -2
- package/dist/agents/prompts/tool-guidance.d.ts +0 -2
- package/dist/agents/prompts/tool-guidance.d.ts.map +1 -1
- package/dist/agents/prompts/tool-guidance.js +1 -32
- package/dist/agents/prompts/tool-guidance.js.map +1 -1
- package/dist/agents/sandbox-filesystem.d.ts.map +1 -1
- package/dist/agents/sandbox-filesystem.js +9 -7
- package/dist/agents/sandbox-filesystem.js.map +1 -1
- package/dist/agents/subagents/execute.js +1 -2
- package/dist/agents/subagents/explore.js +1 -2
- package/dist/agents/subagents/index.d.ts +6 -0
- package/dist/agents/subagents/index.d.ts.map +1 -0
- package/dist/agents/subagents/index.js +17 -0
- package/dist/agents/subagents/index.js.map +1 -0
- package/dist/agents/subagents/plan.js +1 -2
- package/dist/agents/thread-caveman-state.js +1 -2
- package/dist/agents/tool-availability.js +1 -2
- package/dist/agents/tools.d.ts.map +1 -1
- package/dist/agents/tools.js +1 -2
- package/dist/agents/workflow-builder-agent.js +1 -2
- package/dist/agents/workspace.js +1 -2
- package/dist/analytics.js +1 -2
- package/dist/auth/account-rotation-processor.d.ts +12 -13
- package/dist/auth/account-rotation-processor.d.ts.map +1 -1
- package/dist/auth/account-rotation-processor.js +43 -52
- package/dist/auth/account-rotation-processor.js.map +1 -1
- package/dist/auth/account-routing-context.js +1 -2
- package/dist/auth/authorization-input.js +1 -2
- package/dist/auth/device-code.js +1 -2
- package/dist/auth/pkce.js +1 -2
- package/dist/auth/provider-auth-error.d.ts +2 -0
- package/dist/auth/provider-auth-error.d.ts.map +1 -1
- package/dist/auth/provider-auth-error.js +8 -3
- package/dist/auth/provider-auth-error.js.map +1 -1
- package/dist/auth/providers/anthropic.js +1 -2
- package/dist/auth/providers/github-copilot.d.ts +3 -3
- package/dist/auth/providers/github-copilot.d.ts.map +1 -1
- package/dist/auth/providers/github-copilot.js +1 -2
- package/dist/auth/providers/kimi-coding.js +1 -2
- package/dist/auth/providers/openai-codex.js +1 -2
- package/dist/auth/providers/xai.js +1 -2
- package/dist/auth/storage.d.ts.map +1 -1
- package/dist/auth/storage.js +1 -2
- package/dist/clipboard/index.js +1 -2
- package/dist/constants.d.ts +17 -0
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +19 -3
- package/dist/constants.js.map +1 -1
- package/dist/error-classification.js +1 -2
- package/dist/evals/context-builder.js +1 -2
- package/dist/evals/scorers/classify-command.d.ts +1 -2
- package/dist/evals/scorers/classify-command.d.ts.map +1 -1
- package/dist/evals/scorers/classify-command.js +7 -17
- package/dist/evals/scorers/classify-command.js.map +1 -1
- package/dist/evals/scorers/efficiency.js +1 -2
- package/dist/evals/scorers/extract-tools.js +1 -2
- package/dist/evals/scorers/outcome.d.ts.map +1 -1
- package/dist/evals/scorers/outcome.js +36 -22
- package/dist/evals/scorers/outcome.js.map +1 -1
- package/dist/experimental-agent.js +1 -2
- package/dist/factory/client.js +1 -2
- package/dist/factory/remote-controller.d.ts.map +1 -1
- package/dist/factory/remote-controller.js +1 -2
- package/dist/factory/remote-session.d.ts +2 -2
- package/dist/factory/remote-session.d.ts.map +1 -1
- package/dist/factory/remote-session.js +1 -2
- package/dist/goal-manager.d.ts.map +1 -1
- package/dist/goal-manager.js +1 -2
- package/dist/goal-signal.d.ts +1 -1
- package/dist/goal-signal.d.ts.map +1 -1
- package/dist/goal-signal.js +1 -2
- package/dist/headless/cli.d.ts.map +1 -1
- package/dist/headless/cli.js +4 -3
- package/dist/headless/cli.js.map +1 -1
- package/dist/headless/flags.d.ts +2 -2
- package/dist/headless/flags.d.ts.map +1 -1
- package/dist/headless/flags.js +1 -2
- package/dist/headless/format.js +1 -2
- package/dist/headless/policy.js +1 -2
- package/dist/headless/run-mc.js +1 -2
- package/dist/headless/types.d.ts +3 -3
- package/dist/headless/types.d.ts.map +1 -1
- package/dist/headless/types.js +1 -2
- package/dist/hooks/config.js +1 -2
- package/dist/hooks/executor.js +1 -2
- package/dist/hooks/manager.d.ts.map +1 -1
- package/dist/hooks/manager.js +1 -2
- package/dist/hooks/types.js +1 -2
- package/dist/index.d.ts +25 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +37 -34
- package/dist/index.js.map +1 -1
- package/dist/ipc/ipc-reporter.d.ts.map +1 -1
- package/dist/ipc/ipc-reporter.js +1 -2
- package/dist/knowledge-inspector.d.ts +26 -64
- package/dist/knowledge-inspector.d.ts.map +1 -1
- package/dist/knowledge-inspector.js +259 -372
- package/dist/knowledge-inspector.js.map +1 -1
- package/dist/knowledge-scope.d.ts +19 -27
- package/dist/knowledge-scope.d.ts.map +1 -1
- package/dist/knowledge-scope.js +47 -41
- package/dist/knowledge-scope.js.map +1 -1
- package/dist/lsp/client.d.ts.map +1 -1
- package/dist/lsp/client.js +1 -2
- package/dist/lsp/client.js.map +1 -1
- package/dist/lsp/language.js +1 -2
- package/dist/lsp/manager.d.ts.map +1 -1
- package/dist/lsp/manager.js +1 -2
- package/dist/lsp/server.js +1 -2
- package/dist/lsp/workspace.js +1 -2
- package/dist/mcp/config.js +1 -2
- package/dist/mcp/manager.d.ts.map +1 -1
- package/dist/mcp/manager.js +11 -13
- package/dist/mcp/manager.js.map +1 -1
- package/dist/mcp/state.js +1 -2
- package/dist/onboarding/custom-packs.js +1 -2
- package/dist/onboarding/custom-providers.js +1 -2
- package/dist/onboarding/om-settings.js +1 -2
- package/dist/onboarding/pack-activation.js +1 -2
- package/dist/onboarding/packs.js +1 -2
- package/dist/onboarding/settings.d.ts +2 -0
- package/dist/onboarding/settings.d.ts.map +1 -1
- package/dist/onboarding/settings.js +4 -3
- package/dist/onboarding/settings.js.map +1 -1
- package/dist/permissions.d.ts.map +1 -1
- package/dist/permissions.js +1 -2
- package/dist/platform/index.js +1 -2
- package/dist/plugin.js +1 -2
- package/dist/plugins/dependencies.js +1 -2
- package/dist/plugins/install.js +1 -2
- package/dist/plugins/loader.js +1 -2
- package/dist/plugins/manager.d.ts.map +1 -1
- package/dist/plugins/manager.js +1 -2
- package/dist/plugins/manifest.js +1 -2
- package/dist/plugins/package-link.js +1 -2
- package/dist/plugins/paths.js +1 -2
- package/dist/plugins/registry.js +1 -2
- package/dist/plugins/scaffold.js +1 -2
- package/dist/plugins/signal-lane.d.ts.map +1 -1
- package/dist/plugins/signal-lane.js +1 -2
- package/dist/process-memory-diagnostics.d.ts.map +1 -1
- package/dist/process-memory-diagnostics.js +1 -2
- package/dist/processors/plan-rejection-abort.d.ts +1 -1
- package/dist/processors/plan-rejection-abort.d.ts.map +1 -1
- package/dist/processors/plan-rejection-abort.js +1 -2
- package/dist/providers/amazon-bedrock-gateway.d.ts.map +1 -1
- package/dist/providers/amazon-bedrock-gateway.js +1 -2
- package/dist/providers/amazon-bedrock.js +1 -2
- package/dist/providers/anthropic-prompt-cache.d.ts +1 -1
- package/dist/providers/anthropic-prompt-cache.js +1 -2
- package/dist/providers/anthropic-thinking.js +1 -2
- package/dist/providers/claude-max.d.ts.map +1 -1
- package/dist/providers/claude-max.js +4 -4
- package/dist/providers/claude-max.js.map +1 -1
- package/dist/providers/github-copilot-gateway.d.ts.map +1 -1
- package/dist/providers/github-copilot-gateway.js +1 -2
- package/dist/providers/github-copilot.d.ts.map +1 -1
- package/dist/providers/github-copilot.js +5 -5
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/providers/google-thinking.js +1 -2
- package/dist/providers/kimi-coding.d.ts.map +1 -1
- package/dist/providers/kimi-coding.js +8 -7
- package/dist/providers/kimi-coding.js.map +1 -1
- package/dist/providers/model-ids.js +1 -2
- package/dist/providers/openai-codex.d.ts +26 -0
- package/dist/providers/openai-codex.d.ts.map +1 -1
- package/dist/providers/openai-codex.js +86 -13
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/providers/provider-thinking.d.ts.map +1 -1
- package/dist/providers/provider-thinking.js +1 -2
- package/dist/providers/thinking-request.js +1 -2
- package/dist/providers/xai.d.ts.map +1 -1
- package/dist/providers/xai.js +5 -5
- package/dist/providers/xai.js.map +1 -1
- package/dist/schedules/interval.js +1 -2
- package/dist/schedules/prompt.js +1 -2
- package/dist/schedules/run-script.js +1 -2
- package/dist/schedules/scheduler.d.ts.map +1 -1
- package/dist/schedules/scheduler.js +1 -2
- package/dist/schedules/tools.d.ts +6 -6
- package/dist/schedules/tools.d.ts.map +1 -1
- package/dist/schedules/tools.js +1 -2
- package/dist/schema.d.ts +87 -87
- package/dist/schema.js +1 -2
- package/dist/theme-palette.d.ts +7 -7
- package/dist/theme-palette.d.ts.map +1 -1
- package/dist/theme-palette.js +1 -2
- package/dist/thinking-catalog.js +1 -2
- package/dist/thinking.d.ts.map +1 -1
- package/dist/thinking.js +1 -2
- package/dist/tool-names.d.ts +18 -18
- package/dist/tool-names.d.ts.map +1 -1
- package/dist/tool-names.js +1 -2
- package/dist/tools/request-sandbox-access.d.ts.map +1 -1
- package/dist/tools/request-sandbox-access.js +3 -3
- package/dist/tools/request-sandbox-access.js.map +1 -1
- package/dist/tools/utils.js +1 -2
- package/dist/tools/web-search.d.ts.map +1 -1
- package/dist/tools/web-search.js +1 -2
- package/dist/tools/workflows/create-workflow.js +1 -2
- package/dist/tools/workflows/delete-workflow.js +1 -2
- package/dist/tools/workflows/ephemeral-memory.js +1 -2
- package/dist/tools/workflows/extract-json-schema.js +1 -2
- package/dist/tools/workflows/get-workflow.d.ts +1 -1
- package/dist/tools/workflows/get-workflow.js +1 -2
- package/dist/tools/workflows/list-available-agents.d.ts +1 -1
- package/dist/tools/workflows/list-available-agents.js +1 -2
- package/dist/tools/workflows/list-available-classifiers.d.ts +7 -7
- package/dist/tools/workflows/list-available-classifiers.js +1 -2
- package/dist/tools/workflows/list-available-tools.js +1 -2
- package/dist/tools/workflows/list-available-workflows.js +1 -2
- package/dist/tools/workflows/list-workflows.d.ts +1 -1
- package/dist/tools/workflows/list-workflows.js +1 -2
- package/dist/tools/workflows/run-workflow.js +1 -2
- package/dist/tools/workflows/save-workflow.d.ts +328 -328
- package/dist/tools/workflows/save-workflow.js +1 -2
- package/dist/tools/workflows/tool-ids.d.ts +11 -11
- package/dist/tools/workflows/tool-ids.d.ts.map +1 -1
- package/dist/tools/workflows/tool-ids.js +1 -2
- package/dist/utils/binaries.js +1 -2
- package/dist/utils/debug-log.js +1 -2
- package/dist/utils/discarding-scores-storage.d.ts.map +1 -1
- package/dist/utils/discarding-scores-storage.js +1 -2
- package/dist/utils/errors.d.ts +1 -1
- package/dist/utils/errors.d.ts.map +1 -1
- package/dist/utils/errors.js +99 -80
- package/dist/utils/errors.js.map +1 -1
- package/dist/utils/gateway-sync.js +1 -2
- package/dist/utils/local-observability.js +2 -3
- package/dist/utils/local-observability.js.map +1 -1
- package/dist/utils/maintenance-lock.d.ts.map +1 -1
- package/dist/utils/maintenance-lock.js +1 -2
- package/dist/utils/notification-dispatch.js +1 -2
- package/dist/utils/open-url.js +1 -2
- package/dist/utils/path-security.js +1 -2
- package/dist/utils/plan-diff.js +1 -2
- package/dist/utils/plans.js +1 -2
- package/dist/utils/project.js +1 -2
- package/dist/utils/prune-cli.js +1 -2
- package/dist/utils/signals-pubsub.d.ts.map +1 -1
- package/dist/utils/signals-pubsub.js +1 -2
- package/dist/utils/slash-command-loader.js +1 -2
- package/dist/utils/slash-command-processor.js +1 -2
- package/dist/utils/stdin-pipe.js +1 -2
- package/dist/utils/storage-factory.d.ts.map +1 -1
- package/dist/utils/storage-factory.js +1 -2
- package/dist/utils/storage-maintenance.js +1 -2
- package/dist/utils/thread-lock.d.ts.map +1 -1
- package/dist/utils/thread-lock.js +1 -2
- package/dist/utils/token-estimator.js +1 -2
- package/dist/utils/update-check.js +1 -2
- package/dist/utils/wake-session.js +1 -2
- package/dist/voice/stt-registry.js +1 -2
- package/dist/workflows/register-primitives.js +1 -2
- package/dist/workflows/service.js +1 -2
- package/package.json +38 -34
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { getExitCode, isBuildCommand, isTestCommand } from "./classify-command.js";
|
|
1
|
+
import { getExitCode, isBuildCommand, isSuccessResult, isTestCommand } from "./classify-command.js";
|
|
2
2
|
import { extractToolCalls } from "./extract-tools.js";
|
|
3
3
|
import { createScorer, filterRun } from "@mastra/core/evals";
|
|
4
|
-
|
|
4
|
+
// src/evals/scorers/outcome.ts
|
|
5
5
|
/**
|
|
6
6
|
* Dimension weights. Used to compute the weighted average of applicable dimensions.
|
|
7
7
|
* Dimensions that don't apply (e.g. no build ran) are excluded from the average.
|
|
@@ -48,11 +48,14 @@ function isBuildArgs(args) {
|
|
|
48
48
|
function isTestArgs(args) {
|
|
49
49
|
return isTestCommand(String(args.command ?? ""));
|
|
50
50
|
}
|
|
51
|
+
function isForegroundCommand(result) {
|
|
52
|
+
return result.args.background !== true;
|
|
53
|
+
}
|
|
51
54
|
/**
|
|
52
55
|
* Score build/typecheck outcome (final state).
|
|
53
56
|
*/
|
|
54
57
|
function scoreBuild(execResults) {
|
|
55
|
-
const builds = execResults.filter((r) => r.toolName === "execute_command" && isBuildArgs(r.args));
|
|
58
|
+
const builds = execResults.filter((r) => r.toolName === "execute_command" && isForegroundCommand(r) && isBuildArgs(r.args));
|
|
56
59
|
if (builds.length === 0) return {
|
|
57
60
|
score: 0,
|
|
58
61
|
detail: "No build/typecheck ran",
|
|
@@ -65,22 +68,27 @@ function scoreBuild(execResults) {
|
|
|
65
68
|
applicable: true
|
|
66
69
|
};
|
|
67
70
|
const exitCode = getExitCode(last.result);
|
|
68
|
-
if (exitCode === 0) return {
|
|
69
|
-
score: 1,
|
|
70
|
-
detail: "Build/typecheck passed",
|
|
71
|
-
applicable: true
|
|
72
|
-
};
|
|
73
71
|
if (exitCode !== null && exitCode !== 0) return {
|
|
74
72
|
score: 0,
|
|
75
73
|
detail: `Build failed (exit ${exitCode})`,
|
|
76
74
|
applicable: true
|
|
77
75
|
};
|
|
78
|
-
|
|
76
|
+
if (typeof last.result === "string") return {
|
|
77
|
+
score: 1,
|
|
78
|
+
detail: "Build/typecheck passed",
|
|
79
|
+
applicable: true
|
|
80
|
+
};
|
|
81
|
+
const text = JSON.stringify(last.result ?? "");
|
|
79
82
|
if (/error TS\d+|Cannot find module|is not assignable/i.test(text)) return {
|
|
80
83
|
score: 0,
|
|
81
84
|
detail: "Build failed (TypeScript errors in output)",
|
|
82
85
|
applicable: true
|
|
83
86
|
};
|
|
87
|
+
if (isSuccessResult(last.result)) return {
|
|
88
|
+
score: 1,
|
|
89
|
+
detail: "Build/typecheck passed",
|
|
90
|
+
applicable: true
|
|
91
|
+
};
|
|
84
92
|
return {
|
|
85
93
|
score: THRESHOLDS.ambiguousExitScore,
|
|
86
94
|
detail: "Build ran, outcome unclear",
|
|
@@ -91,7 +99,7 @@ function scoreBuild(execResults) {
|
|
|
91
99
|
* Score test outcome (final state).
|
|
92
100
|
*/
|
|
93
101
|
function scoreTests(execResults) {
|
|
94
|
-
const tests = execResults.filter((r) => r.toolName === "execute_command" && isTestArgs(r.args));
|
|
102
|
+
const tests = execResults.filter((r) => r.toolName === "execute_command" && isForegroundCommand(r) && isTestArgs(r.args));
|
|
95
103
|
if (tests.length === 0) return {
|
|
96
104
|
score: 0,
|
|
97
105
|
detail: "No tests ran",
|
|
@@ -104,25 +112,30 @@ function scoreTests(execResults) {
|
|
|
104
112
|
applicable: true
|
|
105
113
|
};
|
|
106
114
|
const exitCode = getExitCode(last.result);
|
|
107
|
-
if (exitCode
|
|
115
|
+
if (exitCode !== null && exitCode !== 0) return {
|
|
116
|
+
score: 0,
|
|
117
|
+
detail: `Tests failed (exit ${exitCode})`,
|
|
118
|
+
applicable: true
|
|
119
|
+
};
|
|
120
|
+
if (typeof last.result === "string") return {
|
|
108
121
|
score: 1,
|
|
109
122
|
detail: "Tests passed",
|
|
110
123
|
applicable: true
|
|
111
124
|
};
|
|
112
|
-
|
|
125
|
+
const text = JSON.stringify(last.result ?? "");
|
|
126
|
+
if (/\bFAIL\b|failed|✗|✘/i.test(text)) return {
|
|
113
127
|
score: 0,
|
|
114
|
-
detail:
|
|
128
|
+
detail: "Tests failed (inferred)",
|
|
115
129
|
applicable: true
|
|
116
130
|
};
|
|
117
|
-
const text = typeof last.result === "string" ? last.result : JSON.stringify(last.result ?? "");
|
|
118
131
|
if (/\d+ (?:tests? )?passed|✓|PASS/i.test(text) && !/\bfail(?:ed|ure)?\b|\berror\b/i.test(text)) return {
|
|
119
132
|
score: 1,
|
|
120
133
|
detail: "Tests passed (inferred)",
|
|
121
134
|
applicable: true
|
|
122
135
|
};
|
|
123
|
-
if (
|
|
124
|
-
score:
|
|
125
|
-
detail: "Tests
|
|
136
|
+
if (isSuccessResult(last.result)) return {
|
|
137
|
+
score: 1,
|
|
138
|
+
detail: "Tests passed",
|
|
126
139
|
applicable: true
|
|
127
140
|
};
|
|
128
141
|
return {
|
|
@@ -207,13 +220,15 @@ function scoreStuckLoops(results) {
|
|
|
207
220
|
function scoreRegression(execResults) {
|
|
208
221
|
const regressions = [];
|
|
209
222
|
for (const [label, filter] of [["Build", isBuildArgs], ["Tests", isTestArgs]]) {
|
|
210
|
-
const cmds = execResults.filter((r) => r.toolName === "execute_command" && filter(r.args));
|
|
223
|
+
const cmds = execResults.filter((r) => r.toolName === "execute_command" && isForegroundCommand(r) && filter(r.args));
|
|
211
224
|
if (cmds.length < 2) continue;
|
|
212
225
|
let sawPass = false;
|
|
213
226
|
let sawRegression = false;
|
|
214
227
|
for (const cmd of cmds) {
|
|
215
|
-
const
|
|
216
|
-
|
|
228
|
+
const exitCode = getExitCode(cmd.result);
|
|
229
|
+
const passed = isSuccessResult(cmd.result, cmd.isError);
|
|
230
|
+
const failed = cmd.isError || exitCode !== null && exitCode !== 0;
|
|
231
|
+
if (passed) {
|
|
217
232
|
if (sawRegression) {
|
|
218
233
|
regressions.push({
|
|
219
234
|
label,
|
|
@@ -223,7 +238,7 @@ function scoreRegression(execResults) {
|
|
|
223
238
|
}
|
|
224
239
|
sawPass = true;
|
|
225
240
|
}
|
|
226
|
-
if (sawPass &&
|
|
241
|
+
if (sawPass && failed) sawRegression = true;
|
|
227
242
|
}
|
|
228
243
|
if (sawRegression) regressions.push({
|
|
229
244
|
label,
|
|
@@ -342,7 +357,6 @@ function createOutcomeScorer() {
|
|
|
342
357
|
return parts.join("\n");
|
|
343
358
|
});
|
|
344
359
|
}
|
|
345
|
-
//#endregion
|
|
346
360
|
export { createOutcomeScorer };
|
|
347
361
|
|
|
348
362
|
//# sourceMappingURL=outcome.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outcome.js","names":[],"sources":["../../../src/evals/scorers/outcome.ts"],"sourcesContent":["/**\n * MastraCode Outcome Scorer (Code-based, Agent type, always-on)\n *\n * Grades the objective outcome of a coding session by checking hard facts:\n * - Did the build/typecheck pass?\n * - Did tests pass?\n * - What was the tool error rate?\n * - Did the agent get stuck in a loop?\n * - Was there a regression (build passed earlier, failed later)?\n * - Did the agent use ask_user unnecessarily? (autonomy)\n *\n * This scorer is always-on (no sampling) because it's cheap — it only\n * reads exit codes and error states from tool results already in the messages.\n *\n * Scoring philosophy (from Anthropic's eval guidance):\n * \"Grade outcomes, not paths\" — we check what happened, not how.\n * Partial credit: a session that passes build but fails tests scores\n * higher than one that fails build entirely.\n *\n * Dimensions that don't apply to a session (e.g. build for a docs-only task)\n * are excluded from the weighted average, so sessions aren't penalized for\n * irrelevant criteria.\n */\n\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { createScorer, filterRun } from '@mastra/core/evals';\n\nimport { isBuildCommand, isTestCommand, getExitCode } from './classify-command.js';\nimport type { ExtractedToolCall } from './extract-tools.js';\nimport { extractToolCalls } from './extract-tools.js';\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// CONFIGURATION — Adjust weights and thresholds here\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Dimension weights. Used to compute the weighted average of applicable dimensions.\n * Dimensions that don't apply (e.g. no build ran) are excluded from the average.\n */\nconst WEIGHTS = {\n build: 0.3,\n tests: 0.25,\n toolErrors: 0.2,\n loops: 0.1,\n regression: 0.1,\n autonomy: 0.05,\n} as const;\n\n/**\n * Scoring thresholds and multipliers.\n */\nconst THRESHOLDS = {\n /** Multiplier for tool error rate penalty. Score = max(0, 1 - rate × this). */\n toolErrorPenaltyMultiplier: 1.0,\n\n /** How many consecutive identical calls (or same-error repeats) before it's a \"loop\". */\n loopMinRepetitions: 3,\n\n /** Score penalty per detected loop. */\n loopPenaltyPerOccurrence: 0.3,\n\n /** Score deducted per ask_user call. */\n autonomyPenaltyPerAsk: 0.25,\n\n /** Score when a command ran but exit code is ambiguous. */\n ambiguousExitScore: 0.75,\n\n /** Minimum tool calls required to produce a meaningful score. */\n minToolCalls: 1,\n\n /** Tool names whose errors are expected/benign (not penalized). */\n benignErrorTools: ['search_content', 'find_files', 'lsp_inspect'] as string[],\n} as const;\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\ntype DimensionResult = { score: number; detail: string; applicable: boolean };\n\n/**\n * Check if the primary verb of an execute_command is a build/typecheck command.\n * Splits compound commands (&&, ;) and checks the first segment.\n */\n/** Extract command string from tool call args, then delegate to shared classifier. */\nfunction isBuildArgs(args: Record<string, unknown>): boolean {\n return isBuildCommand(String(args.command ?? ''));\n}\n\nfunction isTestArgs(args: Record<string, unknown>): boolean {\n return isTestCommand(String(args.command ?? ''));\n}\n\n/**\n * Score build/typecheck outcome (final state).\n */\nfunction scoreBuild(execResults: ExtractedToolCall[]): DimensionResult {\n const builds = execResults.filter(r => r.toolName === 'execute_command' && isBuildArgs(r.args));\n if (builds.length === 0) return { score: 0, detail: 'No build/typecheck ran', applicable: false };\n\n const last = builds[builds.length - 1]!;\n if (last.isError) return { score: 0, detail: 'Build/typecheck tool errored', applicable: true };\n\n const exitCode = getExitCode(last.result);\n if (exitCode === 0) return { score: 1, detail: 'Build/typecheck passed', applicable: true };\n if (exitCode !== null && exitCode !== 0)\n return { score: 0, detail: `Build failed (exit ${exitCode})`, applicable: true };\n\n // Fallback: check result text for TS errors\n const text = typeof last.result === 'string' ? last.result : JSON.stringify(last.result ?? '');\n if (/error TS\\d+|Cannot find module|is not assignable/i.test(text)) {\n return { score: 0, detail: 'Build failed (TypeScript errors in output)', applicable: true };\n }\n\n return { score: THRESHOLDS.ambiguousExitScore, detail: 'Build ran, outcome unclear', applicable: true };\n}\n\n/**\n * Score test outcome (final state).\n */\nfunction scoreTests(execResults: ExtractedToolCall[]): DimensionResult {\n const tests = execResults.filter(r => r.toolName === 'execute_command' && isTestArgs(r.args));\n if (tests.length === 0) return { score: 0, detail: 'No tests ran', applicable: false };\n\n const last = tests[tests.length - 1]!;\n if (last.isError) return { score: 0, detail: 'Test command errored', applicable: true };\n\n const exitCode = getExitCode(last.result);\n if (exitCode === 0) return { score: 1, detail: 'Tests passed', applicable: true };\n if (exitCode !== null && exitCode !== 0)\n return { score: 0, detail: `Tests failed (exit ${exitCode})`, applicable: true };\n\n const text = typeof last.result === 'string' ? last.result : JSON.stringify(last.result ?? '');\n if (/\\d+ (?:tests? )?passed|✓|PASS/i.test(text) && !/\\bfail(?:ed|ure)?\\b|\\berror\\b/i.test(text)) {\n return { score: 1, detail: 'Tests passed (inferred)', applicable: true };\n }\n if (/\\bFAIL\\b|failed|✗|✘/i.test(text)) {\n return { score: 0, detail: 'Tests failed (inferred)', applicable: true };\n }\n\n return { score: THRESHOLDS.ambiguousExitScore, detail: 'Tests ran, outcome unclear', applicable: true };\n}\n\n/**\n * Score tool error rate, excluding benign errors from expected-to-fail tools.\n */\nfunction scoreToolErrors(results: ExtractedToolCall[]): DimensionResult {\n if (results.length === 0) return { score: 1, detail: 'No tool calls', applicable: false };\n\n // Only count errors from non-benign tools\n const nonBenign = results.filter(r => !THRESHOLDS.benignErrorTools.includes(r.toolName));\n if (nonBenign.length === 0) return { score: 1, detail: 'All tool calls are benign-error tools', applicable: true };\n\n const errors = nonBenign.filter(r => r.isError);\n const rate = errors.length / nonBenign.length;\n\n if (rate === 0) return { score: 1, detail: 'No tool errors', applicable: true };\n\n const score = Math.max(0, 1 - rate * THRESHOLDS.toolErrorPenaltyMultiplier);\n return {\n score,\n detail: `${errors.length}/${nonBenign.length} tools errored (${(rate * 100).toFixed(0)}%)`,\n applicable: true,\n };\n}\n\n/**\n * Detect stuck loops: same tool + same args appearing 3+ times consecutively,\n * or same tool + same args erroring 3+ times total.\n */\nfunction scoreStuckLoops(results: ExtractedToolCall[]): DimensionResult {\n if (results.length < 3) return { score: 1, detail: 'Too few calls for loop detection', applicable: true };\n\n const fingerprint = (r: ExtractedToolCall) => `${r.toolName}:${JSON.stringify(r.args)}`;\n\n // Check consecutive identical calls\n let maxConsecutive = 1;\n let currentRun = 1;\n for (let i = 1; i < results.length; i++) {\n if (fingerprint(results[i]!) === fingerprint(results[i - 1]!)) {\n currentRun++;\n maxConsecutive = Math.max(maxConsecutive, currentRun);\n } else {\n currentRun = 1;\n }\n }\n\n // Check repeated error fingerprints\n const errorCounts = new Map<string, number>();\n for (const r of results) {\n if (!r.isError) continue;\n const fp = fingerprint(r);\n errorCounts.set(fp, (errorCounts.get(fp) ?? 0) + 1);\n }\n const maxErrorRepeat = Math.max(0, ...[...errorCounts.values()]);\n\n const minReps = THRESHOLDS.loopMinRepetitions;\n const loopSeverity = Math.max(\n maxConsecutive >= minReps ? maxConsecutive - (minReps - 1) : 0,\n maxErrorRepeat >= minReps ? maxErrorRepeat - (minReps - 1) : 0,\n );\n\n if (loopSeverity === 0) return { score: 1, detail: 'No stuck loops', applicable: true };\n\n const score = Math.max(0, 1 - loopSeverity * THRESHOLDS.loopPenaltyPerOccurrence);\n const details: string[] = [];\n if (maxConsecutive >= minReps) details.push(`${maxConsecutive} consecutive identical calls`);\n if (maxErrorRepeat >= minReps) details.push(`same error repeated ${maxErrorRepeat}x`);\n return { score, detail: details.join('; '), applicable: true };\n}\n\n/**\n * Detect regressions: build/test passed at some point, then failed later.\n * Gives partial credit if the agent recovered (final state passes).\n */\nfunction scoreRegression(execResults: ExtractedToolCall[]): DimensionResult {\n const regressions: { label: string; recovered: boolean }[] = [];\n\n for (const [label, filter] of [\n ['Build', isBuildArgs],\n ['Tests', isTestArgs],\n ] as const) {\n const cmds = execResults.filter(r => r.toolName === 'execute_command' && filter(r.args));\n if (cmds.length < 2) continue;\n\n let sawPass = false;\n let sawRegression = false;\n for (const cmd of cmds) {\n const exit = getExitCode(cmd.result);\n if (exit === 0) {\n if (sawRegression) {\n // Recovered from regression\n regressions.push({ label, recovered: true });\n sawRegression = false;\n }\n sawPass = true;\n }\n if (sawPass && exit !== null && exit !== 0) {\n sawRegression = true;\n }\n }\n\n if (sawRegression) {\n // Regression persisted at end of session\n regressions.push({ label, recovered: false });\n }\n }\n\n if (regressions.length === 0) return { score: 1, detail: 'No regressions', applicable: true };\n\n // Persistent regressions are severe (0), recovered regressions get partial credit (0.5)\n const persistentCount = regressions.filter(r => !r.recovered).length;\n const recoveredCount = regressions.filter(r => r.recovered).length;\n const score = Math.max(0, 1 - persistentCount * 0.5 - recoveredCount * 0.1);\n const details = regressions.map(\n r => `${r.label} ${r.recovered ? 'regressed then recovered' : 'regressed (persisted)'}`,\n );\n return { score, detail: details.join('; '), applicable: true };\n}\n\n/**\n * Score autonomy: penalize ask_user calls.\n * 0 calls = 1.0, each call reduces by 0.25 (up to a floor of 0).\n */\nfunction scoreAutonomy(results: ExtractedToolCall[]): DimensionResult {\n const askUserCalls = results.filter(r => r.toolName === 'ask_user');\n const count = askUserCalls.length;\n\n if (count === 0) return { score: 1, detail: 'No ask_user calls (fully autonomous)', applicable: true };\n\n const score = Math.max(0, 1 - count * THRESHOLDS.autonomyPenaltyPerAsk);\n return { score, detail: `${count} ask_user call${count > 1 ? 's' : ''}`, applicable: true };\n}\n\n/**\n * Compute weighted average of only applicable dimensions.\n * Returns null if no dimensions are applicable.\n */\nfunction weightedAverage(dimensions: Record<string, DimensionResult>, weights: Record<string, number>): number | null {\n let totalWeight = 0;\n let weightedSum = 0;\n\n for (const [key, result] of Object.entries(dimensions)) {\n if (!result.applicable) continue;\n const weight = weights[key] ?? 0;\n totalWeight += weight;\n weightedSum += result.score * weight;\n }\n\n if (totalWeight === 0) return null;\n return weightedSum / totalWeight;\n}\n\nexport function createOutcomeScorer() {\n return createScorer({\n id: 'mastracode-outcome',\n name: 'MastraCode Outcome',\n description:\n 'Grades coding session outcomes: build/test pass, tool errors, stuck loops, regressions, autonomy. Always-on.',\n type: 'agent',\n prepareRun: filterRun({ partTypes: ['tool-invocation', 'text'] }),\n })\n .preprocess(async ({ run }) => {\n const messages = (run.output ?? []) as MastraDBMessage[];\n const allResults = extractToolCalls(messages);\n const totalCalls = allResults.length;\n\n // H1: Empty sessions or sessions with no tool calls → score 0\n if (totalCalls < THRESHOLDS.minToolCalls) {\n const empty: DimensionResult = { score: 0, detail: 'No tool calls', applicable: false };\n return {\n empty: true as const,\n build: empty,\n tests: empty,\n toolErrors: empty,\n loops: empty,\n regression: empty,\n autonomy: empty,\n totalCalls,\n };\n }\n\n const execResults = allResults.filter(r => r.toolName === 'execute_command');\n\n return {\n empty: false as const,\n build: scoreBuild(execResults),\n tests: scoreTests(execResults),\n toolErrors: scoreToolErrors(allResults),\n loops: scoreStuckLoops(allResults),\n regression: scoreRegression(execResults),\n autonomy: scoreAutonomy(allResults),\n totalCalls,\n };\n })\n .generateScore(({ results }) => {\n const p = results.preprocessStepResult;\n if (p.empty) return 0;\n\n const score = weightedAverage(\n {\n build: p.build,\n tests: p.tests,\n toolErrors: p.toolErrors,\n loops: p.loops,\n regression: p.regression,\n autonomy: p.autonomy,\n },\n WEIGHTS,\n );\n\n return score === null ? 0 : Math.round(score * 100) / 100;\n })\n .generateReason(({ results, score }) => {\n const p = results.preprocessStepResult;\n if (p.empty) {\n return `Score: 0 (${p.totalCalls} tool calls — below minimum threshold for scoring)`;\n }\n\n const pct = (w: number) => `${(w * 100).toFixed(0)}%`;\n const dimLine = (name: string, weight: number, r: DimensionResult) =>\n r.applicable\n ? `${name} (${pct(weight)}): ${r.detail} [${r.score}]`\n : `${name}: ${r.detail} [N/A — excluded from average]`;\n\n const parts: string[] = [`Score: ${score} (${p.totalCalls} tool calls total)`];\n parts.push(dimLine('Build', WEIGHTS.build, p.build));\n parts.push(dimLine('Tests', WEIGHTS.tests, p.tests));\n parts.push(dimLine('Tool errors', WEIGHTS.toolErrors, p.toolErrors));\n parts.push(dimLine('Loops', WEIGHTS.loops, p.loops));\n parts.push(dimLine('Regression', WEIGHTS.regression, p.regression));\n parts.push(dimLine('Autonomy', WEIGHTS.autonomy, p.autonomy));\n\n return parts.join('\\n');\n });\n}\n"],"mappings":";;;;;;;;AAuCA,MAAM,UAAU;CACd,OAAO;CACP,OAAO;CACP,YAAY;CACZ,OAAO;CACP,YAAY;CACZ,UAAU;AACZ;;;;AAKA,MAAM,aAAa;;CAEjB,4BAA4B;;CAG5B,oBAAoB;;CAGpB,0BAA0B;;CAG1B,uBAAuB;;CAGvB,oBAAoB;;CAGpB,cAAc;;CAGd,kBAAkB;EAAC;EAAkB;EAAc;CAAa;AAClE;;;;;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,OAAO,EAAE;GACT,OAAO,EAAE;GACT,YAAY,EAAE;GACd,OAAO,EAAE;GACT,YAAY,EAAE;GACd,UAAU,EAAE;EACd,GACA,OACF;EAEA,OAAO,UAAU,OAAO,IAAI,KAAK,MAAM,QAAQ,GAAG,IAAI;CACxD,CAAC,CAAC,CACD,gBAAgB,EAAE,SAAS,YAAY;EACtC,MAAM,IAAI,QAAQ;EAClB,IAAI,EAAE,OACJ,OAAO,aAAa,EAAE,WAAW;EAGnC,MAAM,OAAO,MAAc,IAAI,IAAI,IAAA,CAAK,QAAQ,CAAC,EAAE;EACnD,MAAM,WAAW,MAAc,QAAgB,MAC7C,EAAE,aACE,GAAG,KAAK,IAAI,IAAI,MAAM,EAAE,KAAK,EAAE,OAAO,IAAI,EAAE,MAAM,KAClD,GAAG,KAAK,IAAI,EAAE,OAAO;EAE3B,MAAM,QAAkB,CAAC,UAAU,MAAM,IAAI,EAAE,WAAW,mBAAmB;EAC7E,MAAM,KAAK,QAAQ,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;EACnD,MAAM,KAAK,QAAQ,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;EACnD,MAAM,KAAK,QAAQ,eAAe,QAAQ,YAAY,EAAE,UAAU,CAAC;EACnE,MAAM,KAAK,QAAQ,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;EACnD,MAAM,KAAK,QAAQ,cAAc,QAAQ,YAAY,EAAE,UAAU,CAAC;EAClE,MAAM,KAAK,QAAQ,YAAY,QAAQ,UAAU,EAAE,QAAQ,CAAC;EAE5D,OAAO,MAAM,KAAK,IAAI;CACxB,CAAC;AACL"}
|
|
1
|
+
{"version":3,"file":"outcome.js","names":[],"sources":["../../../src/evals/scorers/outcome.ts"],"sourcesContent":["/**\n * MastraCode Outcome Scorer (Code-based, Agent type, always-on)\n *\n * Grades the objective outcome of a coding session by checking hard facts:\n * - Did the build/typecheck pass?\n * - Did tests pass?\n * - What was the tool error rate?\n * - Did the agent get stuck in a loop?\n * - Was there a regression (build passed earlier, failed later)?\n * - Did the agent use ask_user unnecessarily? (autonomy)\n *\n * This scorer is always-on (no sampling) because it's cheap — it only\n * reads exit codes and error states from tool results already in the messages.\n *\n * Scoring philosophy (from Anthropic's eval guidance):\n * \"Grade outcomes, not paths\" — we check what happened, not how.\n * Partial credit: a session that passes build but fails tests scores\n * higher than one that fails build entirely.\n *\n * Dimensions that don't apply to a session (e.g. build for a docs-only task)\n * are excluded from the weighted average, so sessions aren't penalized for\n * irrelevant criteria.\n */\n\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { createScorer, filterRun } from '@mastra/core/evals';\n\nimport { isBuildCommand, isTestCommand, getExitCode, isSuccessResult } from './classify-command.js';\nimport type { ExtractedToolCall } from './extract-tools.js';\nimport { extractToolCalls } from './extract-tools.js';\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// CONFIGURATION — Adjust weights and thresholds here\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Dimension weights. Used to compute the weighted average of applicable dimensions.\n * Dimensions that don't apply (e.g. no build ran) are excluded from the average.\n */\nconst WEIGHTS = {\n build: 0.3,\n tests: 0.25,\n toolErrors: 0.2,\n loops: 0.1,\n regression: 0.1,\n autonomy: 0.05,\n} as const;\n\n/**\n * Scoring thresholds and multipliers.\n */\nconst THRESHOLDS = {\n /** Multiplier for tool error rate penalty. Score = max(0, 1 - rate × this). */\n toolErrorPenaltyMultiplier: 1.0,\n\n /** How many consecutive identical calls (or same-error repeats) before it's a \"loop\". */\n loopMinRepetitions: 3,\n\n /** Score penalty per detected loop. */\n loopPenaltyPerOccurrence: 0.3,\n\n /** Score deducted per ask_user call. */\n autonomyPenaltyPerAsk: 0.25,\n\n /** Score when a command ran but exit code is ambiguous. */\n ambiguousExitScore: 0.75,\n\n /** Minimum tool calls required to produce a meaningful score. */\n minToolCalls: 1,\n\n /** Tool names whose errors are expected/benign (not penalized). */\n benignErrorTools: ['search_content', 'find_files', 'lsp_inspect'] as string[],\n} as const;\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\ntype DimensionResult = { score: number; detail: string; applicable: boolean };\n\n/**\n * Check if the primary verb of an execute_command is a build/typecheck command.\n * Splits compound commands (&&, ;) and checks the first segment.\n */\n/** Extract command string from tool call args, then delegate to shared classifier. */\nfunction isBuildArgs(args: Record<string, unknown>): boolean {\n return isBuildCommand(String(args.command ?? ''));\n}\n\nfunction isTestArgs(args: Record<string, unknown>): boolean {\n return isTestCommand(String(args.command ?? ''));\n}\n\nfunction isForegroundCommand(result: ExtractedToolCall): boolean {\n return result.args.background !== true;\n}\n\n/**\n * Score build/typecheck outcome (final state).\n */\nfunction scoreBuild(execResults: ExtractedToolCall[]): DimensionResult {\n const builds = execResults.filter(\n r => r.toolName === 'execute_command' && isForegroundCommand(r) && isBuildArgs(r.args),\n );\n if (builds.length === 0) return { score: 0, detail: 'No build/typecheck ran', applicable: false };\n\n const last = builds[builds.length - 1]!;\n if (last.isError) return { score: 0, detail: 'Build/typecheck tool errored', applicable: true };\n\n const exitCode = getExitCode(last.result);\n if (exitCode !== null && exitCode !== 0)\n return { score: 0, detail: `Build failed (exit ${exitCode})`, applicable: true };\n if (typeof last.result === 'string') return { score: 1, detail: 'Build/typecheck passed', applicable: true };\n\n const text = JSON.stringify(last.result ?? '');\n if (/error TS\\d+|Cannot find module|is not assignable/i.test(text)) {\n return { score: 0, detail: 'Build failed (TypeScript errors in output)', applicable: true };\n }\n if (isSuccessResult(last.result)) return { score: 1, detail: 'Build/typecheck passed', applicable: true };\n\n return { score: THRESHOLDS.ambiguousExitScore, detail: 'Build ran, outcome unclear', applicable: true };\n}\n\n/**\n * Score test outcome (final state).\n */\nfunction scoreTests(execResults: ExtractedToolCall[]): DimensionResult {\n const tests = execResults.filter(\n r => r.toolName === 'execute_command' && isForegroundCommand(r) && isTestArgs(r.args),\n );\n if (tests.length === 0) return { score: 0, detail: 'No tests ran', applicable: false };\n\n const last = tests[tests.length - 1]!;\n if (last.isError) return { score: 0, detail: 'Test command errored', applicable: true };\n\n const exitCode = getExitCode(last.result);\n if (exitCode !== null && exitCode !== 0)\n return { score: 0, detail: `Tests failed (exit ${exitCode})`, applicable: true };\n if (typeof last.result === 'string') return { score: 1, detail: 'Tests passed', applicable: true };\n\n const text = JSON.stringify(last.result ?? '');\n if (/\\bFAIL\\b|failed|✗|✘/i.test(text)) {\n return { score: 0, detail: 'Tests failed (inferred)', applicable: true };\n }\n if (/\\d+ (?:tests? )?passed|✓|PASS/i.test(text) && !/\\bfail(?:ed|ure)?\\b|\\berror\\b/i.test(text)) {\n return { score: 1, detail: 'Tests passed (inferred)', applicable: true };\n }\n if (isSuccessResult(last.result)) return { score: 1, detail: 'Tests passed', applicable: true };\n\n return { score: THRESHOLDS.ambiguousExitScore, detail: 'Tests ran, outcome unclear', applicable: true };\n}\n\n/**\n * Score tool error rate, excluding benign errors from expected-to-fail tools.\n */\nfunction scoreToolErrors(results: ExtractedToolCall[]): DimensionResult {\n if (results.length === 0) return { score: 1, detail: 'No tool calls', applicable: false };\n\n // Only count errors from non-benign tools\n const nonBenign = results.filter(r => !THRESHOLDS.benignErrorTools.includes(r.toolName));\n if (nonBenign.length === 0) return { score: 1, detail: 'All tool calls are benign-error tools', applicable: true };\n\n const errors = nonBenign.filter(r => r.isError);\n const rate = errors.length / nonBenign.length;\n\n if (rate === 0) return { score: 1, detail: 'No tool errors', applicable: true };\n\n const score = Math.max(0, 1 - rate * THRESHOLDS.toolErrorPenaltyMultiplier);\n return {\n score,\n detail: `${errors.length}/${nonBenign.length} tools errored (${(rate * 100).toFixed(0)}%)`,\n applicable: true,\n };\n}\n\n/**\n * Detect stuck loops: same tool + same args appearing 3+ times consecutively,\n * or same tool + same args erroring 3+ times total.\n */\nfunction scoreStuckLoops(results: ExtractedToolCall[]): DimensionResult {\n if (results.length < 3) return { score: 1, detail: 'Too few calls for loop detection', applicable: true };\n\n const fingerprint = (r: ExtractedToolCall) => `${r.toolName}:${JSON.stringify(r.args)}`;\n\n // Check consecutive identical calls\n let maxConsecutive = 1;\n let currentRun = 1;\n for (let i = 1; i < results.length; i++) {\n if (fingerprint(results[i]!) === fingerprint(results[i - 1]!)) {\n currentRun++;\n maxConsecutive = Math.max(maxConsecutive, currentRun);\n } else {\n currentRun = 1;\n }\n }\n\n // Check repeated error fingerprints\n const errorCounts = new Map<string, number>();\n for (const r of results) {\n if (!r.isError) continue;\n const fp = fingerprint(r);\n errorCounts.set(fp, (errorCounts.get(fp) ?? 0) + 1);\n }\n const maxErrorRepeat = Math.max(0, ...[...errorCounts.values()]);\n\n const minReps = THRESHOLDS.loopMinRepetitions;\n const loopSeverity = Math.max(\n maxConsecutive >= minReps ? maxConsecutive - (minReps - 1) : 0,\n maxErrorRepeat >= minReps ? maxErrorRepeat - (minReps - 1) : 0,\n );\n\n if (loopSeverity === 0) return { score: 1, detail: 'No stuck loops', applicable: true };\n\n const score = Math.max(0, 1 - loopSeverity * THRESHOLDS.loopPenaltyPerOccurrence);\n const details: string[] = [];\n if (maxConsecutive >= minReps) details.push(`${maxConsecutive} consecutive identical calls`);\n if (maxErrorRepeat >= minReps) details.push(`same error repeated ${maxErrorRepeat}x`);\n return { score, detail: details.join('; '), applicable: true };\n}\n\n/**\n * Detect regressions: build/test passed at some point, then failed later.\n * Gives partial credit if the agent recovered (final state passes).\n */\nfunction scoreRegression(execResults: ExtractedToolCall[]): DimensionResult {\n const regressions: { label: string; recovered: boolean }[] = [];\n\n for (const [label, filter] of [\n ['Build', isBuildArgs],\n ['Tests', isTestArgs],\n ] as const) {\n const cmds = execResults.filter(r => r.toolName === 'execute_command' && isForegroundCommand(r) && filter(r.args));\n if (cmds.length < 2) continue;\n\n let sawPass = false;\n let sawRegression = false;\n for (const cmd of cmds) {\n const exitCode = getExitCode(cmd.result);\n const passed = isSuccessResult(cmd.result, cmd.isError);\n const failed = cmd.isError || (exitCode !== null && exitCode !== 0);\n\n if (passed) {\n if (sawRegression) {\n // Recovered from regression\n regressions.push({ label, recovered: true });\n sawRegression = false;\n }\n sawPass = true;\n }\n if (sawPass && failed) {\n sawRegression = true;\n }\n }\n\n if (sawRegression) {\n // Regression persisted at end of session\n regressions.push({ label, recovered: false });\n }\n }\n\n if (regressions.length === 0) return { score: 1, detail: 'No regressions', applicable: true };\n\n // Persistent regressions are severe (0), recovered regressions get partial credit (0.5)\n const persistentCount = regressions.filter(r => !r.recovered).length;\n const recoveredCount = regressions.filter(r => r.recovered).length;\n const score = Math.max(0, 1 - persistentCount * 0.5 - recoveredCount * 0.1);\n const details = regressions.map(\n r => `${r.label} ${r.recovered ? 'regressed then recovered' : 'regressed (persisted)'}`,\n );\n return { score, detail: details.join('; '), applicable: true };\n}\n\n/**\n * Score autonomy: penalize ask_user calls.\n * 0 calls = 1.0, each call reduces by 0.25 (up to a floor of 0).\n */\nfunction scoreAutonomy(results: ExtractedToolCall[]): DimensionResult {\n const askUserCalls = results.filter(r => r.toolName === 'ask_user');\n const count = askUserCalls.length;\n\n if (count === 0) return { score: 1, detail: 'No ask_user calls (fully autonomous)', applicable: true };\n\n const score = Math.max(0, 1 - count * THRESHOLDS.autonomyPenaltyPerAsk);\n return { score, detail: `${count} ask_user call${count > 1 ? 's' : ''}`, applicable: true };\n}\n\n/**\n * Compute weighted average of only applicable dimensions.\n * Returns null if no dimensions are applicable.\n */\nfunction weightedAverage(dimensions: Record<string, DimensionResult>, weights: Record<string, number>): number | null {\n let totalWeight = 0;\n let weightedSum = 0;\n\n for (const [key, result] of Object.entries(dimensions)) {\n if (!result.applicable) continue;\n const weight = weights[key] ?? 0;\n totalWeight += weight;\n weightedSum += result.score * weight;\n }\n\n if (totalWeight === 0) return null;\n return weightedSum / totalWeight;\n}\n\nexport function createOutcomeScorer() {\n return createScorer({\n id: 'mastracode-outcome',\n name: 'MastraCode Outcome',\n description:\n 'Grades coding session outcomes: build/test pass, tool errors, stuck loops, regressions, autonomy. Always-on.',\n type: 'agent',\n prepareRun: filterRun({ partTypes: ['tool-invocation', 'text'] }),\n })\n .preprocess(async ({ run }) => {\n const messages = (run.output ?? []) as MastraDBMessage[];\n const allResults = extractToolCalls(messages);\n const totalCalls = allResults.length;\n\n // H1: Empty sessions or sessions with no tool calls → score 0\n if (totalCalls < THRESHOLDS.minToolCalls) {\n const empty: DimensionResult = { score: 0, detail: 'No tool calls', applicable: false };\n return {\n empty: true as const,\n build: empty,\n tests: empty,\n toolErrors: empty,\n loops: empty,\n regression: empty,\n autonomy: empty,\n totalCalls,\n };\n }\n\n const execResults = allResults.filter(r => r.toolName === 'execute_command');\n\n return {\n empty: false as const,\n build: scoreBuild(execResults),\n tests: scoreTests(execResults),\n toolErrors: scoreToolErrors(allResults),\n loops: scoreStuckLoops(allResults),\n regression: scoreRegression(execResults),\n autonomy: scoreAutonomy(allResults),\n totalCalls,\n };\n })\n .generateScore(({ results }) => {\n const p = results.preprocessStepResult;\n if (p.empty) return 0;\n\n const score = weightedAverage(\n {\n build: p.build,\n tests: p.tests,\n toolErrors: p.toolErrors,\n loops: p.loops,\n regression: p.regression,\n autonomy: p.autonomy,\n },\n WEIGHTS,\n );\n\n return score === null ? 0 : Math.round(score * 100) / 100;\n })\n .generateReason(({ results, score }) => {\n const p = results.preprocessStepResult;\n if (p.empty) {\n return `Score: 0 (${p.totalCalls} tool calls — below minimum threshold for scoring)`;\n }\n\n const pct = (w: number) => `${(w * 100).toFixed(0)}%`;\n const dimLine = (name: string, weight: number, r: DimensionResult) =>\n r.applicable\n ? `${name} (${pct(weight)}): ${r.detail} [${r.score}]`\n : `${name}: ${r.detail} [N/A — excluded from average]`;\n\n const parts: string[] = [`Score: ${score} (${p.totalCalls} tool calls total)`];\n parts.push(dimLine('Build', WEIGHTS.build, p.build));\n parts.push(dimLine('Tests', WEIGHTS.tests, p.tests));\n parts.push(dimLine('Tool errors', WEIGHTS.toolErrors, p.toolErrors));\n parts.push(dimLine('Loops', WEIGHTS.loops, p.loops));\n parts.push(dimLine('Regression', WEIGHTS.regression, p.regression));\n parts.push(dimLine('Autonomy', WEIGHTS.autonomy, p.autonomy));\n\n return parts.join('\\n');\n });\n}\n"],"mappings":";;;;;;;;AAuCA,MAAM,UAAU;CACd,OAAO;CACP,OAAO;CACP,YAAY;CACZ,OAAO;CACP,YAAY;CACZ,UAAU;AACZ;;;;AAKA,MAAM,aAAa;;CAEjB,4BAA4B;;CAG5B,oBAAoB;;CAGpB,0BAA0B;;CAG1B,uBAAuB;;CAGvB,oBAAoB;;CAGpB,cAAc;;CAGd,kBAAkB;EAAC;EAAkB;EAAc;CAAa;AAClE;;;;;;AAWA,SAAS,YAAY,MAAwC;CAC3D,OAAO,eAAe,OAAO,KAAK,WAAW,EAAE,CAAC;AAClD;AAEA,SAAS,WAAW,MAAwC;CAC1D,OAAO,cAAc,OAAO,KAAK,WAAW,EAAE,CAAC;AACjD;AAEA,SAAS,oBAAoB,QAAoC;CAC/D,OAAO,OAAO,KAAK,eAAe;AACpC;;;;AAKA,SAAS,WAAW,aAAmD;CACrE,MAAM,SAAS,YAAY,QACzB,MAAK,EAAE,aAAa,qBAAqB,oBAAoB,CAAC,KAAK,YAAY,EAAE,IAAI,CACvF;CACA,IAAI,OAAO,WAAW,GAAG,OAAO;EAAE,OAAO;EAAG,QAAQ;EAA0B,YAAY;CAAM;CAEhG,MAAM,OAAO,OAAO,OAAO,SAAS;CACpC,IAAI,KAAK,SAAS,OAAO;EAAE,OAAO;EAAG,QAAQ;EAAgC,YAAY;CAAK;CAE9F,MAAM,WAAW,YAAY,KAAK,MAAM;CACxC,IAAI,aAAa,QAAQ,aAAa,GACpC,OAAO;EAAE,OAAO;EAAG,QAAQ,sBAAsB,SAAS;EAAI,YAAY;CAAK;CACjF,IAAI,OAAO,KAAK,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MAAc,QAAgB,MAC7C,EAAE,aACE,GAAG,KAAK,IAAI,IAAI,MAAM,EAAE,KAAK,EAAE,OAAO,IAAI,EAAE,MAAM,KAClD,GAAG,KAAK,IAAI,EAAE,OAAO;EAE3B,MAAM,QAAkB,CAAC,UAAU,MAAM,IAAI,EAAE,WAAW,mBAAmB;EAC7E,MAAM,KAAK,QAAQ,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;EACnD,MAAM,KAAK,QAAQ,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;EACnD,MAAM,KAAK,QAAQ,eAAe,QAAQ,YAAY,EAAE,UAAU,CAAC;EACnE,MAAM,KAAK,QAAQ,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;EACnD,MAAM,KAAK,QAAQ,cAAc,QAAQ,YAAY,EAAE,UAAU,CAAC;EAClE,MAAM,KAAK,QAAQ,YAAY,QAAQ,UAAU,EAAE,QAAQ,CAAC;EAE5D,OAAO,MAAM,KAAK,IAAI;CACxB,CAAC;AACL"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { parseExperimentalAgentSetting } from "./onboarding/settings.js";
|
|
2
2
|
import { createDurableAgent, createEventedAgent, isDurableAgent, isEventedAgent } from "@mastra/core/agent/durable";
|
|
3
|
-
|
|
3
|
+
// src/experimental-agent.ts
|
|
4
4
|
const ACCEPTED_VALUES = "\"durable\", \"evented\", or unset";
|
|
5
5
|
function parseExperimentalAgentEnvironment(env = process.env) {
|
|
6
6
|
const value = env.MASTRACODE_EXPERIMENTAL_AGENT;
|
|
@@ -30,7 +30,6 @@ function validateExperimentalAgent(agent, mastra, report = console.info) {
|
|
|
30
30
|
if (engineType !== expectedEngine) throw new Error(`Experimental agent "${selection}" resolved workflow engine ${JSON.stringify(engineType)} instead of "${expectedEngine}".`);
|
|
31
31
|
report(`Experimental agent: ${selection} (workflow engine: ${engineType})`);
|
|
32
32
|
}
|
|
33
|
-
//#endregion
|
|
34
33
|
export { parseExperimentalAgentEnvironment, resolveExperimentalAgent, validateExperimentalAgent, wrapExperimentalAgent };
|
|
35
34
|
|
|
36
35
|
//# sourceMappingURL=experimental-agent.js.map
|
package/dist/factory/client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getPlatformSession } from "../platform/index.js";
|
|
2
2
|
import { MastraClient } from "@mastra/client-js";
|
|
3
|
-
|
|
3
|
+
// src/factory/client.ts
|
|
4
4
|
/** The agent controller every Factory serves its coding sessions under. */
|
|
5
5
|
const FACTORY_CONTROLLER_ID = "code";
|
|
6
6
|
const ORGANIZATION_ID_HEADER = "X-Mastra-Organization-Id";
|
|
@@ -92,7 +92,6 @@ function createFactoryClient(address) {
|
|
|
92
92
|
fetch: refreshingFetch(address)
|
|
93
93
|
});
|
|
94
94
|
}
|
|
95
|
-
//#endregion
|
|
96
95
|
export { FACTORY_CONTROLLER_ID, createFactoryClient, createFactoryUserSession, factoryHeaders, listFactoryProjects, refreshingFetch };
|
|
97
96
|
|
|
98
97
|
//# sourceMappingURL=client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-controller.d.ts","sourceRoot":"","sources":["../../src/factory/remote-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAErF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAyB,MAAM,aAAa,CAAC;AAEzE,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,KAAK,gBAAgB,GAAG,UAAU,CAAC,UA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,CAAC,CAK/F;CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { FACTORY_CONTROLLER_ID, createFactoryClient } from "./client.js";
|
|
2
|
-
|
|
2
|
+
// src/factory/remote-controller.ts
|
|
3
3
|
/**
|
|
4
4
|
* The Factory-side counterpart to the local agent controller. Modes, models, and
|
|
5
5
|
* provider auth come from the Factory, never from local settings or auth storage.
|
|
@@ -37,7 +37,6 @@ var RemoteController = class {
|
|
|
37
37
|
} : { hasAuth: true };
|
|
38
38
|
}
|
|
39
39
|
};
|
|
40
|
-
//#endregion
|
|
41
40
|
export { RemoteController };
|
|
42
41
|
|
|
43
42
|
//# sourceMappingURL=remote-controller.js.map
|
|
@@ -87,7 +87,7 @@ export declare class RemoteSession {
|
|
|
87
87
|
hasSelection: () => boolean;
|
|
88
88
|
resolve: () => {
|
|
89
89
|
id: string;
|
|
90
|
-
name?: string | undefined
|
|
90
|
+
name?: string | undefined;
|
|
91
91
|
};
|
|
92
92
|
set: ({ modeId }: {
|
|
93
93
|
modeId: string;
|
|
@@ -179,7 +179,7 @@ export declare class RemoteSession {
|
|
|
179
179
|
}): Promise<void>;
|
|
180
180
|
sendSignal(input: Parameters<Session['sendSignal']>[0]): {
|
|
181
181
|
id: `${string}-${string}-${string}-${string}-${string}`;
|
|
182
|
-
type:
|
|
182
|
+
type: 'user';
|
|
183
183
|
accepted: Promise<{
|
|
184
184
|
accepted: true;
|
|
185
185
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-session.d.ts","sourceRoot":"","sources":["../../src/factory/remote-session.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAuC,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AACtG,OAAO,KAAK,EACV,2BAA2B,EAE3B,4BAA4B,EAC5B,kCAAkC,EAClC,qBAAqB,EACrB,eAAe,EACf,OAAO,EACR,MAAM,+BAA+B,CAAC;AAGvC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM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AAE,KAAK,EAAE,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,KAAK,CAAA;KAAE,iBAEvE;IAEK,YAAY,CAAC,EAAE,OAAO,EAAE,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,iBAElD;IAED,UAAU,CAAC,KAAK,EAAE,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;;cAkBjC,MAAM;;;;;MAC1B;IAEK,KAAK,CAAC,EAAE,OAAO,EAAE,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,iBAE3C;IAEK,QAAQ,CAAC,EAAE,OAAO,EAAE,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,iBAE9C;IAED,qBAAqB,CAAC,EACpB,QAAQ,EACR,UAAU,GACX,EAAE;QACD,QAAQ,EAAE,SAAS,GAAG,SAAS,GAAG,uBAAuB,CAAC;QAC1D,UAAU,EAAE,MAAM,CAAC;KACpB;QAWU,QAAQ;MAClB;IAEK,uBAAuB,CAAC,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE;QAAE,UAAU,EAAE,OAAO,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,iBAOrG;IAED,iBAAiB,IAAI,OAAO,CAE3B;IAED,mBAAmB,IAAI,IAAI,CAAG;IAE9B,KAAK,IAAI,IAAI,CAIZ;IAED,QAAQ,IAAI,IAAI,CAEf;CACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createFactoryClient } from "./client.js";
|
|
2
2
|
import { randomUUID } from "crypto";
|
|
3
3
|
import { defaultDisplayState } from "@mastra/core/agent-controller";
|
|
4
|
-
|
|
4
|
+
// src/factory/remote-session.ts
|
|
5
5
|
const MAP_FIELDS = [
|
|
6
6
|
"activeTools",
|
|
7
7
|
"toolInputBuffers",
|
|
@@ -412,7 +412,6 @@ var RemoteSession = class {
|
|
|
412
412
|
this.abort();
|
|
413
413
|
}
|
|
414
414
|
};
|
|
415
|
-
//#endregion
|
|
416
415
|
export { RemoteSession };
|
|
417
416
|
|
|
418
417
|
//# sourceMappingURL=remote-session.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-manager.d.ts","sourceRoot":"","sources":["../src/goal-manager.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAI9E,MAAM,WAAW,gBAAgB,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAChG,UAAU,EAAE,eAAe,CAAC,MAAM,CAAC,CAAC;IACpC,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;CAC1B;AAMD,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEtD;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,UAAU,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,0FAA0F;IAC1F,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAMD,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAWpC,qBAAa,WAAW;IACtB,kGAAkG;IAClG,OAAO,CAAC,MAAM,CAAuD;IACrE,OAAO,CAAC,QAAQ,CAAqB;IACrC,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,6BAA6B,CAAS;IAC9C;;;;;OAKG;IACH,OAAO,CAAC,aAAa,CAAkE;IAMvF,OAAO,IAA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}
|
package/dist/goal-manager.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { loadSettings } from "./onboarding/settings.js";
|
|
2
2
|
import { getGoalActivityDurationMs } from "@mastra/core/agent";
|
|
3
|
-
|
|
3
|
+
// src/goal-manager.ts
|
|
4
4
|
/**
|
|
5
5
|
* GoalManager — persistent cross-turn goals, backed by the Agent's native goal
|
|
6
6
|
* mechanism.
|
|
@@ -348,7 +348,6 @@ var GoalManager = class {
|
|
|
348
348
|
};
|
|
349
349
|
}
|
|
350
350
|
};
|
|
351
|
-
//#endregion
|
|
352
351
|
export { DEFAULT_MAX_TURNS, GoalManager };
|
|
353
352
|
|
|
354
353
|
//# sourceMappingURL=goal-manager.js.map
|
package/dist/goal-signal.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-signal.d.ts","sourceRoot":"","sources":["../src/goal-signal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEnD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,SAAS
|
|
1
|
+
{"version":3,"file":"goal-signal.d.ts","sourceRoot":"","sources":["../src/goal-signal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEnD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,SAAS;IAEpD,IAAI,EAAE,iBAAiB;IACvB,QAAQ;IACR,UAAU;QAAI,IAAI;;IAClB,QAAQ;QACN,MAAM;QAGN,YAAY;QACZ,YAAY;;EAGjB"}
|
package/dist/goal-signal.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/goal-signal.ts
|
|
2
2
|
function createGoalReminderSignal(goal) {
|
|
3
3
|
return {
|
|
4
4
|
type: "system-reminder",
|
|
@@ -11,7 +11,6 @@ function createGoalReminderSignal(goal) {
|
|
|
11
11
|
}
|
|
12
12
|
};
|
|
13
13
|
}
|
|
14
|
-
//#endregion
|
|
15
14
|
export { createGoalReminderSignal };
|
|
16
15
|
|
|
17
16
|
//# sourceMappingURL=goal-signal.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/headless/cli.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/headless/cli.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAoB5C,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEzE,kFAAkF;AAClF,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,CAAC;AAEpD,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,UAAU,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,OAAO,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gFAAgF;IAChF,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC;AAKD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAcvD;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,YAAY,CAsC9D;AAED,wBAAgB,kBAAkB,IAAI,IAAI,CA+BzC;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,CAShE;AAED;;;GAGG;AACH,wBAAsB,QAAQ,CAC5B,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,EAC/B,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GACzD,OAAO,CAAC,KAAK,CAAC,CA4LhB"}
|
package/dist/headless/cli.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { listBuiltinModePacks } from "../onboarding/packs.js";
|
|
2
2
|
import { loadSettings, resolveModelDefaults, saveSettings } from "../onboarding/settings.js";
|
|
3
|
+
import { resolveSubagentsSetting } from "../agents/subagents/index.js";
|
|
3
4
|
import { releaseAllThreadLocks } from "../utils/thread-lock.js";
|
|
4
5
|
import { permissionModeToPolicy } from "./policy.js";
|
|
5
6
|
import { runMC } from "./run-mc.js";
|
|
@@ -11,7 +12,7 @@ import { FLAGS, buildParseArgsOptions, renderFlagUsage } from "./flags.js";
|
|
|
11
12
|
import { createMastraCode } from "../index.js";
|
|
12
13
|
import { existsSync } from "fs";
|
|
13
14
|
import { parseArgs } from "util";
|
|
14
|
-
|
|
15
|
+
// src/headless/cli.ts
|
|
15
16
|
/**
|
|
16
17
|
* CLI adapter for headless MastraCode runs.
|
|
17
18
|
*
|
|
@@ -168,7 +169,8 @@ async function runMCCli(predrainedInput, options) {
|
|
|
168
169
|
try {
|
|
169
170
|
boot = await createMastraCode({
|
|
170
171
|
settingsPath: args.settings,
|
|
171
|
-
coAuthor: options?.coAuthor
|
|
172
|
+
coAuthor: options?.coAuthor,
|
|
173
|
+
subagents: resolveSubagentsSetting(settings.preferences.subagentsEnabled)
|
|
172
174
|
});
|
|
173
175
|
const { controller, session, mcpManager } = boot;
|
|
174
176
|
const effectiveDefaults = resolveModelDefaults(settings, listBuiltinModePacks());
|
|
@@ -250,7 +252,6 @@ async function runMCCli(predrainedInput, options) {
|
|
|
250
252
|
if (!stdoutFlushed && exitCode === 0) exitCode = 1;
|
|
251
253
|
process.exit(exitCode);
|
|
252
254
|
}
|
|
253
|
-
//#endregion
|
|
254
255
|
export { flushWritable, hasHeadlessFlag, parseHeadlessArgs, printHeadlessUsage, runMCCli };
|
|
255
256
|
|
|
256
257
|
//# sourceMappingURL=cli.js.map
|
package/dist/headless/cli.js.map
CHANGED
|
@@ -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 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 =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E,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;CAIA,MAAM,CAAC,iBAAiB,MAAM,QAAQ,IAAI,CAAC,cAAc,QAAQ,MAAM,GAAG,cAAc,QAAQ,MAAM,CAAC,CAAC;CACxG,IAAI,CAAC,iBAAiB,aAAa,GAAG,WAAW;CACjD,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 { resolveSubagentsSetting } from '../agents/subagents/index.js';\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({\n settingsPath: args.settings,\n coAuthor: options?.coAuthor,\n subagents: resolveSubagentsSetting(settings.preferences.subagentsEnabled),\n });\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) exit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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;CAIA,MAAM,CAAC,iBAAiB,MAAM,QAAQ,IAAI,CAAC,cAAc,QAAQ,MAAM,GAAG,cAAc,QAAQ,MAAM,CAAC,CAAC;CACxG,IAAI,CAAC,iBAAiB,aAAa,GAAG,WAAW;CACjD,QAAQ,KAAK,QAAQ;AACvB"}
|
package/dist/headless/flags.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const VALID_OUTPUTS: readonly [
|
|
1
|
+
export declare const VALID_OUTPUTS: readonly ['human', 'json', 'jsonl'];
|
|
2
2
|
/**
|
|
3
3
|
* One CLI flag. `key` is the long name (e.g. `output`); `field` is the
|
|
4
4
|
* {@link import('./cli.js').HeadlessArgs} property it populates. `coerce`
|
|
@@ -24,7 +24,7 @@ export interface FlagSpec {
|
|
|
24
24
|
export declare const FLAGS: FlagSpec[];
|
|
25
25
|
/** `parseArgs` option config derived from {@link FLAGS}. */
|
|
26
26
|
export declare function buildParseArgsOptions(): Record<string, {
|
|
27
|
-
type:
|
|
27
|
+
type: 'string' | 'boolean';
|
|
28
28
|
short?: string;
|
|
29
29
|
default?: boolean;
|
|
30
30
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flags.d.ts","sourceRoot":"","sources":["../../src/headless/flags.ts"],"names":[],"mappings":"AAgBA,eAAO,MAAM,aAAa,
|
|
1
|
+
{"version":3,"file":"flags.d.ts","sourceRoot":"","sources":["../../src/headless/flags.ts"],"names":[],"mappings":"AAgBA,eAAO,MAAM,aAAa,YAAI,OAAO,EAAE,MAAM,EAAE,OAAO,CAAU,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"}
|
package/dist/headless/flags.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { VALID_MODES, VALID_PERMISSION_MODES, VALID_THINKING_LEVELS } from "./types.js";
|
|
2
|
-
|
|
2
|
+
// src/headless/flags.ts
|
|
3
3
|
const VALID_OUTPUTS = [
|
|
4
4
|
"human",
|
|
5
5
|
"json",
|
|
@@ -198,7 +198,6 @@ function renderFlagUsage() {
|
|
|
198
198
|
return [`${label.padEnd(width)}${lines[0]}`, ...lines.slice(1).map((line) => `${" ".repeat(width)}${line}`)].join("\n");
|
|
199
199
|
}).join("\n");
|
|
200
200
|
}
|
|
201
|
-
//#endregion
|
|
202
201
|
export { FLAGS, VALID_OUTPUTS, buildParseArgsOptions, renderFlagUsage };
|
|
203
202
|
|
|
204
203
|
//# sourceMappingURL=flags.js.map
|
package/dist/headless/format.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/headless/format.ts
|
|
2
2
|
/** Truncate a string to `max` characters, appending "..." if truncated. */
|
|
3
3
|
function truncate(s, max) {
|
|
4
4
|
return s.length > max ? s.slice(0, max) + "..." : s;
|
|
@@ -91,7 +91,6 @@ function renderJsonResult(result) {
|
|
|
91
91
|
exitCode: result.exitCode
|
|
92
92
|
}) + "\n";
|
|
93
93
|
}
|
|
94
|
-
//#endregion
|
|
95
94
|
export { createHumanFormatState, formatHuman, formatJsonl, isJsonlEvent, renderJsonResult, renderTextResult, truncate };
|
|
96
95
|
|
|
97
96
|
//# sourceMappingURL=format.js.map
|