@mastra/code-sdk 0.0.0-agent-tags-alpha-20261125185303
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/LICENSE.md +32 -0
- package/README.md +284 -0
- package/dist/acp/agent.d.ts +48 -0
- package/dist/acp/agent.js +414 -0
- package/dist/acp/errors.d.ts +3 -0
- package/dist/acp/errors.js +11 -0
- package/dist/acp/event-mapper.d.ts +28 -0
- package/dist/acp/event-mapper.js +274 -0
- package/dist/acp/index.d.ts +9 -0
- package/dist/acp/index.js +21 -0
- package/dist/acp/runtime.d.ts +5 -0
- package/dist/acp/runtime.js +91 -0
- package/dist/acp/server.d.ts +4 -0
- package/dist/acp/server.js +35 -0
- package/dist/acp/skills.d.ts +6 -0
- package/dist/acp/skills.js +30 -0
- package/dist/acp.d.ts +2 -0
- package/dist/acp.js +1 -0
- package/dist/agent-connections/messaging-processor.d.ts +17 -0
- package/dist/agent-connections/messaging-processor.js +131 -0
- package/dist/agent-connections/ownership.d.ts +24 -0
- package/dist/agent-connections/ownership.js +96 -0
- package/dist/agent-connections/registry.d.ts +20 -0
- package/dist/agent-connections/registry.js +167 -0
- package/dist/agent-connections/session-advertisement.d.ts +27 -0
- package/dist/agent-connections/session-advertisement.js +86 -0
- package/dist/agent-connections/signal-provider.d.ts +141 -0
- package/dist/agent-connections/signal-provider.js +35 -0
- package/dist/agent-connections/state-processor.d.ts +23 -0
- package/dist/agent-connections/state-processor.js +270 -0
- package/dist/agent-connections/thread-state.d.ts +41 -0
- package/dist/agent-connections/thread-state.js +157 -0
- package/dist/agent-connections/tools.d.ts +133 -0
- package/dist/agent-connections/tools.js +616 -0
- package/dist/agent-connections/types.d.ts +99 -0
- package/dist/agent-connections/types.js +4 -0
- package/dist/agent-connections/untrusted-text.d.ts +5 -0
- package/dist/agent-connections/untrusted-text.js +19 -0
- package/dist/agents/background-completion-events.d.ts +16 -0
- package/dist/agents/background-completion-events.js +16 -0
- package/dist/agents/background-completion.d.ts +22 -0
- package/dist/agents/background-completion.js +73 -0
- package/dist/agents/context-audit.d.ts +84 -0
- package/dist/agents/context-audit.js +115 -0
- package/dist/agents/credential-resolver.d.ts +74 -0
- package/dist/agents/credential-resolver.js +142 -0
- package/dist/agents/custom-provider-source.d.ts +35 -0
- package/dist/agents/custom-provider-source.js +22 -0
- package/dist/agents/fastembed-subprocess.d.ts +52 -0
- package/dist/agents/fastembed-subprocess.js +282 -0
- package/dist/agents/instructions.d.ts +42 -0
- package/dist/agents/instructions.js +69 -0
- package/dist/agents/mastracode-gateway.d.ts +85 -0
- package/dist/agents/mastracode-gateway.js +500 -0
- package/dist/agents/memory.d.ts +36 -0
- package/dist/agents/memory.js +248 -0
- package/dist/agents/model.d.ts +158 -0
- package/dist/agents/model.js +382 -0
- package/dist/agents/modes/build.d.ts +12 -0
- package/dist/agents/modes/build.js +33 -0
- package/dist/agents/modes/explore.d.ts +10 -0
- package/dist/agents/modes/explore.js +25 -0
- package/dist/agents/modes/plan.d.ts +8 -0
- package/dist/agents/modes/plan.js +43 -0
- package/dist/agents/prompts/agent-instructions.d.ts +122 -0
- package/dist/agents/prompts/agent-instructions.js +617 -0
- package/dist/agents/prompts/build.d.ts +12 -0
- package/dist/agents/prompts/build.js +73 -0
- package/dist/agents/prompts/fast.d.ts +5 -0
- package/dist/agents/prompts/fast.js +23 -0
- package/dist/agents/prompts/index.d.ts +61 -0
- package/dist/agents/prompts/index.js +141 -0
- package/dist/agents/prompts/model.d.ts +5 -0
- package/dist/agents/prompts/model.js +20 -0
- package/dist/agents/prompts/plan.d.ts +11 -0
- package/dist/agents/prompts/plan.js +132 -0
- package/dist/agents/prompts/tool-guidance.d.ts +18 -0
- package/dist/agents/prompts/tool-guidance.js +158 -0
- package/dist/agents/sandbox-filesystem.d.ts +232 -0
- package/dist/agents/sandbox-filesystem.js +851 -0
- package/dist/agents/subagents/execute.d.ts +3 -0
- package/dist/agents/subagents/execute.js +24 -0
- package/dist/agents/subagents/explore.d.ts +3 -0
- package/dist/agents/subagents/explore.js +15 -0
- package/dist/agents/subagents/index.d.ts +6 -0
- package/dist/agents/subagents/index.js +15 -0
- package/dist/agents/subagents/plan.d.ts +3 -0
- package/dist/agents/subagents/plan.js +15 -0
- package/dist/agents/thread-caveman-state.d.ts +17 -0
- package/dist/agents/thread-caveman-state.js +104 -0
- package/dist/agents/tool-availability.d.ts +17 -0
- package/dist/agents/tool-availability.js +134 -0
- package/dist/agents/tools.d.ts +37 -0
- package/dist/agents/tools.js +154 -0
- package/dist/agents/workflow-builder-agent.d.ts +2 -0
- package/dist/agents/workflow-builder-agent.js +79 -0
- package/dist/agents/workspace.d.ts +35 -0
- package/dist/agents/workspace.js +207 -0
- package/dist/analytics.d.ts +18 -0
- package/dist/analytics.js +159 -0
- package/dist/auth/account-rotation-processor.d.ts +210 -0
- package/dist/auth/account-rotation-processor.js +662 -0
- package/dist/auth/account-routing-context.d.ts +17 -0
- package/dist/auth/account-routing-context.js +38 -0
- package/dist/auth/authorization-input.d.ts +16 -0
- package/dist/auth/authorization-input.js +39 -0
- package/dist/auth/device-code.d.ts +93 -0
- package/dist/auth/device-code.js +126 -0
- package/dist/auth/index.d.ts +13 -0
- package/dist/auth/index.js +9 -0
- package/dist/auth/pkce.d.ts +13 -0
- package/dist/auth/pkce.js +29 -0
- package/dist/auth/provider-auth-error.d.ts +24 -0
- package/dist/auth/provider-auth-error.js +44 -0
- package/dist/auth/providers/anthropic.d.ts +40 -0
- package/dist/auth/providers/anthropic.js +117 -0
- package/dist/auth/providers/github-copilot.d.ts +154 -0
- package/dist/auth/providers/github-copilot.js +359 -0
- package/dist/auth/providers/kimi-coding.d.ts +38 -0
- package/dist/auth/providers/kimi-coding.js +225 -0
- package/dist/auth/providers/openai-codex.d.ts +141 -0
- package/dist/auth/providers/openai-codex.js +531 -0
- package/dist/auth/providers/xai.d.ts +64 -0
- package/dist/auth/providers/xai.js +223 -0
- package/dist/auth/storage.d.ts +222 -0
- package/dist/auth/storage.js +805 -0
- package/dist/auth/types.d.ts +164 -0
- package/dist/auth/types.js +1 -0
- package/dist/clipboard/index.d.ts +26 -0
- package/dist/clipboard/index.js +224 -0
- package/dist/constants.d.ts +29 -0
- package/dist/constants.js +34 -0
- package/dist/error-classification.d.ts +10 -0
- package/dist/error-classification.js +19 -0
- package/dist/evals/context-builder.d.ts +41 -0
- package/dist/evals/context-builder.js +156 -0
- package/dist/evals/index.d.ts +4 -0
- package/dist/evals/index.js +5 -0
- package/dist/evals/scorers/classify-command.d.ts +30 -0
- package/dist/evals/scorers/classify-command.js +61 -0
- package/dist/evals/scorers/efficiency.d.ts +44 -0
- package/dist/evals/scorers/efficiency.js +256 -0
- package/dist/evals/scorers/extract-tools.d.ts +25 -0
- package/dist/evals/scorers/extract-tools.js +57 -0
- package/dist/evals/scorers/index.d.ts +3 -0
- package/dist/evals/scorers/index.js +3 -0
- package/dist/evals/scorers/outcome.d.ts +49 -0
- package/dist/evals/scorers/outcome.js +360 -0
- package/dist/experimental-agent.d.ts +19 -0
- package/dist/experimental-agent.js +45 -0
- package/dist/factory/client.d.ts +44 -0
- package/dist/factory/client.js +110 -0
- package/dist/factory/remote-controller.d.ts +34 -0
- package/dist/factory/remote-controller.js +40 -0
- package/dist/factory/remote-session.d.ts +210 -0
- package/dist/factory/remote-session.js +415 -0
- package/dist/goal-manager.d.ts +114 -0
- package/dist/goal-manager.js +351 -0
- package/dist/goal-signal.d.ts +14 -0
- package/dist/goal-signal.js +14 -0
- package/dist/headless/cli.d.ts +55 -0
- package/dist/headless/cli.js +261 -0
- package/dist/headless/flags.d.ts +33 -0
- package/dist/headless/flags.js +207 -0
- package/dist/headless/format.d.ts +41 -0
- package/dist/headless/format.js +94 -0
- package/dist/headless/index.d.ts +25 -0
- package/dist/headless/index.js +6 -0
- package/dist/headless/policy.d.ts +17 -0
- package/dist/headless/policy.js +39 -0
- package/dist/headless/run-mc.d.ts +7 -0
- package/dist/headless/run-mc.js +438 -0
- package/dist/headless/types.d.ts +175 -0
- package/dist/headless/types.js +16 -0
- package/dist/hooks/config.d.ts +11 -0
- package/dist/hooks/config.js +77 -0
- package/dist/hooks/executor.d.ts +13 -0
- package/dist/hooks/executor.js +128 -0
- package/dist/hooks/index.d.ts +6 -0
- package/dist/hooks/index.js +5 -0
- package/dist/hooks/manager.d.ts +75 -0
- package/dist/hooks/manager.js +289 -0
- package/dist/hooks/types.d.ts +180 -0
- package/dist/hooks/types.js +5 -0
- package/dist/index.d.ts +537 -0
- package/dist/index.js +1399 -0
- package/dist/ipc/ipc-reporter.d.ts +14 -0
- package/dist/ipc/ipc-reporter.js +18 -0
- package/dist/knowledge-inspector.d.ts +139 -0
- package/dist/knowledge-inspector.js +533 -0
- package/dist/knowledge-scope-id.d.ts +7 -0
- package/dist/knowledge-scope-id.js +10 -0
- package/dist/knowledge-scope.d.ts +41 -0
- package/dist/knowledge-scope.js +85 -0
- package/dist/lsp/client.d.ts +56 -0
- package/dist/lsp/client.js +248 -0
- package/dist/lsp/index.d.ts +4 -0
- package/dist/lsp/index.js +4 -0
- package/dist/lsp/language.d.ts +9 -0
- package/dist/lsp/language.js +41 -0
- package/dist/lsp/manager.d.ts +34 -0
- package/dist/lsp/manager.js +79 -0
- package/dist/lsp/server.d.ts +27 -0
- package/dist/lsp/server.js +158 -0
- package/dist/lsp/workspace.d.ts +9 -0
- package/dist/lsp/workspace.js +52 -0
- package/dist/mcp/config.d.ts +77 -0
- package/dist/mcp/config.js +313 -0
- package/dist/mcp/index.d.ts +6 -0
- package/dist/mcp/index.js +3 -0
- package/dist/mcp/manager.d.ts +104 -0
- package/dist/mcp/manager.js +693 -0
- package/dist/mcp/state.d.ts +35 -0
- package/dist/mcp/state.js +94 -0
- package/dist/mcp/types.d.ts +139 -0
- package/dist/mcp/types.js +1 -0
- package/dist/onboarding/custom-packs.d.ts +7 -0
- package/dist/onboarding/custom-packs.js +17 -0
- package/dist/onboarding/custom-providers.d.ts +4 -0
- package/dist/onboarding/custom-providers.js +27 -0
- package/dist/onboarding/index.d.ts +5 -0
- package/dist/onboarding/index.js +3 -0
- package/dist/onboarding/om-settings.d.ts +47 -0
- package/dist/onboarding/om-settings.js +80 -0
- package/dist/onboarding/pack-activation.d.ts +43 -0
- package/dist/onboarding/pack-activation.js +105 -0
- package/dist/onboarding/packs.d.ts +106 -0
- package/dist/onboarding/packs.js +283 -0
- package/dist/onboarding/settings.d.ts +563 -0
- package/dist/onboarding/settings.js +1110 -0
- package/dist/permissions.d.ts +55 -0
- package/dist/permissions.js +139 -0
- package/dist/platform/index.d.ts +74 -0
- package/dist/platform/index.js +199 -0
- package/dist/plugin.d.ts +156 -0
- package/dist/plugin.js +27 -0
- package/dist/plugins/dependencies.d.ts +9 -0
- package/dist/plugins/dependencies.js +84 -0
- package/dist/plugins/install.d.ts +21 -0
- package/dist/plugins/install.js +187 -0
- package/dist/plugins/loader.d.ts +25 -0
- package/dist/plugins/loader.js +264 -0
- package/dist/plugins/manager.d.ts +115 -0
- package/dist/plugins/manager.js +507 -0
- package/dist/plugins/manifest.d.ts +14 -0
- package/dist/plugins/manifest.js +47 -0
- package/dist/plugins/package-link.d.ts +3 -0
- package/dist/plugins/package-link.js +58 -0
- package/dist/plugins/paths.d.ts +10 -0
- package/dist/plugins/paths.js +22 -0
- package/dist/plugins/registry.d.ts +8 -0
- package/dist/plugins/registry.js +109 -0
- package/dist/plugins/scaffold.d.ts +10 -0
- package/dist/plugins/scaffold.js +115 -0
- package/dist/plugins/signal-lane.d.ts +59 -0
- package/dist/plugins/signal-lane.js +163 -0
- package/dist/plugins/types.d.ts +95 -0
- package/dist/plugins/types.js +1 -0
- package/dist/process-memory-diagnostics.d.ts +136 -0
- package/dist/process-memory-diagnostics.js +497 -0
- package/dist/processors/plan-rejection-abort.d.ts +16 -0
- package/dist/processors/plan-rejection-abort.js +62 -0
- package/dist/providers/amazon-bedrock-gateway.d.ts +47 -0
- package/dist/providers/amazon-bedrock-gateway.js +142 -0
- package/dist/providers/amazon-bedrock.d.ts +28 -0
- package/dist/providers/amazon-bedrock.js +99 -0
- package/dist/providers/anthropic-prompt-cache.d.ts +19 -0
- package/dist/providers/anthropic-prompt-cache.js +8 -0
- package/dist/providers/anthropic-thinking.d.ts +5 -0
- package/dist/providers/anthropic-thinking.js +22 -0
- package/dist/providers/claude-max.d.ts +67 -0
- package/dist/providers/claude-max.js +232 -0
- package/dist/providers/github-copilot-gateway.d.ts +35 -0
- package/dist/providers/github-copilot-gateway.js +58 -0
- package/dist/providers/github-copilot.d.ts +60 -0
- package/dist/providers/github-copilot.js +320 -0
- package/dist/providers/google-thinking.d.ts +31 -0
- package/dist/providers/google-thinking.js +64 -0
- package/dist/providers/google-vertex-gateway.d.ts +23 -0
- package/dist/providers/google-vertex-gateway.js +49 -0
- package/dist/providers/google-vertex.d.ts +6 -0
- package/dist/providers/google-vertex.js +51 -0
- package/dist/providers/kimi-coding.d.ts +14 -0
- package/dist/providers/kimi-coding.js +80 -0
- package/dist/providers/model-ids.d.ts +53 -0
- package/dist/providers/model-ids.js +132 -0
- package/dist/providers/openai-codex.d.ts +114 -0
- package/dist/providers/openai-codex.js +427 -0
- package/dist/providers/provider-thinking.d.ts +23 -0
- package/dist/providers/provider-thinking.js +61 -0
- package/dist/providers/thinking-request.d.ts +14 -0
- package/dist/providers/thinking-request.js +87 -0
- package/dist/providers/xai.d.ts +33 -0
- package/dist/providers/xai.js +72 -0
- package/dist/schedules/index.d.ts +10 -0
- package/dist/schedules/index.js +6 -0
- package/dist/schedules/interval.d.ts +49 -0
- package/dist/schedules/interval.js +212 -0
- package/dist/schedules/prompt.d.ts +36 -0
- package/dist/schedules/prompt.js +36 -0
- package/dist/schedules/run-script.d.ts +8 -0
- package/dist/schedules/run-script.js +80 -0
- package/dist/schedules/scheduler.d.ts +101 -0
- package/dist/schedules/scheduler.js +167 -0
- package/dist/schedules/tools.d.ts +57 -0
- package/dist/schedules/tools.js +217 -0
- package/dist/schema.d.ts +499 -0
- package/dist/schema.js +131 -0
- package/dist/theme-palette.d.ts +17 -0
- package/dist/theme-palette.js +18 -0
- package/dist/thinking-catalog.d.ts +4 -0
- package/dist/thinking-catalog.js +13 -0
- package/dist/thinking.d.ts +37 -0
- package/dist/thinking.js +134 -0
- package/dist/tool-names.d.ts +77 -0
- package/dist/tool-names.js +53 -0
- package/dist/tools/index.d.ts +6 -0
- package/dist/tools/index.js +3 -0
- package/dist/tools/request-sandbox-access.d.ts +6 -0
- package/dist/tools/request-sandbox-access.js +80 -0
- package/dist/tools/utils.d.ts +20 -0
- package/dist/tools/utils.js +31 -0
- package/dist/tools/web-search.d.ts +116 -0
- package/dist/tools/web-search.js +158 -0
- package/dist/tools/workflows/create-workflow.d.ts +7 -0
- package/dist/tools/workflows/create-workflow.js +82 -0
- package/dist/tools/workflows/delete-workflow.d.ts +7 -0
- package/dist/tools/workflows/delete-workflow.js +18 -0
- package/dist/tools/workflows/ephemeral-memory.d.ts +28 -0
- package/dist/tools/workflows/ephemeral-memory.js +41 -0
- package/dist/tools/workflows/extract-json-schema.d.ts +12 -0
- package/dist/tools/workflows/extract-json-schema.js +19 -0
- package/dist/tools/workflows/get-workflow.d.ts +11 -0
- package/dist/tools/workflows/get-workflow.js +31 -0
- package/dist/tools/workflows/list-available-agents.d.ts +8 -0
- package/dist/tools/workflows/list-available-agents.js +29 -0
- package/dist/tools/workflows/list-available-classifiers.d.ts +19 -0
- package/dist/tools/workflows/list-available-classifiers.js +53 -0
- package/dist/tools/workflows/list-available-tools.d.ts +9 -0
- package/dist/tools/workflows/list-available-tools.js +37 -0
- package/dist/tools/workflows/list-available-workflows.d.ts +9 -0
- package/dist/tools/workflows/list-available-workflows.js +29 -0
- package/dist/tools/workflows/list-workflows.d.ts +9 -0
- package/dist/tools/workflows/list-workflows.js +30 -0
- package/dist/tools/workflows/run-workflow.d.ts +9 -0
- package/dist/tools/workflows/run-workflow.js +49 -0
- package/dist/tools/workflows/save-workflow.d.ts +1125 -0
- package/dist/tools/workflows/save-workflow.js +25 -0
- package/dist/tools/workflows/tool-ids.d.ts +16 -0
- package/dist/tools/workflows/tool-ids.js +17 -0
- package/dist/utils/binaries.d.ts +7 -0
- package/dist/utils/binaries.js +97 -0
- package/dist/utils/debug-log.d.ts +12 -0
- package/dist/utils/debug-log.js +56 -0
- package/dist/utils/discarding-scores-storage.d.ts +33 -0
- package/dist/utils/discarding-scores-storage.js +51 -0
- package/dist/utils/errors.d.ts +36 -0
- package/dist/utils/errors.js +215 -0
- package/dist/utils/gateway-sync.d.ts +26 -0
- package/dist/utils/gateway-sync.js +58 -0
- package/dist/utils/local-observability.d.ts +19 -0
- package/dist/utils/local-observability.js +54 -0
- package/dist/utils/maintenance-lock.d.ts +42 -0
- package/dist/utils/maintenance-lock.js +196 -0
- package/dist/utils/notification-dispatch.d.ts +74 -0
- package/dist/utils/notification-dispatch.js +128 -0
- package/dist/utils/open-url.d.ts +10 -0
- package/dist/utils/open-url.js +27 -0
- package/dist/utils/path-security.d.ts +2 -0
- package/dist/utils/path-security.js +7 -0
- package/dist/utils/plan-diff.d.ts +25 -0
- package/dist/utils/plan-diff.js +59 -0
- package/dist/utils/plans.d.ts +61 -0
- package/dist/utils/plans.js +120 -0
- package/dist/utils/project.d.ts +160 -0
- package/dist/utils/project.js +361 -0
- package/dist/utils/prune-cli.d.ts +24 -0
- package/dist/utils/prune-cli.js +124 -0
- package/dist/utils/signals-pubsub.d.ts +103 -0
- package/dist/utils/signals-pubsub.js +409 -0
- package/dist/utils/slash-command-loader.d.ts +52 -0
- package/dist/utils/slash-command-loader.js +139 -0
- package/dist/utils/slash-command-processor.d.ts +14 -0
- package/dist/utils/slash-command-processor.js +106 -0
- package/dist/utils/stdin-pipe.d.ts +33 -0
- package/dist/utils/stdin-pipe.js +93 -0
- package/dist/utils/storage-factory.d.ts +50 -0
- package/dist/utils/storage-factory.js +118 -0
- package/dist/utils/storage-maintenance.d.ts +121 -0
- package/dist/utils/storage-maintenance.js +352 -0
- package/dist/utils/thread-lock.d.ts +26 -0
- package/dist/utils/thread-lock.js +109 -0
- package/dist/utils/token-estimator.d.ts +3 -0
- package/dist/utils/token-estimator.js +19 -0
- package/dist/utils/update-check.d.ts +151 -0
- package/dist/utils/update-check.js +430 -0
- package/dist/utils/wake-session.d.ts +44 -0
- package/dist/utils/wake-session.js +83 -0
- package/dist/voice/stt-registry.d.ts +67 -0
- package/dist/voice/stt-registry.js +144 -0
- package/dist/voice/transcribe.d.ts +10 -0
- package/dist/voice/transcribe.js +75 -0
- package/dist/workflows/register-primitives.d.ts +52 -0
- package/dist/workflows/register-primitives.js +40 -0
- package/dist/workflows/service.d.ts +64 -0
- package/dist/workflows/service.js +50 -0
- package/package.json +117 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { extractTrajectoryFromTrace } from "@mastra/core/evals";
|
|
2
|
+
// src/evals/context-builder.ts
|
|
3
|
+
/**
|
|
4
|
+
* Build an evaluation context from a AgentController session.
|
|
5
|
+
*
|
|
6
|
+
* This extracts messages from storage, builds trajectory from trace spans,
|
|
7
|
+
* and packages everything into the format scorers expect.
|
|
8
|
+
*/
|
|
9
|
+
async function buildEvalContext(options) {
|
|
10
|
+
const { controller, session, lastNTurns } = options;
|
|
11
|
+
const threadId = options.threadId ?? session.thread.getId();
|
|
12
|
+
if (!threadId) throw new Error("No thread ID available. Start a session before building eval context.");
|
|
13
|
+
const storage = controller.getMastra()?.getStorage();
|
|
14
|
+
const { inputMessages, systemMessages, outputMessages } = categorizeMessages(await getRawMessages(storage, threadId, lastNTurns));
|
|
15
|
+
const { trajectory, traceId } = await extractSessionTrajectory(storage, threadId);
|
|
16
|
+
const requestContext = buildRequestContext(session, threadId);
|
|
17
|
+
return {
|
|
18
|
+
agentInput: {
|
|
19
|
+
inputMessages,
|
|
20
|
+
rememberedMessages: [],
|
|
21
|
+
systemMessages,
|
|
22
|
+
taggedSystemMessages: {}
|
|
23
|
+
},
|
|
24
|
+
agentOutput: outputMessages,
|
|
25
|
+
trajectory,
|
|
26
|
+
requestContext,
|
|
27
|
+
threadId,
|
|
28
|
+
traceId
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Fetch raw MastraDBMessage[] from memory storage for a thread.
|
|
33
|
+
*/
|
|
34
|
+
async function getRawMessages(storage, threadId, lastNTurns) {
|
|
35
|
+
if (!storage) return [];
|
|
36
|
+
const memoryStore = await storage.getStore("memory");
|
|
37
|
+
if (!memoryStore) return [];
|
|
38
|
+
let messages = (await memoryStore.listMessages({
|
|
39
|
+
threadId,
|
|
40
|
+
perPage: false
|
|
41
|
+
})).messages;
|
|
42
|
+
if (lastNTurns !== void 0 && lastNTurns > 0) messages = trimToLastNTurns(messages, lastNTurns);
|
|
43
|
+
return messages;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Trim messages to the last N user-assistant turn pairs.
|
|
47
|
+
*/
|
|
48
|
+
function trimToLastNTurns(messages, turns) {
|
|
49
|
+
let turnCount = 0;
|
|
50
|
+
let cutoffIndex = 0;
|
|
51
|
+
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user") {
|
|
52
|
+
turnCount++;
|
|
53
|
+
if (turnCount === turns) {
|
|
54
|
+
cutoffIndex = i;
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return messages.slice(cutoffIndex);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Categorize messages into input (user), system, and output (assistant) groups.
|
|
62
|
+
*/
|
|
63
|
+
function categorizeMessages(messages) {
|
|
64
|
+
const inputMessages = [];
|
|
65
|
+
const systemMessages = [];
|
|
66
|
+
const outputMessages = [];
|
|
67
|
+
for (const msg of messages) switch (msg.role) {
|
|
68
|
+
case "user":
|
|
69
|
+
inputMessages.push(msg);
|
|
70
|
+
break;
|
|
71
|
+
case "system":
|
|
72
|
+
systemMessages.push({
|
|
73
|
+
role: "system",
|
|
74
|
+
content: extractTextContent(msg)
|
|
75
|
+
});
|
|
76
|
+
break;
|
|
77
|
+
case "assistant": outputMessages.push(msg);
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
inputMessages,
|
|
81
|
+
systemMessages,
|
|
82
|
+
outputMessages
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Extract plain text content from a MastraDBMessage.
|
|
87
|
+
*/
|
|
88
|
+
function extractTextContent(msg) {
|
|
89
|
+
if (!msg.content?.parts) return "";
|
|
90
|
+
return msg.content.parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join("\n");
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Extract trajectory from trace spans in observability storage.
|
|
94
|
+
* Looks up traces by threadId metadata.
|
|
95
|
+
*/
|
|
96
|
+
async function extractSessionTrajectory(storage, threadId) {
|
|
97
|
+
if (!storage) return {
|
|
98
|
+
trajectory: void 0,
|
|
99
|
+
traceId: void 0
|
|
100
|
+
};
|
|
101
|
+
try {
|
|
102
|
+
const observabilityStore = await storage.getStore("observability");
|
|
103
|
+
if (!observabilityStore) return {
|
|
104
|
+
trajectory: void 0,
|
|
105
|
+
traceId: void 0
|
|
106
|
+
};
|
|
107
|
+
const result = await observabilityStore.listTraces({
|
|
108
|
+
filters: { threadId },
|
|
109
|
+
pagination: {
|
|
110
|
+
page: 0,
|
|
111
|
+
perPage: 1
|
|
112
|
+
},
|
|
113
|
+
orderBy: {
|
|
114
|
+
field: "startedAt",
|
|
115
|
+
direction: "DESC"
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
if (!result?.spans?.length) return {
|
|
119
|
+
trajectory: void 0,
|
|
120
|
+
traceId: void 0
|
|
121
|
+
};
|
|
122
|
+
const traceId = result.spans[0].traceId;
|
|
123
|
+
const trace = await observabilityStore.getTrace({ traceId });
|
|
124
|
+
if (!trace?.spans?.length) return {
|
|
125
|
+
trajectory: void 0,
|
|
126
|
+
traceId
|
|
127
|
+
};
|
|
128
|
+
return {
|
|
129
|
+
trajectory: extractTrajectoryFromTrace(trace.spans),
|
|
130
|
+
traceId
|
|
131
|
+
};
|
|
132
|
+
} catch {
|
|
133
|
+
return {
|
|
134
|
+
trajectory: void 0,
|
|
135
|
+
traceId: void 0
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Build request context from AgentController state for scorer evaluation.
|
|
141
|
+
*/
|
|
142
|
+
function buildRequestContext(session, threadId) {
|
|
143
|
+
const state = session.state.get();
|
|
144
|
+
return {
|
|
145
|
+
threadId,
|
|
146
|
+
mode: state.currentMode ?? state.mode,
|
|
147
|
+
modelId: session.model.get(),
|
|
148
|
+
projectPath: state.projectPath,
|
|
149
|
+
projectName: state.projectName,
|
|
150
|
+
gitBranch: state.gitBranch,
|
|
151
|
+
thinkingLevel: state.thinkingLevel,
|
|
152
|
+
yolo: state.yolo,
|
|
153
|
+
smartEditing: state.smartEditing
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
export { buildEvalContext };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { buildEvalContext } from "./context-builder.js";
|
|
2
|
+
import { createOutcomeScorer } from "./scorers/outcome.js";
|
|
3
|
+
import { createEfficiencyScorer } from "./scorers/efficiency.js";
|
|
4
|
+
import "./scorers/index.js";
|
|
5
|
+
export { buildEvalContext, createEfficiencyScorer, createOutcomeScorer };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared command classification utilities for scoring.
|
|
3
|
+
*
|
|
4
|
+
* Used by scorers to consistently identify build, test, and other command types.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Check if a command string is a build/typecheck command.
|
|
8
|
+
* Handles compound commands (e.g. `pnpm build && pnpm test`) by checking each segment.
|
|
9
|
+
*/
|
|
10
|
+
export declare function isBuildCommand(command: string): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Check if a command string is a test command.
|
|
13
|
+
*/
|
|
14
|
+
export declare function isTestCommand(command: string): boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Extract exit code from an `execute_command` result.
|
|
17
|
+
* Only trusts explicit exitCode/code fields — no heuristic fallbacks.
|
|
18
|
+
*/
|
|
19
|
+
export declare function getExitCode(result: unknown): number | null;
|
|
20
|
+
/**
|
|
21
|
+
* Determine if a tool call result indicates success (exit code 0, no explicit error).
|
|
22
|
+
* Works with both structured result objects and string results.
|
|
23
|
+
*/
|
|
24
|
+
export declare function isSuccessResult(result: unknown, error?: unknown): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Match a file path from tool output against an expected path.
|
|
27
|
+
* Supports exact match and suffix match (e.g. "src/foo.ts" matches "/abs/path/src/foo.ts").
|
|
28
|
+
*/
|
|
29
|
+
export declare function matchFilePath(actual: string, expected: string): boolean;
|
|
30
|
+
//# sourceMappingURL=classify-command.d.ts.map
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// src/evals/scorers/classify-command.ts
|
|
2
|
+
/**
|
|
3
|
+
* Shared command classification utilities for scoring.
|
|
4
|
+
*
|
|
5
|
+
* Used by scorers to consistently identify build, test, and other command types.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Check if a command string is a build/typecheck command.
|
|
9
|
+
* Handles compound commands (e.g. `pnpm build && pnpm test`) by checking each segment.
|
|
10
|
+
*/
|
|
11
|
+
function isBuildCommand(command) {
|
|
12
|
+
return command.split(/\s*(?:&&|\|\||;)\s*/).some((seg) => {
|
|
13
|
+
const trimmed = seg.trim();
|
|
14
|
+
if (!/\b(tsc|typecheck|type-check|build)\b/.test(trimmed)) return false;
|
|
15
|
+
const primaryVerb = trimmed.replace(/^(?:pnpm|npm|yarn|npx|bunx?|turbo)\s+(?:run\s+)?/, "").split(/\s/)[0] ?? "";
|
|
16
|
+
return !/^(test|vitest|jest|mocha|pytest)$/.test(primaryVerb);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Check if a command string is a test command.
|
|
21
|
+
*/
|
|
22
|
+
function isTestCommand(command) {
|
|
23
|
+
return /\b(test|vitest|jest|mocha|pytest|spec)\b/.test(command);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Extract exit code from an `execute_command` result.
|
|
27
|
+
* Only trusts explicit exitCode/code fields — no heuristic fallbacks.
|
|
28
|
+
*/
|
|
29
|
+
function getExitCode(result) {
|
|
30
|
+
if (result == null) return null;
|
|
31
|
+
if (typeof result === "string") {
|
|
32
|
+
const exitMatch = result.match(/(?:^|\n)(?:exit code\s*:?|process exited with code)\s*(-?\d+)\s*$/i);
|
|
33
|
+
if (exitMatch) return parseInt(exitMatch[1], 10);
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
if (typeof result === "object") {
|
|
37
|
+
const obj = result;
|
|
38
|
+
if ("exitCode" in obj && typeof obj.exitCode === "number") return obj.exitCode;
|
|
39
|
+
if ("code" in obj && typeof obj.code === "number") return obj.code;
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Determine if a tool call result indicates success (exit code 0, no explicit error).
|
|
45
|
+
* Works with both structured result objects and string results.
|
|
46
|
+
*/
|
|
47
|
+
function isSuccessResult(result, error) {
|
|
48
|
+
if (error || !result) return false;
|
|
49
|
+
const exitCode = getExitCode(result);
|
|
50
|
+
if (exitCode !== null) return exitCode === 0;
|
|
51
|
+
return typeof result === "string";
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Match a file path from tool output against an expected path.
|
|
55
|
+
* Supports exact match and suffix match (e.g. "src/foo.ts" matches "/abs/path/src/foo.ts").
|
|
56
|
+
*/
|
|
57
|
+
function matchFilePath(actual, expected) {
|
|
58
|
+
if (actual === expected) return true;
|
|
59
|
+
return actual.endsWith(`/${expected}`) || expected.endsWith(`/${actual}`);
|
|
60
|
+
}
|
|
61
|
+
export { getExitCode, isBuildCommand, isSuccessResult, isTestCommand, matchFilePath };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MastraCode Efficiency Scorer (Code-based, Agent type, 30% sampling)
|
|
3
|
+
*
|
|
4
|
+
* Measures how efficiently the agent completes work through quantitative ratios.
|
|
5
|
+
* Unlike the Outcome Scorer (which checks *what* happened), this checks
|
|
6
|
+
* *how much work* it took.
|
|
7
|
+
*
|
|
8
|
+
* This scorer produces a score from 0-1 but also exposes raw metrics in the
|
|
9
|
+
* reason text for trend analysis. The score represents "how cleanly did the
|
|
10
|
+
* agent work?" — not whether it got the right answer.
|
|
11
|
+
*
|
|
12
|
+
* Sampled at 30% because it's slightly more expensive (analyzes message sequences).
|
|
13
|
+
*/
|
|
14
|
+
export declare function createEfficiencyScorer(): import("@mastra/core/evals").MastraScorer<"mastracode-efficiency", import("@mastra/core/evals").ScorerRunInputForAgent, import("@mastra/core/evals").ScorerRunOutputForAgent, Record<"preprocessStepResult", {
|
|
15
|
+
empty: true;
|
|
16
|
+
totalCalls: number;
|
|
17
|
+
totalTurns: number;
|
|
18
|
+
redundancy?: undefined;
|
|
19
|
+
turnCount?: undefined;
|
|
20
|
+
retryEfficiency?: undefined;
|
|
21
|
+
readBeforeEdit?: undefined;
|
|
22
|
+
} | {
|
|
23
|
+
empty: false;
|
|
24
|
+
redundancy: {
|
|
25
|
+
score: number;
|
|
26
|
+
ratio: number;
|
|
27
|
+
detail: string;
|
|
28
|
+
};
|
|
29
|
+
turnCount: {
|
|
30
|
+
score: number;
|
|
31
|
+
detail: string;
|
|
32
|
+
};
|
|
33
|
+
retryEfficiency: {
|
|
34
|
+
score: number;
|
|
35
|
+
detail: string;
|
|
36
|
+
};
|
|
37
|
+
readBeforeEdit: {
|
|
38
|
+
score: number;
|
|
39
|
+
detail: string;
|
|
40
|
+
};
|
|
41
|
+
totalCalls: number;
|
|
42
|
+
totalTurns: number;
|
|
43
|
+
}> & Record<"generateScoreStepResult", number> & Record<"generateReasonStepResult", string>>;
|
|
44
|
+
//# sourceMappingURL=efficiency.d.ts.map
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { extractToolCalls } from "./extract-tools.js";
|
|
2
|
+
import { createScorer, filterRun } from "@mastra/core/evals";
|
|
3
|
+
// src/evals/scorers/efficiency.ts
|
|
4
|
+
/**
|
|
5
|
+
* Dimension weights (must sum to 1.0).
|
|
6
|
+
*
|
|
7
|
+
* - redundancy: Duplicate mutation tool calls with identical args.
|
|
8
|
+
* - turnCount: Total assistant turns to complete the task.
|
|
9
|
+
* - retryEfficiency: How quickly the agent recovers from tool failures.
|
|
10
|
+
* - readBeforeEdit: Whether files are read before being edited.
|
|
11
|
+
*/
|
|
12
|
+
const WEIGHTS = {
|
|
13
|
+
redundancy: .35,
|
|
14
|
+
turnCount: .3,
|
|
15
|
+
retryEfficiency: .2,
|
|
16
|
+
readBeforeEdit: .15
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Scoring thresholds and multipliers.
|
|
20
|
+
*/
|
|
21
|
+
const THRESHOLDS = {
|
|
22
|
+
/** Redundancy ratio below this is considered acceptable (no penalty). */
|
|
23
|
+
redundancyAcceptableRate: .05,
|
|
24
|
+
/** Penalty multiplier applied to redundancy ratio above the acceptable rate. */
|
|
25
|
+
redundancyPenaltyMultiplier: 3,
|
|
26
|
+
/** Turns at or below this is considered normal (score 1.0). */
|
|
27
|
+
turnCountNormalMax: 8,
|
|
28
|
+
/** Penalty per turn beyond the normal maximum (for turns 9–15). */
|
|
29
|
+
turnCountPenaltyPerTurn: .04,
|
|
30
|
+
/** Penalty per turn beyond 15. */
|
|
31
|
+
turnCountExtendedPenaltyPerTurn: .03,
|
|
32
|
+
/** Number of consecutive failures before a retry chain is "excessive". */
|
|
33
|
+
retryExcessiveThreshold: 3,
|
|
34
|
+
/** Tools considered "edit" tools that should be preceded by a read. */
|
|
35
|
+
editTools: ["string_replace_lsp", "ast_smart_edit"],
|
|
36
|
+
/** Tools that satisfy read-before-edit (only `view` truly reads a specific file). */
|
|
37
|
+
readTools: ["view"],
|
|
38
|
+
/** Tools whose repeated identical calls are intentional (idempotent reads). */
|
|
39
|
+
redundancyWhitelist: [
|
|
40
|
+
"view",
|
|
41
|
+
"search_content",
|
|
42
|
+
"find_files",
|
|
43
|
+
"lsp_inspect",
|
|
44
|
+
"web_search",
|
|
45
|
+
"web_extract"
|
|
46
|
+
],
|
|
47
|
+
/** Minimum tool calls required to produce a meaningful score. */
|
|
48
|
+
minToolCalls: 2
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Count assistant turns (messages with role === 'assistant').
|
|
52
|
+
*/
|
|
53
|
+
function countAssistantTurns(messages) {
|
|
54
|
+
return messages.filter((m) => m.role === "assistant").length;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Calculate redundant call ratio.
|
|
58
|
+
* Only counts mutation/action tools as redundant — reads are whitelisted.
|
|
59
|
+
*/
|
|
60
|
+
function scoreRedundancy(calls) {
|
|
61
|
+
if (calls.length < 2) return {
|
|
62
|
+
score: 1,
|
|
63
|
+
ratio: 0,
|
|
64
|
+
detail: "Too few calls"
|
|
65
|
+
};
|
|
66
|
+
const mutationCalls = calls.filter((c) => !THRESHOLDS.redundancyWhitelist.includes(c.toolName));
|
|
67
|
+
if (mutationCalls.length < 2) return {
|
|
68
|
+
score: 1,
|
|
69
|
+
ratio: 0,
|
|
70
|
+
detail: "No mutation tools to check"
|
|
71
|
+
};
|
|
72
|
+
const fingerprints = /* @__PURE__ */ new Map();
|
|
73
|
+
for (const call of mutationCalls) {
|
|
74
|
+
const fp = `${call.toolName}:${JSON.stringify(call.args)}`;
|
|
75
|
+
const existing = fingerprints.get(fp) ?? {
|
|
76
|
+
count: 0,
|
|
77
|
+
successCount: 0
|
|
78
|
+
};
|
|
79
|
+
existing.count++;
|
|
80
|
+
if (!call.isError) existing.successCount++;
|
|
81
|
+
fingerprints.set(fp, existing);
|
|
82
|
+
}
|
|
83
|
+
let redundantCount = 0;
|
|
84
|
+
for (const { successCount } of fingerprints.values()) if (successCount > 1) redundantCount += successCount - 1;
|
|
85
|
+
const ratio = redundantCount / mutationCalls.length;
|
|
86
|
+
const acceptable = THRESHOLDS.redundancyAcceptableRate;
|
|
87
|
+
return {
|
|
88
|
+
score: ratio <= acceptable ? 1 : Math.max(0, 1 - (ratio - acceptable) * THRESHOLDS.redundancyPenaltyMultiplier),
|
|
89
|
+
ratio,
|
|
90
|
+
detail: `${redundantCount}/${mutationCalls.length} redundant mutations (${(ratio * 100).toFixed(0)}%)`
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Score turn count efficiency.
|
|
95
|
+
* Fewer turns to accomplish the task = more efficient.
|
|
96
|
+
*/
|
|
97
|
+
function scoreTurnCount(turns) {
|
|
98
|
+
const normalMax = THRESHOLDS.turnCountNormalMax;
|
|
99
|
+
const penaltyPerTurn = THRESHOLDS.turnCountPenaltyPerTurn;
|
|
100
|
+
const extendedPenalty = THRESHOLDS.turnCountExtendedPenaltyPerTurn;
|
|
101
|
+
if (turns <= 1) return {
|
|
102
|
+
score: 1,
|
|
103
|
+
detail: `${turns} turn`
|
|
104
|
+
};
|
|
105
|
+
if (turns <= normalMax) return {
|
|
106
|
+
score: 1,
|
|
107
|
+
detail: `${turns} turns (within normal range)`
|
|
108
|
+
};
|
|
109
|
+
if (turns <= 15) return {
|
|
110
|
+
score: 1 - (turns - normalMax) * penaltyPerTurn,
|
|
111
|
+
detail: `${turns} turns (slightly extended)`
|
|
112
|
+
};
|
|
113
|
+
const midPenalty = (15 - normalMax) * penaltyPerTurn;
|
|
114
|
+
return {
|
|
115
|
+
score: Math.max(0, 1 - midPenalty - (turns - 15) * extendedPenalty),
|
|
116
|
+
detail: `${turns} turns (extended session)`
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Score failed-then-succeeded ratio.
|
|
121
|
+
* Groups retry chains by tool name + target file path for more accurate detection.
|
|
122
|
+
*/
|
|
123
|
+
function scoreRetryEfficiency(calls) {
|
|
124
|
+
if (calls.length < 2) return {
|
|
125
|
+
score: 1,
|
|
126
|
+
detail: "Too few calls"
|
|
127
|
+
};
|
|
128
|
+
const groupKey = (call) => {
|
|
129
|
+
const path = String(call.args.path ?? call.args.command ?? "");
|
|
130
|
+
return `${call.toolName}:${path}`;
|
|
131
|
+
};
|
|
132
|
+
const byGroup = /* @__PURE__ */ new Map();
|
|
133
|
+
for (const call of calls) {
|
|
134
|
+
const key = groupKey(call);
|
|
135
|
+
const arr = byGroup.get(key) ?? [];
|
|
136
|
+
arr.push(call);
|
|
137
|
+
byGroup.set(key, arr);
|
|
138
|
+
}
|
|
139
|
+
let totalRetryChains = 0;
|
|
140
|
+
let excessiveRetries = 0;
|
|
141
|
+
const threshold = THRESHOLDS.retryExcessiveThreshold;
|
|
142
|
+
for (const [, toolCalls] of byGroup) {
|
|
143
|
+
let consecutiveFailures = 0;
|
|
144
|
+
for (const call of toolCalls) if (call.isError) consecutiveFailures++;
|
|
145
|
+
else {
|
|
146
|
+
if (consecutiveFailures > 0) {
|
|
147
|
+
totalRetryChains++;
|
|
148
|
+
if (consecutiveFailures >= threshold) excessiveRetries++;
|
|
149
|
+
}
|
|
150
|
+
consecutiveFailures = 0;
|
|
151
|
+
}
|
|
152
|
+
if (consecutiveFailures > 0) {
|
|
153
|
+
totalRetryChains++;
|
|
154
|
+
if (consecutiveFailures >= threshold) excessiveRetries++;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (totalRetryChains === 0) return {
|
|
158
|
+
score: 1,
|
|
159
|
+
detail: "No retry chains"
|
|
160
|
+
};
|
|
161
|
+
if (excessiveRetries === 0) return {
|
|
162
|
+
score: .9,
|
|
163
|
+
detail: `${totalRetryChains} retry chain(s), all resolved quickly`
|
|
164
|
+
};
|
|
165
|
+
return {
|
|
166
|
+
score: Math.max(0, .8 - excessiveRetries * .2),
|
|
167
|
+
detail: `${excessiveRetries} excessive retry chain(s) (${threshold}+ failures before success)`
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Score read-before-edit compliance.
|
|
172
|
+
* Only `view` satisfies a read — search/find don't provide specific file content.
|
|
173
|
+
*/
|
|
174
|
+
function scoreReadBeforeEdit(calls) {
|
|
175
|
+
const editTools = THRESHOLDS.editTools;
|
|
176
|
+
const readTools = THRESHOLDS.readTools;
|
|
177
|
+
if (calls.filter((c) => editTools.includes(c.toolName)).length === 0) return {
|
|
178
|
+
score: 1,
|
|
179
|
+
detail: "No edits to check"
|
|
180
|
+
};
|
|
181
|
+
const readPaths = /* @__PURE__ */ new Set();
|
|
182
|
+
let compliant = 0;
|
|
183
|
+
let total = 0;
|
|
184
|
+
for (const call of calls) {
|
|
185
|
+
const rawPath = String(call.args.path ?? "");
|
|
186
|
+
if (!rawPath) continue;
|
|
187
|
+
if (readTools.includes(call.toolName)) readPaths.add(rawPath);
|
|
188
|
+
else if (editTools.includes(call.toolName)) {
|
|
189
|
+
total++;
|
|
190
|
+
if (hasReadPath(readPaths, rawPath)) compliant++;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (total === 0) return {
|
|
194
|
+
score: 1,
|
|
195
|
+
detail: "No path-targeted edits"
|
|
196
|
+
};
|
|
197
|
+
const ratio = compliant / total;
|
|
198
|
+
const violations = total - compliant;
|
|
199
|
+
if (violations === 0) return {
|
|
200
|
+
score: 1,
|
|
201
|
+
detail: `All ${total} edits had prior reads`
|
|
202
|
+
};
|
|
203
|
+
return {
|
|
204
|
+
score: ratio,
|
|
205
|
+
detail: `${violations}/${total} edits without prior read`
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
/** Check if any read path matches the edit path, using suffix matching for mixed abs/relative paths. */
|
|
209
|
+
function hasReadPath(readPaths, editPath) {
|
|
210
|
+
if (readPaths.has(editPath)) return true;
|
|
211
|
+
for (const rp of readPaths) if (rp.endsWith(`/${editPath}`) || editPath.endsWith(`/${rp}`)) return true;
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
function createEfficiencyScorer() {
|
|
215
|
+
return createScorer({
|
|
216
|
+
id: "mastracode-efficiency",
|
|
217
|
+
name: "MastraCode Efficiency",
|
|
218
|
+
description: "Measures coding session efficiency: redundancy, turn count, retry patterns, read-before-edit. 30% sampled.",
|
|
219
|
+
type: "agent",
|
|
220
|
+
prepareRun: filterRun({ partTypes: ["tool-invocation", "text"] })
|
|
221
|
+
}).preprocess(async ({ run }) => {
|
|
222
|
+
const messages = run.output ?? [];
|
|
223
|
+
const calls = extractToolCalls(messages);
|
|
224
|
+
const turns = countAssistantTurns(messages);
|
|
225
|
+
if (calls.length < THRESHOLDS.minToolCalls) return {
|
|
226
|
+
empty: true,
|
|
227
|
+
totalCalls: calls.length,
|
|
228
|
+
totalTurns: turns
|
|
229
|
+
};
|
|
230
|
+
return {
|
|
231
|
+
empty: false,
|
|
232
|
+
redundancy: scoreRedundancy(calls),
|
|
233
|
+
turnCount: scoreTurnCount(turns),
|
|
234
|
+
retryEfficiency: scoreRetryEfficiency(calls),
|
|
235
|
+
readBeforeEdit: scoreReadBeforeEdit(calls),
|
|
236
|
+
totalCalls: calls.length,
|
|
237
|
+
totalTurns: turns
|
|
238
|
+
};
|
|
239
|
+
}).generateScore(({ results }) => {
|
|
240
|
+
const p = results.preprocessStepResult;
|
|
241
|
+
if (p.empty) return 0;
|
|
242
|
+
const score = p.redundancy.score * WEIGHTS.redundancy + p.turnCount.score * WEIGHTS.turnCount + p.retryEfficiency.score * WEIGHTS.retryEfficiency + p.readBeforeEdit.score * WEIGHTS.readBeforeEdit;
|
|
243
|
+
return Math.round(score * 100) / 100;
|
|
244
|
+
}).generateReason(({ results, score }) => {
|
|
245
|
+
const p = results.preprocessStepResult;
|
|
246
|
+
if (p.empty) return `Score: 0 (${p.totalCalls} tool calls — below minimum threshold for scoring)`;
|
|
247
|
+
const pct = (w) => `${(w * 100).toFixed(0)}%`;
|
|
248
|
+
const parts = [`Score: ${score} (${p.totalCalls} calls, ${p.totalTurns} turns)`];
|
|
249
|
+
parts.push(`Redundancy (${pct(WEIGHTS.redundancy)}): ${p.redundancy.detail} [${p.redundancy.score}]`);
|
|
250
|
+
parts.push(`Turn count (${pct(WEIGHTS.turnCount)}): ${p.turnCount.detail} [${p.turnCount.score}]`);
|
|
251
|
+
parts.push(`Retry efficiency (${pct(WEIGHTS.retryEfficiency)}): ${p.retryEfficiency.detail} [${p.retryEfficiency.score}]`);
|
|
252
|
+
parts.push(`Read-before-edit (${pct(WEIGHTS.readBeforeEdit)}): ${p.readBeforeEdit.detail} [${p.readBeforeEdit.score}]`);
|
|
253
|
+
return parts.join("\n");
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
export { createEfficiencyScorer };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared tool invocation extraction from MastraDBMessages.
|
|
3
|
+
*
|
|
4
|
+
* Used by both the Outcome and Efficiency scorers to extract completed
|
|
5
|
+
* tool calls from message content, handling both the `parts` array (primary)
|
|
6
|
+
* and the legacy `toolInvocations` array.
|
|
7
|
+
*/
|
|
8
|
+
import type { MastraDBMessage } from '@mastra/core/agent';
|
|
9
|
+
export type ExtractedToolCall = {
|
|
10
|
+
toolCallId?: string;
|
|
11
|
+
toolName: string;
|
|
12
|
+
args: Record<string, unknown>;
|
|
13
|
+
result: unknown;
|
|
14
|
+
isError: boolean;
|
|
15
|
+
index: number;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Extract completed tool invocations from MastraDBMessages.
|
|
19
|
+
*
|
|
20
|
+
* Handles both:
|
|
21
|
+
* - `content.parts` (primary format, MastraToolInvocationPart)
|
|
22
|
+
* - `content.toolInvocations` (legacy format, AI SDK ToolInvocation[])
|
|
23
|
+
*/
|
|
24
|
+
export declare function extractToolCalls(messages: MastraDBMessage[]): ExtractedToolCall[];
|
|
25
|
+
//# sourceMappingURL=extract-tools.d.ts.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// src/evals/scorers/extract-tools.ts
|
|
2
|
+
function isToolInvocationPart(part) {
|
|
3
|
+
return "type" in part && part.type === "tool-invocation" && "toolInvocation" in part;
|
|
4
|
+
}
|
|
5
|
+
function isCompleted(inv) {
|
|
6
|
+
return inv.state === "result" || inv.state === "error" || inv.state === "output-error" || inv.state === "output-denied";
|
|
7
|
+
}
|
|
8
|
+
function isErrorState(inv) {
|
|
9
|
+
return inv.state === "error" || inv.state === "output-error" || inv.state === "output-denied";
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Extract completed tool invocations from MastraDBMessages.
|
|
13
|
+
*
|
|
14
|
+
* Handles both:
|
|
15
|
+
* - `content.parts` (primary format, MastraToolInvocationPart)
|
|
16
|
+
* - `content.toolInvocations` (legacy format, AI SDK ToolInvocation[])
|
|
17
|
+
*/
|
|
18
|
+
function extractToolCalls(messages) {
|
|
19
|
+
const results = [];
|
|
20
|
+
const seenToolCallIds = /* @__PURE__ */ new Set();
|
|
21
|
+
let index = 0;
|
|
22
|
+
for (const msg of messages) {
|
|
23
|
+
if (!msg.content) continue;
|
|
24
|
+
for (const part of msg.content.parts ?? []) if (isToolInvocationPart(part)) {
|
|
25
|
+
const inv = part.toolInvocation;
|
|
26
|
+
if (isCompleted(inv)) {
|
|
27
|
+
const toolCallId = "toolCallId" in inv ? inv.toolCallId : void 0;
|
|
28
|
+
if (toolCallId) seenToolCallIds.add(toolCallId);
|
|
29
|
+
results.push({
|
|
30
|
+
toolCallId,
|
|
31
|
+
toolName: inv.toolName ?? "",
|
|
32
|
+
args: inv.args ?? {},
|
|
33
|
+
result: inv.result,
|
|
34
|
+
isError: isErrorState(inv),
|
|
35
|
+
index: index++
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (msg.content.toolInvocations) {
|
|
40
|
+
for (const inv of msg.content.toolInvocations) if (inv.state === "result") {
|
|
41
|
+
const toolCallId = "toolCallId" in inv ? inv.toolCallId : void 0;
|
|
42
|
+
if (toolCallId && seenToolCallIds.has(toolCallId)) continue;
|
|
43
|
+
if (toolCallId) seenToolCallIds.add(toolCallId);
|
|
44
|
+
results.push({
|
|
45
|
+
toolCallId,
|
|
46
|
+
toolName: inv.toolName ?? "",
|
|
47
|
+
args: inv.args ?? {},
|
|
48
|
+
result: inv.result,
|
|
49
|
+
isError: false,
|
|
50
|
+
index: index++
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return results;
|
|
56
|
+
}
|
|
57
|
+
export { extractToolCalls };
|