@mastra/code-sdk 1.9.0-alpha.9 → 1.9.0

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.
Files changed (59) hide show
  1. package/dist/agents/tools.d.ts +1 -1
  2. package/dist/agents/tools.d.ts.map +1 -1
  3. package/dist/agents/tools.js +2 -1
  4. package/dist/agents/tools.js.map +1 -1
  5. package/dist/goal-manager.d.ts +39 -3
  6. package/dist/goal-manager.d.ts.map +1 -1
  7. package/dist/goal-manager.js +111 -28
  8. package/dist/goal-manager.js.map +1 -1
  9. package/dist/index.d.ts +12 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +72 -5
  12. package/dist/index.js.map +1 -1
  13. package/dist/onboarding/settings.d.ts +2 -0
  14. package/dist/onboarding/settings.d.ts.map +1 -1
  15. package/dist/onboarding/settings.js +3 -1
  16. package/dist/onboarding/settings.js.map +1 -1
  17. package/dist/permissions.d.ts.map +1 -1
  18. package/dist/permissions.js +6 -1
  19. package/dist/permissions.js.map +1 -1
  20. package/dist/process-memory-diagnostics.js +1 -1
  21. package/dist/schedules/index.d.ts +10 -0
  22. package/dist/schedules/index.d.ts.map +1 -0
  23. package/dist/schedules/index.js +6 -0
  24. package/dist/schedules/interval.d.ts +49 -0
  25. package/dist/schedules/interval.d.ts.map +1 -0
  26. package/dist/schedules/interval.js +215 -0
  27. package/dist/schedules/interval.js.map +1 -0
  28. package/dist/schedules/prompt.d.ts +36 -0
  29. package/dist/schedules/prompt.d.ts.map +1 -0
  30. package/dist/schedules/prompt.js +39 -0
  31. package/dist/schedules/prompt.js.map +1 -0
  32. package/dist/schedules/run-script.d.ts +8 -0
  33. package/dist/schedules/run-script.d.ts.map +1 -0
  34. package/dist/schedules/run-script.js +83 -0
  35. package/dist/schedules/run-script.js.map +1 -0
  36. package/dist/schedules/scheduler.d.ts +101 -0
  37. package/dist/schedules/scheduler.d.ts.map +1 -0
  38. package/dist/schedules/scheduler.js +169 -0
  39. package/dist/schedules/scheduler.js.map +1 -0
  40. package/dist/schedules/tools.d.ts +57 -0
  41. package/dist/schedules/tools.d.ts.map +1 -0
  42. package/dist/schedules/tools.js +220 -0
  43. package/dist/schedules/tools.js.map +1 -0
  44. package/dist/utils/discarding-scores-storage.d.ts +33 -0
  45. package/dist/utils/discarding-scores-storage.d.ts.map +1 -0
  46. package/dist/utils/discarding-scores-storage.js +54 -0
  47. package/dist/utils/discarding-scores-storage.js.map +1 -0
  48. package/dist/utils/maintenance-lock.d.ts +42 -0
  49. package/dist/utils/maintenance-lock.d.ts.map +1 -0
  50. package/dist/utils/maintenance-lock.js +199 -0
  51. package/dist/utils/maintenance-lock.js.map +1 -0
  52. package/dist/utils/prune-cli.d.ts +24 -0
  53. package/dist/utils/prune-cli.d.ts.map +1 -0
  54. package/dist/utils/prune-cli.js +125 -0
  55. package/dist/utils/prune-cli.js.map +1 -0
  56. package/dist/utils/storage-maintenance.d.ts.map +1 -1
  57. package/dist/utils/storage-maintenance.js +33 -3
  58. package/dist/utils/storage-maintenance.js.map +1 -1
  59. package/package.json +20 -14
