@mastra/code-sdk 1.2.1-alpha.2 → 1.2.1-alpha.4

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 CHANGED
@@ -1,5 +1,30 @@
1
1
  # @mastra/code-sdk
2
2
 
3
+ ## 1.2.1-alpha.4
4
+
5
+ ### Patch Changes
6
+
7
+ - Send opaque acting-user subjects with Platform sandbox requests, including Factory creation and reattachment flows. ([#20754](https://github.com/mastra-ai/mastra/pull/20754))
8
+
9
+ ```typescript
10
+ import { PlatformSandbox } from '@mastra/platform-workspace';
11
+
12
+ const sandbox = new PlatformSandbox({
13
+ environmentId: 'env_abc',
14
+ actingUserId: auth.user.id,
15
+ });
16
+ ```
17
+
18
+ - Updated dependencies [[`79dd7c2`](https://github.com/mastra-ai/mastra/commit/79dd7c261ee6be1fafedd4651959394db21d2cba), [`b9a28ec`](https://github.com/mastra-ai/mastra/commit/b9a28ecf7acdc0cb7a543d5b660f9fbee301df9a), [`be31796`](https://github.com/mastra-ai/mastra/commit/be3179624ad5f77cff5fa342cd08046bf7605283)]:
19
+ - @mastra/core@1.59.0-alpha.4
20
+
21
+ ## 1.2.1-alpha.3
22
+
23
+ ### Patch Changes
24
+
25
+ - Updated dependencies [[`d118873`](https://github.com/mastra-ai/mastra/commit/d118873cfd5074b1f814a1c169a97ca7a3a29174), [`161258b`](https://github.com/mastra-ai/mastra/commit/161258b3473a6d0fce00a43cab59d119a49a232f), [`8ea8038`](https://github.com/mastra-ai/mastra/commit/8ea80386fde53d26e2c0b2060c53bc9bd9be10f3)]:
26
+ - @mastra/core@1.59.0-alpha.3
27
+
3
28
  ## 1.2.1-alpha.2
4
29
 
5
30
  ### Patch Changes
@@ -11,9 +11,12 @@ import type { SandboxExec } from './sandbox-filesystem.js';
11
11
  export interface ReattachedSandbox extends SandboxExec {
12
12
  start(): Promise<void>;
13
13
  }
14
- export type SandboxReattachFn = (providerSandboxId: string) => Promise<ReattachedSandbox>;
14
+ export interface SandboxReattachOptions {
15
+ actingUserId?: string;
16
+ }
17
+ export type SandboxReattachFn = (providerSandboxId: string, options?: SandboxReattachOptions) => Promise<ReattachedSandbox>;
15
18
  /** Register the sandbox reattach implementation (called by the web surface at startup). */
16
19
  export declare function registerSandboxReattach(fn: SandboxReattachFn): void;
17
20
  /** Reattach to an already-provisioned sandbox by provider id. */
18
- export declare function reattachProjectSandbox(providerSandboxId: string): Promise<ReattachedSandbox>;
21
+ export declare function reattachProjectSandbox(providerSandboxId: string, options?: SandboxReattachOptions): Promise<ReattachedSandbox>;
19
22
  //# sourceMappingURL=sandbox-reattach.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox-reattach.d.ts","sourceRoot":"","sources":["../../src/agents/sandbox-reattach.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAE3D,uEAAuE;AACvE,MAAM,WAAW,iBAAkB,SAAQ,WAAW;IACpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,MAAM,MAAM,iBAAiB,GAAG,CAAC,iBAAiB,EAAE,MAAM,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAI1F,2FAA2F;AAC3F,wBAAgB,uBAAuB,CAAC,EAAE,EAAE,iBAAiB,GAAG,IAAI,CAEnE;AAED,iEAAiE;AACjE,wBAAsB,sBAAsB,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAOlG"}
1
+ {"version":3,"file":"sandbox-reattach.d.ts","sourceRoot":"","sources":["../../src/agents/sandbox-reattach.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAE3D,uEAAuE;AACvE,MAAM,WAAW,iBAAkB,SAAQ,WAAW;IACpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,MAAM,WAAW,sBAAsB;IACrC,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,MAAM,iBAAiB,GAAG,CAC9B,iBAAiB,EAAE,MAAM,EACzB,OAAO,CAAC,EAAE,sBAAsB,KAC7B,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAIhC,2FAA2F;AAC3F,wBAAgB,uBAAuB,CAAC,EAAE,EAAE,iBAAiB,GAAG,IAAI,CAEnE;AAED,iEAAiE;AACjE,wBAAsB,sBAAsB,CAC1C,iBAAiB,EAAE,MAAM,EACzB,OAAO,CAAC,EAAE,sBAAsB,GAC/B,OAAO,CAAC,iBAAiB,CAAC,CAO5B"}
@@ -5,9 +5,9 @@ function registerSandboxReattach(fn) {
5
5
  reattachFn = fn;
6
6
  }
7
7
  /** Reattach to an already-provisioned sandbox by provider id. */
8
- async function reattachProjectSandbox(providerSandboxId) {
8
+ async function reattachProjectSandbox(providerSandboxId, options) {
9
9
  if (!reattachFn) throw new Error("No sandbox reattach implementation registered. Sandbox-backed workspaces are only available when the web surface has called registerSandboxReattach().");
10
- return reattachFn(providerSandboxId);
10
+ return reattachFn(providerSandboxId, options);
11
11
  }
12
12
  //#endregion
13
13
  export { reattachProjectSandbox, registerSandboxReattach };
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox-reattach.js","names":[],"sources":["../../src/agents/sandbox-reattach.ts"],"sourcesContent":["/**\n * Seam between the core workspace wiring and the web surface's sandbox\n * provisioning. GitHub/cloud-sandbox projects are only reachable through the\n * web tenant server, which owns the sandbox provider factory and its DB-backed\n * bookkeeping. The web package registers its `reattachProjectSandbox`\n * implementation here at startup so `getDynamicWorkspace` can reattach\n * sandboxes without core depending on the web stack.\n */\nimport type { SandboxExec } from './sandbox-filesystem.js';\n\n/** Minimal sandbox surface the workspace seam needs after reattach. */\nexport interface ReattachedSandbox extends SandboxExec {\n start(): Promise<void>;\n}\n\nexport type SandboxReattachFn = (providerSandboxId: string) => Promise<ReattachedSandbox>;\n\nlet reattachFn: SandboxReattachFn | undefined;\n\n/** Register the sandbox reattach implementation (called by the web surface at startup). */\nexport function registerSandboxReattach(fn: SandboxReattachFn): void {\n reattachFn = fn;\n}\n\n/** Reattach to an already-provisioned sandbox by provider id. */\nexport async function reattachProjectSandbox(providerSandboxId: string): Promise<ReattachedSandbox> {\n if (!reattachFn) {\n throw new Error(\n 'No sandbox reattach implementation registered. Sandbox-backed workspaces are only available when the web surface has called registerSandboxReattach().',\n );\n }\n return reattachFn(providerSandboxId);\n}\n"],"mappings":";AAiBA,IAAI;;AAGJ,SAAgB,wBAAwB,IAA6B;CACnE,aAAa;AACf;;AAGA,eAAsB,uBAAuB,mBAAuD;CAClG,IAAI,CAAC,YACH,MAAM,IAAI,MACR,wJACF;CAEF,OAAO,WAAW,iBAAiB;AACrC"}
1
+ {"version":3,"file":"sandbox-reattach.js","names":[],"sources":["../../src/agents/sandbox-reattach.ts"],"sourcesContent":["/**\n * Seam between the core workspace wiring and the web surface's sandbox\n * provisioning. GitHub/cloud-sandbox projects are only reachable through the\n * web tenant server, which owns the sandbox provider factory and its DB-backed\n * bookkeeping. The web package registers its `reattachProjectSandbox`\n * implementation here at startup so `getDynamicWorkspace` can reattach\n * sandboxes without core depending on the web stack.\n */\nimport type { SandboxExec } from './sandbox-filesystem.js';\n\n/** Minimal sandbox surface the workspace seam needs after reattach. */\nexport interface ReattachedSandbox extends SandboxExec {\n start(): Promise<void>;\n}\n\nexport interface SandboxReattachOptions {\n actingUserId?: string;\n}\n\nexport type SandboxReattachFn = (\n providerSandboxId: string,\n options?: SandboxReattachOptions,\n) => Promise<ReattachedSandbox>;\n\nlet reattachFn: SandboxReattachFn | undefined;\n\n/** Register the sandbox reattach implementation (called by the web surface at startup). */\nexport function registerSandboxReattach(fn: SandboxReattachFn): void {\n reattachFn = fn;\n}\n\n/** Reattach to an already-provisioned sandbox by provider id. */\nexport async function reattachProjectSandbox(\n providerSandboxId: string,\n options?: SandboxReattachOptions,\n): Promise<ReattachedSandbox> {\n if (!reattachFn) {\n throw new Error(\n 'No sandbox reattach implementation registered. Sandbox-backed workspaces are only available when the web surface has called registerSandboxReattach().',\n );\n }\n return reattachFn(providerSandboxId, options);\n}\n"],"mappings":";AAwBA,IAAI;;AAGJ,SAAgB,wBAAwB,IAA6B;CACnE,aAAa;AACf;;AAGA,eAAsB,uBACpB,mBACA,SAC4B;CAC5B,IAAI,CAAC,YACH,MAAM,IAAI,MACR,wJACF;CAEF,OAAO,WAAW,mBAAmB,OAAO;AAC9C"}
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../../src/agents/workspace.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAwB,MAAM,wBAAwB,CAAC;AACxG,OAAO,KAAK,EAAa,WAAW,EAAE,MAAM,wBAAwB,CAAC;AA0GrE,wBAAgB,eAAe,CAC7B,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,SAAe,EACtB,gBAAgB,GAAE,MAAM,EAAO,GAC9B,MAAM,EAAE,CA0BV;AAED,MAAM,WAAW,uBAAuB;IACtC,yEAAyE;IACzE,EAAE,EAAE,MAAM,CAAC;IACX,uFAAuF;IACvF,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,6EAA6E;IAC7E,YAAY,EAAE,CAAC,QAAQ,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC;CACpF;AAyFD,wBAAsB,mBAAmB,CAAC,EACxC,cAAc,EACd,MAAM,EACN,cAAc,GACf,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAA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AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,cAAc,EACd,MAAM,GACP,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAclC"}
@@ -129,10 +129,11 @@ function detectPackageRunner(projectPath) {
129
129
  * is reattached by its persisted provider id and a `SandboxFilesystem` is layered
130
130
  * over the in-sandbox checkout so file tools and command tools share one VM.
131
131
  */
132
- async function getSandboxWorkspace({ projectRepositoryId, sandboxId, workdir, worktreePath, configDir, mastra, skillExtension }) {
132
+ async function getSandboxWorkspace({ projectRepositoryId, sandboxId, workdir, worktreePath, configDir, mastra, skillExtension, actingUserId }) {
133
133
  const boundWorkdir = worktreePath || workdir;
134
134
  const extensionId = skillExtension ? `-${skillExtension.id}` : "";
135
- const workspaceId = `${WORKSPACE_ID_PREFIX}-repository-${projectRepositoryId}-${sandboxId}-${boundWorkdir}${extensionId}`;
135
+ const actingUserScope = actingUserId ? `-user-${encodeURIComponent(actingUserId)}` : "";
136
+ const workspaceId = `${WORKSPACE_ID_PREFIX}-repository-${projectRepositoryId}-${sandboxId}-${boundWorkdir}${extensionId}${actingUserScope}`;
136
137
  try {
137
138
  const existing = mastra?.getWorkspaceById(workspaceId);
138
139
  if (existing) {
@@ -140,7 +141,7 @@ async function getSandboxWorkspace({ projectRepositoryId, sandboxId, workdir, wo
140
141
  return existing;
141
142
  }
142
143
  } catch {}
143
- const sandbox = await reattachProjectSandbox(sandboxId);
144
+ const sandbox = await reattachProjectSandbox(sandboxId, { actingUserId });
144
145
  const filesystem = new SandboxFilesystem({
145
146
  sandbox,
146
147
  workdir: boundWorkdir
@@ -162,6 +163,8 @@ async function getSandboxWorkspace({ projectRepositoryId, sandboxId, workdir, wo
162
163
  }
163
164
  async function getDynamicWorkspace({ requestContext, mastra, skillExtension }) {
164
165
  const state = requestContext.get("controller")?.getState();
166
+ const user = requestContext.get("user");
167
+ const actingUserId = typeof user?.workosId === "string" ? user.workosId : typeof user?.id === "string" ? user.id : void 0;
165
168
  if (state?.projectRepositoryId && state.sandboxId && state.sandboxWorkdir) return getSandboxWorkspace({
166
169
  projectRepositoryId: state.projectRepositoryId,
167
170
  sandboxId: state.sandboxId,
@@ -169,7 +172,8 @@ async function getDynamicWorkspace({ requestContext, mastra, skillExtension }) {
169
172
  worktreePath: state.worktreePath,
170
173
  configDir: state.configDir ?? ".mastracode",
171
174
  mastra,
172
- skillExtension
175
+ skillExtension,
176
+ actingUserId
173
177
  });
174
178
  const rawProjectPath = state?.projectPath;
175
179
  if (!rawProjectPath) throw new Error("Project path is required");
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\nimport { SandboxFilesystem } from './sandbox-filesystem.js';\nimport { reattachProjectSandbox } from './sandbox-reattach.js';\nimport { GOAL_JUDGE_READONLY_TOOLS, MASTRACODE_WORKSPACE_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\n/**\n * Build (or reuse) a sandbox-backed Workspace for a linked project repository. The sandbox\n * is reattached by its persisted provider id and a `SandboxFilesystem` is layered\n * over the in-sandbox checkout so file tools and command tools share one VM.\n */\nasync function getSandboxWorkspace({\n projectRepositoryId,\n sandboxId,\n workdir,\n worktreePath,\n configDir,\n mastra,\n skillExtension,\n}: {\n projectRepositoryId: string;\n sandboxId: string;\n workdir: string;\n worktreePath?: string;\n configDir: string;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n}): Promise<Workspace> {\n // Bind the workspace to the active worktree when one is set, so file tools and\n // command tools operate inside the feature branch's working tree rather than\n // the base checkout. Falls back to the repo root when no worktree is active.\n const boundWorkdir = worktreePath || workdir;\n\n // Include the sandbox id *and* worktree path in the reuse key: a new sandbox\n // (e.g. the previous one expired) or a different worktree must each get a\n // fresh Workspace/ProcessManager instead of reusing one bound to a stale\n // sandbox or the wrong working tree.\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-repository-${projectRepositoryId}-${sandboxId}-${boundWorkdir}${extensionId}`;\n\n // Reuse the existing remote workspace if already registered (preserves the\n // reattached sandbox + ProcessManager state across re-opens).\n try {\n const existing = mastra?.getWorkspaceById(workspaceId) as Workspace | undefined;\n if (existing) {\n existing.setToolsConfig(MASTRACODE_WORKSPACE_TOOLS);\n return existing;\n }\n } catch {\n // Not registered yet.\n }\n\n const sandbox = await reattachProjectSandbox(sandboxId);\n const filesystem = new SandboxFilesystem({ sandbox, workdir: boundWorkdir });\n const projectSkillPaths = [path.join(configDir, 'skills'), '.claude/skills', '.agents/skills'];\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Sandbox Workspace',\n filesystem,\n sandbox: sandbox as unknown as ConstructorParameters<typeof Workspace>[0]['sandbox'],\n tools: MASTRACODE_WORKSPACE_TOOLS,\n skills: skillPaths,\n skillSource: skillExtension?.createSource(filesystem, projectSkillPaths) ?? filesystem,\n });\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n\n // Repository-backed project: the repo lives inside a remote sandbox, not on\n // the server host. Reattach to the already-provisioned + materialized sandbox\n // and build a sandbox-backed Workspace. Optional embedders may add read-only\n // skill roots while project skills remain sandbox-backed.\n if (state?.projectRepositoryId && state.sandboxId && state.sandboxWorkdir) {\n return getSandboxWorkspace({\n projectRepositoryId: state.projectRepositoryId,\n sandboxId: state.sandboxId,\n workdir: state.sandboxWorkdir,\n worktreePath: state.worktreePath,\n configDir: state.configDir ?? DEFAULT_CONFIG_DIR,\n mastra,\n skillExtension,\n });\n }\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = MASTRACODE_WORKSPACE_TOOLS;\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n const userLsp = loadSettings().lsp ?? {};\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n const lspConfig: LSPConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];\n }\n return Object.keys(readonly).length > 0 ? readonly : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,kBAAqC;CAC5C,OAAO;EACL,GAAG,QAAQ;EAEX,aAAa;EACb,gBAAgB;EAChB,MAAM,QAAQ,IAAI,QAAQ;EAC1B,IAAI;EACJ,gBAAgB;EAChB,iBAAiB;CACnB;AACF;AAkBA,SAAS,kBAAkB,YAAsB,aAAgC;CAC/E,MAAM,QAAkB,CAAC;CACzB,MAAM,uBAAO,IAAI,IAAY;CAC7B,IAAI;CAEJ,IAAI,aACF,IAAI;EACF,kBAAkB,GAAG,aAAa,WAAW;CAC/C,QAAQ;EACN,OAAO,CAAC;CACV;CAGF,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,kBAAkB,GAAG,WAAW,SAAS;EAC/C,IAAI,mBAAmB,iBACrB,IAAI;GAEF,IAAI,CAAC,iBADiB,GAAG,aAAa,SACJ,GAAG,eAAe,GAAG;EACzD,QAAQ;GACN;EACF;EAGF,MAAM,WAAW,KAAK,QAAQ,SAAS;EACvC,IAAI,CAAC,KAAK,IAAI,QAAQ,GAAG;GACvB,KAAK,IAAI,QAAQ;GACjB,MAAM,KAAK,SAAS;EACtB;EAEA,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,SAAS,eAAe,cAAc;EACtC,OAAO;CACT;CAEA,MAAM,UAAU,aAAa,CAAC,CAAC,OAAO,CAAC;CACvC,MAAM,eAAe,KAAK,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC,GAAG,IAAI;CACvE,MAAM,YAAuB;EAC3B,gBAAgB;EAChB,GAAG;EACH,eAAe,QAAQ,iBAAiB,oBAAoB,WAAW;EACvE,aAAa,CAAC,cAAc,GAAI,QAAQ,eAAe,CAAC,CAAE;CAC5D;CAGA,MAAM,aAAa,IAAI,gBAAgB;EACrC,UAAU;EACV;CACF,CAAC;CACD,OAAO,IAAI,UAAU;EACnB,IAAI;EACJ,MAAM;EACN;EACA,SAAS,IAAI,aAAa;GACxB,kBAAkB;GAClB,KAAK,gBAAgB;EACvB,CAAC;EACD,OAAO;EACP,QAAQ;EACR,GAAI,iBAAiB,EAAE,aAAa,eAAe,aAAa,YAAY,iBAAiB,EAAE,IAAI,CAAC;EACpG,KAAK;CACP,CAAC;AACH;;;;;;;;;AAUA,eAAsB,kBAAkB,EACtC,gBACA,UAIkC;CAClC,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,oBAAoB;GAAE;GAAgB;EAAO,CAAC;CAClE,QAAQ;EACN;CACF;CAEA,MAAM,WAAW,MAAM,qBAAqB,WAAW;EAAE;EAAgB;CAAU,CAAC;CACpF,MAAM,WAAuB,CAAC;CAC9B,KAAK,MAAM,QAAQ,2BACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS;CAEhD,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,WAAW,KAAA;AACvD"}
1
+ {"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\nimport { SandboxFilesystem } from './sandbox-filesystem.js';\nimport { reattachProjectSandbox } from './sandbox-reattach.js';\nimport { GOAL_JUDGE_READONLY_TOOLS, MASTRACODE_WORKSPACE_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\n/**\n * Build (or reuse) a sandbox-backed Workspace for a linked project repository. The sandbox\n * is reattached by its persisted provider id and a `SandboxFilesystem` is layered\n * over the in-sandbox checkout so file tools and command tools share one VM.\n */\nasync function getSandboxWorkspace({\n projectRepositoryId,\n sandboxId,\n workdir,\n worktreePath,\n configDir,\n mastra,\n skillExtension,\n actingUserId,\n}: {\n projectRepositoryId: string;\n sandboxId: string;\n workdir: string;\n worktreePath?: string;\n configDir: string;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n actingUserId?: string;\n}): Promise<Workspace> {\n // Bind the workspace to the active worktree when one is set, so file tools and\n // command tools operate inside the feature branch's working tree rather than\n // the base checkout. Falls back to the repo root when no worktree is active.\n const boundWorkdir = worktreePath || workdir;\n\n // Include the sandbox id, worktree path, and acting user in the reuse key: a\n // new sandbox, different worktree, or different caller must each get a fresh\n // Workspace/ProcessManager instead of reusing one bound to stale resources or\n // another user's PlatformSandbox credentials.\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const actingUserScope = actingUserId ? `-user-${encodeURIComponent(actingUserId)}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-repository-${projectRepositoryId}-${sandboxId}-${boundWorkdir}${extensionId}${actingUserScope}`;\n\n // Reuse the existing remote workspace if already registered (preserves the\n // reattached sandbox + ProcessManager state across re-opens).\n try {\n const existing = mastra?.getWorkspaceById(workspaceId) as Workspace | undefined;\n if (existing) {\n existing.setToolsConfig(MASTRACODE_WORKSPACE_TOOLS);\n return existing;\n }\n } catch {\n // Not registered yet.\n }\n\n const sandbox = await reattachProjectSandbox(sandboxId, { actingUserId });\n const filesystem = new SandboxFilesystem({ sandbox, workdir: boundWorkdir });\n const projectSkillPaths = [path.join(configDir, 'skills'), '.claude/skills', '.agents/skills'];\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Sandbox Workspace',\n filesystem,\n sandbox: sandbox as unknown as ConstructorParameters<typeof Workspace>[0]['sandbox'],\n tools: MASTRACODE_WORKSPACE_TOOLS,\n skills: skillPaths,\n skillSource: skillExtension?.createSource(filesystem, projectSkillPaths) ?? filesystem,\n });\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n const user = requestContext.get('user') as { workosId?: unknown; id?: unknown } | undefined;\n const actingUserId =\n typeof user?.workosId === 'string' ? user.workosId : typeof user?.id === 'string' ? user.id : undefined;\n\n // Repository-backed project: the repo lives inside a remote sandbox, not on\n // the server host. Reattach to the already-provisioned + materialized sandbox\n // and build a sandbox-backed Workspace. Optional embedders may add read-only\n // skill roots while project skills remain sandbox-backed.\n if (state?.projectRepositoryId && state.sandboxId && state.sandboxWorkdir) {\n return getSandboxWorkspace({\n projectRepositoryId: state.projectRepositoryId,\n sandboxId: state.sandboxId,\n workdir: state.sandboxWorkdir,\n worktreePath: state.worktreePath,\n configDir: state.configDir ?? DEFAULT_CONFIG_DIR,\n mastra,\n skillExtension,\n actingUserId,\n });\n }\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = MASTRACODE_WORKSPACE_TOOLS;\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n const userLsp = loadSettings().lsp ?? {};\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n const lspConfig: LSPConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readon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B,WAAW;EACvE,aAAa,CAAC,cAAc,GAAI,QAAQ,eAAe,CAAC,CAAE;CAC5D;CAGA,MAAM,aAAa,IAAI,gBAAgB;EACrC,UAAU;EACV;CACF,CAAC;CACD,OAAO,IAAI,UAAU;EACnB,IAAI;EACJ,MAAM;EACN;EACA,SAAS,IAAI,aAAa;GACxB,kBAAkB;GAClB,KAAK,gBAAgB;EACvB,CAAC;EACD,OAAO;EACP,QAAQ;EACR,GAAI,iBAAiB,EAAE,aAAa,eAAe,aAAa,YAAY,iBAAiB,EAAE,IAAI,CAAC;EACpG,KAAK;CACP,CAAC;AACH;;;;;;;;;AAUA,eAAsB,kBAAkB,EACtC,gBACA,UAIkC;CAClC,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,oBAAoB;GAAE;GAAgB;EAAO,CAAC;CAClE,QAAQ;EACN;CACF;CAEA,MAAM,WAAW,MAAM,qBAAqB,WAAW;EAAE;EAAgB;CAAU,CAAC;CACpF,MAAM,WAAuB,CAAC;CAC9B,KAAK,MAAM,QAAQ,2BACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS;CAEhD,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,WAAW,KAAA;AACvD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/code-sdk",
3
- "version": "1.2.1-alpha.2",
3
+ "version": "1.2.1-alpha.4",
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": {
@@ -57,18 +57,18 @@
57
57
  "yaml": "^2.7.1",
58
58
  "zod": "^4.3.6",
59
59
  "@mastra/agent-browser": "0.5.1",
60
- "@mastra/core": "1.59.0-alpha.2",
61
- "@mastra/fastembed": "1.2.0",
62
- "@mastra/github-signals": "0.2.5",
63
60
  "@mastra/duckdb": "1.6.1",
64
- "@mastra/mcp": "1.16.0",
65
- "@mastra/memory": "1.26.2-alpha.1",
66
- "@mastra/observability": "1.17.0-alpha.1",
61
+ "@mastra/core": "1.59.0-alpha.4",
62
+ "@mastra/github-signals": "0.2.5",
63
+ "@mastra/fastembed": "1.2.0",
67
64
  "@mastra/libsql": "1.20.0",
68
- "@mastra/pg": "1.20.0",
65
+ "@mastra/mcp": "1.16.0",
69
66
  "@mastra/schema-compat": "1.3.7-alpha.0",
70
67
  "@mastra/stagehand": "0.3.2",
71
- "@mastra/tavily": "1.1.1"
68
+ "@mastra/tavily": "1.1.1",
69
+ "@mastra/pg": "1.20.0",
70
+ "@mastra/memory": "1.26.2-alpha.1",
71
+ "@mastra/observability": "1.17.0-alpha.1"
72
72
  },
73
73
  "devDependencies": {
74
74
  "@libsql/client": "^0.17.4",
@@ -79,9 +79,9 @@
79
79
  "typescript": "^6.0.3",
80
80
  "typescript-eslint": "^8.57.0",
81
81
  "vitest": "4.1.10",
82
- "@internal/types-builder": "0.0.97",
83
82
  "@internal/lint": "0.0.122",
84
- "@internal/workspace-test-utils": "0.0.66"
83
+ "@internal/workspace-test-utils": "0.0.66",
84
+ "@internal/types-builder": "0.0.97"
85
85
  },
86
86
  "engines": {
87
87
  "node": ">=22.19.0"