@mastra/code-sdk 1.0.0-alpha.13 → 1.0.0-alpha.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/dist/agents/memory.d.ts.map +1 -1
- package/dist/agents/memory.js +2 -2
- package/dist/agents/memory.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -2
- package/dist/index.js.map +1 -1
- package/dist/plugins/manager.d.ts +4 -0
- package/dist/plugins/manager.d.ts.map +1 -1
- package/dist/plugins/manager.js +18 -6
- package/dist/plugins/manager.js.map +1 -1
- package/package.json +9 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
1
|
# @mastra/code-sdk
|
|
2
2
|
|
|
3
|
+
## 1.0.0-alpha.15
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fixed provider request history repair so incompatible tool-call IDs are sanitized and retried instead of being blindly resent after a provider rejects the request ([#19969](https://github.com/mastra-ai/mastra/pull/19969))
|
|
8
|
+
|
|
9
|
+
- Fixed session thread cloning failing with "Source thread not found" when the cached dynamic memory instance was bound to a previous storage instance. The memory cache is now scoped to the storage it was created with. ([#19969](https://github.com/mastra-ai/mastra/pull/19969))
|
|
10
|
+
|
|
11
|
+
- Fixed cloned session threads reading from a previous storage instance. The dynamic memory cache now invalidates when the storage or vector instance changes, so thread cloning always uses the current database. ([#19966](https://github.com/mastra-ai/mastra/pull/19966))
|
|
12
|
+
|
|
13
|
+
## 1.0.0-alpha.14
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- Added a session notification when a GitHub plugin is automatically updated to its latest version ([#19943](https://github.com/mastra-ai/mastra/pull/19943))
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
const unsubscribe = pluginManager.onGithubPluginsUpdated(pluginNames => {
|
|
21
|
+
console.log(`Updated plugins: ${pluginNames.join(', ')}`);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// Call during shutdown.
|
|
25
|
+
unsubscribe();
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
- Updated dependencies [[`d7385ad`](https://github.com/mastra-ai/mastra/commit/d7385ad9e88f9e4f33d15c0ec0bfebedde0cbc2e), [`3d6e539`](https://github.com/mastra-ai/mastra/commit/3d6e539272eb2ea0407034605ee1906b3be06b39), [`35865a5`](https://github.com/mastra-ai/mastra/commit/35865a53e194aa9634d6a70a97010e7a6b9d58b1), [`70687f7`](https://github.com/mastra-ai/mastra/commit/70687f7e495a322a02070b4a67cb0c77a5ca91ec), [`3d6e539`](https://github.com/mastra-ai/mastra/commit/3d6e539272eb2ea0407034605ee1906b3be06b39)]:
|
|
29
|
+
- @mastra/core@1.52.0-alpha.12
|
|
30
|
+
|
|
3
31
|
## 1.0.0-alpha.13
|
|
4
32
|
|
|
5
33
|
### Patch Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAkExC;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,YAAY,IAM3E,oBAAoB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,YA4D/D"}
|
package/dist/agents/memory.js
CHANGED
|
@@ -3,8 +3,6 @@ import { Memory } from "@mastra/memory";
|
|
|
3
3
|
import { DEFAULT_OM_MODEL_ID, DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from "../constants.js";
|
|
4
4
|
import { getOmScope } from "../utils/project.js";
|
|
5
5
|
import { resolveModel } from "./model.js";
|
|
6
|
-
let cachedMemory = null;
|
|
7
|
-
let cachedMemoryKey = null;
|
|
8
6
|
function getAgentControllerState(requestContext) {
|
|
9
7
|
const ctx = requestContext.get("controller");
|
|
10
8
|
return ctx?.getState();
|
|
@@ -47,6 +45,8 @@ Don't say "Agent did x", say "did x". It will be assumed the agent did what was
|
|
|
47
45
|
|
|
48
46
|
Drop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;
|
|
49
47
|
function getDynamicMemory(storage, vector) {
|
|
48
|
+
let cachedMemory = null;
|
|
49
|
+
let cachedMemoryKey = null;
|
|
50
50
|
return ({ requestContext }) => {
|
|
51
51
|
const state = getAgentControllerState(requestContext);
|
|
52
52
|
const omScope = state?.omScope ?? getOmScope(state?.projectPath);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { fastembed } from '@mastra/fastembed';\nimport { Memory } from '@mastra/memory';\nimport { DEFAULT_OM_MODEL_ID, DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel } from './model.js';\n\
|
|
1
|
+
{"version":3,"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { fastembed } from '@mastra/fastembed';\nimport { Memory } from '@mastra/memory';\nimport { DEFAULT_OM_MODEL_ID, DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel } from './model.js';\n\n/**\n * Read controller state from requestContext.\n * Used by both the memory factory and the OM model functions.\n */\nfunction getAgentControllerState(requestContext: RequestContext): MastraCodeState | undefined {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return ctx?.getState() as MastraCodeState | undefined;\n}\n\n/**\n * Observer model function — reads the current observer model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getObserverModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.observerModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\n}\n\n/**\n * Reflector model function — reads the current reflector model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getReflectorModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.reflectorModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\n🔴 14:31 user asks why React component rerenders\n🟡 14:32 saw inline object prop create new ref each render, cause rerender\n✅ 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟡 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector) {\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n\n return ({ requestContext }: { requestContext: RequestContext }) => {\n const state = getAgentControllerState(requestContext);\n const omScope = state?.omScope ?? getOmScope(state?.projectPath);\n\n const obsThreshold = state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD;\n const refThreshold = state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD;\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n const observeAttachments = state?.observeAttachments;\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n // Async buffering is not supported with resource scope — disable it\n const isResourceScope = omScope === 'resource';\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n cachedMemory = new Memory({\n storage,\n vector: vector || false,\n embedder: vector ? fastembed.small : undefined,\n options: {\n observationalMemory: {\n enabled: true,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n scope: omScope,\n activateAfterIdle: 'auto',\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n}\n"],"mappings":"AAIA,SAAS,iBAAiB;AAC1B,SAAS,cAAc;AACvB,SAAS,qBAAqB,uBAAuB,6BAA6B;AAElF,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAM7B,SAAS,wBAAwB,gBAA6D;AAC5F,QAAM,MAAM,eAAe,IAAI,YAAY;AAC3C,SAAO,KAAK,SAAS;AACvB;AAMA,SAAS,iB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Q;AAAA,MACrC,SAAS;AAAA,QACP,qBAAqB;AAAA,UACnB,SAAS;AAAA,UACT,iBAAiB;AAAA,UACjB,WAAW,SAAS,EAAE,QAAQ,KAAK,IAAI;AAAA,UACvC,OAAO;AAAA,UACP,mBAAmB;AAAA,UACnB,0BAA0B;AAAA,UAC1B,aAAa;AAAA,YACX,cAAc,kBAAkB,QAAQ,IAAI;AAAA,YAC5C,kBAAkB,kBAAkB,SAAY;AAAA,YAChD,OAAO;AAAA,YACP,eAAe;AAAA,YACf,YAAY;AAAA,YACZ,wBAAwB;AAAA,YACxB,aAAa;AAAA,YACb,aAAa;AAAA,YACb;AAAA,UACF;AAAA,UACA,YAAY;AAAA,YACV,kBAAkB,kBAAkB,SAAY,IAAI;AAAA,YACpD,YAAY;AAAA,YACZ,OAAO;AAAA,YACP,mBAAmB;AAAA,YACnB,aAAa;AAAA,UACf;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AACD,sBAAkB;AAElB,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EAErB,mBAAmB,EACnB,uBAAuB,EAEvB,OAAO,EACR,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGlD,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAQ7C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAmB,oBAAoB,EAAE,MAA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EACZ,WAAW,EACX,WAAW,EACX,UAAU,EACV,aAAa,EACb,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,KAAK,EACL,gBAAgB,EAChB,cAAc,GACf,MAAM,qBAAqB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -413,6 +413,13 @@ async function createMastraCodeAgentController(config) {
|
|
|
413
413
|
new ProviderHistoryCompat()
|
|
414
414
|
],
|
|
415
415
|
errorProcessors: [
|
|
416
|
+
// ProviderHistoryCompat must run before StreamErrorRetryProcessor: both react to
|
|
417
|
+
// HTTP 400s, but ProviderHistoryCompat repairs the incompatible history (e.g.
|
|
418
|
+
// sanitizing tool-call IDs) before retrying, while StreamErrorRetryProcessor's
|
|
419
|
+
// isBadRequestError matcher retries the identical request. Error processors
|
|
420
|
+
// short-circuit on the first `retry: true`, so a blind retry first would resend
|
|
421
|
+
// the broken history and fail again.
|
|
422
|
+
new ProviderHistoryCompat(),
|
|
416
423
|
new StreamErrorRetryProcessor({
|
|
417
424
|
matchers: [
|
|
418
425
|
{ match: isBadRequestError, maxRetries: 1, delayMs: 2e3 },
|
|
@@ -426,8 +433,7 @@ async function createMastraCodeAgentController(config) {
|
|
|
426
433
|
}
|
|
427
434
|
]
|
|
428
435
|
}),
|
|
429
|
-
new PrefillErrorHandler()
|
|
430
|
-
new ProviderHistoryCompat()
|
|
436
|
+
new PrefillErrorHandler()
|
|
431
437
|
]
|
|
432
438
|
});
|
|
433
439
|
const defaultModes = [
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { hostname } from 'node:os';\nimport path from 'node:path';\n\nimport type { Agent } from '@mastra/core/agent';\nimport { AgentController } from '@mastra/core/agent-controller';\nimport type {\n IntervalHandler,\n AgentControllerConfig,\n AgentControllerEvent,\n AgentControllerMode,\n AgentControllerSubagent,\n AgentControllerRequestContext,\n Session,\n} from '@mastra/core/agent-controller';\nimport { createCodingAgent } from '@mastra/core/coding-agent';\nimport type { PubSub } from '@mastra/core/events';\nimport { PROVIDER_REGISTRY } from '@mastra/core/llm';\nimport type { ProviderConfig } from '@mastra/core/llm';\nimport { Mastra } from '@mastra/core/mastra';\nimport {\n AgentsMDInjector,\n isBadRequestError,\n PrefillErrorHandler,\n ProviderHistoryCompat,\n StreamErrorRetryProcessor,\n} from '@mastra/core/processors';\nimport type { InputProcessor } from '@mastra/core/processors';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { PublicSchema } from '@mastra/core/schema';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { TaskSignalProvider } from '@mastra/core/signals';\nimport { InMemoryHarness, MastraCompositeStore } from '@mastra/core/storage';\nimport { DEFAULT_GOAL_JUDGE_PROMPT } from '@mastra/core/tools';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { DuckDBStore } from '@mastra/duckdb';\n\nimport { GithubSignals } from '@mastra/github-signals';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport {\n Observability,\n MastraStorageExporter,\n MastraPlatformExporter,\n SensitiveDataFilter,\n} from '@mastra/observability';\nimport { PostgresStore } from '@mastra/pg';\n\nimport { hasCredentialStoreProvider } from './agents/credential-resolver.js';\nimport { getDynamicInstructions } from './agents/instructions.js';\nimport { getDynamicMemory } from './agents/memory.js';\nimport { createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel } from './agents/model.js';\nimport { buildMode } from './agents/modes/build.js';\nimport { fastMode } from './agents/modes/explore.js';\nimport { planMode } from './agents/modes/plan.js';\nimport { getStaticallyLoadedInstructionPaths } from './agents/prompts/agent-instructions.js';\n// import { executeSubagent } from './agents/subagents/execute.js';\n// import { exploreSubagent } from './agents/subagents/explore.js';\n// import { planSubagent } from './agents/subagents/plan.js';\nimport { attachOMThreadStatePersistence, restoreOMThreadStateForCurrentThread } from './agents/thread-caveman-state.js';\nimport { createDynamicTools, createToolHooks } from './agents/tools.js';\nimport type { PostToolObserver, ToolLike } from './agents/tools.js';\n\nimport { getDynamicWorkspace, getGoalJudgeTools } from './agents/workspace.js';\nimport { AuthStorage } from './auth/storage.js';\nimport { DEFAULT_CONFIG_DIR, validateConfigDirName } from './constants.js';\nimport { createOutcomeScorer, createEfficiencyScorer } from './evals/scorers/index.js';\nimport { HookManager } from './hooks/index.js';\nimport { createMcpManager } from './mcp/index.js';\nimport type { McpServerConfig } from './mcp/index.js';\nimport type { ProviderAccess } from './onboarding/packs.js';\nimport { getAvailableModePacks, getAvailableOmPacks } from './onboarding/packs.js';\nimport {\n loadSettings,\n MASTRA_GATEWAY_PROVIDER,\n OBSERVABILITY_AUTH_PREFIX,\n resolveModelDefaults,\n resolveOmRoleModel,\n saveSettings,\n} from './onboarding/settings.js';\nimport { getToolCategory } from './permissions.js';\nimport { PluginManager } from './plugins/manager.js';\nimport { PlanRejectionAbortProcessor } from './processors/plan-rejection-abort.js';\nimport { createAmazonBedrockGateway } from './providers/amazon-bedrock-gateway.js';\nimport { setAuthStorage } from './providers/claude-max.js';\nimport { setAuthStorage as setGitHubCopilotAuthStorage } from './providers/github-copilot.js';\nimport { setAuthStorage as setOpenAIAuthStorage } from './providers/openai-codex.js';\nimport { setAuthStorage as setXAIAuthStorage } from './providers/xai.js';\n\nimport { stateSchema } from './schema.js';\nimport type { MastraCodeState } from './schema.js';\n\nimport { mastraBrand } from './theme-palette.js';\nimport { syncGateways } from './utils/gateway-sync.js';\nimport {\n detectProject,\n getObservabilityDatabasePath,\n getStorageConfig,\n getResourceIdOverride,\n} from './utils/project.js';\nimport type { StorageConfig } from './utils/project.js';\nimport { createSignalsPubSub } from './utils/signals-pubsub.js';\nimport { createStorage, createVectorStore } from './utils/storage-factory.js';\nimport type { StorageResult } from './utils/storage-factory.js';\nimport { createStorageMaintenance, DEFAULT_RETENTION, resolveLocalDbFiles } from './utils/storage-maintenance.js';\nimport type { StorageMaintenance } from './utils/storage-maintenance.js';\nimport { acquireThreadLock, releaseThreadLock } from './utils/thread-lock.js';\n\nconst CODE_AGENT_ID = 'code-agent';\n\n// Global retry policy for transient connection failures (e.g. provider sockets dropping mid-stream).\n// Applied centrally to every model call via StreamErrorRetryProcessor, independent of model-pack\n// settings, so all modes/subagents benefit from a short wait before retrying a dropped connection.\n// Delay uses exponential backoff: initialDelay * 2^retryCount, capped at maxDelay.\nconst MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES = 2;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS = 1000;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS = 30000;\n\nconst TRANSIENT_CONNECTION_ERROR_CODES = new Set(['ECONNRESET', 'EPIPE']);\nconst TRANSIENT_CONNECTION_MESSAGE_PATTERN = /econnreset|socket hang up|write epipe|other side closed/i;\n\n/**\n * Matcher for transient connection failures. Cause-chain traversal is handled\n * by `StreamErrorRetryProcessor.isRetryableStreamError`, which calls each\n * matcher at every level of the cause chain.\n */\nfunction isTransientConnectionError(error: unknown): boolean {\n if (!error) return false;\n\n const code = typeof error === 'object' && 'code' in error ? (error as { code?: unknown }).code : undefined;\n if (typeof code === 'string' && TRANSIENT_CONNECTION_ERROR_CODES.has(code.toUpperCase())) return true;\n\n const message = error instanceof Error ? error.message : undefined;\n if (typeof message === 'string' && TRANSIENT_CONNECTION_MESSAGE_PATTERN.test(message)) return true;\n\n return false;\n}\n\n/** Short deterministic hash (sha256, first 12 hex chars) matching project.ts shortHash style. */\nfunction shortHash(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 12);\n}\n\nfunction applyEffectiveDefaultsToModes(\n modes: AgentControllerMode[],\n effectiveDefaults: Record<string, string>,\n): AgentControllerMode[] {\n return modes.map(mode => {\n const savedModel = effectiveDefaults[mode.id];\n if (!savedModel) {\n return mode;\n }\n return {\n ...mode,\n defaultModelId: savedModel,\n };\n });\n}\n\nfunction addPluginToolsToModeAllowlists(\n modes: AgentControllerMode[],\n pluginToolNames: string[],\n): AgentControllerMode[] {\n if (pluginToolNames.length === 0) return modes;\n return modes.map(mode => {\n if (!mode.availableTools) return mode;\n return {\n ...mode,\n availableTools: Array.from(new Set([...mode.availableTools, ...pluginToolNames])),\n };\n });\n}\n\nexport interface MastraCodeConfig {\n /** Working directory for project detection. Default: process.cwd() */\n cwd?: string;\n /** Home directory for global config discovery. Default: os.homedir() */\n homeDir?: string;\n /** Override modes (model IDs, colors, which modes exist). Default: build/plan/fast */\n modes?: AgentControllerMode[];\n /** Override or extend subagent definitions. Default: explore/plan/execute */\n subagents?: AgentControllerSubagent[];\n /** Extra tools merged into the dynamic tool set. Can be a static record or a (sync or async) function that receives requestContext. */\n extraTools?:\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n /** Observe completed tool calls without replacing or modifying the built-in tool implementation. */\n postToolObserver?: PostToolObserver;\n /**\n * Stateless input processor instances prepended before Mastra Code's mandatory processors.\n * Embedders may extend processing but cannot replace built-in safety and compatibility policy.\n */\n inputProcessors?: InputProcessor[];\n /** Tools removed from the dynamic tool set before exposure to the model */\n disabledTools?: string[];\n /**\n * Custom storage config instead of auto-detected default, or a pre-built\n * store instance. An instance is used as-is: no connection test and no\n * LibSQL fallback — if the injected store fails, that's a hard error.\n */\n storage?: StorageConfig | MastraCompositeStore;\n /** Backend for an injected custom storage instance. Inferred for LibSQLStore and PostgresStore. */\n storageBackend?: 'libsql' | 'pg';\n /** Pre-built vector store instance for recall search. Skips the default vector store creation. */\n vector?: MastraVector;\n /** Observational memory scope. Default: auto-detected from env/config files, falls back to 'thread' */\n omScope?: 'thread' | 'resource';\n /** Path to a custom settings.json file. Default: global settings */\n settingsPath?: string;\n /** Initial state overrides (yolo, thinkingLevel, etc.) */\n initialState?: Partial<MastraCodeState>;\n /** Override id generation for threads/messages. Primarily useful for deterministic tests. */\n idGenerator?: AgentControllerConfig<MastraCodeState>['idGenerator'];\n /** Override interval handlers. Default: gateway-sync */\n intervalHandlers?: IntervalHandler[];\n /** Override the workspace. Default: local filesystem + local sandbox based on detected project */\n workspace?: AgentControllerConfig<MastraCodeState>['workspace'];\n /** Override the config directory name. Default: '.mastracode'. Replaces '.mastracode' in all project-level and global config paths (MCP, hooks, commands, database, skills, agent instructions). */\n configDir?: string;\n /** Programmatic MCP server configurations, merged with (and overriding) file-based configs. */\n mcpServers?: Record<string, McpServerConfig>;\n /** Disable MCP server discovery. Default: false */\n disableMcp?: boolean;\n /** Disable hooks. Default: false */\n disableHooks?: boolean;\n /** Disable plugin discovery/loading. Default: false */\n disablePlugins?: boolean;\n /** Disable the polling-based GitHub signal provider even when enabled in global settings. Default: false */\n disableGithubSignals?: boolean;\n /** Override the plugin manager. Primarily useful for tests or embedding. */\n pluginManager?: PluginManager;\n /**\n * Override the memory instance (or dynamic factory) passed to the AgentController.\n * When provided, this replaces the default `getDynamicMemory(storage, vector)` which\n * uses mastracode's built-in model gateway (Anthropic OAuth, OpenAI Codex,\n * custom providers, and models.dev fallback).\n *\n * Use this when you need to override memory model behavior completely.\n */\n memory?: AgentControllerConfig<MastraCodeState>['memory'] | false;\n /** Browser provider for browser automation tools. When set, the agent gains access to browser tools. */\n browser?: AgentControllerConfig<MastraCodeState>['browser'];\n /** PubSub for signal routing. When crossProcessPubSub is true, thread locks are disabled. */\n pubsub?: PubSub;\n /** Use Mastra Code's built-in Unix socket PubSub for local cross-process signal routing. */\n unixSocketPubSub?: boolean;\n /** Marks the configured PubSub as cross-process-safe, allowing Mastra Code to skip file thread locks. */\n crossProcessPubSub?: boolean;\n}\n\nexport function createAuthStorage() {\n const authStorage = new AuthStorage();\n setAuthStorage(authStorage);\n setOpenAIAuthStorage(authStorage);\n setGitHubCopilotAuthStorage(authStorage);\n setXAIAuthStorage(authStorage);\n return authStorage;\n}\n\n/**\n * Resolve cloud observability credentials for the MastraPlatformExporter.\n * Priority: per-resource settings > environment variables > disabled.\n */\nfunction resolveCloudObservabilityConfig(\n settings: ReturnType<typeof loadSettings>,\n authStorage: AuthStorage,\n resourceId: string,\n): { accessToken?: string; projectId?: string } {\n const resourceConfig = settings.observability.resources[resourceId];\n if (resourceConfig) {\n const token = authStorage.getStoredApiKey(`${OBSERVABILITY_AUTH_PREFIX}${resourceId}`);\n if (token) {\n return { accessToken: token, projectId: resourceConfig.projectId };\n }\n }\n // Fall back to environment variables for backwards compatibility\n return {\n accessToken: process.env.MASTRA_CLOUD_ACCESS_TOKEN,\n projectId: process.env.MASTRA_PROJECT_ID,\n };\n}\n\n/**\n * Base factory: builds every shared MastraCode resource (storage, observability,\n * memory, MCP, providers, gateways, agent, modes) and the {@link AgentController}, but\n * does NOT call `init()` or create a session. The controller is returned inert so\n * the composition layer can decide its Mastra ownership and session model.\n *\n * See {@link bootLocalAgentController} (Case 3) and `mountAgentControllerOnMastra` (Cases 1 & 2).\n */\nfunction resolveInjectedStorageBackend(\n storage: MastraCompositeStore,\n configuredBackend?: 'libsql' | 'pg',\n): 'libsql' | 'pg' {\n if (configuredBackend) return configuredBackend;\n if (storage instanceof LibSQLStore) return 'libsql';\n if (storage instanceof PostgresStore) return 'pg';\n throw new Error('storageBackend is required when injecting a custom storage instance.');\n}\n\nexport async function createMastraCodeAgentController(config?: MastraCodeConfig) {\n const cwd = config?.cwd ?? process.cwd();\n const homeDir = config?.homeDir ?? config?.initialState?.homeDir;\n const configDir = config?.configDir ?? DEFAULT_CONFIG_DIR;\n // The single session for this process, assigned once `createSession()` runs\n // below. Config callbacks defined before then (e.g. notification stream\n // options) read it lazily through this holder.\n let activeSession: Session<MastraCodeState> | undefined;\n if (configDir !== DEFAULT_CONFIG_DIR) {\n validateConfigDirName(configDir);\n }\n\n // Load .env file from cwd if present (for observability API keys, etc.)\n try {\n process.loadEnvFile(path.join(cwd, '.env'));\n } catch {\n // No .env file — that's fine, keys may be in shell environment\n }\n\n // Auth storage (shared with Claude Max / OpenAI providers and AgentController)\n const authStorage = createAuthStorage();\n const globalSettings = loadSettings(config?.settingsPath);\n const storedGatewayKey = authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER);\n const storedGatewayUrl = globalSettings.memoryGateway?.baseUrl;\n\n if (storedGatewayKey) {\n process.env['MASTRA_GATEWAY_API_KEY'] ??= storedGatewayKey;\n }\n\n if (storedGatewayUrl) {\n process.env['MASTRA_GATEWAY_URL'] ??= storedGatewayUrl;\n }\n\n // Load user-entered API keys from auth.json into process.env\n // (only sets env vars that aren't already present — env vars take precedence).\n // Skipped in deployed multi-tenant mode: when a per-tenant credential store\n // provider is registered, provider keys are resolved per request and must\n // never leak into process-global env vars.\n if (!hasCredentialStoreProvider()) {\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n const providerEnvVars: Record<string, string | undefined> = {};\n for (const [provider, cfg] of Object.entries(registry)) {\n const envVars = cfg?.apiKeyEnvVar;\n providerEnvVars[provider] = Array.isArray(envVars) ? envVars[0] : envVars;\n }\n providerEnvVars[MASTRA_GATEWAY_PROVIDER] ??= 'MASTRA_GATEWAY_API_KEY';\n authStorage.loadStoredApiKeysIntoEnv(providerEnvVars);\n } catch {\n // Registry unavailable — load well-known provider keys so non-gateway flows still work\n authStorage.loadStoredApiKeysIntoEnv({\n [MASTRA_GATEWAY_PROVIDER]: 'MASTRA_GATEWAY_API_KEY',\n anthropic: 'ANTHROPIC_API_KEY',\n openai: 'OPENAI_API_KEY',\n google: 'GOOGLE_GENERATIVE_AI_API_KEY',\n cerebras: 'CEREBRAS_API_KEY',\n deepseek: 'DEEPSEEK_API_KEY',\n });\n }\n }\n\n const mgApiKey = process.env['MASTRA_GATEWAY_API_KEY'] ?? storedGatewayKey;\n const mastraGatewayBaseUrl = (\n process.env['MASTRA_GATEWAY_URL'] ??\n storedGatewayUrl ??\n 'https://gateway-api.mastra.ai'\n )\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n const mastraCodeGateway = createMastraCodeGateway({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: false,\n settingsPath: config?.settingsPath,\n });\n const amazonBedrockGateway = createAmazonBedrockGateway();\n\n // Project detection\n const project = detectProject(cwd);\n\n const resourceIdOverride = getResourceIdOverride(project.rootPath, configDir);\n if (resourceIdOverride) {\n project.resourceId = resourceIdOverride;\n project.resourceIdOverride = true;\n }\n\n // Stable session id unique to this project/resource, and a machine-bound owner\n // id. resourceId encodes root path + git identity and honors overrides, so it\n // is the right input for scoping the session to the cwd/project.\n const sessionId = `mastracode-session-${shortHash(project.resourceId)}`;\n const ownerId = `mastracode-${shortHash(`${hostname()}\\0${project.rootPath}`)}`;\n\n const configuredPubSub = config?.pubsub;\n const useUnixSocketPubSub =\n (config?.unixSocketPubSub ?? globalSettings.signals?.unixSocketPubSub ?? false) && process.platform !== 'win32';\n const signalsPubSub = configuredPubSub ?? (useUnixSocketPubSub ? createSignalsPubSub(project.resourceId) : undefined);\n const crossProcessPubSub = config?.crossProcessPubSub ?? (!configuredPubSub && useUnixSocketPubSub);\n if (crossProcessPubSub && !signalsPubSub) {\n throw new Error('crossProcessPubSub requires a pubsub instance');\n }\n\n // Storage. An injected instance is used as-is — no connection test, no\n // LibSQL fallback: if the injected store fails, that's a hard error.\n const injectedStorage = config?.storage instanceof MastraCompositeStore ? config.storage : undefined;\n const storageConfig = injectedStorage\n ? undefined\n : ((config?.storage as StorageConfig | undefined) ??\n getStorageConfig(project.rootPath, globalSettings.storage, configDir));\n const storageResult: StorageResult = injectedStorage\n ? { storage: injectedStorage, backend: resolveInjectedStorageBackend(injectedStorage, config?.storageBackend) }\n : await createStorage(storageConfig!);\n const storageWarning = storageResult.warning;\n\n // Observability storage (DuckDB — separate file for OLAP-style trace/score/feedback queries).\n // Local tracing is opt-in via `/observability local on`. When disabled, the\n // MastraStorageExporter is omitted entirely so traces never fall through to\n // the default libsql backend.\n let observabilityDomain: DuckDBStore['observability'] | undefined;\n let observabilityWarning: string | undefined;\n if (globalSettings.observability.localTracing) {\n try {\n const observabilityDuckDB = new DuckDBStore({\n id: 'mastra-code-observability',\n path: getObservabilityDatabasePath(),\n });\n // Force an early connection attempt so the lock error surfaces now, not mid-session.\n await observabilityDuckDB.db.getConnection();\n observabilityDomain = observabilityDuckDB.observability;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const isLockError = /lock|locked|busy/i.test(message);\n if (isLockError) {\n observabilityWarning =\n 'Observability unavailable — another MastraCode instance holds the database lock. Traces, scores, and feedback will not be recorded in this session.';\n } else {\n observabilityWarning = `Observability unavailable — DuckDB initialization failed: ${message}`;\n }\n }\n }\n\n const harnessStorage = new InMemoryHarness();\n\n const storage = new MastraCompositeStore({\n id: 'mastra-code-storage',\n default: storageResult.storage,\n domains: {\n // When local tracing is off, disable the observability domain entirely so\n // trace/score/feedback writes never fall through to the default libsql store.\n observability: observabilityDomain ?? false,\n harness: harnessStorage,\n },\n });\n\n // Observability (tracing, scoring, feedback)\n const observability = new Observability({\n configs: {\n default: {\n serviceName: 'mastracode',\n // Only these requestContext keys are stored on spans — prevents leaking\n // large objects (controller state, workspace, env vars) into trace data.\n // Use dot-notation because these are nested inside the 'controller' key.\n //\n // Session identifiers:\n // threadId, resourceId, session.modeId, agentControllerId\n // Environment & project:\n // state.projectName, state.gitBranch\n // Model configuration:\n // session.modelId, state.subagentModelId\n // Agent settings:\n // state.yolo, state.thinkingLevel, state.smartEditing\n // Observational memory settings:\n // state.omScope, state.observerModelId, state.reflectorModelId,\n // state.observationThreshold, state.reflectionThreshold\n requestContextKeys: [\n // Session identifiers\n 'controller.threadId',\n 'controller.resourceId',\n 'controller.session.modeId',\n 'controller.controllerId',\n // Environment & project\n 'controller.state.projectName',\n 'controller.state.gitBranch',\n // Model configuration\n 'controller.session.modelId',\n 'controller.state.subagentModelId',\n // Agent settings\n 'controller.state.yolo',\n 'controller.state.thinkingLevel',\n 'controller.state.smartEditing',\n // Observational memory settings\n 'controller.state.omScope',\n 'controller.state.observerModelId',\n 'controller.state.reflectorModelId',\n 'controller.state.observationThreshold',\n 'controller.state.reflectionThreshold',\n ],\n exporters: [\n // Only persist traces locally when DuckDB observability is available\n // (via `/observability local on`). Without this guard the storage\n // exporter falls through to the default libsql backend and silently\n // fills the main database with gigabytes of span data.\n ...(observabilityDomain ? [new MastraStorageExporter({ strategy: 'event-sourced' })] : []),\n new MastraPlatformExporter(resolveCloudObservabilityConfig(globalSettings, authStorage, project.resourceId)),\n ],\n spanOutputProcessors: [new SensitiveDataFilter()],\n },\n },\n });\n\n // Vector store for recall search (separate DB file to avoid bloating main\n // storage). An injected instance is used as-is; with an injected storage\n // instance and no injected vector, recall search stays vector-less.\n const vector =\n config?.vector ?? (storageConfig ? await createVectorStore(storageConfig, storageResult.backend) : undefined);\n\n // Maintenance handle for /prune: prunes via the inner store (whose retention\n // config covers every domain, including legacy libsql observability spans)\n // and can compact local libsql files to reclaim disk. The vector store's\n // connection must close alongside storage — the compaction's file swap\n // refuses to run while any connection is open.\n const storageMaintenance: StorageMaintenance = createStorageMaintenance({\n storage: storageResult.storage,\n backend: storageResult.backend,\n retention: DEFAULT_RETENTION,\n localDbFiles: storageConfig ? resolveLocalDbFiles(storageConfig, storageResult.backend) : [],\n closeVector: vector instanceof LibSQLVector ? () => vector.close() : undefined,\n });\n\n const memory = config?.memory === false ? undefined : (config?.memory ?? getDynamicMemory(storage, vector));\n\n // MCP\n const mcpManager = config?.disableMcp ? undefined : createMcpManager(project.rootPath, configDir, config?.mcpServers);\n\n // Hooks\n const hookManager = config?.disableHooks\n ? undefined\n : new HookManager(project.rootPath, 'session-init', configDir, homeDir);\n\n const pluginManager = config?.disablePlugins\n ? undefined\n : (config?.pluginManager ?? new PluginManager({ projectRoot: project.rootPath, configDir, homeDir }));\n const loadedPlugins = pluginManager ? await pluginManager.reload() : [];\n const pluginTools = pluginManager?.getPluginTools() ?? {};\n\n // Scorers (live evaluation with sampling)\n const outcomeScorer = createOutcomeScorer();\n const efficiencyScorer = createEfficiencyScorer();\n\n // Agent — githubSignals is created before `controller` but the closure below\n // captures `controller` by reference; it is only invoked at notification time,\n // well after controller is constructed (line ~692). Explicit type annotations\n // on githubSignals, codeAgent, modes, and controller break the circular\n // inference chain this forward reference would otherwise create.\n const githubSignals: GithubSignals | undefined =\n globalSettings.signals?.experimentalGithubSignals && !config?.disableGithubSignals\n ? new GithubSignals({\n cwd: project.rootPath,\n gitcrawlCommand:\n process.env.MASTRACODE_GITCRAWL_BIN ??\n process.env.GITCRAWL_BIN ??\n process.env.MASTRACODE_GITCRAWL_COMMAND ??\n process.env.GITCRAWL_COMMAND,\n getNotificationStreamOptions: async ({ resourceId, threadId }) => {\n // Run the woken notification as the session that owns the target\n // resource so it uses that session's model/mode/state. Fall back to\n // the current session only when no session owns the resource yet.\n const session = (await controller.getSessionByResource(resourceId)) ?? activeSession!;\n // A long-running system must be able to drive work unattended, so a\n // target session without an explicit model selection falls back to a\n // real model rather than failing the run: the current session's live\n // selection (what the user actually picked), then the mode's default.\n const modeId = session.mode.get();\n const defaultModeModelId = controller.listModes().find(mode => mode.id === modeId)?.defaultModelId;\n const modelId = session.model.get() || activeSession?.model.get() || defaultModeModelId || '';\n const requestContext = new RequestContext();\n const agentControllerContext: AgentControllerRequestContext = {\n controllerId: controller.id,\n state: session.state.get(),\n getState: () => session.state.get(),\n setState: updates => session.state.set(updates),\n threadId,\n resourceId,\n session: {\n id: session.identity.getId(),\n ownerId: session.identity.getOwnerId(),\n modeId,\n modelId,\n state: {\n get: () => session.state.get(),\n set: updates => session.state.set(updates),\n update: updater => session.state.update(updater),\n },\n },\n workspace: controller.getWorkspace(),\n getSubagentModelId: params => session.subagents.model.get(params ?? {}),\n };\n requestContext.set('controller', agentControllerContext);\n\n return {\n memory: { thread: threadId, resource: resourceId },\n requestContext,\n maxSteps: 1000,\n savePerStep: false,\n requireToolApproval: (session.state.get() as Record<string, unknown>).yolo !== true,\n modelSettings: { temperature: 1 },\n };\n },\n })\n : undefined;\n const codeAgent: Agent = createCodingAgent({\n id: CODE_AGENT_ID,\n name: 'Code Agent',\n // Workspace is wired per-request at the AgentController level (see\n // `config.workspace` below), so opt out of the factory's default local\n // workspace. An explicit `undefined` is required: the factory only builds a\n // default when the `workspace` key is absent.\n workspace: undefined,\n instructions: getDynamicInstructions,\n model: getDynamicModel,\n tools: createDynamicTools(mcpManager, config?.extraTools, config?.disabledTools, storage, pluginTools),\n hooks: createToolHooks(hookManager, config?.postToolObserver),\n scorers: {\n outcome: {\n scorer: outcomeScorer,\n sampling: { type: 'none' },\n },\n efficiency: {\n scorer: efficiencyScorer,\n sampling: { type: 'ratio', rate: 0.3 },\n },\n },\n // TaskSignalProvider bundles the task tools + TaskStateProcessor: it merges\n // the tools into the toolset and registers the task state-signal processor,\n // so the task list persists across turns and survives OM truncation.\n signals: [new TaskSignalProvider(), ...(githubSignals ? [githubSignals] : [])],\n // Native goal mechanism: the in-loop goal step judges the thread's active\n // objective each qualifying iteration. The judge model is required for any\n // gating to occur; when unset the goal step is a complete no-op. A6 auto-wires\n // the GoalStateProcessor so the `<current-objective>` signal persists across\n // turns. Per-thread overrides live in the ThreadState `goal` record and win\n // over these defaults.\n goal: {\n // Resolve the judge model through mastracode's gateway (a model-resolver\n // function) so provider credentials are injected; returns undefined when no\n // judge model is configured, keeping the goal step a no-op. Bind the same\n // `settingsPath` used above so the judge model and `maxRuns` come from one\n // config (a custom settings file would otherwise diverge).\n judge: ctx => getGoalJudgeModel(ctx, config?.settingsPath),\n maxRuns: globalSettings.models.goalMaxTurns ?? 50,\n maxSteps: 1000,\n prompt: DEFAULT_GOAL_JUDGE_PROMPT,\n // Read-only workspace tools the default goal judge may call to verify the\n // agent's work against the actual filesystem (view, search_content,\n // find_files, file_stat, lsp_inspect) rather than grading prose alone —\n // restoring the original MastraCode judge's verification ability. Resolved\n // per-request from the active workspace (mirrors `judge`).\n tools: getGoalJudgeTools,\n },\n inputProcessors: [\n ...(config?.inputProcessors ?? []),\n new PlanRejectionAbortProcessor(),\n new AgentsMDInjector({\n getIgnoredInstructionPaths: ({ requestContext }) => {\n const agentControllerContext = requestContext?.get('controller') as\n AgentControllerRequestContext<{ projectPath?: string }> | undefined;\n const state = agentControllerContext?.getState();\n return getStaticallyLoadedInstructionPaths(state?.projectPath ?? project.rootPath);\n },\n }),\n new ProviderHistoryCompat(),\n ],\n errorProcessors: [\n new StreamErrorRetryProcessor({\n matchers: [\n { match: isBadRequestError, maxRetries: 1, delayMs: 2000 },\n {\n match: isTransientConnectionError,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n delayMs: ({ retryCount }) =>\n Math.min(\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS * Math.pow(2, retryCount),\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS,\n ),\n },\n ],\n }),\n new PrefillErrorHandler(),\n new ProviderHistoryCompat(),\n ],\n });\n\n // const defaultSubAgents: Array<AgentControllerSubagent> = [];\n // const defaultSubagents = [exploreSubagent, planSubagent, executeSubagent];\n\n const defaultModes: AgentControllerMode[] = [\n {\n ...buildMode,\n metadata: {\n ...buildMode.metadata,\n color: mastraBrand.green,\n },\n },\n {\n ...planMode,\n metadata: {\n ...planMode.metadata,\n color: mastraBrand.purple,\n },\n },\n {\n ...fastMode,\n metadata: {\n ...fastMode.metadata,\n color: mastraBrand.orange,\n },\n },\n ];\n\n const defaultIntervalHandlers: IntervalHandler[] = [\n {\n id: 'gateway-sync',\n intervalMs: 5 * 60 * 1000,\n immediate: false,\n handler: () => syncGateways(),\n },\n ];\n const intervalHandlers = config?.intervalHandlers ?? defaultIntervalHandlers;\n\n // Build lightweight provider access for resolving built-in packs at startup.\n // Anthropic/OpenAI use AuthStorage; other providers use env API keys.\n // Also scan the full provider registry so configured API keys satisfy access checks.\n const anthropicCred = authStorage.get('anthropic');\n const openaiCred = authStorage.get('openai-codex');\n const githubCopilotCred = authStorage.get('github-copilot');\n const startupAccess: ProviderAccess = {\n anthropic:\n anthropicCred?.type === 'oauth'\n ? 'oauth'\n : anthropicCred?.type === 'api_key' && anthropicCred.key.trim().length > 0\n ? 'apikey'\n : false,\n openai:\n openaiCred?.type === 'oauth'\n ? 'oauth'\n : openaiCred?.type === 'api_key' && openaiCred.key.trim().length > 0\n ? 'apikey'\n : false,\n cerebras: process.env.CEREBRAS_API_KEY ? 'apikey' : false,\n google: process.env.GOOGLE_GENERATIVE_AI_API_KEY ? 'apikey' : false,\n deepseek: process.env.DEEPSEEK_API_KEY ? 'apikey' : false,\n 'github-copilot': githubCopilotCred?.type === 'oauth' ? 'oauth' : false,\n };\n // Gateway covers all providers — ensure Anthropic/OpenAI packs are visible\n if (mgApiKey) {\n if (!startupAccess.anthropic) startupAccess.anthropic = 'apikey';\n if (!startupAccess.openai) startupAccess.openai = 'apikey';\n }\n // Check all providers in the registry for API keys\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n for (const [provider, config] of Object.entries(registry)) {\n if (startupAccess[provider] === 'oauth' || startupAccess[provider] === 'apikey') continue; // Already enabled above\n if (provider === 'anthropic' || provider === 'openai') continue;\n const envVars = config?.apiKeyEnvVar;\n const envVarList = Array.isArray(envVars) ? envVars : envVars ? [envVars] : [];\n if (envVarList.some(envVar => process.env[envVar])) {\n startupAccess[provider] = 'apikey';\n }\n }\n } catch {\n // Registry may not be loaded yet; the 5 hardcoded providers are sufficient fallback\n }\n const builtinPacks = getAvailableModePacks(startupAccess);\n const builtinOmPacks = getAvailableOmPacks(startupAccess);\n const effectiveDefaults = resolveModelDefaults(globalSettings, builtinPacks);\n const effectiveObserverModel = resolveOmRoleModel(globalSettings, 'observer', builtinOmPacks);\n const effectiveReflectorModel = resolveOmRoleModel(globalSettings, 'reflector', builtinOmPacks);\n const effectiveObservationThreshold = globalSettings.models.omObservationThreshold ?? undefined;\n const effectiveReflectionThreshold = globalSettings.models.omReflectionThreshold ?? undefined;\n const effectiveCavemanObservations = globalSettings.models.omCavemanObservations ?? undefined;\n const effectiveObserveAttachments = globalSettings.models.omObserveAttachments ?? 'auto';\n\n const modes = addPluginToolsToModeAllowlists(\n applyEffectiveDefaultsToModes(config?.modes ? config.modes : defaultModes, effectiveDefaults),\n Object.keys(pluginTools),\n );\n const defaultModeId =\n modes.find(mode => mode.metadata?.default === true)?.id ??\n modes.find(mode => mode.id === 'build')?.id ??\n modes[0]?.id;\n if (!defaultModeId) {\n throw new Error('MastraCode requires at least one mode');\n }\n\n // Map subagent types to mode models: explore→fast, plan→plan, execute→build\n // const subagentModeMap: Record<string, string> = { explore: 'fast', plan: 'plan', execute: 'build' };\n // Subagents inherit workspace tools from the parent agent's workspace automatically.\n // Apply disabledTools filter to both default and custom subagents.\n // const subagents = [];\n\n // Build initial state with global preferences\n const globalInitialState: Partial<MastraCodeState> = {};\n if (effectiveObserverModel) {\n globalInitialState.observerModelId = effectiveObserverModel;\n }\n if (effectiveReflectorModel) {\n globalInitialState.reflectorModelId = effectiveReflectorModel;\n }\n if (effectiveObservationThreshold !== undefined) {\n globalInitialState.observationThreshold = effectiveObservationThreshold;\n }\n if (effectiveReflectionThreshold !== undefined) {\n globalInitialState.reflectionThreshold = effectiveReflectionThreshold;\n }\n if (effectiveCavemanObservations !== undefined) {\n globalInitialState.cavemanObservations = effectiveCavemanObservations;\n }\n if (effectiveObserveAttachments !== undefined) {\n globalInitialState.observeAttachments = effectiveObserveAttachments;\n }\n if (globalSettings.preferences.yolo !== null) {\n globalInitialState.yolo = globalSettings.preferences.yolo;\n }\n globalInitialState.thinkingLevel = globalSettings.preferences.thinkingLevel;\n if (config?.omScope) {\n globalInitialState.omScope = config.omScope;\n }\n // Seed subagent models from global settings\n for (const [key, modelId] of Object.entries(globalSettings.models.subagentModels)) {\n if (key === 'default' || key === '_default') {\n globalInitialState.subagentModelId = modelId;\n } else {\n globalInitialState[`subagentModelId_${key}`] = modelId;\n }\n }\n\n const typedStateSchema = stateSchema as PublicSchema<MastraCodeState>;\n const controller: AgentController<MastraCodeState> = new AgentController<MastraCodeState>({\n id: 'mastra-code',\n resourceId: project.resourceId,\n storage,\n observability,\n memory,\n pubsub: signalsPubSub,\n stateSchema: typedStateSchema,\n agent: codeAgent,\n subagents: config?.subagents ?? [],\n gateways: [amazonBedrockGateway, mastraCodeGateway],\n workspace: config?.workspace ?? (args => getDynamicWorkspace(args)),\n browser: config?.browser,\n idGenerator: config?.idGenerator,\n toolCategoryResolver: getToolCategory,\n initialState: {\n projectPath: project.rootPath,\n projectName: project.name,\n gitBranch: project.gitBranch,\n pluginSkillPaths: loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.skillPaths ?? []) : [])),\n pluginCommandPaths: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' ? (plugin.commandPaths ?? []) : [],\n ),\n pluginInstructions: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' && plugin.instructions ? [plugin.instructions] : [],\n ),\n yolo: true,\n ...globalInitialState,\n ...config?.initialState,\n // configDir must always win over initialState spreads to stay in sync\n // with MCP/hooks/storage which were already initialized with this value.\n configDir,\n },\n modes,\n intervalHandlers,\n modelUseCountProvider: () => loadSettings().modelUseCounts,\n modelUseCountTracker: modelId => {\n try {\n const settings = loadSettings();\n settings.modelUseCounts[modelId] = (settings.modelUseCounts[modelId] ?? 0) + 1;\n saveSettings(settings);\n } catch (error) {\n console.error('Failed to persist model usage count', error);\n }\n },\n threadLock: crossProcessPubSub\n ? undefined\n : {\n acquire: acquireThreadLock,\n release: releaseThreadLock,\n },\n });\n\n // The AgentController is fully constructed but intentionally NOT inited here. Init and\n // session creation are deferred to the composition layer (see below) so the\n // controller can be wired in three ways:\n //\n // 1. Server + Web — registered on a server Mastra, then inited; sessions\n // minted per browser client over HTTP.\n // 2. Server + TUI — same server composition; the TUI drives a session\n // (in-process today; remote transport is future work).\n // 3. Local + TUI — controller builds its own internal Mastra on init() and\n // mints one eager session for the whole process.\n //\n // Cases 1 & 2 use `mountAgentControllerOnMastra` (register-before-init, no eager\n // session). Case 3 uses `bootLocalAgentController` (init + one wired session).\n return {\n controller: controller,\n storage,\n storageMaintenance,\n observability,\n memory,\n mcpManager,\n hookManager,\n pluginManager,\n loadedPlugins,\n pluginTools,\n signalsPubSub,\n authStorage,\n resolveModel,\n storageWarning,\n observabilityWarning,\n builtinPacks,\n builtinOmPacks,\n effectiveDefaults,\n githubSignals,\n // Identity for the single local session (Case 3). Servers ignore these and\n // mint per-request sessions with client-supplied resourceIds instead.\n sessionId,\n ownerId,\n // Lets the composition layer publish the created session back into the\n // config closures (e.g. notification stream options read it lazily).\n setActiveSession: (session: Session<MastraCodeState>) => {\n activeSession = session;\n },\n };\n}\n\n/**\n * Result of {@link createMastraCodeAgentController}: every shared resource plus the\n * inert AgentController, ready to be either booted locally or mounted on a server\n * Mastra.\n */\nexport type MastraCodeAgentController = Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n\n/**\n * Wires the session-scoped concerns MastraCode layers on top of a Session:\n * hookManager thread-id sync, GitHub PR polling for the current thread, and\n * per-thread persistence of the mastracode-only `/om` settings.\n *\n * Used by {@link bootLocalAgentController} for the single local session. A server can\n * call this for any session it mints if it wants the same background wiring.\n */\nexport async function wireSessionConcerns(\n base: Pick<MastraCodeAgentController, 'hookManager' | 'githubSignals' | 'setActiveSession'>,\n session: Session<MastraCodeState>,\n): Promise<void> {\n const { hookManager, githubSignals } = base;\n base.setActiveSession(session);\n\n // Sync hookManager session ID on thread changes\n if (hookManager) {\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') {\n hookManager.setSessionId(event.threadId);\n } else if (event.type === 'thread_created') {\n hookManager.setSessionId(event.thread.id);\n }\n });\n }\n\n if (githubSignals) {\n const startGithubPollingForCurrentThread = async (threadId?: string | null) => {\n if (!threadId) return;\n githubSignals.stopAllPolling();\n try {\n const threads = await session.thread.list({ allResources: true });\n const thread = threads.find((item: { id: string }) => item.id === threadId);\n await githubSignals.startPollingForThread(\n {\n threadId,\n resourceId: thread?.resourceId ?? session.identity.getResourceId(),\n },\n { pollImmediately: true },\n );\n } catch (error) {\n console.warn('Failed to start GitHub PR polling:', error);\n }\n };\n\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') void startGithubPollingForCurrentThread(event.threadId);\n else if (event.type === 'thread_created') void startGithubPollingForCurrentThread(event.thread.id);\n });\n void startGithubPollingForCurrentThread(session.thread.getId());\n }\n\n // Persist MastraCode-owned /om settings per-thread (mastracode-only concern;\n // intentionally not in core's controller loadThreadMetadata).\n const omThreadStateSession = session as unknown as Session<Record<string, unknown>>;\n attachOMThreadStatePersistence(omThreadStateSession);\n await restoreOMThreadStateForCurrentThread(omThreadStateSession).catch(() => {\n // Persistence is best-effort; don't crash startup if storage hiccups.\n });\n}\n\n/**\n * Case 3 (AgentController local + TUI/headless): build the controller, let it stand up its\n * own internal Mastra via `init()`, and mint the single eager session that all\n * work in this process runs through. The AgentController owns no session of its own.\n */\nexport async function bootLocalAgentController(config?: MastraCodeConfig) {\n const base = await createMastraCodeAgentController(config);\n const { controller, sessionId, ownerId } = base;\n\n await controller.init();\n await controller.getMastra()?.startWorkers();\n const session = await controller.createSession({ id: sessionId, ownerId });\n await wireSessionConcerns(base, session);\n\n return { ...base, session };\n}\n\n/** Result of {@link mountAgentControllerOnMastra}: shared handles plus the owning Mastra. */\nexport type MountedMastraCode = MastraCodeAgentController & { mastra: Mastra };\n\n/**\n * Cases 1 & 2 (AgentController in Server + Web/TUI): build the controller, register it on a\n * server-owned Mastra, THEN init it. Registering before `init()` is what makes\n * the controller inherit the server's Mastra (storage, agents, gateways) instead of\n * spinning up its own internal one — there is a single shared Mastra.\n *\n * No eager session is minted: each client (browser or terminal) creates/resumes\n * its own isolated session via `controller.createSession({ resourceId })`, so one\n * server can drive many concurrent users.\n *\n * Pass an existing `mastra` to mount onto a Mastra that already hosts other\n * primitives; otherwise a Mastra is created that owns the controller's storage so\n * durability is configured in one place.\n */\nexport async function mountAgentControllerOnMastra(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n /**\n * Additional `server` config to fold onto the constructed Mastra alongside\n * the assembled `apiRoutes` (e.g. `middleware`, `cors`). Used by the\n * platform entry (`src/mastra/index.ts`) to own the WorkOS gate + tenant\n * dispatcher + CORS on the instance the deployer generates its server from.\n * Ignored when `mastra` is provided (mounting onto a caller-owned instance).\n */\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<MountedMastraCode> {\n const prepared = await prepareAgentControllerMount(config);\n if (config?.mastra) {\n // Mounting onto a Mastra the caller already built. Ensure the controller's\n // back-reference points at it (idempotent — only sets #externalMastra).\n prepared.base.controller.__registerMastra(config.mastra);\n await prepared.finalize();\n return { ...prepared.base, mastra: config.mastra };\n }\n const mastra = new Mastra(prepared.mastraArgs);\n await prepared.finalize();\n return { ...prepared.base, mastra };\n}\n\n/**\n * Assemble everything needed to construct the server-owned Mastra WITHOUT\n * constructing it, so a caller (the platform entry `src/mastra/index.ts`) can\n * run the `new Mastra(...)` literal in its own module. The deployer's\n * `checkConfigExport` Babel plugin only marks the config valid when it finds a\n * top-level `new Mastra(...)` exported as `mastra` in the ENTRY file; hiding the\n * construction inside this helper would trip the \"Invalid Mastra config\" warning.\n *\n * Returns the constructor args plus a `finalize()` that runs the post-construct\n * boot (`controller.init()` + `startWorkers()`). The controller is registered on\n * the Mastra via the `agentControllers` arg at construction time.\n */\nexport async function prepareAgentControllerMount(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<{\n base: Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n mastraArgs: NonNullable<ConstructorParameters<typeof Mastra>[0]>;\n finalize: () => Promise<void>;\n}> {\n const base = await createMastraCodeAgentController(config);\n const { controller, storage, authStorage } = base;\n const controllerId = config?.controllerId ?? controller.id;\n const apiRoutes = config?.buildApiRoutes?.({ controller, authStorage });\n const extraServerConfig = config?.buildServerConfig?.({ controller, authStorage });\n\n const serverConfig = {\n ...extraServerConfig,\n ...(apiRoutes?.length ? { apiRoutes } : {}),\n };\n const mastraArgs = {\n agentControllers: { [controllerId]: controller },\n storage,\n // Mirror the controller's internal-Mastra construction (which passes\n // `config.pubsub` through): the server-owned Mastra must run its event\n // bus on the same transport so streams/workflows/signals stay\n // cross-process when a distributed PubSub (e.g. Redis Streams) is\n // configured.\n ...(base.signalsPubSub ? { pubsub: base.signalsPubSub } : {}),\n ...(Object.keys(serverConfig).length ? { server: serverConfig } : {}),\n };\n\n const finalize = async () => {\n await controller.init();\n await controller.getMastra()?.startWorkers();\n };\n\n return { base, mastraArgs, finalize };\n}\n\n/**\n * Back-compat alias. Historically `createMastraCode` built and booted a local\n * controller with a single session; that behavior now lives in\n * {@link bootLocalAgentController}. New code should call the explicit factory for its\n * case: `bootLocalAgentController` (local) or {@link mountAgentControllerOnMastra} (server).\n */\nexport const createMastraCode = bootLocalAgentController;\n\n/**\n * Programmatic headless API. `runMC` runs an already-built controller/session\n * (from {@link createMastraCode}) as an async-iterable run that also resolves to\n * a typed result. Also available via the `mastracode/headless` subpath.\n */\nexport {\n runMC,\n runMCCli,\n hasHeadlessFlag,\n autoApprovePolicy,\n denyPolicy,\n permissionModeToPolicy,\n formatHuman,\n formatJsonl,\n renderTextResult,\n renderJsonResult,\n} from './headless/index.js';\nexport type {\n RunMCOptions,\n RunMCResult,\n RunMCStatus,\n RunMCUsage,\n RunMCToolCall,\n RunMCToolResult,\n RunMCError,\n RunMCThreadOptions,\n MCRun,\n ResolutionPolicy,\n PermissionMode,\n} from './headless/index.js';\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O;AACpC;AAcA,eAAsB,4BACpB,QAaC;AACD,QAAM,OAAO,MAAM,gCAAgC,MAAM;AACzD,QAAM,EAAE,YAAY,SAAS,YAAY,IAAI;AAC7C,QAAM,eAAe,QAAQ,gBAAgB,WAAW;AACxD,QAAM,YAAY,QAAQ,iBAAiB,EAAE,YAAY,YAAY,CAAC;AACtE,QAAM,oBAAoB,QAAQ,oBAAoB,EAAE,YAAY,YAAY,CAAC;AAEjF,QAAM,eAAe;AAAA,IACnB,GAAG;AAAA,IACH,GAAI,WAAW,SAAS,EAAE,UAAU,IAAI,CAAC;AAAA,EAC3C;AACA,QAAM,aAAa;AAAA,IACjB,kBAAkB,EAAE,CAAC,YAAY,GAAG,WAAW;AAAA,IAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,GAAI,KAAK,gBAAgB,EAAE,QAAQ,KAAK,cAAc,IAAI,CAAC;AAAA,IAC3D,GAAI,OAAO,KAAK,YAAY,EAAE,SAAS,EAAE,QAAQ,aAAa,IAAI,CAAC;AAAA,EACrE;AAEA,QAAM,WAAW,YAAY;AAC3B,UAAM,WAAW,KAAK;AACtB,UAAM,WAAW,UAAU,GAAG,aAAa;AAAA,EAC7C;AAEA,SAAO,EAAE,MAAM,YAAY,SAAS;AACtC;AAQO,MAAM,mBAAmB;AAOhC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["config"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { hostname } from 'node:os';\nimport path from 'node:path';\n\nimport type { Agent } from '@mastra/core/agent';\nimport { AgentController } from '@mastra/core/agent-controller';\nimport type {\n IntervalHandler,\n AgentControllerConfig,\n AgentControllerEvent,\n AgentControllerMode,\n AgentControllerSubagent,\n AgentControllerRequestContext,\n Session,\n} from '@mastra/core/agent-controller';\nimport { createCodingAgent } from '@mastra/core/coding-agent';\nimport type { PubSub } from '@mastra/core/events';\nimport { PROVIDER_REGISTRY } from '@mastra/core/llm';\nimport type { ProviderConfig } from '@mastra/core/llm';\nimport { Mastra } from '@mastra/core/mastra';\nimport {\n AgentsMDInjector,\n isBadRequestError,\n PrefillErrorHandler,\n ProviderHistoryCompat,\n StreamErrorRetryProcessor,\n} from '@mastra/core/processors';\nimport type { InputProcessor } from '@mastra/core/processors';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { PublicSchema } from '@mastra/core/schema';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { TaskSignalProvider } from '@mastra/core/signals';\nimport { InMemoryHarness, MastraCompositeStore } from '@mastra/core/storage';\nimport { DEFAULT_GOAL_JUDGE_PROMPT } from '@mastra/core/tools';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { DuckDBStore } from '@mastra/duckdb';\n\nimport { GithubSignals } from '@mastra/github-signals';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport {\n Observability,\n MastraStorageExporter,\n MastraPlatformExporter,\n SensitiveDataFilter,\n} from '@mastra/observability';\nimport { PostgresStore } from '@mastra/pg';\n\nimport { hasCredentialStoreProvider } from './agents/credential-resolver.js';\nimport { getDynamicInstructions } from './agents/instructions.js';\nimport { getDynamicMemory } from './agents/memory.js';\nimport { createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel } from './agents/model.js';\nimport { buildMode } from './agents/modes/build.js';\nimport { fastMode } from './agents/modes/explore.js';\nimport { planMode } from './agents/modes/plan.js';\nimport { getStaticallyLoadedInstructionPaths } from './agents/prompts/agent-instructions.js';\n// import { executeSubagent } from './agents/subagents/execute.js';\n// import { exploreSubagent } from './agents/subagents/explore.js';\n// import { planSubagent } from './agents/subagents/plan.js';\nimport { attachOMThreadStatePersistence, restoreOMThreadStateForCurrentThread } from './agents/thread-caveman-state.js';\nimport { createDynamicTools, createToolHooks } from './agents/tools.js';\nimport type { PostToolObserver, ToolLike } from './agents/tools.js';\n\nimport { getDynamicWorkspace, getGoalJudgeTools } from './agents/workspace.js';\nimport { AuthStorage } from './auth/storage.js';\nimport { DEFAULT_CONFIG_DIR, validateConfigDirName } from './constants.js';\nimport { createOutcomeScorer, createEfficiencyScorer } from './evals/scorers/index.js';\nimport { HookManager } from './hooks/index.js';\nimport { createMcpManager } from './mcp/index.js';\nimport type { McpServerConfig } from './mcp/index.js';\nimport type { ProviderAccess } from './onboarding/packs.js';\nimport { getAvailableModePacks, getAvailableOmPacks } from './onboarding/packs.js';\nimport {\n loadSettings,\n MASTRA_GATEWAY_PROVIDER,\n OBSERVABILITY_AUTH_PREFIX,\n resolveModelDefaults,\n resolveOmRoleModel,\n saveSettings,\n} from './onboarding/settings.js';\nimport { getToolCategory } from './permissions.js';\nimport { PluginManager } from './plugins/manager.js';\nimport { PlanRejectionAbortProcessor } from './processors/plan-rejection-abort.js';\nimport { createAmazonBedrockGateway } from './providers/amazon-bedrock-gateway.js';\nimport { setAuthStorage } from './providers/claude-max.js';\nimport { setAuthStorage as setGitHubCopilotAuthStorage } from './providers/github-copilot.js';\nimport { setAuthStorage as setOpenAIAuthStorage } from './providers/openai-codex.js';\nimport { setAuthStorage as setXAIAuthStorage } from './providers/xai.js';\n\nimport { stateSchema } from './schema.js';\nimport type { MastraCodeState } from './schema.js';\n\nimport { mastraBrand } from './theme-palette.js';\nimport { syncGateways } from './utils/gateway-sync.js';\nimport {\n detectProject,\n getObservabilityDatabasePath,\n getStorageConfig,\n getResourceIdOverride,\n} from './utils/project.js';\nimport type { StorageConfig } from './utils/project.js';\nimport { createSignalsPubSub } from './utils/signals-pubsub.js';\nimport { createStorage, createVectorStore } from './utils/storage-factory.js';\nimport type { StorageResult } from './utils/storage-factory.js';\nimport { createStorageMaintenance, DEFAULT_RETENTION, resolveLocalDbFiles } from './utils/storage-maintenance.js';\nimport type { StorageMaintenance } from './utils/storage-maintenance.js';\nimport { acquireThreadLock, releaseThreadLock } from './utils/thread-lock.js';\n\nconst CODE_AGENT_ID = 'code-agent';\n\n// Global retry policy for transient connection failures (e.g. provider sockets dropping mid-stream).\n// Applied centrally to every model call via StreamErrorRetryProcessor, independent of model-pack\n// settings, so all modes/subagents benefit from a short wait before retrying a dropped connection.\n// Delay uses exponential backoff: initialDelay * 2^retryCount, capped at maxDelay.\nconst MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES = 2;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS = 1000;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS = 30000;\n\nconst TRANSIENT_CONNECTION_ERROR_CODES = new Set(['ECONNRESET', 'EPIPE']);\nconst TRANSIENT_CONNECTION_MESSAGE_PATTERN = /econnreset|socket hang up|write epipe|other side closed/i;\n\n/**\n * Matcher for transient connection failures. Cause-chain traversal is handled\n * by `StreamErrorRetryProcessor.isRetryableStreamError`, which calls each\n * matcher at every level of the cause chain.\n */\nfunction isTransientConnectionError(error: unknown): boolean {\n if (!error) return false;\n\n const code = typeof error === 'object' && 'code' in error ? (error as { code?: unknown }).code : undefined;\n if (typeof code === 'string' && TRANSIENT_CONNECTION_ERROR_CODES.has(code.toUpperCase())) return true;\n\n const message = error instanceof Error ? error.message : undefined;\n if (typeof message === 'string' && TRANSIENT_CONNECTION_MESSAGE_PATTERN.test(message)) return true;\n\n return false;\n}\n\n/** Short deterministic hash (sha256, first 12 hex chars) matching project.ts shortHash style. */\nfunction shortHash(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 12);\n}\n\nfunction applyEffectiveDefaultsToModes(\n modes: AgentControllerMode[],\n effectiveDefaults: Record<string, string>,\n): AgentControllerMode[] {\n return modes.map(mode => {\n const savedModel = effectiveDefaults[mode.id];\n if (!savedModel) {\n return mode;\n }\n return {\n ...mode,\n defaultModelId: savedModel,\n };\n });\n}\n\nfunction addPluginToolsToModeAllowlists(\n modes: AgentControllerMode[],\n pluginToolNames: string[],\n): AgentControllerMode[] {\n if (pluginToolNames.length === 0) return modes;\n return modes.map(mode => {\n if (!mode.availableTools) return mode;\n return {\n ...mode,\n availableTools: Array.from(new Set([...mode.availableTools, ...pluginToolNames])),\n };\n });\n}\n\nexport interface MastraCodeConfig {\n /** Working directory for project detection. Default: process.cwd() */\n cwd?: string;\n /** Home directory for global config discovery. Default: os.homedir() */\n homeDir?: string;\n /** Override modes (model IDs, colors, which modes exist). Default: build/plan/fast */\n modes?: AgentControllerMode[];\n /** Override or extend subagent definitions. Default: explore/plan/execute */\n subagents?: AgentControllerSubagent[];\n /** Extra tools merged into the dynamic tool set. Can be a static record or a (sync or async) function that receives requestContext. */\n extraTools?:\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n /** Observe completed tool calls without replacing or modifying the built-in tool implementation. */\n postToolObserver?: PostToolObserver;\n /**\n * Stateless input processor instances prepended before Mastra Code's mandatory processors.\n * Embedders may extend processing but cannot replace built-in safety and compatibility policy.\n */\n inputProcessors?: InputProcessor[];\n /** Tools removed from the dynamic tool set before exposure to the model */\n disabledTools?: string[];\n /**\n * Custom storage config instead of auto-detected default, or a pre-built\n * store instance. An instance is used as-is: no connection test and no\n * LibSQL fallback — if the injected store fails, that's a hard error.\n */\n storage?: StorageConfig | MastraCompositeStore;\n /** Backend for an injected custom storage instance. Inferred for LibSQLStore and PostgresStore. */\n storageBackend?: 'libsql' | 'pg';\n /** Pre-built vector store instance for recall search. Skips the default vector store creation. */\n vector?: MastraVector;\n /** Observational memory scope. Default: auto-detected from env/config files, falls back to 'thread' */\n omScope?: 'thread' | 'resource';\n /** Path to a custom settings.json file. Default: global settings */\n settingsPath?: string;\n /** Initial state overrides (yolo, thinkingLevel, etc.) */\n initialState?: Partial<MastraCodeState>;\n /** Override id generation for threads/messages. Primarily useful for deterministic tests. */\n idGenerator?: AgentControllerConfig<MastraCodeState>['idGenerator'];\n /** Override interval handlers. Default: gateway-sync */\n intervalHandlers?: IntervalHandler[];\n /** Override the workspace. Default: local filesystem + local sandbox based on detected project */\n workspace?: AgentControllerConfig<MastraCodeState>['workspace'];\n /** Override the config directory name. Default: '.mastracode'. Replaces '.mastracode' in all project-level and global config paths (MCP, hooks, commands, database, skills, agent instructions). */\n configDir?: string;\n /** Programmatic MCP server configurations, merged with (and overriding) file-based configs. */\n mcpServers?: Record<string, McpServerConfig>;\n /** Disable MCP server discovery. Default: false */\n disableMcp?: boolean;\n /** Disable hooks. Default: false */\n disableHooks?: boolean;\n /** Disable plugin discovery/loading. Default: false */\n disablePlugins?: boolean;\n /** Disable the polling-based GitHub signal provider even when enabled in global settings. Default: false */\n disableGithubSignals?: boolean;\n /** Override the plugin manager. Primarily useful for tests or embedding. */\n pluginManager?: PluginManager;\n /**\n * Override the memory instance (or dynamic factory) passed to the AgentController.\n * When provided, this replaces the default `getDynamicMemory(storage, vector)` which\n * uses mastracode's built-in model gateway (Anthropic OAuth, OpenAI Codex,\n * custom providers, and models.dev fallback).\n *\n * Use this when you need to override memory model behavior completely.\n */\n memory?: AgentControllerConfig<MastraCodeState>['memory'] | false;\n /** Browser provider for browser automation tools. When set, the agent gains access to browser tools. */\n browser?: AgentControllerConfig<MastraCodeState>['browser'];\n /** PubSub for signal routing. When crossProcessPubSub is true, thread locks are disabled. */\n pubsub?: PubSub;\n /** Use Mastra Code's built-in Unix socket PubSub for local cross-process signal routing. */\n unixSocketPubSub?: boolean;\n /** Marks the configured PubSub as cross-process-safe, allowing Mastra Code to skip file thread locks. */\n crossProcessPubSub?: boolean;\n}\n\nexport function createAuthStorage() {\n const authStorage = new AuthStorage();\n setAuthStorage(authStorage);\n setOpenAIAuthStorage(authStorage);\n setGitHubCopilotAuthStorage(authStorage);\n setXAIAuthStorage(authStorage);\n return authStorage;\n}\n\n/**\n * Resolve cloud observability credentials for the MastraPlatformExporter.\n * Priority: per-resource settings > environment variables > disabled.\n */\nfunction resolveCloudObservabilityConfig(\n settings: ReturnType<typeof loadSettings>,\n authStorage: AuthStorage,\n resourceId: string,\n): { accessToken?: string; projectId?: string } {\n const resourceConfig = settings.observability.resources[resourceId];\n if (resourceConfig) {\n const token = authStorage.getStoredApiKey(`${OBSERVABILITY_AUTH_PREFIX}${resourceId}`);\n if (token) {\n return { accessToken: token, projectId: resourceConfig.projectId };\n }\n }\n // Fall back to environment variables for backwards compatibility\n return {\n accessToken: process.env.MASTRA_CLOUD_ACCESS_TOKEN,\n projectId: process.env.MASTRA_PROJECT_ID,\n };\n}\n\n/**\n * Base factory: builds every shared MastraCode resource (storage, observability,\n * memory, MCP, providers, gateways, agent, modes) and the {@link AgentController}, but\n * does NOT call `init()` or create a session. The controller is returned inert so\n * the composition layer can decide its Mastra ownership and session model.\n *\n * See {@link bootLocalAgentController} (Case 3) and `mountAgentControllerOnMastra` (Cases 1 & 2).\n */\nfunction resolveInjectedStorageBackend(\n storage: MastraCompositeStore,\n configuredBackend?: 'libsql' | 'pg',\n): 'libsql' | 'pg' {\n if (configuredBackend) return configuredBackend;\n if (storage instanceof LibSQLStore) return 'libsql';\n if (storage instanceof PostgresStore) return 'pg';\n throw new Error('storageBackend is required when injecting a custom storage instance.');\n}\n\nexport async function createMastraCodeAgentController(config?: MastraCodeConfig) {\n const cwd = config?.cwd ?? process.cwd();\n const homeDir = config?.homeDir ?? config?.initialState?.homeDir;\n const configDir = config?.configDir ?? DEFAULT_CONFIG_DIR;\n // The single session for this process, assigned once `createSession()` runs\n // below. Config callbacks defined before then (e.g. notification stream\n // options) read it lazily through this holder.\n let activeSession: Session<MastraCodeState> | undefined;\n if (configDir !== DEFAULT_CONFIG_DIR) {\n validateConfigDirName(configDir);\n }\n\n // Load .env file from cwd if present (for observability API keys, etc.)\n try {\n process.loadEnvFile(path.join(cwd, '.env'));\n } catch {\n // No .env file — that's fine, keys may be in shell environment\n }\n\n // Auth storage (shared with Claude Max / OpenAI providers and AgentController)\n const authStorage = createAuthStorage();\n const globalSettings = loadSettings(config?.settingsPath);\n const storedGatewayKey = authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER);\n const storedGatewayUrl = globalSettings.memoryGateway?.baseUrl;\n\n if (storedGatewayKey) {\n process.env['MASTRA_GATEWAY_API_KEY'] ??= storedGatewayKey;\n }\n\n if (storedGatewayUrl) {\n process.env['MASTRA_GATEWAY_URL'] ??= storedGatewayUrl;\n }\n\n // Load user-entered API keys from auth.json into process.env\n // (only sets env vars that aren't already present — env vars take precedence).\n // Skipped in deployed multi-tenant mode: when a per-tenant credential store\n // provider is registered, provider keys are resolved per request and must\n // never leak into process-global env vars.\n if (!hasCredentialStoreProvider()) {\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n const providerEnvVars: Record<string, string | undefined> = {};\n for (const [provider, cfg] of Object.entries(registry)) {\n const envVars = cfg?.apiKeyEnvVar;\n providerEnvVars[provider] = Array.isArray(envVars) ? envVars[0] : envVars;\n }\n providerEnvVars[MASTRA_GATEWAY_PROVIDER] ??= 'MASTRA_GATEWAY_API_KEY';\n authStorage.loadStoredApiKeysIntoEnv(providerEnvVars);\n } catch {\n // Registry unavailable — load well-known provider keys so non-gateway flows still work\n authStorage.loadStoredApiKeysIntoEnv({\n [MASTRA_GATEWAY_PROVIDER]: 'MASTRA_GATEWAY_API_KEY',\n anthropic: 'ANTHROPIC_API_KEY',\n openai: 'OPENAI_API_KEY',\n google: 'GOOGLE_GENERATIVE_AI_API_KEY',\n cerebras: 'CEREBRAS_API_KEY',\n deepseek: 'DEEPSEEK_API_KEY',\n });\n }\n }\n\n const mgApiKey = process.env['MASTRA_GATEWAY_API_KEY'] ?? storedGatewayKey;\n const mastraGatewayBaseUrl = (\n process.env['MASTRA_GATEWAY_URL'] ??\n storedGatewayUrl ??\n 'https://gateway-api.mastra.ai'\n )\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n const mastraCodeGateway = createMastraCodeGateway({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: false,\n settingsPath: config?.settingsPath,\n });\n const amazonBedrockGateway = createAmazonBedrockGateway();\n\n // Project detection\n const project = detectProject(cwd);\n\n const resourceIdOverride = getResourceIdOverride(project.rootPath, configDir);\n if (resourceIdOverride) {\n project.resourceId = resourceIdOverride;\n project.resourceIdOverride = true;\n }\n\n // Stable session id unique to this project/resource, and a machine-bound owner\n // id. resourceId encodes root path + git identity and honors overrides, so it\n // is the right input for scoping the session to the cwd/project.\n const sessionId = `mastracode-session-${shortHash(project.resourceId)}`;\n const ownerId = `mastracode-${shortHash(`${hostname()}\\0${project.rootPath}`)}`;\n\n const configuredPubSub = config?.pubsub;\n const useUnixSocketPubSub =\n (config?.unixSocketPubSub ?? globalSettings.signals?.unixSocketPubSub ?? false) && process.platform !== 'win32';\n const signalsPubSub = configuredPubSub ?? (useUnixSocketPubSub ? createSignalsPubSub(project.resourceId) : undefined);\n const crossProcessPubSub = config?.crossProcessPubSub ?? (!configuredPubSub && useUnixSocketPubSub);\n if (crossProcessPubSub && !signalsPubSub) {\n throw new Error('crossProcessPubSub requires a pubsub instance');\n }\n\n // Storage. An injected instance is used as-is — no connection test, no\n // LibSQL fallback: if the injected store fails, that's a hard error.\n const injectedStorage = config?.storage instanceof MastraCompositeStore ? config.storage : undefined;\n const storageConfig = injectedStorage\n ? undefined\n : ((config?.storage as StorageConfig | undefined) ??\n getStorageConfig(project.rootPath, globalSettings.storage, configDir));\n const storageResult: StorageResult = injectedStorage\n ? { storage: injectedStorage, backend: resolveInjectedStorageBackend(injectedStorage, config?.storageBackend) }\n : await createStorage(storageConfig!);\n const storageWarning = storageResult.warning;\n\n // Observability storage (DuckDB — separate file for OLAP-style trace/score/feedback queries).\n // Local tracing is opt-in via `/observability local on`. When disabled, the\n // MastraStorageExporter is omitted entirely so traces never fall through to\n // the default libsql backend.\n let observabilityDomain: DuckDBStore['observability'] | undefined;\n let observabilityWarning: string | undefined;\n if (globalSettings.observability.localTracing) {\n try {\n const observabilityDuckDB = new DuckDBStore({\n id: 'mastra-code-observability',\n path: getObservabilityDatabasePath(),\n });\n // Force an early connection attempt so the lock error surfaces now, not mid-session.\n await observabilityDuckDB.db.getConnection();\n observabilityDomain = observabilityDuckDB.observability;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const isLockError = /lock|locked|busy/i.test(message);\n if (isLockError) {\n observabilityWarning =\n 'Observability unavailable — another MastraCode instance holds the database lock. Traces, scores, and feedback will not be recorded in this session.';\n } else {\n observabilityWarning = `Observability unavailable — DuckDB initialization failed: ${message}`;\n }\n }\n }\n\n const harnessStorage = new InMemoryHarness();\n\n const storage = new MastraCompositeStore({\n id: 'mastra-code-storage',\n default: storageResult.storage,\n domains: {\n // When local tracing is off, disable the observability domain entirely so\n // trace/score/feedback writes never fall through to the default libsql store.\n observability: observabilityDomain ?? false,\n harness: harnessStorage,\n },\n });\n\n // Observability (tracing, scoring, feedback)\n const observability = new Observability({\n configs: {\n default: {\n serviceName: 'mastracode',\n // Only these requestContext keys are stored on spans — prevents leaking\n // large objects (controller state, workspace, env vars) into trace data.\n // Use dot-notation because these are nested inside the 'controller' key.\n //\n // Session identifiers:\n // threadId, resourceId, session.modeId, agentControllerId\n // Environment & project:\n // state.projectName, state.gitBranch\n // Model configuration:\n // session.modelId, state.subagentModelId\n // Agent settings:\n // state.yolo, state.thinkingLevel, state.smartEditing\n // Observational memory settings:\n // state.omScope, state.observerModelId, state.reflectorModelId,\n // state.observationThreshold, state.reflectionThreshold\n requestContextKeys: [\n // Session identifiers\n 'controller.threadId',\n 'controller.resourceId',\n 'controller.session.modeId',\n 'controller.controllerId',\n // Environment & project\n 'controller.state.projectName',\n 'controller.state.gitBranch',\n // Model configuration\n 'controller.session.modelId',\n 'controller.state.subagentModelId',\n // Agent settings\n 'controller.state.yolo',\n 'controller.state.thinkingLevel',\n 'controller.state.smartEditing',\n // Observational memory settings\n 'controller.state.omScope',\n 'controller.state.observerModelId',\n 'controller.state.reflectorModelId',\n 'controller.state.observationThreshold',\n 'controller.state.reflectionThreshold',\n ],\n exporters: [\n // Only persist traces locally when DuckDB observability is available\n // (via `/observability local on`). Without this guard the storage\n // exporter falls through to the default libsql backend and silently\n // fills the main database with gigabytes of span data.\n ...(observabilityDomain ? [new MastraStorageExporter({ strategy: 'event-sourced' })] : []),\n new MastraPlatformExporter(resolveCloudObservabilityConfig(globalSettings, authStorage, project.resourceId)),\n ],\n spanOutputProcessors: [new SensitiveDataFilter()],\n },\n },\n });\n\n // Vector store for recall search (separate DB file to avoid bloating main\n // storage). An injected instance is used as-is; with an injected storage\n // instance and no injected vector, recall search stays vector-less.\n const vector =\n config?.vector ?? (storageConfig ? await createVectorStore(storageConfig, storageResult.backend) : undefined);\n\n // Maintenance handle for /prune: prunes via the inner store (whose retention\n // config covers every domain, including legacy libsql observability spans)\n // and can compact local libsql files to reclaim disk. The vector store's\n // connection must close alongside storage — the compaction's file swap\n // refuses to run while any connection is open.\n const storageMaintenance: StorageMaintenance = createStorageMaintenance({\n storage: storageResult.storage,\n backend: storageResult.backend,\n retention: DEFAULT_RETENTION,\n localDbFiles: storageConfig ? resolveLocalDbFiles(storageConfig, storageResult.backend) : [],\n closeVector: vector instanceof LibSQLVector ? () => vector.close() : undefined,\n });\n\n const memory = config?.memory === false ? undefined : (config?.memory ?? getDynamicMemory(storage, vector));\n\n // MCP\n const mcpManager = config?.disableMcp ? undefined : createMcpManager(project.rootPath, configDir, config?.mcpServers);\n\n // Hooks\n const hookManager = config?.disableHooks\n ? undefined\n : new HookManager(project.rootPath, 'session-init', configDir, homeDir);\n\n const pluginManager = config?.disablePlugins\n ? undefined\n : (config?.pluginManager ?? new PluginManager({ projectRoot: project.rootPath, configDir, homeDir }));\n const loadedPlugins = pluginManager ? await pluginManager.reload() : [];\n const pluginTools = pluginManager?.getPluginTools() ?? {};\n\n // Scorers (live evaluation with sampling)\n const outcomeScorer = createOutcomeScorer();\n const efficiencyScorer = createEfficiencyScorer();\n\n // Agent — githubSignals is created before `controller` but the closure below\n // captures `controller` by reference; it is only invoked at notification time,\n // well after controller is constructed (line ~692). Explicit type annotations\n // on githubSignals, codeAgent, modes, and controller break the circular\n // inference chain this forward reference would otherwise create.\n const githubSignals: GithubSignals | undefined =\n globalSettings.signals?.experimentalGithubSignals && !config?.disableGithubSignals\n ? new GithubSignals({\n cwd: project.rootPath,\n gitcrawlCommand:\n process.env.MASTRACODE_GITCRAWL_BIN ??\n process.env.GITCRAWL_BIN ??\n process.env.MASTRACODE_GITCRAWL_COMMAND ??\n process.env.GITCRAWL_COMMAND,\n getNotificationStreamOptions: async ({ resourceId, threadId }) => {\n // Run the woken notification as the session that owns the target\n // resource so it uses that session's model/mode/state. Fall back to\n // the current session only when no session owns the resource yet.\n const session = (await controller.getSessionByResource(resourceId)) ?? activeSession!;\n // A long-running system must be able to drive work unattended, so a\n // target session without an explicit model selection falls back to a\n // real model rather than failing the run: the current session's live\n // selection (what the user actually picked), then the mode's default.\n const modeId = session.mode.get();\n const defaultModeModelId = controller.listModes().find(mode => mode.id === modeId)?.defaultModelId;\n const modelId = session.model.get() || activeSession?.model.get() || defaultModeModelId || '';\n const requestContext = new RequestContext();\n const agentControllerContext: AgentControllerRequestContext = {\n controllerId: controller.id,\n state: session.state.get(),\n getState: () => session.state.get(),\n setState: updates => session.state.set(updates),\n threadId,\n resourceId,\n session: {\n id: session.identity.getId(),\n ownerId: session.identity.getOwnerId(),\n modeId,\n modelId,\n state: {\n get: () => session.state.get(),\n set: updates => session.state.set(updates),\n update: updater => session.state.update(updater),\n },\n },\n workspace: controller.getWorkspace(),\n getSubagentModelId: params => session.subagents.model.get(params ?? {}),\n };\n requestContext.set('controller', agentControllerContext);\n\n return {\n memory: { thread: threadId, resource: resourceId },\n requestContext,\n maxSteps: 1000,\n savePerStep: false,\n requireToolApproval: (session.state.get() as Record<string, unknown>).yolo !== true,\n modelSettings: { temperature: 1 },\n };\n },\n })\n : undefined;\n const codeAgent: Agent = createCodingAgent({\n id: CODE_AGENT_ID,\n name: 'Code Agent',\n // Workspace is wired per-request at the AgentController level (see\n // `config.workspace` below), so opt out of the factory's default local\n // workspace. An explicit `undefined` is required: the factory only builds a\n // default when the `workspace` key is absent.\n workspace: undefined,\n instructions: getDynamicInstructions,\n model: getDynamicModel,\n tools: createDynamicTools(mcpManager, config?.extraTools, config?.disabledTools, storage, pluginTools),\n hooks: createToolHooks(hookManager, config?.postToolObserver),\n scorers: {\n outcome: {\n scorer: outcomeScorer,\n sampling: { type: 'none' },\n },\n efficiency: {\n scorer: efficiencyScorer,\n sampling: { type: 'ratio', rate: 0.3 },\n },\n },\n // TaskSignalProvider bundles the task tools + TaskStateProcessor: it merges\n // the tools into the toolset and registers the task state-signal processor,\n // so the task list persists across turns and survives OM truncation.\n signals: [new TaskSignalProvider(), ...(githubSignals ? [githubSignals] : [])],\n // Native goal mechanism: the in-loop goal step judges the thread's active\n // objective each qualifying iteration. The judge model is required for any\n // gating to occur; when unset the goal step is a complete no-op. A6 auto-wires\n // the GoalStateProcessor so the `<current-objective>` signal persists across\n // turns. Per-thread overrides live in the ThreadState `goal` record and win\n // over these defaults.\n goal: {\n // Resolve the judge model through mastracode's gateway (a model-resolver\n // function) so provider credentials are injected; returns undefined when no\n // judge model is configured, keeping the goal step a no-op. Bind the same\n // `settingsPath` used above so the judge model and `maxRuns` come from one\n // config (a custom settings file would otherwise diverge).\n judge: ctx => getGoalJudgeModel(ctx, config?.settingsPath),\n maxRuns: globalSettings.models.goalMaxTurns ?? 50,\n maxSteps: 1000,\n prompt: DEFAULT_GOAL_JUDGE_PROMPT,\n // Read-only workspace tools the default goal judge may call to verify the\n // agent's work against the actual filesystem (view, search_content,\n // find_files, file_stat, lsp_inspect) rather than grading prose alone —\n // restoring the original MastraCode judge's verification ability. Resolved\n // per-request from the active workspace (mirrors `judge`).\n tools: getGoalJudgeTools,\n },\n inputProcessors: [\n ...(config?.inputProcessors ?? []),\n new PlanRejectionAbortProcessor(),\n new AgentsMDInjector({\n getIgnoredInstructionPaths: ({ requestContext }) => {\n const agentControllerContext = requestContext?.get('controller') as\n AgentControllerRequestContext<{ projectPath?: string }> | undefined;\n const state = agentControllerContext?.getState();\n return getStaticallyLoadedInstructionPaths(state?.projectPath ?? project.rootPath);\n },\n }),\n new ProviderHistoryCompat(),\n ],\n errorProcessors: [\n // ProviderHistoryCompat must run before StreamErrorRetryProcessor: both react to\n // HTTP 400s, but ProviderHistoryCompat repairs the incompatible history (e.g.\n // sanitizing tool-call IDs) before retrying, while StreamErrorRetryProcessor's\n // isBadRequestError matcher retries the identical request. Error processors\n // short-circuit on the first `retry: true`, so a blind retry first would resend\n // the broken history and fail again.\n new ProviderHistoryCompat(),\n new StreamErrorRetryProcessor({\n matchers: [\n { match: isBadRequestError, maxRetries: 1, delayMs: 2000 },\n {\n match: isTransientConnectionError,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n delayMs: ({ retryCount }) =>\n Math.min(\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS * Math.pow(2, retryCount),\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS,\n ),\n },\n ],\n }),\n new PrefillErrorHandler(),\n ],\n });\n\n // const defaultSubAgents: Array<AgentControllerSubagent> = [];\n // const defaultSubagents = [exploreSubagent, planSubagent, executeSubagent];\n\n const defaultModes: AgentControllerMode[] = [\n {\n ...buildMode,\n metadata: {\n ...buildMode.metadata,\n color: mastraBrand.green,\n },\n },\n {\n ...planMode,\n metadata: {\n ...planMode.metadata,\n color: mastraBrand.purple,\n },\n },\n {\n ...fastMode,\n metadata: {\n ...fastMode.metadata,\n color: mastraBrand.orange,\n },\n },\n ];\n\n const defaultIntervalHandlers: IntervalHandler[] = [\n {\n id: 'gateway-sync',\n intervalMs: 5 * 60 * 1000,\n immediate: false,\n handler: () => syncGateways(),\n },\n ];\n const intervalHandlers = config?.intervalHandlers ?? defaultIntervalHandlers;\n\n // Build lightweight provider access for resolving built-in packs at startup.\n // Anthropic/OpenAI use AuthStorage; other providers use env API keys.\n // Also scan the full provider registry so configured API keys satisfy access checks.\n const anthropicCred = authStorage.get('anthropic');\n const openaiCred = authStorage.get('openai-codex');\n const githubCopilotCred = authStorage.get('github-copilot');\n const startupAccess: ProviderAccess = {\n anthropic:\n anthropicCred?.type === 'oauth'\n ? 'oauth'\n : anthropicCred?.type === 'api_key' && anthropicCred.key.trim().length > 0\n ? 'apikey'\n : false,\n openai:\n openaiCred?.type === 'oauth'\n ? 'oauth'\n : openaiCred?.type === 'api_key' && openaiCred.key.trim().length > 0\n ? 'apikey'\n : false,\n cerebras: process.env.CEREBRAS_API_KEY ? 'apikey' : false,\n google: process.env.GOOGLE_GENERATIVE_AI_API_KEY ? 'apikey' : false,\n deepseek: process.env.DEEPSEEK_API_KEY ? 'apikey' : false,\n 'github-copilot': githubCopilotCred?.type === 'oauth' ? 'oauth' : false,\n };\n // Gateway covers all providers — ensure Anthropic/OpenAI packs are visible\n if (mgApiKey) {\n if (!startupAccess.anthropic) startupAccess.anthropic = 'apikey';\n if (!startupAccess.openai) startupAccess.openai = 'apikey';\n }\n // Check all providers in the registry for API keys\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n for (const [provider, config] of Object.entries(registry)) {\n if (startupAccess[provider] === 'oauth' || startupAccess[provider] === 'apikey') continue; // Already enabled above\n if (provider === 'anthropic' || provider === 'openai') continue;\n const envVars = config?.apiKeyEnvVar;\n const envVarList = Array.isArray(envVars) ? envVars : envVars ? [envVars] : [];\n if (envVarList.some(envVar => process.env[envVar])) {\n startupAccess[provider] = 'apikey';\n }\n }\n } catch {\n // Registry may not be loaded yet; the 5 hardcoded providers are sufficient fallback\n }\n const builtinPacks = getAvailableModePacks(startupAccess);\n const builtinOmPacks = getAvailableOmPacks(startupAccess);\n const effectiveDefaults = resolveModelDefaults(globalSettings, builtinPacks);\n const effectiveObserverModel = resolveOmRoleModel(globalSettings, 'observer', builtinOmPacks);\n const effectiveReflectorModel = resolveOmRoleModel(globalSettings, 'reflector', builtinOmPacks);\n const effectiveObservationThreshold = globalSettings.models.omObservationThreshold ?? undefined;\n const effectiveReflectionThreshold = globalSettings.models.omReflectionThreshold ?? undefined;\n const effectiveCavemanObservations = globalSettings.models.omCavemanObservations ?? undefined;\n const effectiveObserveAttachments = globalSettings.models.omObserveAttachments ?? 'auto';\n\n const modes = addPluginToolsToModeAllowlists(\n applyEffectiveDefaultsToModes(config?.modes ? config.modes : defaultModes, effectiveDefaults),\n Object.keys(pluginTools),\n );\n const defaultModeId =\n modes.find(mode => mode.metadata?.default === true)?.id ??\n modes.find(mode => mode.id === 'build')?.id ??\n modes[0]?.id;\n if (!defaultModeId) {\n throw new Error('MastraCode requires at least one mode');\n }\n\n // Map subagent types to mode models: explore→fast, plan→plan, execute→build\n // const subagentModeMap: Record<string, string> = { explore: 'fast', plan: 'plan', execute: 'build' };\n // Subagents inherit workspace tools from the parent agent's workspace automatically.\n // Apply disabledTools filter to both default and custom subagents.\n // const subagents = [];\n\n // Build initial state with global preferences\n const globalInitialState: Partial<MastraCodeState> = {};\n if (effectiveObserverModel) {\n globalInitialState.observerModelId = effectiveObserverModel;\n }\n if (effectiveReflectorModel) {\n globalInitialState.reflectorModelId = effectiveReflectorModel;\n }\n if (effectiveObservationThreshold !== undefined) {\n globalInitialState.observationThreshold = effectiveObservationThreshold;\n }\n if (effectiveReflectionThreshold !== undefined) {\n globalInitialState.reflectionThreshold = effectiveReflectionThreshold;\n }\n if (effectiveCavemanObservations !== undefined) {\n globalInitialState.cavemanObservations = effectiveCavemanObservations;\n }\n if (effectiveObserveAttachments !== undefined) {\n globalInitialState.observeAttachments = effectiveObserveAttachments;\n }\n if (globalSettings.preferences.yolo !== null) {\n globalInitialState.yolo = globalSettings.preferences.yolo;\n }\n globalInitialState.thinkingLevel = globalSettings.preferences.thinkingLevel;\n if (config?.omScope) {\n globalInitialState.omScope = config.omScope;\n }\n // Seed subagent models from global settings\n for (const [key, modelId] of Object.entries(globalSettings.models.subagentModels)) {\n if (key === 'default' || key === '_default') {\n globalInitialState.subagentModelId = modelId;\n } else {\n globalInitialState[`subagentModelId_${key}`] = modelId;\n }\n }\n\n const typedStateSchema = stateSchema as PublicSchema<MastraCodeState>;\n const controller: AgentController<MastraCodeState> = new AgentController<MastraCodeState>({\n id: 'mastra-code',\n resourceId: project.resourceId,\n storage,\n observability,\n memory,\n pubsub: signalsPubSub,\n stateSchema: typedStateSchema,\n agent: codeAgent,\n subagents: config?.subagents ?? [],\n gateways: [amazonBedrockGateway, mastraCodeGateway],\n workspace: config?.workspace ?? (args => getDynamicWorkspace(args)),\n browser: config?.browser,\n idGenerator: config?.idGenerator,\n toolCategoryResolver: getToolCategory,\n initialState: {\n projectPath: project.rootPath,\n projectName: project.name,\n gitBranch: project.gitBranch,\n pluginSkillPaths: loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.skillPaths ?? []) : [])),\n pluginCommandPaths: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' ? (plugin.commandPaths ?? []) : [],\n ),\n pluginInstructions: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' && plugin.instructions ? [plugin.instructions] : [],\n ),\n yolo: true,\n ...globalInitialState,\n ...config?.initialState,\n // configDir must always win over initialState spreads to stay in sync\n // with MCP/hooks/storage which were already initialized with this value.\n configDir,\n },\n modes,\n intervalHandlers,\n modelUseCountProvider: () => loadSettings().modelUseCounts,\n modelUseCountTracker: modelId => {\n try {\n const settings = loadSettings();\n settings.modelUseCounts[modelId] = (settings.modelUseCounts[modelId] ?? 0) + 1;\n saveSettings(settings);\n } catch (error) {\n console.error('Failed to persist model usage count', error);\n }\n },\n threadLock: crossProcessPubSub\n ? undefined\n : {\n acquire: acquireThreadLock,\n release: releaseThreadLock,\n },\n });\n\n // The AgentController is fully constructed but intentionally NOT inited here. Init and\n // session creation are deferred to the composition layer (see below) so the\n // controller can be wired in three ways:\n //\n // 1. Server + Web — registered on a server Mastra, then inited; sessions\n // minted per browser client over HTTP.\n // 2. Server + TUI — same server composition; the TUI drives a session\n // (in-process today; remote transport is future work).\n // 3. Local + TUI — controller builds its own internal Mastra on init() and\n // mints one eager session for the whole process.\n //\n // Cases 1 & 2 use `mountAgentControllerOnMastra` (register-before-init, no eager\n // session). Case 3 uses `bootLocalAgentController` (init + one wired session).\n return {\n controller: controller,\n storage,\n storageMaintenance,\n observability,\n memory,\n mcpManager,\n hookManager,\n pluginManager,\n loadedPlugins,\n pluginTools,\n signalsPubSub,\n authStorage,\n resolveModel,\n storageWarning,\n observabilityWarning,\n builtinPacks,\n builtinOmPacks,\n effectiveDefaults,\n githubSignals,\n // Identity for the single local session (Case 3). Servers ignore these and\n // mint per-request sessions with client-supplied resourceIds instead.\n sessionId,\n ownerId,\n // Lets the composition layer publish the created session back into the\n // config closures (e.g. notification stream options read it lazily).\n setActiveSession: (session: Session<MastraCodeState>) => {\n activeSession = session;\n },\n };\n}\n\n/**\n * Result of {@link createMastraCodeAgentController}: every shared resource plus the\n * inert AgentController, ready to be either booted locally or mounted on a server\n * Mastra.\n */\nexport type MastraCodeAgentController = Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n\n/**\n * Wires the session-scoped concerns MastraCode layers on top of a Session:\n * hookManager thread-id sync, GitHub PR polling for the current thread, and\n * per-thread persistence of the mastracode-only `/om` settings.\n *\n * Used by {@link bootLocalAgentController} for the single local session. A server can\n * call this for any session it mints if it wants the same background wiring.\n */\nexport async function wireSessionConcerns(\n base: Pick<MastraCodeAgentController, 'hookManager' | 'githubSignals' | 'setActiveSession'>,\n session: Session<MastraCodeState>,\n): Promise<void> {\n const { hookManager, githubSignals } = base;\n base.setActiveSession(session);\n\n // Sync hookManager session ID on thread changes\n if (hookManager) {\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') {\n hookManager.setSessionId(event.threadId);\n } else if (event.type === 'thread_created') {\n hookManager.setSessionId(event.thread.id);\n }\n });\n }\n\n if (githubSignals) {\n const startGithubPollingForCurrentThread = async (threadId?: string | null) => {\n if (!threadId) return;\n githubSignals.stopAllPolling();\n try {\n const threads = await session.thread.list({ allResources: true });\n const thread = threads.find((item: { id: string }) => item.id === threadId);\n await githubSignals.startPollingForThread(\n {\n threadId,\n resourceId: thread?.resourceId ?? session.identity.getResourceId(),\n },\n { pollImmediately: true },\n );\n } catch (error) {\n console.warn('Failed to start GitHub PR polling:', error);\n }\n };\n\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') void startGithubPollingForCurrentThread(event.threadId);\n else if (event.type === 'thread_created') void startGithubPollingForCurrentThread(event.thread.id);\n });\n void startGithubPollingForCurrentThread(session.thread.getId());\n }\n\n // Persist MastraCode-owned /om settings per-thread (mastracode-only concern;\n // intentionally not in core's controller loadThreadMetadata).\n const omThreadStateSession = session as unknown as Session<Record<string, unknown>>;\n attachOMThreadStatePersistence(omThreadStateSession);\n await restoreOMThreadStateForCurrentThread(omThreadStateSession).catch(() => {\n // Persistence is best-effort; don't crash startup if storage hiccups.\n });\n}\n\n/**\n * Case 3 (AgentController local + TUI/headless): build the controller, let it stand up its\n * own internal Mastra via `init()`, and mint the single eager session that all\n * work in this process runs through. The AgentController owns no session of its own.\n */\nexport async function bootLocalAgentController(config?: MastraCodeConfig) {\n const base = await createMastraCodeAgentController(config);\n const { controller, sessionId, ownerId } = base;\n\n await controller.init();\n await controller.getMastra()?.startWorkers();\n const session = await controller.createSession({ id: sessionId, ownerId });\n await wireSessionConcerns(base, session);\n\n return { ...base, session };\n}\n\n/** Result of {@link mountAgentControllerOnMastra}: shared handles plus the owning Mastra. */\nexport type MountedMastraCode = MastraCodeAgentController & { mastra: Mastra };\n\n/**\n * Cases 1 & 2 (AgentController in Server + Web/TUI): build the controller, register it on a\n * server-owned Mastra, THEN init it. Registering before `init()` is what makes\n * the controller inherit the server's Mastra (storage, agents, gateways) instead of\n * spinning up its own internal one — there is a single shared Mastra.\n *\n * No eager session is minted: each client (browser or terminal) creates/resumes\n * its own isolated session via `controller.createSession({ resourceId })`, so one\n * server can drive many concurrent users.\n *\n * Pass an existing `mastra` to mount onto a Mastra that already hosts other\n * primitives; otherwise a Mastra is created that owns the controller's storage so\n * durability is configured in one place.\n */\nexport async function mountAgentControllerOnMastra(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n /**\n * Additional `server` config to fold onto the constructed Mastra alongside\n * the assembled `apiRoutes` (e.g. `middleware`, `cors`). Used by the\n * platform entry (`src/mastra/index.ts`) to own the WorkOS gate + tenant\n * dispatcher + CORS on the instance the deployer generates its server from.\n * Ignored when `mastra` is provided (mounting onto a caller-owned instance).\n */\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<MountedMastraCode> {\n const prepared = await prepareAgentControllerMount(config);\n if (config?.mastra) {\n // Mounting onto a Mastra the caller already built. Ensure the controller's\n // back-reference points at it (idempotent — only sets #externalMastra).\n prepared.base.controller.__registerMastra(config.mastra);\n await prepared.finalize();\n return { ...prepared.base, mastra: config.mastra };\n }\n const mastra = new Mastra(prepared.mastraArgs);\n await prepared.finalize();\n return { ...prepared.base, mastra };\n}\n\n/**\n * Assemble everything needed to construct the server-owned Mastra WITHOUT\n * constructing it, so a caller (the platform entry `src/mastra/index.ts`) can\n * run the `new Mastra(...)` literal in its own module. The deployer's\n * `checkConfigExport` Babel plugin only marks the config valid when it finds a\n * top-level `new Mastra(...)` exported as `mastra` in the ENTRY file; hiding the\n * construction inside this helper would trip the \"Invalid Mastra config\" warning.\n *\n * Returns the constructor args plus a `finalize()` that runs the post-construct\n * boot (`controller.init()` + `startWorkers()`). The controller is registered on\n * the Mastra via the `agentControllers` arg at construction time.\n */\nexport async function prepareAgentControllerMount(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<{\n base: Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n mastraArgs: NonNullable<ConstructorParameters<typeof Mastra>[0]>;\n finalize: () => Promise<void>;\n}> {\n const base = await createMastraCodeAgentController(config);\n const { controller, storage, authStorage } = base;\n const controllerId = config?.controllerId ?? controller.id;\n const apiRoutes = config?.buildApiRoutes?.({ controller, authStorage });\n const extraServerConfig = config?.buildServerConfig?.({ controller, authStorage });\n\n const serverConfig = {\n ...extraServerConfig,\n ...(apiRoutes?.length ? { apiRoutes } : {}),\n };\n const mastraArgs = {\n agentControllers: { [controllerId]: controller },\n storage,\n // Mirror the controller's internal-Mastra construction (which passes\n // `config.pubsub` through): the server-owned Mastra must run its event\n // bus on the same transport so streams/workflows/signals stay\n // cross-process when a distributed PubSub (e.g. Redis Streams) is\n // configured.\n ...(base.signalsPubSub ? { pubsub: base.signalsPubSub } : {}),\n ...(Object.keys(serverConfig).length ? { server: serverConfig } : {}),\n };\n\n const finalize = async () => {\n await controller.init();\n await controller.getMastra()?.startWorkers();\n };\n\n return { base, mastraArgs, finalize };\n}\n\n/**\n * Back-compat alias. Historically `createMastraCode` built and booted a local\n * controller with a single session; that behavior now lives in\n * {@link bootLocalAgentController}. New code should call the explicit factory for its\n * case: `bootLocalAgentController` (local) or {@link mountAgentControllerOnMastra} (server).\n */\nexport const createMastraCode = bootLocalAgentController;\n\n/**\n * Programmatic headless API. `runMC` runs an already-built controller/session\n * (from {@link createMastraCode}) as an async-iterable run that also resolves to\n * a typed result. Also available via the `mastracode/headless` subpath.\n */\nexport {\n runMC,\n runMCCli,\n hasHeadlessFlag,\n autoApprovePolicy,\n denyPolicy,\n permissionModeToPolicy,\n formatHuman,\n formatJsonl,\n renderTextResult,\n renderJsonResult,\n} from './headless/index.js';\nexport type {\n RunMCOptions,\n RunMCResult,\n RunMCStatus,\n RunMCUsage,\n RunMCToolCall,\n RunMCToolResult,\n RunMCError,\n RunMCThreadOptions,\n MCRun,\n ResolutionPolicy,\n PermissionMode,\n} from './headless/index.js';\n"],"mappings":"AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,OAAO,UAAU;AAGjB,SAAS,uBAAuB;AAUhC,SAAS,yBAAyB;AAElC,SAAS,yBAAyB;AAElC,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,sBAAsB;AAG/B,SAAS,0BAA0B;AACnC,SAAS,iBAAiB,4BAA4B;AACtD,SAAS,iCAAiC;AAE1C,SAAS,mBAAmB;AAE5B,SAAS,qBAAqB;AAC9B,SAAS,aAAa,oBAAoB;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAE9B,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AACvC,SAAS,wBAAwB;AACjC,SAAS,yBAAyB,iBAAiB,mBAAmB,oBAAoB;AAC1F,SAAS,iBAAiB;AAC1B,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AACzB,SAAS,2CAA2C;AAIpD,SAAS,gCAAgC,4CAA4C;AACrF,SAAS,oBAAoB,uBAAuB;AAGpD,SAAS,qBAAqB,yBAAyB;AACvD,SAAS,mBAAmB;AAC5B,SAAS,oBAAoB,6BAA6B;AAC1D,SAAS,qBAAqB,8BAA8B;AAC5D,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AAGjC,SAAS,uBAAuB,2BAA2B;AAC3D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,qBAAqB;AA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|
18
18
|
private githubPollInFlight;
|
|
19
19
|
private reloadInFlight;
|
|
20
20
|
private readonly reloadListeners;
|
|
21
|
+
private readonly githubUpdateListeners;
|
|
21
22
|
constructor(options: PluginManagerOptions);
|
|
22
23
|
onReload(listener: (plugins: LoadedPlugin[]) => void | Promise<void>): () => void;
|
|
24
|
+
/** Notified with the display names of GitHub plugins that were updated by the background poll. */
|
|
25
|
+
onGithubPluginsUpdated(listener: (pluginNames: string[]) => void | Promise<void>): () => void;
|
|
23
26
|
reload(): Promise<LoadedPlugin[]>;
|
|
24
27
|
listPlugins(): Promise<LoadedPlugin[]>;
|
|
25
28
|
getLoadedPlugins(): LoadedPlugin[];
|
|
@@ -38,6 +41,7 @@ export declare class PluginManager {
|
|
|
38
41
|
private updateGithubPoller;
|
|
39
42
|
pollGithubSourcesForUpdates(): Promise<boolean>;
|
|
40
43
|
private pollGithubSourcesForUpdatesOnce;
|
|
44
|
+
private notifyGithubUpdateListeners;
|
|
41
45
|
private refreshGithubCheckout;
|
|
42
46
|
private backupGitCheckout;
|
|
43
47
|
private resolveGitUpstream;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/plugins/manager.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAEhE,OAAO,EAAE,oBAAoB,EAAoE,MAAM,cAAc,CAAC;AACtH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAIzD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAa5D,KAAK,oBAAoB,GAAG,iBAAiB,GAAG;IAC9C,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,qBAAa,aAAa;
|
|
1
|
+
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../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AG,OAAO,CAAC,IAAI,CAAC;IAWjF,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,2BAA2B,GACjC,OAAO,CAAC,IAAI,CAAC;IAkBV,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;CAoBrE"}
|
package/dist/plugins/manager.js
CHANGED
|
@@ -30,10 +30,16 @@ class PluginManager {
|
|
|
30
30
|
githubPollInFlight;
|
|
31
31
|
reloadInFlight;
|
|
32
32
|
reloadListeners = /* @__PURE__ */ new Set();
|
|
33
|
+
githubUpdateListeners = /* @__PURE__ */ new Set();
|
|
33
34
|
onReload(listener) {
|
|
34
35
|
this.reloadListeners.add(listener);
|
|
35
36
|
return () => this.reloadListeners.delete(listener);
|
|
36
37
|
}
|
|
38
|
+
/** Notified with the display names of GitHub plugins that were updated by the background poll. */
|
|
39
|
+
onGithubPluginsUpdated(listener) {
|
|
40
|
+
this.githubUpdateListeners.add(listener);
|
|
41
|
+
return () => this.githubUpdateListeners.delete(listener);
|
|
42
|
+
}
|
|
37
43
|
async reload() {
|
|
38
44
|
if (this.reloadInFlight) return this.reloadInFlight;
|
|
39
45
|
this.reloadInFlight = (async () => {
|
|
@@ -189,7 +195,7 @@ class PluginManager {
|
|
|
189
195
|
return this.githubPollInFlight;
|
|
190
196
|
}
|
|
191
197
|
async pollGithubSourcesForUpdatesOnce() {
|
|
192
|
-
|
|
198
|
+
const changedCheckouts = /* @__PURE__ */ new Set();
|
|
193
199
|
const seen = /* @__PURE__ */ new Set();
|
|
194
200
|
for (const plugin of this.loadedPlugins) {
|
|
195
201
|
if (plugin.source !== "github" || plugin.status === "inactive" || plugin.status === "blocked") continue;
|
|
@@ -199,12 +205,18 @@ class PluginManager {
|
|
|
199
205
|
const before = await this.readGitHead(checkoutPath);
|
|
200
206
|
const checkoutChanged = await this.refreshGithubCheckout(plugin, checkoutPath, before);
|
|
201
207
|
const after = await this.readGitHead(checkoutPath);
|
|
202
|
-
if (checkoutChanged || before !== after)
|
|
203
|
-
}
|
|
204
|
-
if (changed) {
|
|
205
|
-
await this.reload();
|
|
208
|
+
if (checkoutChanged || before !== after) changedCheckouts.add(checkoutPath);
|
|
206
209
|
}
|
|
207
|
-
return
|
|
210
|
+
if (changedCheckouts.size === 0) return false;
|
|
211
|
+
await this.reload();
|
|
212
|
+
const updatedPluginNames = this.loadedPlugins.filter(
|
|
213
|
+
(plugin) => plugin.source === "github" && plugin.status !== "inactive" && plugin.status !== "blocked" && changedCheckouts.has(this.resolvePluginSourcePath(plugin))
|
|
214
|
+
).map((plugin) => plugin.name ?? plugin.id);
|
|
215
|
+
await this.notifyGithubUpdateListeners(updatedPluginNames);
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
async notifyGithubUpdateListeners(pluginNames) {
|
|
219
|
+
await Promise.all([...this.githubUpdateListeners].map((listener) => Promise.resolve(listener(pluginNames))));
|
|
208
220
|
}
|
|
209
221
|
async refreshGithubCheckout(plugin, checkoutPath, currentHead) {
|
|
210
222
|
await execa("git", ["fetch", "origin"], gitExecOptions(checkoutPath));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugins/manager.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { execa } from 'execa';\n\nimport type { MastraCodePluginConfigValue } from '../plugin.js';\nimport { getEntryPackageRoot, installPluginDependenciesForEntry } from './dependencies.js';\nimport { discoverLocalPlugins, installGithubPlugin, installLocalPlugin, NON_INTERACTIVE_GIT_ENV } from './install.js';\nimport type { InstallPluginOptions } from './install.js';\nimport { collectActivePluginTools, isInsideDirectory, loadPlugins, resolvePluginEntryPath } from './loader.js';\nimport { ensureMastraCodePackageLink } from './package-link.js';\nimport { getPluginScopePaths } from './paths.js';\nimport type { PluginPathOptions } from './paths.js';\nimport { loadPluginRegistry, removePluginRecord, savePluginRegistry, setPluginRecord } from './registry.js';\nimport type { LoadedPlugin, PluginScope } from './types.js';\n\nconst GITHUB_PLUGIN_POLL_INTERVAL_MS = 60_000;\n\nfunction gitExecOptions(cwd: string) {\n return { cwd, env: NON_INTERACTIVE_GIT_ENV };\n}\n\nfunction getEntryVersion(entryPath: string): string {\n const stat = fs.statSync(entryPath, { bigint: true });\n return `${stat.mtimeNs}:${stat.size}`;\n}\n\ntype PluginManagerOptions = PluginPathOptions & {\n githubCliPath?: string;\n};\n\nexport class PluginManager {\n private loadedPlugins: LoadedPlugin[] = [];\n private readonly pluginTools: ReturnType<typeof collectActivePluginTools> = {};\n private readonly rawPluginTools: ReturnType<typeof collectActivePluginTools> = {};\n private readonly toolRenderConfigs = new Map<string, NonNullable<LoadedPlugin['renderConfigs']>[string]>();\n private readonly watchedLocalEntries = new Set<string>();\n private readonly localEntryVersions = new Map<string, string>();\n private githubPollTimer: ReturnType<typeof setInterval> | undefined;\n private githubPollInFlight: Promise<boolean> | undefined;\n private reloadInFlight: Promise<LoadedPlugin[]> | undefined;\n private readonly reloadListeners = new Set<(plugins: LoadedPlugin[]) => void | Promise<void>>();\n\n constructor(private readonly options: PluginManagerOptions) {}\n\n onReload(listener: (plugins: LoadedPlugin[]) => void | Promise<void>): () => void {\n this.reloadListeners.add(listener);\n return () => this.reloadListeners.delete(listener);\n }\n\n async reload(): Promise<LoadedPlugin[]> {\n if (this.reloadInFlight) return this.reloadInFlight;\n\n this.reloadInFlight = (async () => {\n this.loadedPlugins = await loadPlugins(this.options);\n this.updateLocalEntryWatchers(this.loadedPlugins);\n this.updateGithubPoller(this.loadedPlugins);\n this.updatePluginRenderConfigs(this.loadedPlugins);\n this.updatePluginTools(collectActivePluginTools(this.loadedPlugins));\n await this.notifyReloadListeners(this.loadedPlugins);\n return this.loadedPlugins;\n })().finally(() => {\n this.reloadInFlight = undefined;\n });\n\n return this.reloadInFlight;\n }\n\n async listPlugins(): Promise<LoadedPlugin[]> {\n if (this.loadedPlugins.length === 0) {\n await this.reload();\n }\n return this.loadedPlugins;\n }\n\n getLoadedPlugins(): LoadedPlugin[] {\n return this.loadedPlugins;\n }\n\n getPluginTools() {\n return this.pluginTools;\n }\n\n getToolRenderConfig(toolName: string) {\n return this.toolRenderConfigs.get(toolName);\n }\n\n getPluginSkillPaths(): string[] {\n return this.loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.skillPaths ?? []) : []));\n }\n\n getPluginCommandPaths(): string[] {\n return this.loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.commandPaths ?? []) : []));\n }\n\n getPluginInstructions(): string[] {\n return this.loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' && plugin.instructions ? [plugin.instructions] : [],\n );\n }\n\n private async notifyReloadListeners(plugins: LoadedPlugin[]): Promise<void> {\n await Promise.all([...this.reloadListeners].map(listener => Promise.resolve(listener(plugins))));\n }\n\n private updatePluginRenderConfigs(plugins: LoadedPlugin[]): void {\n this.toolRenderConfigs.clear();\n for (const plugin of plugins) {\n if (plugin.status !== 'active') continue;\n for (const [toolName, renderConfig] of Object.entries(plugin.renderConfigs ?? {})) {\n if (!this.toolRenderConfigs.has(toolName)) {\n this.toolRenderConfigs.set(toolName, renderConfig);\n }\n }\n }\n }\n\n private updatePluginTools(nextTools: ReturnType<typeof collectActivePluginTools>): void {\n for (const name of Object.keys(this.rawPluginTools)) {\n if (!(name in nextTools)) {\n delete this.rawPluginTools[name];\n delete this.pluginTools[name];\n }\n }\n\n for (const [name, tool] of Object.entries(nextTools)) {\n this.rawPluginTools[name] = tool;\n if (!this.pluginTools[name]) {\n this.pluginTools[name] = this.createLiveToolProxy(name);\n }\n this.syncLiveToolProxy(name, tool);\n }\n }\n\n private createLiveToolProxy(toolName: string) {\n return {\n execute: async (...args: any[]) => {\n await this.reloadChangedLocalPlugins();\n const latestTool = this.rawPluginTools[toolName];\n if (!latestTool?.execute) {\n throw new Error(`Plugin tool \"${toolName}\" is no longer available`);\n }\n return (latestTool.execute as (...args: any[]) => unknown)(...args);\n },\n } as LoadedPlugin['tools'][string];\n }\n\n private syncLiveToolProxy(toolName: string, tool: LoadedPlugin['tools'][string]): void {\n const proxy = this.pluginTools[toolName];\n if (!proxy) return;\n const mutableProxy = proxy as unknown as Record<string, unknown>;\n for (const key of Object.keys(mutableProxy)) {\n delete mutableProxy[key];\n }\n Object.assign(proxy, tool);\n proxy.execute = this.createLiveToolProxy(toolName).execute;\n }\n\n private async reloadChangedLocalPlugins(): Promise<void> {\n for (const plugin of this.loadedPlugins) {\n if (plugin.source !== 'local' || plugin.status !== 'active') continue;\n const entryPath = resolvePluginEntryPath(plugin, this.options);\n const currentVersion = getEntryVersion(entryPath);\n if (this.localEntryVersions.get(entryPath) !== currentVersion) {\n await this.reload();\n return;\n }\n }\n }\n\n private updateLocalEntryWatchers(plugins: LoadedPlugin[]): void {\n const nextEntries = new Set<string>();\n for (const plugin of plugins) {\n if (plugin.source !== 'local' || plugin.status !== 'active') continue;\n let entryPath: string;\n let entryVersion: string;\n try {\n entryPath = resolvePluginEntryPath(plugin, this.options);\n entryVersion = getEntryVersion(entryPath);\n } catch {\n continue;\n }\n nextEntries.add(entryPath);\n this.localEntryVersions.set(entryPath, entryVersion);\n if (this.watchedLocalEntries.has(entryPath)) continue;\n\n const watcher = fs.watchFile(entryPath, { interval: 500 }, (current, previous) => {\n if (current.mtimeMs === previous.mtimeMs) return;\n void this.reload().catch(() => undefined);\n });\n watcher.unref?.();\n this.watchedLocalEntries.add(entryPath);\n }\n\n for (const entryPath of this.watchedLocalEntries) {\n if (nextEntries.has(entryPath)) continue;\n fs.unwatchFile(entryPath);\n this.watchedLocalEntries.delete(entryPath);\n this.localEntryVersions.delete(entryPath);\n }\n }\n\n private updateGithubPoller(plugins: LoadedPlugin[]): void {\n const hasGithubPlugin = plugins.some(\n plugin => plugin.source === 'github' && plugin.status !== 'inactive' && plugin.status !== 'blocked',\n );\n if (hasGithubPlugin && !this.githubPollTimer) {\n this.githubPollTimer = setInterval(() => {\n void this.pollGithubSourcesForUpdates().catch(() => undefined);\n }, GITHUB_PLUGIN_POLL_INTERVAL_MS);\n this.githubPollTimer.unref?.();\n }\n if (!hasGithubPlugin && this.githubPollTimer) {\n clearInterval(this.githubPollTimer);\n this.githubPollTimer = undefined;\n }\n }\n\n async pollGithubSourcesForUpdates(): Promise<boolean> {\n if (this.githubPollInFlight) return this.githubPollInFlight;\n this.githubPollInFlight = this.pollGithubSourcesForUpdatesOnce().finally(() => {\n this.githubPollInFlight = undefined;\n });\n return this.githubPollInFlight;\n }\n\n private async pollGithubSourcesForUpdatesOnce(): Promise<boolean> {\n let changed = false;\n const seen = new Set<string>();\n for (const plugin of this.loadedPlugins) {\n if (plugin.source !== 'github' || plugin.status === 'inactive' || plugin.status === 'blocked') continue;\n const checkoutPath = this.resolvePluginSourcePath(plugin);\n if (seen.has(checkoutPath) || !fs.existsSync(path.join(checkoutPath, '.git'))) continue;\n seen.add(checkoutPath);\n\n const before = await this.readGitHead(checkoutPath);\n const checkoutChanged = await this.refreshGithubCheckout(plugin, checkoutPath, before);\n const after = await this.readGitHead(checkoutPath);\n if (checkoutChanged || before !== after) changed = true;\n }\n\n if (changed) {\n await this.reload();\n }\n return changed;\n }\n\n private async refreshGithubCheckout(\n plugin: LoadedPlugin,\n checkoutPath: string,\n currentHead: string,\n ): Promise<boolean> {\n await execa('git', ['fetch', 'origin'], gitExecOptions(checkoutPath));\n const upstream = await this.resolveGitUpstream(checkoutPath, plugin.ref);\n if (!upstream) return false;\n const [localOnly, remoteOnly] = await this.readGitAheadBehind(checkoutPath, upstream);\n const hasLocalChanges = await this.hasGitWorkingTreeChanges(checkoutPath);\n\n if (localOnly > 0 || hasLocalChanges) {\n await this.backupGitCheckout(checkoutPath, currentHead, hasLocalChanges);\n }\n\n if (remoteOnly > 0 || localOnly > 0 || hasLocalChanges) {\n await execa('git', ['reset', '--hard', upstream], gitExecOptions(checkoutPath));\n try {\n await installPluginDependenciesForEntry(checkoutPath, plugin.entry);\n ensureMastraCodePackageLink(getEntryPackageRoot(checkoutPath, plugin.entry));\n } catch (error) {\n await execa('git', ['reset', '--hard', currentHead], gitExecOptions(checkoutPath));\n throw error;\n }\n return true;\n }\n\n return false;\n }\n\n private async backupGitCheckout(\n checkoutPath: string,\n currentHead: string,\n includeWorkingTree: boolean,\n ): Promise<void> {\n const backupBranch = this.createGitBackupBranchName(currentHead);\n\n if (includeWorkingTree) {\n const currentBranch = await this.readGitCurrentBranch(checkoutPath);\n await execa('git', ['switch', '-c', backupBranch], gitExecOptions(checkoutPath));\n await execa('git', ['add', '-A'], gitExecOptions(checkoutPath));\n const hasStagedChanges = await this.hasGitStagedChanges(checkoutPath);\n if (hasStagedChanges) {\n await execa(\n 'git',\n [\n '-c',\n 'user.name=Mastra Code',\n '-c',\n 'user.email=noreply@mastra.ai',\n 'commit',\n '-m',\n 'chore: backup local plugin checkout changes',\n ],\n gitExecOptions(checkoutPath),\n );\n }\n await this.restoreGitCheckout(checkoutPath, currentBranch, currentHead);\n return;\n }\n\n await execa('git', ['branch', backupBranch, 'HEAD'], gitExecOptions(checkoutPath));\n }\n\n private async resolveGitUpstream(cwd: string, installedRef?: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\n 'git',\n ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'],\n gitExecOptions(cwd),\n );\n return stdout.trim();\n } catch {\n return installedRef ? undefined : 'origin/main';\n }\n }\n\n private async readGitAheadBehind(cwd: string, upstream: string): Promise<[number, number]> {\n const { stdout } = await execa(\n 'git',\n ['rev-list', '--left-right', '--count', `HEAD...${upstream}`],\n gitExecOptions(cwd),\n );\n const [ahead = '0', behind = '0'] = stdout.trim().split(/\\s+/);\n return [Number(ahead) || 0, Number(behind) || 0];\n }\n\n private async hasGitWorkingTreeChanges(cwd: string): Promise<boolean> {\n const { stdout } = await execa('git', ['status', '--porcelain'], gitExecOptions(cwd));\n return stdout.trim().length > 0;\n }\n\n private async hasGitStagedChanges(cwd: string): Promise<boolean> {\n try {\n await execa('git', ['diff', '--cached', '--quiet'], gitExecOptions(cwd));\n return false;\n } catch {\n return true;\n }\n }\n\n private async restoreGitCheckout(cwd: string, branch: string | undefined, fallbackHead: string): Promise<void> {\n if (branch) {\n await execa('git', ['switch', branch], gitExecOptions(cwd));\n return;\n }\n await execa('git', ['checkout', fallbackHead], gitExecOptions(cwd));\n }\n\n private async readGitCurrentBranch(cwd: string): Promise<string | undefined> {\n const { stdout } = await execa('git', ['branch', '--show-current'], gitExecOptions(cwd));\n const branch = stdout.trim();\n return branch.length > 0 ? branch : undefined;\n }\n\n private createGitBackupBranchName(currentHead: string): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n return `mastracode/plugin-backup/${timestamp}-${currentHead.slice(0, 8)}`;\n }\n\n private resolvePluginSourcePath(plugin: LoadedPlugin): string {\n const paths = getPluginScopePaths(plugin.scope, this.options);\n return path.isAbsolute(plugin.path) ? plugin.path : path.join(paths.root, plugin.path);\n }\n\n private async readGitHead(cwd: string): Promise<string> {\n const { stdout } = await execa('git', ['rev-parse', 'HEAD'], gitExecOptions(cwd));\n return stdout.trim();\n }\n\n discoverLocal(searchRoot = '.'): ReturnType<typeof discoverLocalPlugins> {\n return discoverLocalPlugins(searchRoot, this.options);\n }\n\n async installLocal(\n localPath: string,\n scope: PluginScope,\n options: Pick<InstallPluginOptions, 'entry'> = {},\n ): Promise<string> {\n const id = await installLocalPlugin(localPath, scope, { ...this.options, ...options });\n await this.reload();\n return id;\n }\n\n async installGithub(\n url: string,\n scope: PluginScope,\n options: Pick<InstallPluginOptions, 'entry' | 'ref' | 'onOutput' | 'signal'> = {},\n ): Promise<string> {\n const id = await installGithubPlugin(url, scope, { ...this.options, ...options });\n await this.reload();\n return id;\n }\n\n async setEnabled(pluginId: string, scope: PluginScope, enabled: boolean): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n savePluginRegistry(paths.registryPath, setPluginRecord(registry, pluginId, { ...record, enabled }));\n await this.reload();\n }\n\n async setConfigValue(\n pluginId: string,\n scope: PluginScope,\n key: string,\n value: MastraCodePluginConfigValue,\n ): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n const config = { ...(record.config ?? {}) };\n if (value === undefined || value === '') {\n delete config[key];\n } else {\n config[key] = value;\n }\n const nextRecord = { ...record, config: Object.keys(config).length > 0 ? config : undefined };\n savePluginRegistry(paths.registryPath, setPluginRecord(registry, pluginId, nextRecord));\n await this.reload();\n }\n\n async uninstall(pluginId: string, scope: PluginScope): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n\n savePluginRegistry(paths.registryPath, removePluginRecord(registry, pluginId));\n if (record.source === 'github') {\n const checkoutPath = path.resolve(\n path.isAbsolute(record.path) ? record.path : path.join(paths.root, record.path),\n );\n const githubSourcesPath = path.resolve(paths.sourcesPath, 'github');\n if (isInsideDirectory(checkoutPath, githubSourcesPath)) {\n fs.rmSync(checkoutPath, { recursive: true, force: true });\n }\n }\n await this.reload();\n }\n}\n"],"mappings":"AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,SAAS,aAAa;AAGtB,SAAS,qBAAqB,yCAAyC;AACvE,SAAS,sBAAsB,qBAAqB,oBAAoB,+BAA+B;AAEvG,SAAS,0BAA0B,mBAAmB,aAAa,8BAA8B;AACjG,SAAS,mCAAmC;AAC5C,SAAS,2BAA2B;AAEpC,SAAS,oBAAoB,oBAAoB,oBAAoB,uBAAuB;AAG5F,MAAM,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EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,MAC1D;AAAA,IACF;AACA,UAAM,KAAK,OAAO;AAAA,EACpB;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/plugins/manager.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { execa } from 'execa';\n\nimport type { MastraCodePluginConfigValue } from '../plugin.js';\nimport { getEntryPackageRoot, installPluginDependenciesForEntry } from './dependencies.js';\nimport { discoverLocalPlugins, installGithubPlugin, installLocalPlugin, NON_INTERACTIVE_GIT_ENV } from './install.js';\nimport type { InstallPluginOptions } from './install.js';\nimport { collectActivePluginTools, isInsideDirectory, loadPlugins, resolvePluginEntryPath } from './loader.js';\nimport { ensureMastraCodePackageLink } from './package-link.js';\nimport { getPluginScopePaths } from './paths.js';\nimport type { PluginPathOptions } from './paths.js';\nimport { loadPluginRegistry, removePluginRecord, savePluginRegistry, setPluginRecord } from './registry.js';\nimport type { LoadedPlugin, PluginScope } from './types.js';\n\nconst GITHUB_PLUGIN_POLL_INTERVAL_MS = 60_000;\n\nfunction gitExecOptions(cwd: string) {\n return { cwd, env: NON_INTERACTIVE_GIT_ENV };\n}\n\nfunction getEntryVersion(entryPath: string): string {\n const stat = fs.statSync(entryPath, { bigint: true });\n return `${stat.mtimeNs}:${stat.size}`;\n}\n\ntype PluginManagerOptions = PluginPathOptions & {\n githubCliPath?: string;\n};\n\nexport class PluginManager {\n private loadedPlugins: LoadedPlugin[] = [];\n private readonly pluginTools: ReturnType<typeof collectActivePluginTools> = {};\n private readonly rawPluginTools: ReturnType<typeof collectActivePluginTools> = {};\n private readonly toolRenderConfigs = new Map<string, NonNullable<LoadedPlugin['renderConfigs']>[string]>();\n private readonly watchedLocalEntries = new Set<string>();\n private readonly localEntryVersions = new Map<string, string>();\n private githubPollTimer: ReturnType<typeof setInterval> | undefined;\n private githubPollInFlight: Promise<boolean> | undefined;\n private reloadInFlight: Promise<LoadedPlugin[]> | undefined;\n private readonly reloadListeners = new Set<(plugins: LoadedPlugin[]) => void | Promise<void>>();\n private readonly githubUpdateListeners = new Set<(pluginNames: string[]) => void | Promise<void>>();\n\n constructor(private readonly options: PluginManagerOptions) {}\n\n onReload(listener: (plugins: LoadedPlugin[]) => void | Promise<void>): () => void {\n this.reloadListeners.add(listener);\n return () => this.reloadListeners.delete(listener);\n }\n\n /** Notified with the display names of GitHub plugins that were updated by the background poll. */\n onGithubPluginsUpdated(listener: (pluginNames: string[]) => void | Promise<void>): () => void {\n this.githubUpdateListeners.add(listener);\n return () => this.githubUpdateListeners.delete(listener);\n }\n\n async reload(): Promise<LoadedPlugin[]> {\n if (this.reloadInFlight) return this.reloadInFlight;\n\n this.reloadInFlight = (async () => {\n this.loadedPlugins = await loadPlugins(this.options);\n this.updateLocalEntryWatchers(this.loadedPlugins);\n this.updateGithubPoller(this.loadedPlugins);\n this.updatePluginRenderConfigs(this.loadedPlugins);\n this.updatePluginTools(collectActivePluginTools(this.loadedPlugins));\n await this.notifyReloadListeners(this.loadedPlugins);\n return this.loadedPlugins;\n })().finally(() => {\n this.reloadInFlight = undefined;\n });\n\n return this.reloadInFlight;\n }\n\n async listPlugins(): Promise<LoadedPlugin[]> {\n if (this.loadedPlugins.length === 0) {\n await this.reload();\n }\n return this.loadedPlugins;\n }\n\n getLoadedPlugins(): LoadedPlugin[] {\n return this.loadedPlugins;\n }\n\n getPluginTools() {\n return this.pluginTools;\n }\n\n getToolRenderConfig(toolName: string) {\n return this.toolRenderConfigs.get(toolName);\n }\n\n getPluginSkillPaths(): string[] {\n return this.loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.skillPaths ?? []) : []));\n }\n\n getPluginCommandPaths(): string[] {\n return this.loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.commandPaths ?? []) : []));\n }\n\n getPluginInstructions(): string[] {\n return this.loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' && plugin.instructions ? [plugin.instructions] : [],\n );\n }\n\n private async notifyReloadListeners(plugins: LoadedPlugin[]): Promise<void> {\n await Promise.all([...this.reloadListeners].map(listener => Promise.resolve(listener(plugins))));\n }\n\n private updatePluginRenderConfigs(plugins: LoadedPlugin[]): void {\n this.toolRenderConfigs.clear();\n for (const plugin of plugins) {\n if (plugin.status !== 'active') continue;\n for (const [toolName, renderConfig] of Object.entries(plugin.renderConfigs ?? {})) {\n if (!this.toolRenderConfigs.has(toolName)) {\n this.toolRenderConfigs.set(toolName, renderConfig);\n }\n }\n }\n }\n\n private updatePluginTools(nextTools: ReturnType<typeof collectActivePluginTools>): void {\n for (const name of Object.keys(this.rawPluginTools)) {\n if (!(name in nextTools)) {\n delete this.rawPluginTools[name];\n delete this.pluginTools[name];\n }\n }\n\n for (const [name, tool] of Object.entries(nextTools)) {\n this.rawPluginTools[name] = tool;\n if (!this.pluginTools[name]) {\n this.pluginTools[name] = this.createLiveToolProxy(name);\n }\n this.syncLiveToolProxy(name, tool);\n }\n }\n\n private createLiveToolProxy(toolName: string) {\n return {\n execute: async (...args: any[]) => {\n await this.reloadChangedLocalPlugins();\n const latestTool = this.rawPluginTools[toolName];\n if (!latestTool?.execute) {\n throw new Error(`Plugin tool \"${toolName}\" is no longer available`);\n }\n return (latestTool.execute as (...args: any[]) => unknown)(...args);\n },\n } as LoadedPlugin['tools'][string];\n }\n\n private syncLiveToolProxy(toolName: string, tool: LoadedPlugin['tools'][string]): void {\n const proxy = this.pluginTools[toolName];\n if (!proxy) return;\n const mutableProxy = proxy as unknown as Record<string, unknown>;\n for (const key of Object.keys(mutableProxy)) {\n delete mutableProxy[key];\n }\n Object.assign(proxy, tool);\n proxy.execute = this.createLiveToolProxy(toolName).execute;\n }\n\n private async reloadChangedLocalPlugins(): Promise<void> {\n for (const plugin of this.loadedPlugins) {\n if (plugin.source !== 'local' || plugin.status !== 'active') continue;\n const entryPath = resolvePluginEntryPath(plugin, this.options);\n const currentVersion = getEntryVersion(entryPath);\n if (this.localEntryVersions.get(entryPath) !== currentVersion) {\n await this.reload();\n return;\n }\n }\n }\n\n private updateLocalEntryWatchers(plugins: LoadedPlugin[]): void {\n const nextEntries = new Set<string>();\n for (const plugin of plugins) {\n if (plugin.source !== 'local' || plugin.status !== 'active') continue;\n let entryPath: string;\n let entryVersion: string;\n try {\n entryPath = resolvePluginEntryPath(plugin, this.options);\n entryVersion = getEntryVersion(entryPath);\n } catch {\n continue;\n }\n nextEntries.add(entryPath);\n this.localEntryVersions.set(entryPath, entryVersion);\n if (this.watchedLocalEntries.has(entryPath)) continue;\n\n const watcher = fs.watchFile(entryPath, { interval: 500 }, (current, previous) => {\n if (current.mtimeMs === previous.mtimeMs) return;\n void this.reload().catch(() => undefined);\n });\n watcher.unref?.();\n this.watchedLocalEntries.add(entryPath);\n }\n\n for (const entryPath of this.watchedLocalEntries) {\n if (nextEntries.has(entryPath)) continue;\n fs.unwatchFile(entryPath);\n this.watchedLocalEntries.delete(entryPath);\n this.localEntryVersions.delete(entryPath);\n }\n }\n\n private updateGithubPoller(plugins: LoadedPlugin[]): void {\n const hasGithubPlugin = plugins.some(\n plugin => plugin.source === 'github' && plugin.status !== 'inactive' && plugin.status !== 'blocked',\n );\n if (hasGithubPlugin && !this.githubPollTimer) {\n this.githubPollTimer = setInterval(() => {\n void this.pollGithubSourcesForUpdates().catch(() => undefined);\n }, GITHUB_PLUGIN_POLL_INTERVAL_MS);\n this.githubPollTimer.unref?.();\n }\n if (!hasGithubPlugin && this.githubPollTimer) {\n clearInterval(this.githubPollTimer);\n this.githubPollTimer = undefined;\n }\n }\n\n async pollGithubSourcesForUpdates(): Promise<boolean> {\n if (this.githubPollInFlight) return this.githubPollInFlight;\n this.githubPollInFlight = this.pollGithubSourcesForUpdatesOnce().finally(() => {\n this.githubPollInFlight = undefined;\n });\n return this.githubPollInFlight;\n }\n\n private async pollGithubSourcesForUpdatesOnce(): Promise<boolean> {\n const changedCheckouts = new Set<string>();\n const seen = new Set<string>();\n for (const plugin of this.loadedPlugins) {\n if (plugin.source !== 'github' || plugin.status === 'inactive' || plugin.status === 'blocked') continue;\n const checkoutPath = this.resolvePluginSourcePath(plugin);\n if (seen.has(checkoutPath) || !fs.existsSync(path.join(checkoutPath, '.git'))) continue;\n seen.add(checkoutPath);\n\n const before = await this.readGitHead(checkoutPath);\n const checkoutChanged = await this.refreshGithubCheckout(plugin, checkoutPath, before);\n const after = await this.readGitHead(checkoutPath);\n if (checkoutChanged || before !== after) changedCheckouts.add(checkoutPath);\n }\n\n if (changedCheckouts.size === 0) return false;\n\n await this.reload();\n // Derive names from the reloaded state so a manifest display-name change reports the new name.\n // Multiple plugins can share one checkout — report every plugin whose source changed.\n const updatedPluginNames = this.loadedPlugins\n .filter(\n plugin =>\n plugin.source === 'github' &&\n plugin.status !== 'inactive' &&\n plugin.status !== 'blocked' &&\n changedCheckouts.has(this.resolvePluginSourcePath(plugin)),\n )\n .map(plugin => plugin.name ?? plugin.id);\n await this.notifyGithubUpdateListeners(updatedPluginNames);\n return true;\n }\n\n private async notifyGithubUpdateListeners(pluginNames: string[]): Promise<void> {\n await Promise.all([...this.githubUpdateListeners].map(listener => Promise.resolve(listener(pluginNames))));\n }\n\n private async refreshGithubCheckout(\n plugin: LoadedPlugin,\n checkoutPath: string,\n currentHead: string,\n ): Promise<boolean> {\n await execa('git', ['fetch', 'origin'], gitExecOptions(checkoutPath));\n const upstream = await this.resolveGitUpstream(checkoutPath, plugin.ref);\n if (!upstream) return false;\n const [localOnly, remoteOnly] = await this.readGitAheadBehind(checkoutPath, upstream);\n const hasLocalChanges = await this.hasGitWorkingTreeChanges(checkoutPath);\n\n if (localOnly > 0 || hasLocalChanges) {\n await this.backupGitCheckout(checkoutPath, currentHead, hasLocalChanges);\n }\n\n if (remoteOnly > 0 || localOnly > 0 || hasLocalChanges) {\n await execa('git', ['reset', '--hard', upstream], gitExecOptions(checkoutPath));\n try {\n await installPluginDependenciesForEntry(checkoutPath, plugin.entry);\n ensureMastraCodePackageLink(getEntryPackageRoot(checkoutPath, plugin.entry));\n } catch (error) {\n await execa('git', ['reset', '--hard', currentHead], gitExecOptions(checkoutPath));\n throw error;\n }\n return true;\n }\n\n return false;\n }\n\n private async backupGitCheckout(\n checkoutPath: string,\n currentHead: string,\n includeWorkingTree: boolean,\n ): Promise<void> {\n const backupBranch = this.createGitBackupBranchName(currentHead);\n\n if (includeWorkingTree) {\n const currentBranch = await this.readGitCurrentBranch(checkoutPath);\n await execa('git', ['switch', '-c', backupBranch], gitExecOptions(checkoutPath));\n await execa('git', ['add', '-A'], gitExecOptions(checkoutPath));\n const hasStagedChanges = await this.hasGitStagedChanges(checkoutPath);\n if (hasStagedChanges) {\n await execa(\n 'git',\n [\n '-c',\n 'user.name=Mastra Code',\n '-c',\n 'user.email=noreply@mastra.ai',\n 'commit',\n '-m',\n 'chore: backup local plugin checkout changes',\n ],\n gitExecOptions(checkoutPath),\n );\n }\n await this.restoreGitCheckout(checkoutPath, currentBranch, currentHead);\n return;\n }\n\n await execa('git', ['branch', backupBranch, 'HEAD'], gitExecOptions(checkoutPath));\n }\n\n private async resolveGitUpstream(cwd: string, installedRef?: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\n 'git',\n ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'],\n gitExecOptions(cwd),\n );\n return stdout.trim();\n } catch {\n return installedRef ? undefined : 'origin/main';\n }\n }\n\n private async readGitAheadBehind(cwd: string, upstream: string): Promise<[number, number]> {\n const { stdout } = await execa(\n 'git',\n ['rev-list', '--left-right', '--count', `HEAD...${upstream}`],\n gitExecOptions(cwd),\n );\n const [ahead = '0', behind = '0'] = stdout.trim().split(/\\s+/);\n return [Number(ahead) || 0, Number(behind) || 0];\n }\n\n private async hasGitWorkingTreeChanges(cwd: string): Promise<boolean> {\n const { stdout } = await execa('git', ['status', '--porcelain'], gitExecOptions(cwd));\n return stdout.trim().length > 0;\n }\n\n private async hasGitStagedChanges(cwd: string): Promise<boolean> {\n try {\n await execa('git', ['diff', '--cached', '--quiet'], gitExecOptions(cwd));\n return false;\n } catch {\n return true;\n }\n }\n\n private async restoreGitCheckout(cwd: string, branch: string | undefined, fallbackHead: string): Promise<void> {\n if (branch) {\n await execa('git', ['switch', branch], gitExecOptions(cwd));\n return;\n }\n await execa('git', ['checkout', fallbackHead], gitExecOptions(cwd));\n }\n\n private async readGitCurrentBranch(cwd: string): Promise<string | undefined> {\n const { stdout } = await execa('git', ['branch', '--show-current'], gitExecOptions(cwd));\n const branch = stdout.trim();\n return branch.length > 0 ? branch : undefined;\n }\n\n private createGitBackupBranchName(currentHead: string): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n return `mastracode/plugin-backup/${timestamp}-${currentHead.slice(0, 8)}`;\n }\n\n private resolvePluginSourcePath(plugin: LoadedPlugin): string {\n const paths = getPluginScopePaths(plugin.scope, this.options);\n return path.isAbsolute(plugin.path) ? plugin.path : path.join(paths.root, plugin.path);\n }\n\n private async readGitHead(cwd: string): Promise<string> {\n const { stdout } = await execa('git', ['rev-parse', 'HEAD'], gitExecOptions(cwd));\n return stdout.trim();\n }\n\n discoverLocal(searchRoot = '.'): ReturnType<typeof discoverLocalPlugins> {\n return discoverLocalPlugins(searchRoot, this.options);\n }\n\n async installLocal(\n localPath: string,\n scope: PluginScope,\n options: Pick<InstallPluginOptions, 'entry'> = {},\n ): Promise<string> {\n const id = await installLocalPlugin(localPath, scope, { ...this.options, ...options });\n await this.reload();\n return id;\n }\n\n async installGithub(\n url: string,\n scope: PluginScope,\n options: Pick<InstallPluginOptions, 'entry' | 'ref' | 'onOutput' | 'signal'> = {},\n ): Promise<string> {\n const id = await installGithubPlugin(url, scope, { ...this.options, ...options });\n await this.reload();\n return id;\n }\n\n async setEnabled(pluginId: string, scope: PluginScope, enabled: boolean): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n savePluginRegistry(paths.registryPath, setPluginRecord(registry, pluginId, { ...record, enabled }));\n await this.reload();\n }\n\n async setConfigValue(\n pluginId: string,\n scope: PluginScope,\n key: string,\n value: MastraCodePluginConfigValue,\n ): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n const config = { ...(record.config ?? {}) };\n if (value === undefined || value === '') {\n delete config[key];\n } else {\n config[key] = value;\n }\n const nextRecord = { ...record, config: Object.keys(config).length > 0 ? config : undefined };\n savePluginRegistry(paths.registryPath, setPluginRecord(registry, pluginId, nextRecord));\n await this.reload();\n }\n\n async uninstall(pluginId: string, scope: PluginScope): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n\n savePluginRegistry(paths.registryPath, removePluginRecord(registry, pluginId));\n if (record.source === 'github') {\n const checkoutPath = path.resolve(\n path.isAbsolute(record.path) ? record.path : path.join(paths.root, record.path),\n );\n const githubSourcesPath = path.resolve(paths.sourcesPath, 'github');\n if (isInsideDirectory(checkoutPath, githubSourcesPath)) {\n fs.rmSync(checkoutPath, { recursive: true, force: true });\n }\n }\n await this.reload();\n }\n}\n"],"mappings":"AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,SAAS,aAAa;AAGtB,SAAS,qBAAqB,yCAAyC;AACvE,SAAS,sBAAsB,qBAAqB,oBAAoB,+BAA+B;AAEvG,SAAS,0BAA0B,mBAAmB,aAAa,8BAA8B;AACjG,SAAS,mCAAmC;AAC5C,SAAS,2BAA2B;AAEpC,SAAS,oBAAoB,oBAAoB,oBAAoB,uBAAuB;AAG5F,MAAM,iCAAiC;AAEvC,SAAS,eAAe,KAAa;AACnC,SAAO,EAAE,KAAK,KAAK,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M,QAAQ,oBAAoB,OAAO,KAAK,OAAO;AACrD,UAAM,WAAW,mBAAmB,MAAM,YAAY;AACtD,UAAM,SAAS,SAAS,QAAQ,QAAQ;AACxC,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,MAAM,WAAW,QAAQ,yBAAyB,KAAK,QAAQ;AAAA,IAC3E;AAEA,uBAAmB,MAAM,cAAc,mBAAmB,UAAU,QAAQ,CAAC;AAC7E,QAAI,OAAO,WAAW,UAAU;AAC9B,YAAM,eAAe,KAAK;AAAA,QACxB,KAAK,WAAW,OAAO,IAAI,IAAI,OAAO,OAAO,KAAK,KAAK,MAAM,MAAM,OAAO,IAAI;AAAA,MAChF;AACA,YAAM,oBAAoB,KAAK,QAAQ,MAAM,aAAa,QAAQ;AAClE,UAAI,kBAAkB,cAAc,iBAAiB,GAAG;AACtD,WAAG,OAAO,cAAc,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,MAC1D;AAAA,IACF;AACA,UAAM,KAAK,OAAO;AAAA,EACpB;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/code-sdk",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.15",
|
|
4
4
|
"description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -56,19 +56,19 @@
|
|
|
56
56
|
"vscode-languageserver-protocol": "^3.17.5",
|
|
57
57
|
"yaml": "^2.7.1",
|
|
58
58
|
"zod": "^4.3.6",
|
|
59
|
-
"@mastra/
|
|
59
|
+
"@mastra/agent-browser": "0.4.1",
|
|
60
|
+
"@mastra/core": "1.52.0-alpha.12",
|
|
61
|
+
"@mastra/github-signals": "0.2.2",
|
|
60
62
|
"@mastra/duckdb": "1.5.1",
|
|
61
63
|
"@mastra/fastembed": "1.2.0",
|
|
62
64
|
"@mastra/libsql": "1.17.0-alpha.3",
|
|
63
65
|
"@mastra/mcp": "1.15.0-alpha.0",
|
|
64
|
-
"@mastra/github-signals": "0.2.2",
|
|
65
66
|
"@mastra/memory": "1.23.1-alpha.1",
|
|
66
|
-
"@mastra/agent-browser": "0.4.1",
|
|
67
|
-
"@mastra/observability": "1.16.2-alpha.1",
|
|
68
67
|
"@mastra/pg": "1.17.0-alpha.3",
|
|
68
|
+
"@mastra/observability": "1.16.2-alpha.1",
|
|
69
69
|
"@mastra/schema-compat": "1.3.4",
|
|
70
|
-
"@mastra/
|
|
71
|
-
"@mastra/
|
|
70
|
+
"@mastra/tavily": "1.1.1-alpha.0",
|
|
71
|
+
"@mastra/stagehand": "0.3.1-alpha.0"
|
|
72
72
|
},
|
|
73
73
|
"devDependencies": {
|
|
74
74
|
"@libsql/client": "^0.17.4",
|
|
@@ -79,8 +79,8 @@
|
|
|
79
79
|
"typescript": "^6.0.3",
|
|
80
80
|
"typescript-eslint": "^8.57.0",
|
|
81
81
|
"vitest": "4.1.10",
|
|
82
|
-
"@internal/
|
|
83
|
-
"@internal/
|
|
82
|
+
"@internal/types-builder": "0.0.89",
|
|
83
|
+
"@internal/lint": "0.0.114"
|
|
84
84
|
},
|
|
85
85
|
"engines": {
|
|
86
86
|
"node": ">=22.19.0"
|