@@ -30,7 +30,7 @@ export declare function createToolHooks(hookManager?: HookManager, postToolObser
30
30
  type DynamicToolProvider = Record<string, ToolLike | undefined> | ((ctx: {
31
31
  requestContext: RequestContext;
32
32
  }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);
33
- export declare function createDynamicTools(mcpManager?: McpManager, extraTools?: DynamicToolProvider, disabledTools?: string[], storage?: MastraCompositeStore, pluginTools?: Record<string, ToolLike>, backgroundToolsEnabled?: boolean): ({ requestContext, }: {
33
+ export declare function createDynamicTools(mcpManager?: McpManager, extraTools?: DynamicToolProvider, disabledTools?: string[], storage?: MastraCompositeStore, pluginTools?: Record<string, ToolLike>, backgroundToolsEnabled?: boolean, builtinTools?: Record<string, ToolLike>): ({ requestContext, }: {
34
34
  requestContext: RequestContext;
35
35
  }) => ToolsInput | Promise<ToolsInput>;
36
36
  export {};
@@ -1 +1 @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,GAAG,EAAE;IACL,cAAc,EAAE,cAAc,CAAC;CAChC,KAAK,MAAM,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;AAEhG,wBAAgB,kBAAkB,CAChC,UAAU,CAAC,EAAE,UAAU,EACvB,UAAU,CAAC,EAAE,mBAAmB,EAChC,aAAa,CAAC,EAAE,MAAM,EAAE,EACxB,OAAO,CAAC,EAAE,oBAAoB,EAC9B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,EACtC,sBAAsB,UAAQ,EAC9B,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,IAEP,qBAE7B;IACD,cAAc,EAAE,cAAc,CAAC;CAChC,KAAG,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAgGrC"}
@@ -78,7 +78,7 @@ function createToolHooks(hookManager, postToolObserver) {
78
78
  }
79
79
  };
80
80
  }
81
- function createDynamicTools(mcpManager, extraTools, disabledTools, storage, pluginTools, backgroundToolsEnabled = false) {
81
+ function createDynamicTools(mcpManager, extraTools, disabledTools, storage, pluginTools, backgroundToolsEnabled = false, builtinTools) {
82
82
  return function getDynamicTools({ requestContext }) {
83
83
  const ctx = requestContext.get("controller");
84
84
  const state = ctx?.getState();
@@ -93,6 +93,7 @@ function createDynamicTools(mcpManager, extraTools, disabledTools, storage, plug
93
93
  [WORKFLOW_MANAGEMENT_TOOL_IDS.runWorkflow]: runWorkflowTool,
94
94
  [WORKFLOW_MANAGEMENT_TOOL_IDS.deleteWorkflow]: deleteWorkflowTool
95
95
  };
96
+ if (builtinTools) Object.assign(tools, builtinTools);
96
97
  if (storage) tools[MC_TOOLS.NOTIFICATION_INBOX] = createNotificationInboxTool({ storage: new LazyNotificationsStorage(storage) });
97
98
  const configuredWebTools = createConfiguredWebTools();
98
99
  if (configuredWebTools) Object.assign(tools, configuredWebTools);
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":[],"sources":["../../src/agents/tools.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { createNotificationInboxTool, NotificationsStorage } from '@mastra/core/notifications';\nimport type {\n CreateNotificationInput,\n ListDueNotificationsInput,\n ListNotificationsInput,\n UpdateNotificationInput,\n UpdateNotificationsStatusInput,\n} from '@mastra/core/notifications';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { ToolAfterHookContext, ToolHooks } from '@mastra/core/tools';\nimport type { HookManager } from '../hooks/index.js';\nimport type { McpManager } from '../mcp/index.js';\nimport type { MastraCodeComposedState } from '../schema.js';\nimport { MC_TOOLS } from '../tool-names.js';\nimport { createConfiguredWebTools, requestSandboxAccessTool } from '../tools/index.js';\nimport { createWorkflowTool } from '../tools/workflows/create-workflow.js';\nimport { deleteWorkflowTool } from '../tools/workflows/delete-workflow.js';\nimport { getWorkflowTool } from '../tools/workflows/get-workflow.js';\nimport { listWorkflowsTool } from '../tools/workflows/list-workflows.js';\nimport { runWorkflowTool } from '../tools/workflows/run-workflow.js';\nimport { WORKFLOW_MANAGEMENT_TOOL_IDS } from '../tools/workflows/tool-ids.js';\n\n/** Minimal shape for tools passed to createDynamicTools. */\nexport type ToolLike = {\n execute?: (...args: any[]) => Promise<unknown> | unknown;\n} & Record<string, any>;\n\nfunction configurePluginTool(tool: ToolLike, backgroundToolsEnabled: boolean): ToolLike {\n if (backgroundToolsEnabled || !tool.background) return tool;\n return { ...tool, background: { ...tool.background, enabled: false } };\n}\n\nexport class LazyNotificationsStorage extends NotificationsStorage {\n constructor(private readonly storage: MastraCompositeStore) {\n super();\n }\n\n private async getNotificationsStorage(): Promise<NotificationsStorage> {\n const notifications = await this.storage.getStore('notifications');\n if (!notifications) {\n throw new Error('notification_inbox requires a notifications storage domain');\n }\n return notifications;\n }\n\n async createNotification(input: CreateNotificationInput) {\n return (await this.getNotificationsStorage()).createNotification(input);\n }\n\n async listNotifications(input: ListNotificationsInput) {\n return (await this.getNotificationsStorage()).listNotifications(input);\n }\n\n async listDueNotifications(input: ListDueNotificationsInput) {\n return (await this.getNotificationsStorage()).listDueNotifications(input);\n }\n\n async getNotification(input: { threadId: string; id: string }) {\n return (await this.getNotificationsStorage()).getNotification(input);\n }\n\n async updateNotification(input: UpdateNotificationInput) {\n return (await this.getNotificationsStorage()).updateNotification(input);\n }\n\n override async updateNotificationsStatus(input: UpdateNotificationsStatusInput) {\n return (await this.getNotificationsStorage()).updateNotificationsStatus(input);\n }\n\n async dangerouslyClearAll() {\n return (await this.getNotificationsStorage()).dangerouslyClearAll();\n }\n}\n\nexport type PostToolObserver = (context: ToolAfterHookContext) => void | Promise<void>;\n\nexport function createToolHooks(hookManager?: HookManager, postToolObserver?: PostToolObserver): ToolHooks | undefined {\n if (!hookManager && !postToolObserver) return undefined;\n\n return {\n beforeToolCall: async ({ toolName, input }) => {\n if (!hookManager) return;\n const preResult = await hookManager.runPreToolUse(toolName, input);\n if (!preResult.allowed) {\n return {\n proceed: false as const,\n output: {\n error: preResult.blockReason ?? `Blocked by PreToolUse hook for tool \"${toolName}\"`,\n },\n };\n }\n },\n afterToolCall: async context => {\n const { toolName, input, output, error } = context;\n if (hookManager) {\n const failed = error !== undefined;\n await hookManager\n .runPostToolUse(\n toolName,\n input,\n failed ? { error: error instanceof Error ? error.message : String(error) } : output,\n failed,\n )\n .catch(() => undefined);\n }\n await Promise.resolve()\n .then(() => postToolObserver?.(context))\n .catch(error => {\n console.warn(`[MastraCode] Post-tool observer failed for ${toolName}.`, error);\n });\n },\n };\n}\n\ntype DynamicToolProvider =\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n\nexport function createDynamicTools(\n mcpManager?: McpManager,\n extraTools?: DynamicToolProvider,\n disabledTools?: string[],\n storage?: MastraCompositeStore,\n pluginTools?: Record<string, ToolLike>,\n backgroundToolsEnabled = false,\n) {\n return function getDynamicTools({\n requestContext,\n }: {\n requestContext: RequestContext;\n }): ToolsInput | Promise<ToolsInput> {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeComposedState> | undefined;\n const state = ctx?.getState();\n\n const modelId = ctx?.session?.modelId;\n const isAnthropicModel = modelId?.startsWith('anthropic/');\n const isOpenAIModel = modelId?.startsWith('openai/');\n\n // Filesystem, grep, glob, edit, write, execute_command, and process\n // management tools are now provided by the workspace (see workspace.ts).\n // Only tools without a workspace equivalent remain here.\n const tools: Record<string, ToolLike> = {\n request_access: requestSandboxAccessTool,\n // Workflow surface. `create-workflow` delegates to the workflow-builder\n // sub-agent; the other four are Dynamic Workflow management operations.\n // Permission categories live in permissions.ts (TOOL_CATEGORY_MAP).\n [WORKFLOW_MANAGEMENT_TOOL_IDS.createWorkflow]: createWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.listWorkflows]: listWorkflowsTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.getWorkflow]: getWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.runWorkflow]: runWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.deleteWorkflow]: deleteWorkflowTool,\n };\n\n if (storage) {\n tools[MC_TOOLS.NOTIFICATION_INBOX] = createNotificationInboxTool({\n storage: new LazyNotificationsStorage(storage),\n });\n }\n\n const configuredWebTools = createConfiguredWebTools();\n if (configuredWebTools) {\n Object.assign(tools, configuredWebTools);\n } else if (isAnthropicModel) {\n const anthropic = createAnthropic({});\n tools.web_search = anthropic.tools.webSearch_20250305();\n } else if (isOpenAIModel) {\n const openai = createOpenAI({});\n tools.web_search = openai.tools.webSearch();\n }\n\n if (mcpManager) {\n const mcpTools = mcpManager.getTools();\n Object.assign(tools, mcpTools);\n }\n\n const finish = (resolvedExtra: Record<string, ToolLike | undefined> | undefined) => {\n if (resolvedExtra) {\n for (const [name, tool] of Object.entries(resolvedExtra)) {\n if (tool && !(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n\n if (pluginTools) {\n for (const [name, tool] of Object.entries(pluginTools)) {\n if (!(name in tools)) {\n tools[name] = configurePluginTool(tool, backgroundToolsEnabled);\n }\n }\n }\n\n // Remove tools explicitly disabled via config so the model never sees them.\n if (disabledTools?.length) {\n for (const toolName of disabledTools) {\n delete tools[toolName];\n }\n }\n\n // Remove tools that have a per-tool 'deny' policy so the model never sees them.\n const permissionRules = state?.permissionRules;\n if (permissionRules?.tools) {\n for (const [name, policy] of Object.entries(permissionRules.tools)) {\n if (policy === 'deny') {\n delete tools[name];\n }\n }\n }\n\n return tools as ToolsInput;\n };\n\n if (typeof extraTools === 'function') {\n const resolved = extraTools({ requestContext });\n // Stay synchronous for sync providers; only go async when the provider does.\n if (resolved && typeof (resolved as PromiseLike<unknown>).then === 'function') {\n return Promise.resolve(resolved).then(finish);\n }\n return finish(resolved as Record<string, ToolLike | undefined>);\n }\n\n return finish(extraTools);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,SAAS,oBAAoB,MAAgB,wBAA2C;CACtF,IAAI,0BAA0B,CAAC,KAAK,YAAY,OAAO;CACvD,OAAO;EAAE,GAAG;EAAM,YAAY;GAAE,GAAG,KAAK;GAAY,SAAS;EAAM;CAAE;AACvE;AAEA,IAAa,2BAAb,cAA8C,qBAAqB;CACpC;CAA7B,YAAY,SAAgD;EAC1D,MAAM;EADqB,KAAA,UAAA;CAE7B;CAEA,MAAc,0BAAyD;EACrE,MAAM,gBAAgB,MAAM,KAAK,QAAQ,SAAS,eAAe;EACjE,IAAI,CAAC,eACH,MAAM,IAAI,MAAM,4DAA4D;EAE9E,OAAO;CACT;CAEA,MAAM,mBAAmB,OAAgC;EACvD,QAAQ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,MAAM,sBAAsB;GAAA;GAMpE,IAAI,eAAe,QACjB,KAAK,MAAM,YAAY,eACrB,OAAO,MAAM;GAKjB,MAAM,kBAAkB,OAAO;GAC/B,IAAI,iBAAiB,OACd;SAAA,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,gBAAgB,KAAK,GAC/D,IAAI,WAAW,QACb,OAAO,MAAM;GAAA;GAKnB,OAAO;EACT;EAEA,IAAI,OAAO,eAAe,YAAY;GACpC,MAAM,WAAW,WAAW,EAAE,eAAe,CAAC;GAE9C,IAAI,YAAY,OAAQ,SAAkC,SAAS,YACjE,OAAO,QAAQ,QAAQ,QAAQ,CAAC,CAAC,KAAK,MAAM;GAE9C,OAAO,OAAO,QAAgD;EAChE;EAEA,OAAO,OAAO,UAAU;CAC1B;AACF"}
1
+ {"version":3,"file":"tools.js","names":[],"sources":["../../src/agents/tools.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { createNotificationInboxTool, NotificationsStorage } from '@mastra/core/notifications';\nimport type {\n CreateNotificationInput,\n ListDueNotificationsInput,\n ListNotificationsInput,\n UpdateNotificationInput,\n UpdateNotificationsStatusInput,\n} from '@mastra/core/notifications';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { ToolAfterHookContext, ToolHooks } from '@mastra/core/tools';\nimport type { HookManager } from '../hooks/index.js';\nimport type { McpManager } from '../mcp/index.js';\nimport type { MastraCodeComposedState } from '../schema.js';\nimport { MC_TOOLS } from '../tool-names.js';\nimport { createConfiguredWebTools, requestSandboxAccessTool } from '../tools/index.js';\nimport { createWorkflowTool } from '../tools/workflows/create-workflow.js';\nimport { deleteWorkflowTool } from '../tools/workflows/delete-workflow.js';\nimport { getWorkflowTool } from '../tools/workflows/get-workflow.js';\nimport { listWorkflowsTool } from '../tools/workflows/list-workflows.js';\nimport { runWorkflowTool } from '../tools/workflows/run-workflow.js';\nimport { WORKFLOW_MANAGEMENT_TOOL_IDS } from '../tools/workflows/tool-ids.js';\n\n/** Minimal shape for tools passed to createDynamicTools. */\nexport type ToolLike = {\n execute?: (...args: any[]) => Promise<unknown> | unknown;\n} & Record<string, any>;\n\nfunction configurePluginTool(tool: ToolLike, backgroundToolsEnabled: boolean): ToolLike {\n if (backgroundToolsEnabled || !tool.background) return tool;\n return { ...tool, background: { ...tool.background, enabled: false } };\n}\n\nexport class LazyNotificationsStorage extends NotificationsStorage {\n constructor(private readonly storage: MastraCompositeStore) {\n super();\n }\n\n private async getNotificationsStorage(): Promise<NotificationsStorage> {\n const notifications = await this.storage.getStore('notifications');\n if (!notifications) {\n throw new Error('notification_inbox requires a notifications storage domain');\n }\n return notifications;\n }\n\n async createNotification(input: CreateNotificationInput) {\n return (await this.getNotificationsStorage()).createNotification(input);\n }\n\n async listNotifications(input: ListNotificationsInput) {\n return (await this.getNotificationsStorage()).listNotifications(input);\n }\n\n async listDueNotifications(input: ListDueNotificationsInput) {\n return (await this.getNotificationsStorage()).listDueNotifications(input);\n }\n\n async getNotification(input: { threadId: string; id: string }) {\n return (await this.getNotificationsStorage()).getNotification(input);\n }\n\n async updateNotification(input: UpdateNotificationInput) {\n return (await this.getNotificationsStorage()).updateNotification(input);\n }\n\n override async updateNotificationsStatus(input: UpdateNotificationsStatusInput) {\n return (await this.getNotificationsStorage()).updateNotificationsStatus(input);\n }\n\n async dangerouslyClearAll() {\n return (await this.getNotificationsStorage()).dangerouslyClearAll();\n }\n}\n\nexport type PostToolObserver = (context: ToolAfterHookContext) => void | Promise<void>;\n\nexport function createToolHooks(hookManager?: HookManager, postToolObserver?: PostToolObserver): ToolHooks | undefined {\n if (!hookManager && !postToolObserver) return undefined;\n\n return {\n beforeToolCall: async ({ toolName, input }) => {\n if (!hookManager) return;\n const preResult = await hookManager.runPreToolUse(toolName, input);\n if (!preResult.allowed) {\n return {\n proceed: false as const,\n output: {\n error: preResult.blockReason ?? `Blocked by PreToolUse hook for tool \"${toolName}\"`,\n },\n };\n }\n },\n afterToolCall: async context => {\n const { toolName, input, output, error } = context;\n if (hookManager) {\n const failed = error !== undefined;\n await hookManager\n .runPostToolUse(\n toolName,\n input,\n failed ? { error: error instanceof Error ? error.message : String(error) } : output,\n failed,\n )\n .catch(() => undefined);\n }\n await Promise.resolve()\n .then(() => postToolObserver?.(context))\n .catch(error => {\n console.warn(`[MastraCode] Post-tool observer failed for ${toolName}.`, error);\n });\n },\n };\n}\n\ntype DynamicToolProvider =\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n\nexport function createDynamicTools(\n mcpManager?: McpManager,\n extraTools?: DynamicToolProvider,\n disabledTools?: string[],\n storage?: MastraCompositeStore,\n pluginTools?: Record<string, ToolLike>,\n backgroundToolsEnabled = false,\n builtinTools?: Record<string, ToolLike>,\n) {\n return function getDynamicTools({\n requestContext,\n }: {\n requestContext: RequestContext;\n }): ToolsInput | Promise<ToolsInput> {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeComposedState> | undefined;\n const state = ctx?.getState();\n\n const modelId = ctx?.session?.modelId;\n const isAnthropicModel = modelId?.startsWith('anthropic/');\n const isOpenAIModel = modelId?.startsWith('openai/');\n\n // Filesystem, grep, glob, edit, write, execute_command, and process\n // management tools are now provided by the workspace (see workspace.ts).\n // Only tools without a workspace equivalent remain here.\n const tools: Record<string, ToolLike> = {\n request_access: requestSandboxAccessTool,\n // Workflow surface. `create-workflow` delegates to the workflow-builder\n // sub-agent; the other four are Dynamic Workflow management operations.\n // Permission categories live in permissions.ts (TOOL_CATEGORY_MAP).\n [WORKFLOW_MANAGEMENT_TOOL_IDS.createWorkflow]: createWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.listWorkflows]: listWorkflowsTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.getWorkflow]: getWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.runWorkflow]: runWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.deleteWorkflow]: deleteWorkflowTool,\n };\n\n // Opt-in built-ins (e.g. the experimental schedule tools).\n if (builtinTools) Object.assign(tools, builtinTools);\n\n if (storage) {\n tools[MC_TOOLS.NOTIFICATION_INBOX] = createNotificationInboxTool({\n storage: new LazyNotificationsStorage(storage),\n });\n }\n\n const configuredWebTools = createConfiguredWebTools();\n if (configuredWebTools) {\n Object.assign(tools, configuredWebTools);\n } else if (isAnthropicModel) {\n const anthropic = createAnthropic({});\n tools.web_search = anthropic.tools.webSearch_20250305();\n } else if (isOpenAIModel) {\n const openai = createOpenAI({});\n tools.web_search = openai.tools.webSearch();\n }\n\n if (mcpManager) {\n const mcpTools = mcpManager.getTools();\n Object.assign(tools, mcpTools);\n }\n\n const finish = (resolvedExtra: Record<string, ToolLike | undefined> | undefined) => {\n if (resolvedExtra) {\n for (const [name, tool] of Object.entries(resolvedExtra)) {\n if (tool && !(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n\n if (pluginTools) {\n for (const [name, tool] of Object.entries(pluginTools)) {\n if (!(name in tools)) {\n tools[name] = configurePluginTool(tool, backgroundToolsEnabled);\n }\n }\n }\n\n // Remove tools explicitly disabled via config so the model never sees them.\n if (disabledTools?.length) {\n for (const toolName of disabledTools) {\n delete tools[toolName];\n }\n }\n\n // Remove tools that have a per-tool 'deny' policy so the model never sees them.\n const permissionRules = state?.permissionRules;\n if (permissionRules?.tools) {\n for (const [name, policy] of Object.entries(permissionRules.tools)) {\n if (policy === 'deny') {\n delete tools[name];\n }\n }\n }\n\n return tools as ToolsInput;\n };\n\n if (typeof extraTools === 'function') {\n const resolved = extraTools({ requestContext });\n // Stay synchronous for sync providers; only go async when the provider does.\n if (resolved && typeof (resolved as PromiseLike<unknown>).then === 'function') {\n return Promise.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AyB,OAAO,EAC/C,CAAC;EAGH,MAAM,qBAAqB,yBAAyB;EACpD,IAAI,oBACF,OAAO,OAAO,OAAO,kBAAkB;OAClC,IAAI,kBAET,MAAM,aADY,gBAAgB,CAAC,CACR,CAAC,CAAC,MAAM,mBAAmB;OACjD,IAAI,eAET,MAAM,aADS,aAAa,CAAC,CACL,CAAC,CAAC,MAAM,UAAU;EAG5C,IAAI,YAAY;GACd,MAAM,WAAW,WAAW,SAAS;GACrC,OAAO,OAAO,OAAO,QAAQ;EAC/B;EAEA,MAAM,UAAU,kBAAoE;GAClF,IAAI,eACG;SAAA,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,aAAa,GACrD,IAAI,QAAQ,EAAE,QAAQ,QACpB,MAAM,QAAQ;GAAA;GAKpB,IAAI,aACG;SAAA,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,WAAW,GACnD,IAAI,EAAE,QAAQ,QACZ,MAAM,QAAQ,oBAAoB,MAAM,sBAAsB;GAAA;GAMpE,IAAI,eAAe,QACjB,KAAK,MAAM,YAAY,eACrB,OAAO,MAAM;GAKjB,MAAM,kBAAkB,OAAO;GAC/B,IAAI,iBAAiB,OACd;SAAA,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,gBAAgB,KAAK,GAC/D,IAAI,WAAW,QACb,OAAO,MAAM;GAAA;GAKnB,OAAO;EACT;EAEA,IAAI,OAAO,eAAe,YAAY;GACpC,MAAM,WAAW,WAAW,EAAE,eAAe,CAAC;GAE9C,IAAI,YAAY,OAAQ,SAAkC,SAAS,YACjE,OAAO,QAAQ,QAAQ,QAAQ,CAAC,CAAC,KAAK,MAAM;GAE9C,OAAO,OAAO,QAAgD;EAChE;EAEA,OAAO,OAAO,UAAU;CAC1B;AACF"}
@@ -19,6 +19,8 @@ export interface GoalState {
19
19
  startedAt: string;
20
20
  activeStartedAt?: string;
21
21
  activeDurationMs?: number;
22
+ /** Why the goal paused (judge failure, budget exhaustion, ...). Only set while paused. */
23
+ pausedReason?: string;
22
24
  }
23
25
  export declare const DEFAULT_MAX_TURNS = 50;
24
26
  export declare class GoalManager {
@@ -27,6 +29,13 @@ export declare class GoalManager {
27
29
  private threadId;
28
30
  private agentId;
29
31
  private persistGoalOnNextThreadCreate;
32
+ /**
33
+ * Set by {@link clear} to the thread the goal was cleared on: the next save
34
+ * with an empty mirror on that same thread deletes the goal. A goal hydrated
35
+ * from legacy metadata has no known thread, so its clear applies to whichever
36
+ * thread the next save runs on (the pre-existing behaviour).
37
+ */
38
+ private pendingDelete;
30
39
  getGoal(): GoalState | null;
31
40
  isActive(): boolean;
32
41
  persistOnNextThreadCreate(): void;
@@ -53,18 +62,45 @@ export declare class GoalManager {
53
62
  applyEvaluation(update: {
54
63
  runsUsed: number;
55
64
  status: GoalStatus;
65
+ pausedReason?: string;
56
66
  }): GoalState | null;
57
67
  /**
58
68
  * Persist the active objective to ThreadState via the agent. The objective
59
- * record is the source of truth; the legacy thread-metadata key is cleared so
60
- * stale state from older sessions does not resurface.
69
+ * record is the source of truth; the legacy thread-metadata key is cleared on
70
+ * a save that actually wrote, so stale state from older sessions cannot
71
+ * shadow the record — and a save that wrote nothing leaves it alone.
72
+ *
73
+ * An empty in-memory mirror means "I have nothing *loaded*", which is not the
74
+ * same statement as "there is nothing": the mirror is also emptied by storage
75
+ * failures and thread switches. So a save with an empty mirror deletes the
76
+ * goal (durable record and legacy key) only right after an explicit
77
+ * {@link clear} on the same thread (or any thread, for a legacy-hydrated goal
78
+ * whose thread is unknown), and is a complete no-op otherwise.
61
79
  */
62
80
  saveToThread(state: GoalManagerState): Promise<void>;
81
+ /**
82
+ * Remove the objective from the thread, whatever the in-memory mirror holds.
83
+ *
84
+ * The durable record needs an agent and a thread; the legacy thread-metadata
85
+ * key does not, so it is wiped either way — unlike {@link saveToThread}, which
86
+ * writes nothing with an empty mirror unless {@link clear} ran. That asymmetry is deliberate: a
87
+ * pre-migration goal must not resurface from the legacy key after a clear.
88
+ * Like the save, this is best-effort: a failed durable delete also skips the
89
+ * legacy wipe. A pending {@link clear} stays pending until both writes
90
+ * succeed, so a later save retries it; loading the thread retries it once
91
+ * and then drops it. Resolves to whether the delete landed.
92
+ */
93
+ deleteFromThread(state: GoalManagerState): Promise<boolean>;
63
94
  /**
64
95
  * Load the objective from ThreadState (called on thread switch). Falls back to
65
96
  * the legacy thread-metadata goal for threads created before this migration.
97
+ *
98
+ * A clear whose delete failed is retried here when it targeted this thread and
99
+ * the stored goal is the one that was cleared; otherwise the stored goal loads,
100
+ * so the mirror never hides a goal core is still judging. Resolves to whether
101
+ * that retried delete landed.
66
102
  */
67
- loadFromThread(state: GoalManagerState, isCurrent?: () => boolean): Promise<void>;
103
+ loadFromThread(state: GoalManagerState, isCurrent?: () => boolean): Promise<boolean>;
68
104
  /**
69
105
  * Legacy entry point retained for thread-switch call sites that only have the
70
106
  * thread metadata available. Hydrates from a previously-persisted GoalState.
@@ -1 +1 @@
1
- {"version":3,"file":"goal-manager.d.ts","sourceRoot":"","sources":["../src/goal-manager.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAI9E,MAAM,WAAW,gBAAgB,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAChG,UAAU,EAAE,eAAe,CAAC,MAAM,CAAC,CAAC;IACpC,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;CAC1B;AAMD,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEtD;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,UAAU,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAA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AG,SAAS,GAAG,IAAI;IA4B3E,OAAO,CAAC,QAAQ;IAQhB,kFAAkF;IAClF,OAAO,CAAC,iBAAiB;IAQzB,OAAO,CAAC,WAAW;CAmBpB"}
@@ -26,6 +26,13 @@ var GoalManager = class {
26
26
  threadId;
27
27
  agentId;
28
28
  persistGoalOnNextThreadCreate = false;
29
+ /**
30
+ * Set by {@link clear} to the thread the goal was cleared on: the next save
31
+ * with an empty mirror on that same thread deletes the goal. A goal hydrated
32
+ * from legacy metadata has no known thread, so its clear applies to whichever
33
+ * thread the next save runs on (the pre-existing behaviour).
34
+ */
35
+ pendingDelete = null;
29
36
  getGoal() {
30
37
  if (!this.record) return null;
31
38
  const { judgeModelId, maxTurns } = this.effectiveSettings(this.record);
@@ -37,6 +44,7 @@ var GoalManager = class {
37
44
  maxTurns,
38
45
  judgeModelId,
39
46
  startedAt: new Date(this.record.startedAt).toISOString(),
47
+ ...this.record.pausedReason ? { pausedReason: this.record.pausedReason } : {},
40
48
  activeDurationMs: this.agentId && this.threadId ? getGoalActivityDurationMs({
41
49
  agentId: this.agentId,
42
50
  threadId: this.threadId,
@@ -66,6 +74,7 @@ var GoalManager = class {
66
74
  const agent = this.getAgent(state);
67
75
  const now = Date.now();
68
76
  const id = randomUUID();
77
+ this.pendingDelete = null;
69
78
  this.threadId = threadId ?? void 0;
70
79
  this.agentId = agent?.id;
71
80
  if (agent && threadId) {
@@ -131,10 +140,15 @@ var GoalManager = class {
131
140
  if (this.record) this.record = {
132
141
  ...this.record,
133
142
  status: "done",
143
+ pausedReason: void 0,
134
144
  updatedAt: Date.now()
135
145
  };
136
146
  }
137
147
  clear() {
148
+ this.pendingDelete = {
149
+ threadId: this.threadId,
150
+ goalId: this.record?.id
151
+ };
138
152
  this.record = null;
139
153
  this.threadId = void 0;
140
154
  this.agentId = void 0;
@@ -146,74 +160,141 @@ var GoalManager = class {
146
160
  */
147
161
  applyEvaluation(update) {
148
162
  if (!this.record) return null;
163
+ const pausedReason = update.status === "paused" ? update.pausedReason ?? (this.record.status === "paused" ? this.record.pausedReason : void 0) : void 0;
149
164
  this.record = {
150
165
  ...this.record,
151
166
  runsUsed: update.runsUsed,
152
167
  status: update.status,
168
+ pausedReason,
153
169
  updatedAt: Date.now()
154
170
  };
155
171
  return this.getGoal();
156
172
  }
157
173
  /**
158
174
  * Persist the active objective to ThreadState via the agent. The objective
159
- * record is the source of truth; the legacy thread-metadata key is cleared so
160
- * stale state from older sessions does not resurface.
175
+ * record is the source of truth; the legacy thread-metadata key is cleared on
176
+ * a save that actually wrote, so stale state from older sessions cannot
177
+ * shadow the record — and a save that wrote nothing leaves it alone.
178
+ *
179
+ * An empty in-memory mirror means "I have nothing *loaded*", which is not the
180
+ * same statement as "there is nothing": the mirror is also emptied by storage
181
+ * failures and thread switches. So a save with an empty mirror deletes the
182
+ * goal (durable record and legacy key) only right after an explicit
183
+ * {@link clear} on the same thread (or any thread, for a legacy-hydrated goal
184
+ * whose thread is unknown), and is a complete no-op otherwise.
161
185
  */
162
186
  async saveToThread(state) {
163
187
  const threadId = state.session.thread.getId();
164
188
  const agent = this.getAgent(state);
189
+ if (!this.record && this.pendingDelete) {
190
+ const clearedThreadId = this.pendingDelete.threadId;
191
+ if (clearedThreadId === void 0 || clearedThreadId === threadId) await this.deleteFromThread(state);
192
+ return;
193
+ }
165
194
  try {
166
- if (agent && threadId) if (this.record) {
167
- if (!await agent.updateObjectiveOptions({
168
- threadId,
169
- status: this.record.status,
170
- ...this.record.pausedReason ? { pausedReason: this.record.pausedReason } : {},
171
- ...this.record.judgeModelId ? { judgeModelId: this.record.judgeModelId } : {},
172
- ...this.record.maxRuns !== void 0 ? { maxRuns: this.record.maxRuns } : {}
173
- })) {
174
- const desiredStatus = this.record.status;
175
- await agent.setObjective(this.record.objective, {
176
- id: this.record.id,
195
+ if (agent && threadId) {
196
+ if (this.record) {
197
+ if (!await agent.updateObjectiveOptions({
177
198
  threadId,
178
- resourceId: state.session.identity.getResourceId(),
179
- activeDurationMs: normalizeActiveDurationMs(this.record.activeDurationMs),
199
+ status: this.record.status,
200
+ ...this.record.pausedReason ? { pausedReason: this.record.pausedReason } : {},
180
201
  ...this.record.judgeModelId ? { judgeModelId: this.record.judgeModelId } : {},
181
202
  ...this.record.maxRuns !== void 0 ? { maxRuns: this.record.maxRuns } : {}
182
- });
183
- if (desiredStatus !== "active") await agent.updateObjectiveOptions({
184
- threadId,
185
- status: desiredStatus,
186
- ...this.record.pausedReason ? { pausedReason: this.record.pausedReason } : {}
203
+ })) {
204
+ const desiredStatus = this.record.status;
205
+ if (!await agent.setObjective(this.record.objective, {
206
+ id: this.record.id,
207
+ threadId,
208
+ resourceId: state.session.identity.getResourceId(),
209
+ activeDurationMs: normalizeActiveDurationMs(this.record.activeDurationMs),
210
+ ...this.record.judgeModelId ? { judgeModelId: this.record.judgeModelId } : {},
211
+ ...this.record.maxRuns !== void 0 ? { maxRuns: this.record.maxRuns } : {}
212
+ })) return;
213
+ if (desiredStatus !== "active") await agent.updateObjectiveOptions({
214
+ threadId,
215
+ status: desiredStatus,
216
+ ...this.record.pausedReason ? { pausedReason: this.record.pausedReason } : {}
217
+ });
218
+ }
219
+ await state.session.thread.setSetting({
220
+ key: THREAD_GOAL_KEY,
221
+ value: void 0
187
222
  });
188
223
  }
189
- } else await agent.clearObjective({ threadId });
224
+ }
225
+ } catch {}
226
+ }
227
+ /**
228
+ * Remove the objective from the thread, whatever the in-memory mirror holds.
229
+ *
230
+ * The durable record needs an agent and a thread; the legacy thread-metadata
231
+ * key does not, so it is wiped either way — unlike {@link saveToThread}, which
232
+ * writes nothing with an empty mirror unless {@link clear} ran. That asymmetry is deliberate: a
233
+ * pre-migration goal must not resurface from the legacy key after a clear.
234
+ * Like the save, this is best-effort: a failed durable delete also skips the
235
+ * legacy wipe. A pending {@link clear} stays pending until both writes
236
+ * succeed, so a later save retries it; loading the thread retries it once
237
+ * and then drops it. Resolves to whether the delete landed.
238
+ */
239
+ async deleteFromThread(state) {
240
+ const threadId = state.session.thread.getId();
241
+ const agent = this.getAgent(state);
242
+ try {
243
+ if (agent && threadId) await agent.clearObjective({ threadId });
190
244
  await state.session.thread.setSetting({
191
245
  key: THREAD_GOAL_KEY,
192
246
  value: void 0
193
247
  });
194
- } catch {}
248
+ this.pendingDelete = null;
249
+ return true;
250
+ } catch {
251
+ if (threadId) this.pendingDelete = {
252
+ threadId,
253
+ goalId: this.pendingDelete?.goalId
254
+ };
255
+ return false;
256
+ }
195
257
  }
196
258
  /**
197
259
  * Load the objective from ThreadState (called on thread switch). Falls back to
198
260
  * the legacy thread-metadata goal for threads created before this migration.
261
+ *
262
+ * A clear whose delete failed is retried here when it targeted this thread and
263
+ * the stored goal is the one that was cleared; otherwise the stored goal loads,
264
+ * so the mirror never hides a goal core is still judging. Resolves to whether
265
+ * that retried delete landed.
199
266
  */
200
267
  async loadFromThread(state, isCurrent = () => true) {
268
+ const pending = this.pendingDelete;
201
269
  const threadId = state.session.thread.getId();
202
270
  const agent = this.getAgent(state);
203
271
  let nextRecord = null;
272
+ let storedId;
204
273
  if (agent && threadId) try {
205
274
  const record = await agent.getObjective({ threadId });
206
- if (record) nextRecord = {
207
- ...record,
208
- id: record.id ?? randomUUID(),
209
- activeDurationMs: normalizeActiveDurationMs(record.activeDurationMs)
210
- };
275
+ if (record) {
276
+ storedId = record.id;
277
+ nextRecord = {
278
+ ...record,
279
+ id: record.id ?? randomUUID(),
280
+ activeDurationMs: normalizeActiveDurationMs(record.activeDurationMs)
281
+ };
282
+ }
211
283
  } catch {}
212
- if (!isCurrent()) return;
284
+ if (!isCurrent()) return false;
285
+ if (pending && this.pendingDelete !== pending) return false;
286
+ let retriedDelete = false;
287
+ if (pending?.goalId && pending.threadId === threadId && storedId === pending.goalId) {
288
+ retriedDelete = await this.deleteFromThread(state);
289
+ if (retriedDelete) nextRecord = null;
290
+ if (!isCurrent()) return false;
291
+ }
213
292
  this.persistGoalOnNextThreadCreate = false;
293
+ this.pendingDelete = null;
214
294
  this.threadId = threadId ?? void 0;
215
295
  this.agentId = agent?.id;
216
296
  this.record = nextRecord;
297
+ return retriedDelete;
217
298
  }
218
299
  /**
219
300
  * Legacy entry point retained for thread-switch call sites that only have the
@@ -222,6 +303,7 @@ var GoalManager = class {
222
303
  loadFromThreadMetadata(metadata) {
223
304
  const saved = metadata?.[THREAD_GOAL_KEY];
224
305
  this.persistGoalOnNextThreadCreate = false;
306
+ this.pendingDelete = null;
225
307
  this.threadId = void 0;
226
308
  this.agentId = void 0;
227
309
  if (saved && saved.objective && saved.status) this.record = {
@@ -231,6 +313,7 @@ var GoalManager = class {
231
313
  activeDurationMs: normalizeActiveDurationMs(saved.activeDurationMs),
232
314
  maxRuns: saved.maxTurns ?? 50,
233
315
  judgeModelId: saved.judgeModelId ?? "",
316
+ ...saved.pausedReason ? { pausedReason: saved.pausedReason } : {},
234
317
  startedAt: saved.startedAt ? Date.parse(saved.startedAt) || Date.now() : Date.now(),
235
318
  updatedAt: Date.now(),
236
319
  id: saved.id ?? randomUUID()
@@ -1 +1 @@
1
- {"version":3,"file":"goal-manager.js","names":[],"sources":["../src/goal-manager.ts"],"sourcesContent":["/**\n * GoalManager — persistent cross-turn goals, backed by the Agent's native goal\n * mechanism.\n *\n * The objective lives in the durable `threadState` `'goal'` slot (via\n * `agent.setObjective`/`getObjective`/`clearObjective`/`updateObjectiveOptions`)\n * and is judged in-loop by the core goal step. This manager is a thin adapter:\n * it keeps a synchronous in-memory view of the current objective for the TUI\n * (status line, modal, keyboard shortcuts) and delegates persistence to the\n * agent. There is no standalone judge agent and no between-turn re-invocation —\n * the core goal step drives continuation and surfaces progress via `goal` stream\n * chunks.\n */\nimport { randomUUID } from 'node:crypto';\nimport { getGoalActivityDurationMs } from '@mastra/core/agent';\nimport type { Agent } from '@mastra/core/agent';\nimport type { AgentController, Session } from '@mastra/core/agent-controller';\nimport type { GoalObjectiveRecord } from '@mastra/core/storage';\nimport { loadSettings } from './onboarding/settings.js';\n\nexport interface GoalManagerState<TState extends Record<string, unknown> = Record<string, unknown>> {\n controller: AgentController<TState>;\n session: Session<TState>;\n}\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport type GoalStatus = 'active' | 'paused' | 'done';\n\n/**\n * TUI-facing view of a goal. Derived from the durable {@link GoalObjectiveRecord}\n * plus the effective judge/max-runs settings, with display-only timer fields and\n * a stable `id` used to match plan-started goals.\n */\nexport interface GoalState {\n id: string;\n objective: string;\n status: GoalStatus;\n turnsUsed: number;\n maxTurns: number;\n judgeModelId: string;\n startedAt: string;\n activeStartedAt?: string;\n activeDurationMs?: number;\n}\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nexport const DEFAULT_MAX_TURNS = 50;\nconst THREAD_GOAL_KEY = 'goal';\n\nfunction normalizeActiveDurationMs(value: number | undefined): number {\n return value !== undefined && Number.isFinite(value) && value >= 0 ? value : 0;\n}\n\n// =============================================================================\n// GoalManager\n// =============================================================================\n\nexport class GoalManager {\n /** Synchronous in-memory view of the active objective record (source of truth is ThreadState). */\n private record: (GoalObjectiveRecord & { id: string }) | null = null;\n private threadId: string | undefined;\n private agentId: string | undefined;\n private persistGoalOnNextThreadCreate = false;\n\n // ---------------------------------------------------------------------------\n // Synchronous TUI surface\n // ---------------------------------------------------------------------------\n\n getGoal(): GoalState | null {\n if (!this.record) return null;\n const { judgeModelId, maxTurns } = this.effectiveSettings(this.record);\n return {\n id: this.record.id,\n objective: this.record.objective,\n status: this.record.status,\n turnsUsed: this.record.runsUsed,\n maxTurns,\n judgeModelId,\n startedAt: new Date(this.record.startedAt).toISOString(),\n activeDurationMs:\n this.agentId && this.threadId\n ? getGoalActivityDurationMs({\n agentId: this.agentId,\n threadId: this.threadId,\n objectiveId: this.record.id,\n activeDurationMs: this.record.activeDurationMs,\n })\n : normalizeActiveDurationMs(this.record.activeDurationMs),\n };\n }\n\n isActive(): boolean {\n return this.record?.status === 'active';\n }\n\n persistOnNextThreadCreate(): void {\n this.persistGoalOnNextThreadCreate = true;\n }\n\n consumePersistOnNextThreadCreate(): boolean {\n if (!this.persistGoalOnNextThreadCreate) return false;\n this.persistGoalOnNextThreadCreate = false;\n return true;\n }\n\n // ---------------------------------------------------------------------------\n // Objective lifecycle (ThreadState-backed via the agent)\n // ---------------------------------------------------------------------------\n\n /**\n * Set a new objective. Persists to ThreadState via `agent.setObjective` and\n * updates the in-memory view. Only the provided settings are persisted into\n * the record; unset ones fall back to the agent's `goal` config at read time.\n */\n async setGoal(\n state: GoalManagerState,\n objective: string,\n judgeModelId: string,\n maxTurns: number = DEFAULT_MAX_TURNS,\n ): Promise<GoalState | null> {\n const threadId = state.session.thread.getId();\n const agent = this.getAgent(state);\n const now = Date.now();\n const id = randomUUID();\n this.threadId = threadId ?? undefined;\n this.agentId = agent?.id;\n\n if (agent && threadId) {\n const persisted = await agent.setObjective(objective, {\n id,\n threadId,\n resourceId: state.session.identity.getResourceId(),\n ...(judgeModelId ? { judgeModelId } : {}),\n maxRuns: maxTurns,\n });\n this.record = persisted\n ? { ...persisted, id: persisted.id ?? id }\n : this.localRecord(objective, judgeModelId, maxTurns, now, id);\n } else {\n this.record = this.localRecord(objective, judgeModelId, maxTurns, now, id);\n }\n\n return this.getGoal();\n }\n\n /**\n * Update the judge model / max-runs defaults. Persists into the active record\n * (so the override is remembered in thread state) when a goal is set.\n */\n async updateJudgeDefaults(\n state: GoalManagerState,\n judgeModelId: string,\n maxTurns: number,\n ): Promise<GoalState | null> {\n if (!this.record) return null;\n const threadId = state.session.thread.getId();\n const agent = this.getAgent(state);\n if (agent && threadId) {\n const updated = await agent.updateObjectiveOptions({\n threadId,\n ...(judgeModelId ? { judgeModelId } : {}),\n maxRuns: maxTurns,\n });\n if (updated) this.record = { ...updated, id: this.record.id };\n } else {\n this.record = {\n ...this.record,\n ...(judgeModelId ? { judgeModelId } : {}),\n maxRuns: maxTurns,\n updatedAt: Date.now(),\n };\n }\n return this.getGoal();\n }\n\n pause(reason?: string): GoalState | null {\n if (this.record && this.record.status === 'active') {\n this.record = { ...this.record, status: 'paused', pausedReason: reason, updatedAt: Date.now() };\n }\n return this.getGoal();\n }\n\n resume(): GoalState | null {\n if (this.record && this.record.status === 'paused') {\n this.record = { ...this.record, status: 'active', pausedReason: undefined, updatedAt: Date.now() };\n }\n return this.getGoal();\n }\n\n markDone(): void {\n if (this.record) {\n this.record = { ...this.record, status: 'done', updatedAt: Date.now() };\n }\n }\n\n clear(): void {\n this.record = null;\n this.threadId = undefined;\n this.agentId = undefined;\n this.persistGoalOnNextThreadCreate = false;\n }\n\n /**\n * Sync the latest objective record from ThreadState into the in-memory view.\n * Called from the `goal` stream-chunk handler after each evaluation.\n */\n applyEvaluation(update: { runsUsed: number; status: GoalStatus }): GoalState | null {\n if (!this.record) return null;\n this.record = { ...this.record, runsUsed: update.runsUsed, status: update.status, updatedAt: Date.now() };\n return this.getGoal();\n }\n\n // ---------------------------------------------------------------------------\n // Persistence\n // ---------------------------------------------------------------------------\n\n /**\n * Persist the active objective to ThreadState via the agent. The objective\n * record is the source of truth; the legacy thread-metadata key is cleared so\n * stale state from older sessions does not resurface.\n */\n async saveToThread(state: GoalManagerState): Promise<void> {\n const threadId = state.session.thread.getId();\n const agent = this.getAgent(state);\n try {\n if (agent && threadId) {\n if (this.record) {\n // Push the current status/options into the existing record. If no\n // record is persisted yet (e.g. first save), create one.\n const updated = await agent.updateObjectiveOptions({\n threadId,\n status: this.record.status,\n ...(this.record.pausedReason ? { pausedReason: this.record.pausedReason } : {}),\n ...(this.record.judgeModelId ? { judgeModelId: this.record.judgeModelId } : {}),\n ...(this.record.maxRuns !== undefined ? { maxRuns: this.record.maxRuns } : {}),\n });\n if (!updated) {\n // No persisted record yet: create one. `setObjective` always writes\n // `status: 'active'`, so re-apply the in-memory status afterwards if\n // the local goal was already paused/done — otherwise the resumed\n // thread state would no longer match the in-memory state.\n const desiredStatus = this.record.status;\n await agent.setObjective(this.record.objective, {\n id: this.record.id,\n threadId,\n resourceId: state.session.identity.getResourceId(),\n activeDurationMs: normalizeActiveDurationMs(this.record.activeDurationMs),\n ...(this.record.judgeModelId ? { judgeModelId: this.record.judgeModelId } : {}),\n ...(this.record.maxRuns !== undefined ? { maxRuns: this.record.maxRuns } : {}),\n });\n if (desiredStatus !== 'active') {\n await agent.updateObjectiveOptions({\n threadId,\n status: desiredStatus,\n ...(this.record.pausedReason ? { pausedReason: this.record.pausedReason } : {}),\n });\n }\n }\n } else {\n await agent.clearObjective({ threadId });\n }\n }\n // Clear any legacy thread-metadata goal so it can't shadow the record.\n await state.session.thread.setSetting({ key: THREAD_GOAL_KEY, value: undefined });\n } catch {\n // Persistence is not critical.\n }\n }\n\n /**\n * Load the objective from ThreadState (called on thread switch). Falls back to\n * the legacy thread-metadata goal for threads created before this migration.\n */\n async loadFromThread(state: GoalManagerState, isCurrent: () => boolean = () => true): Promise<void> {\n const threadId = state.session.thread.getId();\n const agent = this.getAgent(state);\n let nextRecord: typeof this.record = null;\n if (agent && threadId) {\n try {\n const record = await agent.getObjective({ threadId });\n if (record) {\n nextRecord = {\n ...record,\n id: record.id ?? randomUUID(),\n activeDurationMs: normalizeActiveDurationMs(record.activeDurationMs),\n };\n }\n } catch {\n // fall through to legacy metadata\n }\n }\n if (!isCurrent()) return;\n this.persistGoalOnNextThreadCreate = false;\n this.threadId = threadId ?? undefined;\n this.agentId = agent?.id;\n this.record = nextRecord;\n }\n\n /**\n * Legacy entry point retained for thread-switch call sites that only have the\n * thread metadata available. Hydrates from a previously-persisted GoalState.\n */\n loadFromThreadMetadata(metadata: Record<string, unknown> | undefined): void {\n const saved = metadata?.[THREAD_GOAL_KEY] as Partial<GoalState> | undefined;\n this.persistGoalOnNextThreadCreate = false;\n this.threadId = undefined;\n this.agentId = undefined;\n if (saved && saved.objective && saved.status) {\n this.record = {\n objective: saved.objective,\n status: saved.status,\n runsUsed: saved.turnsUsed ?? 0,\n activeDurationMs: normalizeActiveDurationMs(saved.activeDurationMs),\n maxRuns: saved.maxTurns ?? DEFAULT_MAX_TURNS,\n judgeModelId: saved.judgeModelId ?? '',\n startedAt: saved.startedAt ? Date.parse(saved.startedAt) || Date.now() : Date.now(),\n updatedAt: Date.now(),\n id: saved.id ?? randomUUID(),\n };\n } else {\n this.record = null;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private getAgent(state: GoalManagerState): Agent | undefined {\n try {\n return state.controller.getCurrentAgent(state.session);\n } catch {\n return undefined;\n }\n }\n\n /** Resolve effective judge model + max runs (record value → settings default). */\n private effectiveSettings(record: GoalObjectiveRecord): { judgeModelId: string; maxTurns: number } {\n const settings = loadSettings();\n return {\n judgeModelId: record.judgeModelId ?? settings.models.goalJudgeModel ?? '',\n maxTurns: record.maxRuns ?? settings.models.goalMaxTurns ?? DEFAULT_MAX_TURNS,\n };\n }\n\n private localRecord(\n objective: string,\n judgeModelId: string,\n maxTurns: number,\n now: number,\n id: string,\n ): GoalObjectiveRecord & { id: string } {\n return {\n objective,\n status: 'active',\n runsUsed: 0,\n activeDurationMs: 0,\n maxRuns: maxTurns,\n ...(judgeModelId ? { judgeModelId } : {}),\n startedAt: now,\n updatedAt: now,\n id,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoDA,MAAa,oBAAoB;AACjC,MAAM,kBAAkB;AAExB,SAAS,0BAA0B,OAAmC;CACpE,OAAO,UAAU,KAAA,KAAa,OAAO,SAAS,KAAK,KAAK,SAAS,IAAI,QAAQ;AAC/E;AAMA,IAAa,cAAb,MAAyB;;CAEvB,SAAgE;CAChE;CACA;CACA,gCAAwC;CAMxC,UAA4B;EAC1B,IAAI,CAAC,KAAK,QAAQ,OAAO;EACzB,MAAM,EAAE,cAAc,aAAa,KAAK,kBAAkB,KAAK,MAAM;EACrE,OAAO;GACL,IAAI,KAAK,OAAO;GAChB,WAAW,KAAK,OAAO;GACvB,QAAQ,KAAK,OAAO;GACpB,WAAW,KAAK,OAAO;GACvB;GACA;GACA,WAAW,IAAI,KAAK,KAAK,OAAO,SAAS,CAAC,CAAC,YAAY;GACvD,kB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],"sourcesContent":["/**\n * GoalManager — persistent cross-turn goals, backed by the Agent's native goal\n * mechanism.\n *\n * The objective lives in the durable `threadState` `'goal'` slot (via\n * `agent.setObjective`/`getObjective`/`clearObjective`/`updateObjectiveOptions`)\n * and is judged in-loop by the core goal step. This manager is a thin adapter:\n * it keeps a synchronous in-memory view of the current objective for the TUI\n * (status line, modal, keyboard shortcuts) and delegates persistence to the\n * agent. There is no standalone judge agent and no between-turn re-invocation —\n * the core goal step drives continuation and surfaces progress via `goal` stream\n * chunks.\n */\nimport { randomUUID } from 'node:crypto';\nimport { getGoalActivityDurationMs } from '@mastra/core/agent';\nimport type { Agent } from '@mastra/core/agent';\nimport type { AgentController, Session } from '@mastra/core/agent-controller';\nimport type { GoalObjectiveRecord } from '@mastra/core/storage';\nimport { loadSettings } from './onboarding/settings.js';\n\nexport interface GoalManagerState<TState extends Record<string, unknown> = Record<string, unknown>> {\n controller: AgentController<TState>;\n session: Session<TState>;\n}\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport type GoalStatus = 'active' | 'paused' | 'done';\n\n/**\n * TUI-facing view of a goal. Derived from the durable {@link GoalObjectiveRecord}\n * plus the effective judge/max-runs settings, with display-only timer fields and\n * a stable `id` used to match plan-started goals.\n */\nexport interface GoalState {\n id: string;\n objective: string;\n status: GoalStatus;\n turnsUsed: number;\n maxTurns: number;\n judgeModelId: string;\n startedAt: string;\n activeStartedAt?: string;\n activeDurationMs?: number;\n /** Why the goal paused (judge failure, budget exhaustion, ...). Only set while paused. */\n pausedReason?: string;\n}\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nexport const DEFAULT_MAX_TURNS = 50;\nconst THREAD_GOAL_KEY = 'goal';\n\nfunction normalizeActiveDurationMs(value: number | undefined): number {\n return value !== undefined && Number.isFinite(value) && value >= 0 ? value : 0;\n}\n\n// =============================================================================\n// GoalManager\n// =============================================================================\n\nexport class GoalManager {\n /** Synchronous in-memory view of the active objective record (source of truth is ThreadState). */\n private record: (GoalObjectiveRecord & { id: string }) | null = null;\n private threadId: string | undefined;\n private agentId: string | undefined;\n private persistGoalOnNextThreadCreate = false;\n /**\n * Set by {@link clear} to the thread the goal was cleared on: the next save\n * with an empty mirror on that same thread deletes the goal. A goal hydrated\n * from legacy metadata has no known thread, so its clear applies to whichever\n * thread the next save runs on (the pre-existing behaviour).\n */\n private pendingDelete: { threadId: string | undefined; goalId?: string } | null = null;\n\n // ---------------------------------------------------------------------------\n // Synchronous TUI surface\n // ---------------------------------------------------------------------------\n\n getGoal(): GoalState | null {\n if (!this.record) return null;\n const { judgeModelId, maxTurns } = this.effectiveSettings(this.record);\n return {\n id: this.record.id,\n objective: this.record.objective,\n status: this.record.status,\n turnsUsed: this.record.runsUsed,\n maxTurns,\n judgeModelId,\n startedAt: new Date(this.record.startedAt).toISOString(),\n ...(this.record.pausedReason ? { pausedReason: this.record.pausedReason } : {}),\n activeDurationMs:\n this.agentId && this.threadId\n ? getGoalActivityDurationMs({\n agentId: this.agentId,\n threadId: this.threadId,\n objectiveId: this.record.id,\n activeDurationMs: this.record.activeDurationMs,\n })\n : normalizeActiveDurationMs(this.record.activeDurationMs),\n };\n }\n\n isActive(): boolean {\n return this.record?.status === 'active';\n }\n\n persistOnNextThreadCreate(): void {\n this.persistGoalOnNextThreadCreate = true;\n }\n\n consumePersistOnNextThreadCreate(): boolean {\n if (!this.persistGoalOnNextThreadCreate) return false;\n this.persistGoalOnNextThreadCreate = false;\n return true;\n }\n\n // ---------------------------------------------------------------------------\n // Objective lifecycle (ThreadState-backed via the agent)\n // ---------------------------------------------------------------------------\n\n /**\n * Set a new objective. Persists to ThreadState via `agent.setObjective` and\n * updates the in-memory view. Only the provided settings are persisted into\n * the record; unset ones fall back to the agent's `goal` config at read time.\n */\n async setGoal(\n state: GoalManagerState,\n objective: string,\n judgeModelId: string,\n maxTurns: number = DEFAULT_MAX_TURNS,\n ): Promise<GoalState | null> {\n const threadId = state.session.thread.getId();\n const agent = this.getAgent(state);\n const now = Date.now();\n const id = randomUUID();\n this.pendingDelete = null;\n this.threadId = threadId ?? undefined;\n this.agentId = agent?.id;\n\n if (agent && threadId) {\n const persisted = await agent.setObjective(objective, {\n id,\n threadId,\n resourceId: state.session.identity.getResourceId(),\n ...(judgeModelId ? { judgeModelId } : {}),\n maxRuns: maxTurns,\n });\n this.record = persisted\n ? { ...persisted, id: persisted.id ?? id }\n : this.localRecord(objective, judgeModelId, maxTurns, now, id);\n } else {\n this.record = this.localRecord(objective, judgeModelId, maxTurns, now, id);\n }\n\n return this.getGoal();\n }\n\n /**\n * Update the judge model / max-runs defaults. Persists into the active record\n * (so the override is remembered in thread state) when a goal is set.\n */\n async updateJudgeDefaults(\n state: GoalManagerState,\n judgeModelId: string,\n maxTurns: number,\n ): Promise<GoalState | null> {\n if (!this.record) return null;\n const threadId = state.session.thread.getId();\n const agent = this.getAgent(state);\n if (agent && threadId) {\n const updated = await agent.updateObjectiveOptions({\n threadId,\n ...(judgeModelId ? { judgeModelId } : {}),\n maxRuns: maxTurns,\n });\n if (updated) this.record = { ...updated, id: this.record.id };\n } else {\n this.record = {\n ...this.record,\n ...(judgeModelId ? { judgeModelId } : {}),\n maxRuns: maxTurns,\n updatedAt: Date.now(),\n };\n }\n return this.getGoal();\n }\n\n pause(reason?: string): GoalState | null {\n if (this.record && this.record.status === 'active') {\n this.record = { ...this.record, status: 'paused', pausedReason: reason, updatedAt: Date.now() };\n }\n return this.getGoal();\n }\n\n resume(): GoalState | null {\n if (this.record && this.record.status === 'paused') {\n this.record = { ...this.record, status: 'active', pausedReason: undefined, updatedAt: Date.now() };\n }\n return this.getGoal();\n }\n\n markDone(): void {\n if (this.record) {\n this.record = { ...this.record, status: 'done', pausedReason: undefined, updatedAt: Date.now() };\n }\n }\n\n clear(): void {\n this.pendingDelete = { threadId: this.threadId, goalId: this.record?.id };\n this.record = null;\n this.threadId = undefined;\n this.agentId = undefined;\n this.persistGoalOnNextThreadCreate = false;\n }\n\n /**\n * Sync the latest objective record from ThreadState into the in-memory view.\n * Called from the `goal` stream-chunk handler after each evaluation.\n */\n applyEvaluation(update: { runsUsed: number; status: GoalStatus; pausedReason?: string }): GoalState | null {\n if (!this.record) return null;\n const pausedReason =\n update.status === 'paused'\n ? (update.pausedReason ?? (this.record.status === 'paused' ? this.record.pausedReason : undefined))\n : undefined;\n this.record = {\n ...this.record,\n runsUsed: update.runsUsed,\n status: update.status,\n // The cause lasts for one pause; leaving paused retires it.\n pausedReason,\n updatedAt: Date.now(),\n };\n return this.getGoal();\n }\n\n // ---------------------------------------------------------------------------\n // Persistence\n // ---------------------------------------------------------------------------\n\n /**\n * Persist the active objective to ThreadState via the agent. The objective\n * record is the source of truth; the legacy thread-metadata key is cleared on\n * a save that actually wrote, so stale state from older sessions cannot\n * shadow the record — and a save that wrote nothing leaves it alone.\n *\n * An empty in-memory mirror means \"I have nothing *loaded*\", which is not the\n * same statement as \"there is nothing\": the mirror is also emptied by storage\n * failures and thread switches. So a save with an empty mirror deletes the\n * goal (durable record and legacy key) only right after an explicit\n * {@link clear} on the same thread (or any thread, for a legacy-hydrated goal\n * whose thread is unknown), and is a complete no-op otherwise.\n */\n async saveToThread(state: GoalManagerState): Promise<void> {\n const threadId = state.session.thread.getId();\n const agent = this.getAgent(state);\n if (!this.record && this.pendingDelete) {\n const clearedThreadId = this.pendingDelete.threadId;\n if (clearedThreadId === undefined || clearedThreadId === threadId) {\n await this.deleteFromThread(state);\n }\n return;\n }\n try {\n if (agent && threadId) {\n if (this.record) {\n // Push the current status/options into the existing record. If no\n // record is persisted yet (e.g. first save), create one.\n const updated = await agent.updateObjectiveOptions({\n threadId,\n status: this.record.status,\n ...(this.record.pausedReason ? { pausedReason: this.record.pausedReason } : {}),\n ...(this.record.judgeModelId ? { judgeModelId: this.record.judgeModelId } : {}),\n ...(this.record.maxRuns !== undefined ? { maxRuns: this.record.maxRuns } : {}),\n });\n if (!updated) {\n // No persisted record yet: create one. `setObjective` always writes\n // `status: 'active'`, so re-apply the in-memory status afterwards if\n // the local goal was already paused/done — otherwise the resumed\n // thread state would no longer match the in-memory state.\n const desiredStatus = this.record.status;\n const created = await agent.setObjective(this.record.objective, {\n id: this.record.id,\n threadId,\n resourceId: state.session.identity.getResourceId(),\n activeDurationMs: normalizeActiveDurationMs(this.record.activeDurationMs),\n ...(this.record.judgeModelId ? { judgeModelId: this.record.judgeModelId } : {}),\n ...(this.record.maxRuns !== undefined ? { maxRuns: this.record.maxRuns } : {}),\n });\n // Nothing durable was written (no goal store, or no thread), so\n // there is no record for a legacy key to shadow — and wiping it\n // would take a pre-migration thread's only copy with it.\n if (!created) return;\n if (desiredStatus !== 'active') {\n await agent.updateObjectiveOptions({\n threadId,\n status: desiredStatus,\n ...(this.record.pausedReason ? { pausedReason: this.record.pausedReason } : {}),\n });\n }\n }\n // Clear any legacy thread-metadata goal so it can't shadow the\n // record we just wrote. Only on the path that actually wrote: on the\n // no-op path a pre-migration thread's only goal may live in that key.\n await state.session.thread.setSetting({ key: THREAD_GOAL_KEY, value: undefined });\n }\n }\n } catch {\n // Persistence is not critical.\n }\n }\n\n /**\n * Remove the objective from the thread, whatever the in-memory mirror holds.\n *\n * The durable record needs an agent and a thread; the legacy thread-metadata\n * key does not, so it is wiped either way — unlike {@link saveToThread}, which\n * writes nothing with an empty mirror unless {@link clear} ran. That asymmetry is deliberate: a\n * pre-migration goal must not resurface from the legacy key after a clear.\n * Like the save, this is best-effort: a failed durable delete also skips the\n * legacy wipe. A pending {@link clear} stays pending until both writes\n * succeed, so a later save retries it; loading the thread retries it once\n * and then drops it. Resolves to whether the delete landed.\n */\n async deleteFromThread(state: GoalManagerState): Promise<boolean> {\n const threadId = state.session.thread.getId();\n const agent = this.getAgent(state);\n try {\n if (agent && threadId) {\n await agent.clearObjective({ threadId });\n }\n await state.session.thread.setSetting({ key: THREAD_GOAL_KEY, value: undefined });\n this.pendingDelete = null;\n return true;\n } catch {\n // Persistence is not critical, but keep the retry scoped to the thread\n // this delete targeted so an empty save elsewhere cannot delete a goal.\n // An unknown thread would widen the retry to every thread, so keep the old scope then.\n if (threadId) this.pendingDelete = { threadId, goalId: this.pendingDelete?.goalId };\n return false;\n }\n }\n\n /**\n * Load the objective from ThreadState (called on thread switch). Falls back to\n * the legacy thread-metadata goal for threads created before this migration.\n *\n * A clear whose delete failed is retried here when it targeted this thread and\n * the stored goal is the one that was cleared; otherwise the stored goal loads,\n * so the mirror never hides a goal core is still judging. Resolves to whether\n * that retried delete landed.\n */\n async loadFromThread(state: GoalManagerState, isCurrent: () => boolean = () => true): Promise<boolean> {\n const pending = this.pendingDelete;\n const threadId = state.session.thread.getId();\n const agent = this.getAgent(state);\n let nextRecord: typeof this.record = null;\n let storedId: string | undefined;\n if (agent && threadId) {\n try {\n const record = await agent.getObjective({ threadId });\n if (record) {\n storedId = record.id;\n nextRecord = {\n ...record,\n id: record.id ?? randomUUID(),\n activeDurationMs: normalizeActiveDurationMs(record.activeDurationMs),\n };\n }\n } catch {\n // fall through to legacy metadata\n }\n }\n if (!isCurrent()) return false;\n // A goal set or cleared during the read replaced this intent; keep the newer state.\n if (pending && this.pendingDelete !== pending) return false;\n let retriedDelete = false;\n if (pending?.goalId && pending.threadId === threadId && storedId === pending.goalId) {\n retriedDelete = await this.deleteFromThread(state);\n if (retriedDelete) nextRecord = null;\n if (!isCurrent()) return false;\n }\n this.persistGoalOnNextThreadCreate = false;\n this.pendingDelete = null;\n this.threadId = threadId ?? undefined;\n this.agentId = agent?.id;\n this.record = nextRecord;\n return retriedDelete;\n }\n\n /**\n * Legacy entry point retained for thread-switch call sites that only have the\n * thread metadata available. Hydrates from a previously-persisted GoalState.\n */\n loadFromThreadMetadata(metadata: Record<string, unknown> | undefined): void {\n const saved = metadata?.[THREAD_GOAL_KEY] as Partial<GoalState> | undefined;\n this.persistGoalOnNextThreadCreate = false;\n this.pendingDelete = null;\n this.threadId = undefined;\n this.agentId = undefined;\n if (saved && saved.objective && saved.status) {\n this.record = {\n objective: saved.objective,\n status: saved.status,\n runsUsed: saved.turnsUsed ?? 0,\n activeDurationMs: normalizeActiveDurationMs(saved.activeDurationMs),\n maxRuns: saved.maxTurns ?? DEFAULT_MAX_TURNS,\n judgeModelId: saved.judgeModelId ?? '',\n ...(saved.pausedReason ? { pausedReason: saved.pausedReason } : {}),\n startedAt: saved.startedAt ? Date.parse(saved.startedAt) || Date.now() : Date.now(),\n updatedAt: Date.now(),\n id: saved.id ?? randomUUID(),\n };\n } else {\n this.record = null;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private getAgent(state: GoalManagerState): Agent | undefined {\n try {\n return state.controller.getCurrentAgent(state.session);\n } catch {\n return undefined;\n }\n }\n\n /** Resolve effective judge model + max runs (record value → settings default). */\n private effectiveSettings(record: GoalObjectiveRecord): { judgeModelId: string; maxTurns: number } {\n const settings = loadSettings();\n return {\n judgeModelId: record.judgeModelId ?? settings.models.goalJudgeModel ?? '',\n maxTurns: record.maxRuns ?? settings.models.goalMaxTurns ?? DEFAULT_MAX_TURNS,\n };\n }\n\n private localRecord(\n objective: string,\n judgeModelId: string,\n maxTurns: number,\n now: number,\n id: string,\n ): GoalObjectiveRecord & { id: string } {\n return {\n objective,\n status: 'active',\n runsUsed: 0,\n activeDurationMs: 0,\n maxRuns: maxTurns,\n ...(judgeModelId ? { judgeModelId } : {}),\n startedAt: now,\n updatedAt: now,\n id,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsDA,MAAa,oBAAoB;AACjC,MAAM,kBAAkB;AAExB,SAAS,0BAA0B,OAAmC;CACpE,OAAO,UAAU,KAAA,KAAa,OAAO,SAAS,KAAK,KAAK,SAAS,IAAI,QAAQ;AAC/E;AAMA,IAAa,cAAb,MAAyB;;CAEvB,SAAgE;CAChE;CACA;CACA,gCAAwC;;;;;;;CAOxC,gBAAkF;CAMlF,UAA4B;EAC1B,IAAI,CAAC,KAAK,QAAQ,OAAO;EACzB,MAAM,EAAE,cAAc,aAAa,KAAK,kBAAkB,KAAK,MAAM;EACr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F;CAEA,YACE,WACA,cACA,UACA,KACA,IACsC;EACtC,OAAO;GACL;GACA,QAAQ;GACR,UAAU;GACV,kBAAkB;GAClB,SAAS;GACT,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;GACvC,WAAW;GACX,WAAW;GACX;EACF;CACF;AACF"}
package/dist/index.d.ts CHANGED
@@ -18,6 +18,7 @@ import { HookManager } from './hooks/index.js';
18
18
  import type { McpServerConfig } from './mcp/index.js';
19
19
  import { loadSettings } from './onboarding/settings.js';
20
20
  import { PluginManager } from './plugins/manager.js';
21
+ import { ThreadScheduler } from './schedules/index.js';
21
22
  import type { MastraCodeState } from './schema.js';
22
23
  import type { StorageConfig } from './utils/project.js';
23
24
  import type { StorageMaintenance } from './utils/storage-maintenance.js';
@@ -125,6 +126,13 @@ export interface MastraCodeConfig {
125
126
  * uses the configured PubSub when enabled.
126
127
  */
127
128
  crossAgentSignals?: boolean;
129
+ /**
130
+ * Enable the experimental agent schedule tools (`schedule_create`,
131
+ * `schedule_list`, `schedule_update`, `schedule_run`), which manage the same
132
+ * process-local schedules as `/schedules`. Defaults to the
133
+ * `signals.experimentalScheduleTools` global setting (off).
134
+ */
135
+ scheduleTools?: boolean;
128
136
  /**
129
137
  * Prepare the request context of a wake: a run on a thread with no inbound
130
138
  * request, such as a notification or cross-agent signal delivered to an idle
@@ -201,6 +209,8 @@ export declare function createMastraCodeAgentController(config?: MastraCodeConfi
201
209
  * keeps firing for a controller that is gone.
202
210
  */
203
211
  stopPluginSignalProviders: () => void;
212
+ /** Process-local `/schedules` scheduler. Call `stop()` on shutdown. */
213
+ threadScheduler: ThreadScheduler;
204
214
  /**
205
215
  * Hands Mastra to the statically configured input processors.
206
216
  *
@@ -289,6 +299,8 @@ export declare function bootLocalAgentController(config?: MastraCodeConfig): Pro
289
299
  * keeps firing for a controller that is gone.
290
300
  */
291
301
  stopPluginSignalProviders: () => void;
302
+ /** Process-local `/schedules` scheduler. Call `stop()` on shutdown. */
303
+ threadScheduler: ThreadScheduler;
292
304
  /**
293
305
  * Hands Mastra to the statically configured input processors.
294
306
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,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;AAW7C,OAAO,KAAK,EAAE,cAAc,EAAa,MAAM,yBAAyB,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAmB,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE7E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGxD,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvD,OAAO,EACL,aAAa,EAId,MAAM,uBAAuB,CAAC;AAK/B,OAAO,KAAK,EAAE,qCAAqC,EAAE,MAAM,wCAAwC,CAAC;AAMpG,OAAO,EAA+D,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAc9G,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AASpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAG/C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAItD,OAAO,EACL,YAAY,EAOb,MAAM,0BAA0B,C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