@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,39 @@
|
|
|
1
|
+
// src/headless/policy.ts
|
|
2
|
+
/**
|
|
3
|
+
* Default policy — reproduces the historical headless behavior:
|
|
4
|
+
* - approve every tool approval request,
|
|
5
|
+
* - auto-approve `request_access` / sandbox access suspensions ("Yes"),
|
|
6
|
+
* - auto-approve `submit_plan` suspensions (`{ action: 'approved' }`),
|
|
7
|
+
* - answer any other suspension with a "use your best judgment" instruction.
|
|
8
|
+
*/
|
|
9
|
+
const autoApprovePolicy = {
|
|
10
|
+
onToolApproval(_event) {
|
|
11
|
+
return "approve";
|
|
12
|
+
},
|
|
13
|
+
onSuspension(event) {
|
|
14
|
+
const payload = event.suspendPayload ?? {};
|
|
15
|
+
if (event.toolName === "request_access" || payload.kind === "sandbox_access_request") return { resumeData: "Yes" };
|
|
16
|
+
if (event.toolName === "submit_plan") return { resumeData: { action: "approved" } };
|
|
17
|
+
return { resumeData: "Proceed with your best judgment. Do not ask further questions." };
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Strict policy — refuses every tool approval and aborts on any suspension.
|
|
22
|
+
* Useful for CI gating where unattended tool execution must not happen.
|
|
23
|
+
*/
|
|
24
|
+
const denyPolicy = {
|
|
25
|
+
onToolApproval(_event) {
|
|
26
|
+
return "deny";
|
|
27
|
+
},
|
|
28
|
+
onSuspension(_event) {
|
|
29
|
+
return { abort: true };
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
/** Resolve a named {@link PermissionMode} to its built-in {@link ResolutionPolicy}. */
|
|
33
|
+
function permissionModeToPolicy(mode) {
|
|
34
|
+
switch (mode) {
|
|
35
|
+
case "deny": return denyPolicy;
|
|
36
|
+
default: return autoApprovePolicy;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export { autoApprovePolicy, denyPolicy, permissionModeToPolicy };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { MCRun, RunMCOptions } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Run a headless MastraCode turn. Returns an {@link MCRun} handle that is
|
|
4
|
+
* async-iterable over controller events and resolves to a {@link RunMCResult}.
|
|
5
|
+
*/
|
|
6
|
+
export declare function runMC<TState extends Record<string, unknown>>(options: RunMCOptions<TState>): MCRun;
|
|
7
|
+
//# sourceMappingURL=run-mc.d.ts.map
|
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
import { MODEL_FALLBACK_STATE_KEY } from "../auth/account-rotation-processor.js";
|
|
2
|
+
import { GoalManager } from "../goal-manager.js";
|
|
3
|
+
import { createGoalReminderSignal } from "../goal-signal.js";
|
|
4
|
+
import { THREAD_ACTIVE_MODEL_PACK_ID_KEY } from "../onboarding/settings.js";
|
|
5
|
+
import { parseCodexModelSelection } from "../providers/model-ids.js";
|
|
6
|
+
import { autoApprovePolicy } from "./policy.js";
|
|
7
|
+
import { isSessionStartupCancelledError } from "@mastra/core/agent-controller";
|
|
8
|
+
// src/headless/run-mc.ts
|
|
9
|
+
/**
|
|
10
|
+
* Core programmatic runner for MastraCode headless runs.
|
|
11
|
+
*
|
|
12
|
+
* `runMC` is a pure async runner: it takes an already-built `controller` +
|
|
13
|
+
* `session` (from `createMastraCode(...)`), resolves run config, subscribes to
|
|
14
|
+
* the session, applies a {@link ResolutionPolicy} for approvals/suspensions,
|
|
15
|
+
* sends the prompt, and aggregates events into a {@link RunMCResult}.
|
|
16
|
+
*
|
|
17
|
+
* It never touches `process.*` and never calls `process.exit`. The returned
|
|
18
|
+
* {@link MCRun} is async-iterable over controller events and also resolves to a
|
|
19
|
+
* final result via `result`.
|
|
20
|
+
*/
|
|
21
|
+
function exitCodeForStatus(status) {
|
|
22
|
+
switch (status) {
|
|
23
|
+
case "completed":
|
|
24
|
+
case "done": return 0;
|
|
25
|
+
case "timeout": return 2;
|
|
26
|
+
default: return 1;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function aggregate(event, acc) {
|
|
30
|
+
switch (event.type) {
|
|
31
|
+
case "message_start":
|
|
32
|
+
if (event.message.role === "assistant") acc.activeAssistantMessageId = event.message.id;
|
|
33
|
+
break;
|
|
34
|
+
case "message_update":
|
|
35
|
+
if (event.event.type === "text-delta" && event.id === acc.activeAssistantMessageId) acc.text += event.event.delta;
|
|
36
|
+
break;
|
|
37
|
+
case "message_end":
|
|
38
|
+
if (event.id === acc.activeAssistantMessageId) acc.activeAssistantMessageId = void 0;
|
|
39
|
+
break;
|
|
40
|
+
case "tool_start":
|
|
41
|
+
acc.toolCalls.push({
|
|
42
|
+
id: event.toolCallId,
|
|
43
|
+
name: event.toolName,
|
|
44
|
+
args: event.args
|
|
45
|
+
});
|
|
46
|
+
break;
|
|
47
|
+
case "tool_end": {
|
|
48
|
+
const matching = acc.toolCalls.find((c) => c.id === event.toolCallId);
|
|
49
|
+
acc.toolResults.push({
|
|
50
|
+
id: event.toolCallId,
|
|
51
|
+
name: matching?.name ?? "",
|
|
52
|
+
result: event.result,
|
|
53
|
+
isError: event.isError
|
|
54
|
+
});
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
case "usage_update":
|
|
58
|
+
acc.usage = {
|
|
59
|
+
inputTokens: (acc.usage?.inputTokens ?? 0) + event.usage.promptTokens,
|
|
60
|
+
outputTokens: (acc.usage?.outputTokens ?? 0) + event.usage.completionTokens,
|
|
61
|
+
totalTokens: (acc.usage?.totalTokens ?? 0) + event.usage.totalTokens
|
|
62
|
+
};
|
|
63
|
+
break;
|
|
64
|
+
case "error": acc.error = {
|
|
65
|
+
name: event.error.name,
|
|
66
|
+
message: event.error.message,
|
|
67
|
+
stack: event.error.stack
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** Resolve a thread by its exact ID. Titles are not unique, so we don't match on them. */
|
|
72
|
+
async function resolveThread(session, threadId, resourceId) {
|
|
73
|
+
const byId = (await session.thread.list(resourceId ? { allResources: true } : void 0)).find((thread) => thread.id === threadId && (!resourceId || thread.resourceId === resourceId));
|
|
74
|
+
if (byId) return { threadId: byId.id };
|
|
75
|
+
return { error: `No thread found with ID "${threadId}"` };
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* A simple back-pressured async queue. Events are pushed in; consumers pull via
|
|
79
|
+
* the async iterator. `close()` ends iteration after draining buffered events.
|
|
80
|
+
*
|
|
81
|
+
* Buffered events are bounded by `maxBuffer`: if a consumer never iterates (the
|
|
82
|
+
* result-only path, `await run.result` without `for await (...)`) — or simply
|
|
83
|
+
* falls far behind — the oldest buffered events are dropped instead of growing
|
|
84
|
+
* without limit. The aggregated {@link RunMCResult} is built independently of
|
|
85
|
+
* this queue, so dropping buffered events never affects the final result.
|
|
86
|
+
*/
|
|
87
|
+
var EventQueue = class {
|
|
88
|
+
#buffer = [];
|
|
89
|
+
#resolvers = [];
|
|
90
|
+
#closed = false;
|
|
91
|
+
#maxBuffer;
|
|
92
|
+
constructor(maxBuffer = 1e4) {
|
|
93
|
+
this.#maxBuffer = maxBuffer;
|
|
94
|
+
}
|
|
95
|
+
push(value) {
|
|
96
|
+
if (this.#closed) return;
|
|
97
|
+
const resolve = this.#resolvers.shift();
|
|
98
|
+
if (resolve) {
|
|
99
|
+
resolve({
|
|
100
|
+
value,
|
|
101
|
+
done: false
|
|
102
|
+
});
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
this.#buffer.push(value);
|
|
106
|
+
if (this.#buffer.length > this.#maxBuffer) this.#buffer.shift();
|
|
107
|
+
}
|
|
108
|
+
close() {
|
|
109
|
+
if (this.#closed) return;
|
|
110
|
+
this.#closed = true;
|
|
111
|
+
for (const resolve of this.#resolvers.splice(0)) resolve({
|
|
112
|
+
value: void 0,
|
|
113
|
+
done: true
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
[Symbol.asyncIterator]() {
|
|
117
|
+
return { next: () => {
|
|
118
|
+
if (this.#buffer.length > 0) return Promise.resolve({
|
|
119
|
+
value: this.#buffer.shift(),
|
|
120
|
+
done: false
|
|
121
|
+
});
|
|
122
|
+
if (this.#closed) return Promise.resolve({
|
|
123
|
+
value: void 0,
|
|
124
|
+
done: true
|
|
125
|
+
});
|
|
126
|
+
return new Promise((resolve) => this.#resolvers.push(resolve));
|
|
127
|
+
} };
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Run a headless MastraCode turn. Returns an {@link MCRun} handle that is
|
|
132
|
+
* async-iterable over controller events and resolves to a {@link RunMCResult}.
|
|
133
|
+
*/
|
|
134
|
+
function runMC(options) {
|
|
135
|
+
const { controller, session } = options;
|
|
136
|
+
const goal = options.goal;
|
|
137
|
+
const policy = options.policy ?? autoApprovePolicy;
|
|
138
|
+
const queue = new EventQueue();
|
|
139
|
+
const acc = {
|
|
140
|
+
text: "",
|
|
141
|
+
toolCalls: [],
|
|
142
|
+
toolResults: []
|
|
143
|
+
};
|
|
144
|
+
let timeoutId;
|
|
145
|
+
let timedOut = false;
|
|
146
|
+
let aborted = false;
|
|
147
|
+
let maxTurnsExceeded = false;
|
|
148
|
+
let assistantTurns = 0;
|
|
149
|
+
let activeAssistantMessageId;
|
|
150
|
+
let settled = false;
|
|
151
|
+
let agentStarts = 0;
|
|
152
|
+
let unsubscribe;
|
|
153
|
+
let resolveResult;
|
|
154
|
+
const result = new Promise((resolve) => {
|
|
155
|
+
resolveResult = resolve;
|
|
156
|
+
});
|
|
157
|
+
function finish(status, data = {}) {
|
|
158
|
+
if (settled) return;
|
|
159
|
+
settled = true;
|
|
160
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
161
|
+
unsubscribe?.();
|
|
162
|
+
queue.close();
|
|
163
|
+
resolveResult({
|
|
164
|
+
status,
|
|
165
|
+
text: acc.text,
|
|
166
|
+
finishReason: acc.finishReason,
|
|
167
|
+
usage: acc.usage,
|
|
168
|
+
toolCalls: acc.toolCalls,
|
|
169
|
+
toolResults: acc.toolResults,
|
|
170
|
+
threadId: acc.threadId ?? session.thread.getId() ?? void 0,
|
|
171
|
+
error: acc.error,
|
|
172
|
+
exitCode: exitCodeForStatus(status),
|
|
173
|
+
...data
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
function fail(message, name = "Error") {
|
|
177
|
+
if (!acc.error) acc.error = {
|
|
178
|
+
name,
|
|
179
|
+
message
|
|
180
|
+
};
|
|
181
|
+
finish("error");
|
|
182
|
+
}
|
|
183
|
+
function failUnresolvedSuspension(toolName) {
|
|
184
|
+
fail(`Run ended with an unresolved ${toolName ? `${toolName} suspension` : "tool suspension"}.`);
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Ask the policy for the next parked tool. The session starts a fresh
|
|
188
|
+
* run for it, so this run stays open until that run ends. Returns false when
|
|
189
|
+
* nothing is left to resume.
|
|
190
|
+
*/
|
|
191
|
+
function resumeNextSuspension() {
|
|
192
|
+
const next = session.displayState.get().pendingSuspensions.values().next();
|
|
193
|
+
if (next.done) return false;
|
|
194
|
+
const { toolCallId, toolName } = next.value;
|
|
195
|
+
let outcome;
|
|
196
|
+
try {
|
|
197
|
+
outcome = policy.onSuspension({
|
|
198
|
+
type: "tool_suspended",
|
|
199
|
+
...next.value
|
|
200
|
+
});
|
|
201
|
+
} catch (err) {
|
|
202
|
+
fail(`Resolution policy failed: ${err.message}`);
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
if ("abort" in outcome) {
|
|
206
|
+
abort();
|
|
207
|
+
finish("aborted");
|
|
208
|
+
return true;
|
|
209
|
+
}
|
|
210
|
+
const { resumeData } = outcome;
|
|
211
|
+
setTimeout(() => {
|
|
212
|
+
if (settled) return;
|
|
213
|
+
if (timedOut) return finish("timeout");
|
|
214
|
+
if (aborted) return finish("aborted");
|
|
215
|
+
const startsBeforeResume = agentStarts;
|
|
216
|
+
session.respondToToolSuspension({
|
|
217
|
+
toolCallId,
|
|
218
|
+
resumeData
|
|
219
|
+
}).then(() => {
|
|
220
|
+
if (!settled && agentStarts === startsBeforeResume) failUnresolvedSuspension(toolName);
|
|
221
|
+
}, (err) => fail(`Failed to resume ${toolName}: ${err.message}`));
|
|
222
|
+
}, 0);
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
function abort() {
|
|
226
|
+
if (settled) return;
|
|
227
|
+
aborted = true;
|
|
228
|
+
session.abort();
|
|
229
|
+
}
|
|
230
|
+
if (options.signal) {
|
|
231
|
+
if (options.signal.aborted) queueMicrotask(() => abort());
|
|
232
|
+
else options.signal.addEventListener("abort", () => abort(), { once: true });
|
|
233
|
+
}
|
|
234
|
+
function armTimeout() {
|
|
235
|
+
if (!options.timeoutMs || settled) return;
|
|
236
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
237
|
+
timeoutId = setTimeout(() => {
|
|
238
|
+
timedOut = true;
|
|
239
|
+
session.abort();
|
|
240
|
+
if (goal) finish("timeout");
|
|
241
|
+
}, options.timeoutMs);
|
|
242
|
+
}
|
|
243
|
+
(async () => {
|
|
244
|
+
armTimeout();
|
|
245
|
+
unsubscribe = session.subscribe((event) => {
|
|
246
|
+
if (settled) return;
|
|
247
|
+
if (event.type === "agent_start") agentStarts += 1;
|
|
248
|
+
if (goal) armTimeout();
|
|
249
|
+
if (event.type === "tool_approval_required") {
|
|
250
|
+
let decision;
|
|
251
|
+
try {
|
|
252
|
+
decision = policy.onToolApproval(event);
|
|
253
|
+
} catch (err) {
|
|
254
|
+
fail(`Resolution policy failed: ${err.message}`);
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
session.respondToToolApproval({
|
|
258
|
+
decision: decision === "approve" ? "approve" : "decline",
|
|
259
|
+
toolCallId: event.toolCallId
|
|
260
|
+
});
|
|
261
|
+
queue.push(event);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (event.type === "message_start" && event.message.role === "assistant") activeAssistantMessageId = event.message.id;
|
|
265
|
+
aggregate(event, acc);
|
|
266
|
+
queue.push(event);
|
|
267
|
+
if (event.type === "error" && goal) {
|
|
268
|
+
finish("error");
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (event.type === "message_end" && event.id === activeAssistantMessageId && options.maxTurns !== void 0) {
|
|
272
|
+
activeAssistantMessageId = void 0;
|
|
273
|
+
assistantTurns += 1;
|
|
274
|
+
if (assistantTurns >= options.maxTurns && !maxTurnsExceeded) {
|
|
275
|
+
maxTurnsExceeded = true;
|
|
276
|
+
abort();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (event.type === "goal_evaluation" && goal && !event.payload.pending) {
|
|
280
|
+
if (event.payload.status === "done" || event.payload.status === "paused") finish(event.payload.status, {
|
|
281
|
+
objective: goal.objective,
|
|
282
|
+
goalEvent: event,
|
|
283
|
+
reason: event.payload.reason ?? event.payload.results?.[0]?.reason,
|
|
284
|
+
iterations: event.payload.iteration,
|
|
285
|
+
maxRuns: event.payload.maxRuns
|
|
286
|
+
});
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
if (event.type === "agent_end") {
|
|
290
|
+
acc.finishReason = event.reason;
|
|
291
|
+
if (event.reason === "suspended" && !timedOut && !aborted) {
|
|
292
|
+
if (!resumeNextSuspension()) failUnresolvedSuspension();
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (goal) return;
|
|
296
|
+
if (timedOut) finish("timeout");
|
|
297
|
+
else if (event.reason === "error") finish("error");
|
|
298
|
+
else if (maxTurnsExceeded && event.reason !== "complete") finish("max_turns");
|
|
299
|
+
else if ((event.reason === "aborted" || aborted) && !maxTurnsExceeded) finish("aborted");
|
|
300
|
+
else finish("completed");
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
const thread = options.thread;
|
|
304
|
+
const targetResourceId = options.resourceId ?? session.identity.getResourceId();
|
|
305
|
+
let restoredThreadId;
|
|
306
|
+
try {
|
|
307
|
+
if (thread?.id) {
|
|
308
|
+
const resolved = await resolveThread(session, thread.id, targetResourceId);
|
|
309
|
+
if ("error" in resolved) return fail(resolved.error);
|
|
310
|
+
restoredThreadId = resolved.threadId;
|
|
311
|
+
} else if (thread?.continueLatest) {
|
|
312
|
+
const threads = await session.thread.list(targetResourceId ? { allResources: true } : void 0);
|
|
313
|
+
const resourceThreads = targetResourceId ? threads.filter((candidate) => candidate.resourceId === targetResourceId) : threads;
|
|
314
|
+
if (resourceThreads.length > 0) restoredThreadId = [...resourceThreads].sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0].id;
|
|
315
|
+
}
|
|
316
|
+
} catch (err) {
|
|
317
|
+
return fail(`Failed to resolve thread: ${err.message}`);
|
|
318
|
+
}
|
|
319
|
+
const restoredThreadSelection = Boolean(restoredThreadId || thread?.clone);
|
|
320
|
+
const modeIdForModel = options.mode ?? (options.modeDefaults ? session.mode.get() : void 0);
|
|
321
|
+
const configuredDefaultModelId = modeIdForModel ? options.modeDefaults?.[modeIdForModel] : void 0;
|
|
322
|
+
const modelIdToApply = options.pack ? options.model : options.model ?? (options.mode || !restoredThreadSelection ? configuredDefaultModelId : void 0);
|
|
323
|
+
const modelSource = options.model ? "flag" : "mode";
|
|
324
|
+
try {
|
|
325
|
+
if (options.mode && !controller.listModes().some((mode) => mode.id === options.mode)) return fail(`Unknown mode: "${options.mode}"`);
|
|
326
|
+
if (modelIdToApply) {
|
|
327
|
+
const available = await controller.listAvailableModels();
|
|
328
|
+
const { modelId } = parseCodexModelSelection(modelIdToApply);
|
|
329
|
+
const match = available.find((model) => model.id === modelId);
|
|
330
|
+
if (!match) {
|
|
331
|
+
if (modelSource === "flag") return fail(`Unknown model: "${modelIdToApply}"`);
|
|
332
|
+
return fail(`Unknown model "${modelIdToApply}" configured for mode "${modeIdForModel}"`);
|
|
333
|
+
}
|
|
334
|
+
if (!match.hasApiKey) {
|
|
335
|
+
const keyHint = match.apiKeyEnvVar ? ` Set ${match.apiKeyEnvVar} to use this model.` : "";
|
|
336
|
+
if (modelSource === "flag") return fail(`Model "${modelIdToApply}" has no API key configured.${keyHint}`);
|
|
337
|
+
return fail(`Model "${modelIdToApply}" (mode: ${modeIdForModel}) has no API key configured.${keyHint}`);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
} catch (err) {
|
|
341
|
+
return fail(`Failed to resolve run config: ${err.message}`);
|
|
342
|
+
}
|
|
343
|
+
try {
|
|
344
|
+
if (options.resourceId) await controller.setResourceId(session, { resourceId: options.resourceId });
|
|
345
|
+
} catch (err) {
|
|
346
|
+
return fail(`Failed to set resource id: ${err.message}`);
|
|
347
|
+
}
|
|
348
|
+
try {
|
|
349
|
+
if (restoredThreadId) await session.thread.switch({ threadId: restoredThreadId });
|
|
350
|
+
else if (!thread?.clone) await session.thread.create();
|
|
351
|
+
} catch (err) {
|
|
352
|
+
return fail(`Failed to select thread: ${err.message}`);
|
|
353
|
+
}
|
|
354
|
+
if (thread?.clone) try {
|
|
355
|
+
await session.thread.clone();
|
|
356
|
+
} catch (err) {
|
|
357
|
+
return fail(`Failed to clone thread: ${err.message}`);
|
|
358
|
+
}
|
|
359
|
+
try {
|
|
360
|
+
if (options.mode) await session.mode.switch({ modeId: options.mode });
|
|
361
|
+
let packModelId;
|
|
362
|
+
if (options.pack) {
|
|
363
|
+
const packModeId = options.mode ?? session.mode.get();
|
|
364
|
+
const packSelection = options.pack.resolve(packModeId);
|
|
365
|
+
if (!packSelection) return fail(`Model pack "${options.pack.id}" has no model for ${packModeId} mode`);
|
|
366
|
+
const available = await controller.listAvailableModels();
|
|
367
|
+
const { modelId } = parseCodexModelSelection(packSelection.modelId);
|
|
368
|
+
const match = available.find((model) => model.id === modelId);
|
|
369
|
+
if (!match) return fail(`Unknown model "${packSelection.modelId}" from pack "${options.pack.id}"`);
|
|
370
|
+
if (!match.hasApiKey) {
|
|
371
|
+
const keyHint = match.apiKeyEnvVar ? ` Set ${match.apiKeyEnvVar} to use this model.` : "";
|
|
372
|
+
return fail(`Model "${packSelection.modelId}" (pack: ${options.pack.id}) has no API key configured.${keyHint}`);
|
|
373
|
+
}
|
|
374
|
+
packModelId = packSelection.modelId;
|
|
375
|
+
await session.thread.setSetting({
|
|
376
|
+
key: THREAD_ACTIVE_MODEL_PACK_ID_KEY,
|
|
377
|
+
value: options.pack.id
|
|
378
|
+
});
|
|
379
|
+
await session.thread.setSetting({
|
|
380
|
+
key: MODEL_FALLBACK_STATE_KEY,
|
|
381
|
+
value: void 0
|
|
382
|
+
});
|
|
383
|
+
for (const [agentType, modelId] of Object.entries(packSelection.subagentModels ?? {})) await session.subagents.model.set({
|
|
384
|
+
modelId,
|
|
385
|
+
agentType
|
|
386
|
+
});
|
|
387
|
+
await session.state.set({
|
|
388
|
+
modelRoute: packSelection.modelRoute,
|
|
389
|
+
[MODEL_FALLBACK_STATE_KEY]: null
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
const sessionModelId = modelIdToApply ?? packModelId;
|
|
393
|
+
if (sessionModelId) await session.model.switch(sessionModelId);
|
|
394
|
+
options.pack?.onApplied?.();
|
|
395
|
+
if (options.thinkingLevel) await session.state.set({ thinkingLevel: options.thinkingLevel });
|
|
396
|
+
} catch (err) {
|
|
397
|
+
return fail(`Failed to apply run config: ${err.message}`);
|
|
398
|
+
}
|
|
399
|
+
if (options.title) try {
|
|
400
|
+
await session.thread.rename({ title: options.title });
|
|
401
|
+
} catch (err) {
|
|
402
|
+
return fail(`Failed to set thread title: ${err.message}`);
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
if (goal) {
|
|
406
|
+
const threadId = session.thread.getId();
|
|
407
|
+
if (!threadId || !await session.thread.getById({ threadId })) await session.thread.create();
|
|
408
|
+
const goalManager = goal.goalManager ?? new GoalManager();
|
|
409
|
+
const state = {
|
|
410
|
+
controller,
|
|
411
|
+
session,
|
|
412
|
+
goalManager,
|
|
413
|
+
pendingNewThread: false
|
|
414
|
+
};
|
|
415
|
+
const objective = await goalManager.setGoal(state, goal.objective, goal.judgeModelId, goal.maxRuns);
|
|
416
|
+
if (!objective) return fail("Failed to set goal.");
|
|
417
|
+
const persisted = await controller.getCurrentAgent(session).getObjective({ threadId: session.thread.getId() });
|
|
418
|
+
if (!persisted || persisted.id !== objective.id) return fail("Failed to persist goal objective before sending goal signal.");
|
|
419
|
+
await goalManager.saveToThread(state);
|
|
420
|
+
if (!settled) await session.sendSignal(createGoalReminderSignal(objective)).accepted;
|
|
421
|
+
} else {
|
|
422
|
+
if (!options.prompt) return fail("A prompt or goal is required.");
|
|
423
|
+
await session.sendMessage({ content: options.prompt });
|
|
424
|
+
}
|
|
425
|
+
} catch (err) {
|
|
426
|
+
if (isSessionStartupCancelledError(err) || err instanceof Error && err.name === "AbortError" && (aborted || timedOut || options.signal?.aborted)) return finish(timedOut ? "timeout" : maxTurnsExceeded ? "max_turns" : "aborted");
|
|
427
|
+
return fail(`Failed to start run: ${err.message}`);
|
|
428
|
+
}
|
|
429
|
+
})();
|
|
430
|
+
return {
|
|
431
|
+
result,
|
|
432
|
+
abort,
|
|
433
|
+
[Symbol.asyncIterator]() {
|
|
434
|
+
return queue[Symbol.asyncIterator]();
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
export { runMC };
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared types for the headless / programmatic MastraCode API.
|
|
3
|
+
*
|
|
4
|
+
* These types are consumed by the core runner (`runMC`), the resolution policy,
|
|
5
|
+
* the output formatters, and the CLI adapter. They are intentionally free of any
|
|
6
|
+
* `process.*` access so the core API is usable from CI / Node code.
|
|
7
|
+
*/
|
|
8
|
+
import type { AgentController, AgentControllerEvent, Session } from '@mastra/core/agent-controller';
|
|
9
|
+
import type { GoalManager } from '../goal-manager.js';
|
|
10
|
+
import type { PackSelection } from '../onboarding/pack-activation.js';
|
|
11
|
+
export type RunMode = 'build' | 'plan' | 'fast';
|
|
12
|
+
export type ThinkingLevel = 'off' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
|
13
|
+
export declare const VALID_MODES: readonly ['build', 'plan', 'fast'];
|
|
14
|
+
export declare const VALID_THINKING_LEVELS: readonly ['off', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
15
|
+
/**
|
|
16
|
+
* Named permission modes for non-interactive runs. Maps to a built-in
|
|
17
|
+
* {@link ResolutionPolicy}:
|
|
18
|
+
* - `auto` — approve every tool and auto-resolve suspensions (the default).
|
|
19
|
+
* - `deny` — refuse every tool approval and abort on any suspension.
|
|
20
|
+
*/
|
|
21
|
+
export type PermissionMode = 'auto' | 'deny';
|
|
22
|
+
export declare const VALID_PERMISSION_MODES: readonly ['auto', 'deny'];
|
|
23
|
+
/** How `runMC` should resume `tool_approval_required` and `tool_suspended` events. */
|
|
24
|
+
export interface ResolutionPolicy {
|
|
25
|
+
/**
|
|
26
|
+
* Called for every `tool_approval_required` event. Return the decision; the
|
|
27
|
+
* runner forwards it to `session.respondToToolApproval`.
|
|
28
|
+
*/
|
|
29
|
+
onToolApproval(event: Extract<AgentControllerEvent, {
|
|
30
|
+
type: 'tool_approval_required';
|
|
31
|
+
}>): 'approve' | 'deny';
|
|
32
|
+
/**
|
|
33
|
+
* Called for every `tool_suspended` event. Return `resumeData` to resume the
|
|
34
|
+
* tool, or `{ abort: true }` to abort the run.
|
|
35
|
+
*/
|
|
36
|
+
onSuspension(event: Extract<AgentControllerEvent, {
|
|
37
|
+
type: 'tool_suspended';
|
|
38
|
+
}>): {
|
|
39
|
+
resumeData: unknown;
|
|
40
|
+
} | {
|
|
41
|
+
abort: true;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Thread selection / mutation options resolved up front by `runMC`. */
|
|
45
|
+
export interface RunMCThreadOptions {
|
|
46
|
+
/** Resume a specific thread by its exact id. */
|
|
47
|
+
id?: string;
|
|
48
|
+
/** Resume the most recently updated thread instead of creating a new one. */
|
|
49
|
+
continueLatest?: boolean;
|
|
50
|
+
/** Clone the resolved (or current) thread before running — work on a copy. */
|
|
51
|
+
clone?: boolean;
|
|
52
|
+
}
|
|
53
|
+
interface RunMCBaseOptions<TState extends Record<string, unknown> = Record<string, unknown>> {
|
|
54
|
+
/** Controller built via `createMastraCode(...)`. */
|
|
55
|
+
controller: AgentController<TState>;
|
|
56
|
+
/** Session built via `createMastraCode(...)`. */
|
|
57
|
+
session: Session<TState>;
|
|
58
|
+
/** Explicit model id override. Takes precedence over `mode` and `pack`. */
|
|
59
|
+
model?: string;
|
|
60
|
+
/** Execution mode; resolves a model from `modeDefaults` when `model` is absent. */
|
|
61
|
+
mode?: RunMode;
|
|
62
|
+
/** Per-mode default model ids (resolved from settings at startup). */
|
|
63
|
+
modeDefaults?: Record<string, string>;
|
|
64
|
+
/**
|
|
65
|
+
* A model pack to activate for the run (canonical id from
|
|
66
|
+
* `resolveModePackArg`). The selection is resolved via `resolve` only after
|
|
67
|
+
* thread selection, because a resumed thread restores its persisted mode —
|
|
68
|
+
* the mode that decides which model the pack provides. Sets the thread's
|
|
69
|
+
* activeModelPackId, the subagent models, and the model route; `model`
|
|
70
|
+
* still wins for the active mode's session model. `onApplied` fires once
|
|
71
|
+
* the pack has been applied to the session (used by the CLI to persist the
|
|
72
|
+
* activation as the global default only when it actually took effect).
|
|
73
|
+
*/
|
|
74
|
+
pack?: {
|
|
75
|
+
id: string;
|
|
76
|
+
resolve: (modeId: string) => PackSelection | undefined;
|
|
77
|
+
onApplied?: () => void;
|
|
78
|
+
};
|
|
79
|
+
/** Thinking-effort level. */
|
|
80
|
+
thinkingLevel?: ThinkingLevel;
|
|
81
|
+
/** Thread selection / mutation. */
|
|
82
|
+
thread?: RunMCThreadOptions;
|
|
83
|
+
/** Resource id for thread scoping. */
|
|
84
|
+
resourceId?: string;
|
|
85
|
+
/** Set or rename the thread title before running. */
|
|
86
|
+
title?: string;
|
|
87
|
+
/** Abort with `status: 'timeout'` (exit code 2) after this many ms without an event. */
|
|
88
|
+
timeoutMs?: number;
|
|
89
|
+
/**
|
|
90
|
+
* Maximum number of agentic turns (assistant responses). When the limit is
|
|
91
|
+
* reached the run aborts with `status: 'max_turns'` (exit code 1). No limit
|
|
92
|
+
* by default.
|
|
93
|
+
*/
|
|
94
|
+
maxTurns?: number;
|
|
95
|
+
/** How approvals / suspensions are resolved. Defaults to {@link autoApprovePolicy}. */
|
|
96
|
+
policy?: ResolutionPolicy;
|
|
97
|
+
/** External abort signal; aborting it aborts the run. */
|
|
98
|
+
signal?: AbortSignal;
|
|
99
|
+
}
|
|
100
|
+
export interface RunMCGoalOptions {
|
|
101
|
+
objective: string;
|
|
102
|
+
judgeModelId: string;
|
|
103
|
+
maxRuns: number;
|
|
104
|
+
goalManager?: GoalManager;
|
|
105
|
+
}
|
|
106
|
+
export type RunMCOptions<TState extends Record<string, unknown> = Record<string, unknown>> = RunMCBaseOptions<TState> & ({
|
|
107
|
+
/** The task to run as a regular headless turn. */
|
|
108
|
+
prompt: string;
|
|
109
|
+
goal?: never;
|
|
110
|
+
} | {
|
|
111
|
+
prompt?: never;
|
|
112
|
+
/** Run a persisted goal instead of a regular prompt. */
|
|
113
|
+
goal: RunMCGoalOptions;
|
|
114
|
+
});
|
|
115
|
+
export type RunMCStatus = 'completed' | 'done' | 'paused' | 'error' | 'aborted' | 'timeout' | 'max_turns';
|
|
116
|
+
export interface RunMCUsage {
|
|
117
|
+
inputTokens?: number;
|
|
118
|
+
outputTokens?: number;
|
|
119
|
+
totalTokens?: number;
|
|
120
|
+
}
|
|
121
|
+
export interface RunMCToolCall {
|
|
122
|
+
id: string;
|
|
123
|
+
name: string;
|
|
124
|
+
args: unknown;
|
|
125
|
+
}
|
|
126
|
+
export interface RunMCToolResult {
|
|
127
|
+
id: string;
|
|
128
|
+
name: string;
|
|
129
|
+
result: unknown;
|
|
130
|
+
isError: boolean;
|
|
131
|
+
}
|
|
132
|
+
export interface RunMCError {
|
|
133
|
+
name: string;
|
|
134
|
+
message: string;
|
|
135
|
+
stack?: string;
|
|
136
|
+
}
|
|
137
|
+
export interface RunMCResult {
|
|
138
|
+
status: RunMCStatus;
|
|
139
|
+
/** Aggregated assistant text across all message_end events. */
|
|
140
|
+
text: string;
|
|
141
|
+
/** Goal objective when this was a goal run. */
|
|
142
|
+
objective?: string;
|
|
143
|
+
/** Terminal goal evaluation when this was a goal run. */
|
|
144
|
+
goalEvent?: Extract<AgentControllerEvent, {
|
|
145
|
+
type: 'goal_evaluation';
|
|
146
|
+
}>;
|
|
147
|
+
reason?: string;
|
|
148
|
+
iterations?: number;
|
|
149
|
+
maxRuns?: number;
|
|
150
|
+
/** Underlying finish reason from `agent_end`, when the run finished normally. */
|
|
151
|
+
finishReason?: string;
|
|
152
|
+
/** Cumulative token usage for this run, summed from per-step usage events. */
|
|
153
|
+
usage?: RunMCUsage;
|
|
154
|
+
toolCalls: RunMCToolCall[];
|
|
155
|
+
toolResults: RunMCToolResult[];
|
|
156
|
+
threadId?: string;
|
|
157
|
+
error?: RunMCError;
|
|
158
|
+
/** 0 success, 1 error/aborted/max_turns, 2 timeout. */
|
|
159
|
+
exitCode: number;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* A handle to an in-flight `runMC` run. It is async-iterable over controller
|
|
163
|
+
* events and also resolves to a final {@link RunMCResult} via `result`.
|
|
164
|
+
*
|
|
165
|
+
* Both `for await (const e of run)` and `await run.result` work on the same run;
|
|
166
|
+
* awaiting `result` without iterating still drains events internally.
|
|
167
|
+
*/
|
|
168
|
+
export interface MCRun extends AsyncIterable<AgentControllerEvent> {
|
|
169
|
+
/** Resolves once the run completes, times out, errors, or is aborted. */
|
|
170
|
+
result: Promise<RunMCResult>;
|
|
171
|
+
/** Abort the in-flight run. */
|
|
172
|
+
abort(): void;
|
|
173
|
+
}
|
|
174
|
+
export {};
|
|
175
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// src/headless/types.ts
|
|
2
|
+
const VALID_MODES = [
|
|
3
|
+
"build",
|
|
4
|
+
"plan",
|
|
5
|
+
"fast"
|
|
6
|
+
];
|
|
7
|
+
const VALID_THINKING_LEVELS = [
|
|
8
|
+
"off",
|
|
9
|
+
"low",
|
|
10
|
+
"medium",
|
|
11
|
+
"high",
|
|
12
|
+
"xhigh",
|
|
13
|
+
"max"
|
|
14
|
+
];
|
|
15
|
+
const VALID_PERMISSION_MODES = ["auto", "deny"];
|
|
16
|
+
export { VALID_MODES, VALID_PERMISSION_MODES, VALID_THINKING_LEVELS };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook configuration loading from filesystem.
|
|
3
|
+
* Loads from global (~/.mastracode/hooks.json) and project (.mastracode/hooks.json).
|
|
4
|
+
* Global hooks run first, project hooks append.
|
|
5
|
+
*/
|
|
6
|
+
import type { HooksConfig, HookEventName } from './types.js';
|
|
7
|
+
export declare const VALID_EVENTS: HookEventName[];
|
|
8
|
+
export declare function loadHooksConfig(projectDir: string, configDirName?: string, homeDir?: string): HooksConfig;
|
|
9
|
+
export declare function getProjectHooksPath(projectDir: string, configDirName?: string): string;
|
|
10
|
+
export declare function getGlobalHooksPath(configDirName?: string, homeDir?: string): string;
|
|
11
|
+
//# sourceMappingURL=config.d.ts.map
|