@mastra/code-sdk 1.1.1-alpha.0 → 1.1.1-alpha.3

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,39 @@
1
1
  # @mastra/code-sdk
2
2
 
3
+ ## 1.1.1-alpha.3
4
+
5
+ ### Patch Changes
6
+
7
+ - Review sessions now load project AGENTS.md/CLAUDE.md from the pull request's trusted base branch instead of skipping them entirely. The working-tree copies on an untrusted checkout remain excluded from the system prompt and reminder injection; content is served from the base ref via git, and sessions without a known base ref still skip project instruction files. ([#20372](https://github.com/mastra-ai/mastra/pull/20372))
8
+
9
+ - Review sessions no longer ingest AGENTS.md or CLAUDE.md from the checked-out pull request branch. A PR branch is third-party content, so its instruction files are treated as content under review instead of trusted configuration — closing a prompt-injection path into the reviewer agent. The reviewer also runs the PR's install/build/test commands with GitHub tokens stripped from the environment. ([#20372](https://github.com/mastra-ai/mastra/pull/20372))
10
+
11
+ - Added an option to the instruction-file reminder processor that lets hosts disable injection entirely for a request, so instruction files from untrusted checkouts are never surfaced as reminders. ([#20372](https://github.com/mastra-ai/mastra/pull/20372))
12
+
13
+ - Updated dependencies [[`1288cba`](https://github.com/mastra-ai/mastra/commit/1288cba09b8ab906dba38270c7e2a75400344a98), [`723aa54`](https://github.com/mastra-ai/mastra/commit/723aa5437106bdb708ae03c0ef6b77aa11291e73), [`723aa54`](https://github.com/mastra-ai/mastra/commit/723aa5437106bdb708ae03c0ef6b77aa11291e73), [`723aa54`](https://github.com/mastra-ai/mastra/commit/723aa5437106bdb708ae03c0ef6b77aa11291e73)]:
14
+ - @mastra/pg@1.18.1-alpha.0
15
+ - @mastra/core@1.55.0-alpha.3
16
+
17
+ ## 1.1.1-alpha.2
18
+
19
+ ### Patch Changes
20
+
21
+ - Extended Mastra Code's transient retry policy to cover provider server errors with up to 10 retries and exponential backoff starting at 500ms. ([#20393](https://github.com/mastra-ai/mastra/pull/20393))
22
+
23
+ - Updated dependencies [[`55c9e24`](https://github.com/mastra-ai/mastra/commit/55c9e248c27c1d72b5bb7e94ea6b8a3999eee49f), [`07f5b4b`](https://github.com/mastra-ai/mastra/commit/07f5b4ba9d608d88865030732e580298296adf99)]:
24
+ - @mastra/core@1.55.0-alpha.2
25
+
26
+ ## 1.1.1-alpha.1
27
+
28
+ ### Patch Changes
29
+
30
+ - Fixed sandbox file tools (view, write, edit, list) failing with "Path not found" in Factory sessions when called with absolute paths inside the session working directory. File tools now also work on macOS-hosted local sandboxes, not just Linux VMs. ([#20325](https://github.com/mastra-ai/mastra/pull/20325))
31
+
32
+ - Sandbox filesystem operations now behave like local ones: missing files, existing destinations, and directory misuse raise typed errors instead of generic ones, reading a directory as a file fails instead of returning empty content, moving or copying a file into a new directory works, overwrite protection can no longer be raced by concurrent writers, and each filesystem reports a unique id and status. ([#20325](https://github.com/mastra-ai/mastra/pull/20325))
33
+
34
+ - Updated dependencies [[`ba369f2`](https://github.com/mastra-ai/mastra/commit/ba369f2a0aaf998da0d6aa033d26f64f96bef8ac), [`dcfed93`](https://github.com/mastra-ai/mastra/commit/dcfed93e1e256c6abfa792cbb7ca836f5d0e8638), [`2876e15`](https://github.com/mastra-ai/mastra/commit/2876e15b4d2f616a3bc1ed3af57d546c268384ce), [`598080f`](https://github.com/mastra-ai/mastra/commit/598080f224edb3f0f5b801035b067fac50a56a03)]:
35
+ - @mastra/core@1.55.0-alpha.1
36
+
3
37
  ## 1.1.1-alpha.0
4
38
 
5
39
  ### Patch Changes
@@ -6,13 +6,52 @@ export interface InstructionSource {
6
6
  path: string;
7
7
  content: string;
8
8
  scope: 'global' | 'project';
9
+ /** Git ref the content was read from, when not read off the working tree. */
10
+ ref?: string;
9
11
  }
12
+ /**
13
+ * Reads project-scope instruction files. The default implementation reads the
14
+ * working tree via `fs`; alternative readers can serve content from another
15
+ * source (e.g. a trusted git ref) while keeping working-tree paths as the
16
+ * addressing scheme.
17
+ */
18
+ export interface InstructionFileReader {
19
+ exists(path: string): boolean;
20
+ read(path: string): string;
21
+ /** Git ref backing this reader, recorded on the loaded sources. */
22
+ ref?: string;
23
+ }
24
+ /**
25
+ * Create a reader that serves instruction files from a git ref instead of the
26
+ * working tree. Paths are still addressed as working-tree paths under
27
+ * `projectPath`; content comes from `git show <ref>:<relpath>` so an untrusted
28
+ * checkout (e.g. a PR branch under review) cannot influence what is loaded.
29
+ * Tries `origin/<ref>` first (remote truth), then the local ref. Any git
30
+ * failure (missing ref, missing file, no repo) reports the file as absent.
31
+ */
32
+ export declare function createGitRefInstructionReader(projectPath: string, ref: string): InstructionFileReader;
33
+ /**
34
+ * Reader for the reactive reminder channel (AgentsMDInjector) that serves
35
+ * paths under `projectPath` from a trusted git ref. Paths outside the project
36
+ * fall back to the operator machine's filesystem (those are trusted); paths
37
+ * inside the project are only ever resolved against the ref, never the
38
+ * working tree, so an untrusted checkout cannot feed content in.
39
+ */
40
+ export declare function createGitRefReminderReader(projectPath: string, ref: string): {
41
+ pathExists: (path: string) => boolean;
42
+ isDirectory: (path: string) => boolean;
43
+ readFile: (path: string) => string;
44
+ };
10
45
  /**
11
46
  * Load all agent instruction files from global and project locations.
12
47
  * Returns an array of instruction sources, with global ones first.
48
+ *
49
+ * `projectReader` controls where project-scope content comes from (defaults to
50
+ * the working tree). Global instructions always read the operator machine's
51
+ * filesystem.
13
52
  */
14
- export declare function loadAgentInstructions(projectPath: string, configDirName?: string): InstructionSource[];
15
- export declare function getStaticallyLoadedInstructionPaths(projectPath: string): string[];
53
+ export declare function loadAgentInstructions(projectPath: string, configDirName?: string, projectReader?: InstructionFileReader): InstructionSource[];
54
+ export declare function getStaticallyLoadedInstructionPaths(projectPath: string, configDirName?: string, projectReader?: InstructionFileReader): string[];
16
55
  /**
17
56
  * Format loaded instructions into a string for the system prompt.
18
57
  */
@@ -1 +1 @@
1
- {"version":3,"file":"agent-instructions.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/agent-instructions.ts"],"names":[],"mappings":"A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CAAC;IACvC,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;CACpC,CA4CA;AAgBD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,WAAW,EAAE,MAAM,EACnB,aAAa,SAAqB,EAClC,aAAa,GAAE,qBAA2C,GACzD,iBAAiB,EAAE,CAsDrB;AAED,wBAAgB,mCAAmC,CACjD,WAAW,EAAE,MAAM,EACnB,aAAa,SAAqB,EAClC,aAAa,CAAC,EAAE,qBAAqB,GACpC,MAAM,EAAE,CAEV;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,iBAAiB,EAAE,GAAG,MAAM,CAU5E"}
@@ -1,7 +1,8 @@
1
1
  import { DEFAULT_CONFIG_DIR } from "../../constants.js";
2
- import { existsSync, readFileSync } from "fs";
2
+ import { existsSync, readFileSync, statSync } from "fs";
3
3
  import { homedir } from "os";
4
- import { join, normalize } from "path";
4
+ import { isAbsolute, join, normalize, relative, sep } from "path";
5
+ import { execFileSync } from "child_process";
5
6
  //#region src/agents/prompts/agent-instructions.ts
6
7
  /**
7
8
  * Load project and global agent instruction files (AGENTS.md, CLAUDE.md).
@@ -19,22 +20,130 @@ const GLOBAL_LOCATIONS = [
19
20
  ".config/claude",
20
21
  ".config/mastracode"
21
22
  ];
23
+ const fsInstructionReader = {
24
+ exists: (path) => existsSync(path),
25
+ read: (path) => readFileSync(path, "utf-8")
26
+ };
27
+ /**
28
+ * Create a reader that serves instruction files from a git ref instead of the
29
+ * working tree. Paths are still addressed as working-tree paths under
30
+ * `projectPath`; content comes from `git show <ref>:<relpath>` so an untrusted
31
+ * checkout (e.g. a PR branch under review) cannot influence what is loaded.
32
+ * Tries `origin/<ref>` first (remote truth), then the local ref. Any git
33
+ * failure (missing ref, missing file, no repo) reports the file as absent.
34
+ */
35
+ function createGitRefInstructionReader(projectPath, ref) {
36
+ const toRelative = (path) => {
37
+ const rel = relative(projectPath, path);
38
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null;
39
+ return rel.split(sep).join("/");
40
+ };
41
+ const show = (path) => {
42
+ const rel = toRelative(path);
43
+ if (rel === null) return null;
44
+ for (const candidate of [`origin/${ref}`, ref]) try {
45
+ return execFileSync("git", [
46
+ "-C",
47
+ projectPath,
48
+ "show",
49
+ `${candidate}:${rel}`
50
+ ], {
51
+ encoding: "utf-8",
52
+ stdio: [
53
+ "ignore",
54
+ "pipe",
55
+ "ignore"
56
+ ],
57
+ maxBuffer: 1024 * 1024
58
+ });
59
+ } catch {}
60
+ return null;
61
+ };
62
+ return {
63
+ ref,
64
+ exists: (path) => show(path) !== null,
65
+ read: (path) => {
66
+ const content = show(path);
67
+ if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);
68
+ return content;
69
+ }
70
+ };
71
+ }
72
+ /**
73
+ * Reader for the reactive reminder channel (AgentsMDInjector) that serves
74
+ * paths under `projectPath` from a trusted git ref. Paths outside the project
75
+ * fall back to the operator machine's filesystem (those are trusted); paths
76
+ * inside the project are only ever resolved against the ref, never the
77
+ * working tree, so an untrusted checkout cannot feed content in.
78
+ */
79
+ function createGitRefReminderReader(projectPath, ref) {
80
+ const gitReader = createGitRefInstructionReader(projectPath, ref);
81
+ const toRelative = (path) => {
82
+ const rel = relative(projectPath, normalize(path));
83
+ if (rel.startsWith("..") || isAbsolute(rel)) return null;
84
+ return rel.split(sep).join("/");
85
+ };
86
+ const objectType = (rel) => {
87
+ if (rel === "") return "tree";
88
+ for (const candidate of [`origin/${ref}`, ref]) try {
89
+ return execFileSync("git", [
90
+ "-C",
91
+ projectPath,
92
+ "cat-file",
93
+ "-t",
94
+ `${candidate}:${rel}`
95
+ ], {
96
+ encoding: "utf-8",
97
+ stdio: [
98
+ "ignore",
99
+ "pipe",
100
+ "ignore"
101
+ ]
102
+ }).trim();
103
+ } catch {}
104
+ return null;
105
+ };
106
+ return {
107
+ pathExists: (path) => {
108
+ const rel = toRelative(path);
109
+ if (rel === null) return existsSync(path);
110
+ return objectType(rel) !== null;
111
+ },
112
+ isDirectory: (path) => {
113
+ const rel = toRelative(path);
114
+ if (rel === null) try {
115
+ return statSync(path).isDirectory();
116
+ } catch {
117
+ return false;
118
+ }
119
+ return objectType(rel) === "tree";
120
+ },
121
+ readFile: (path) => {
122
+ if (toRelative(path) === null) return readFileSync(path, "utf-8");
123
+ return gitReader.read(path);
124
+ }
125
+ };
126
+ }
22
127
  /**
23
128
  * Find the first existing instruction file at a given base path.
24
129
  * Prefers AGENTS.md over CLAUDE.md.
25
130
  */
26
- function findInstructionFile(basePath) {
131
+ function findInstructionFile(basePath, reader = fsInstructionReader) {
27
132
  for (const filename of INSTRUCTION_FILES) {
28
133
  const fullPath = join(basePath, filename);
29
- if (existsSync(fullPath)) return fullPath;
134
+ if (reader.exists(fullPath)) return fullPath;
30
135
  }
31
136
  return null;
32
137
  }
33
138
  /**
34
139
  * Load all agent instruction files from global and project locations.
35
140
  * Returns an array of instruction sources, with global ones first.
141
+ *
142
+ * `projectReader` controls where project-scope content comes from (defaults to
143
+ * the working tree). Global instructions always read the operator machine's
144
+ * filesystem.
36
145
  */
37
- function loadAgentInstructions(projectPath, configDirName = DEFAULT_CONFIG_DIR) {
146
+ function loadAgentInstructions(projectPath, configDirName = DEFAULT_CONFIG_DIR, projectReader = fsInstructionReader) {
38
147
  const sources = [];
39
148
  const home = homedir();
40
149
  const projectLocations = PROJECT_LOCATIONS.map((loc) => loc === ".mastracode" ? configDirName : loc);
@@ -58,14 +167,15 @@ function loadAgentInstructions(projectPath, configDirName = DEFAULT_CONFIG_DIR)
58
167
  } catch {}
59
168
  }
60
169
  for (const location of projectLocations) {
61
- const filePath = findInstructionFile(location ? join(projectPath, location) : projectPath);
170
+ const filePath = findInstructionFile(location ? join(projectPath, location) : projectPath, projectReader);
62
171
  if (filePath) try {
63
- const content = readFileSync(filePath, "utf-8").trim();
172
+ const content = projectReader.read(filePath).trim();
64
173
  if (content) {
65
174
  sources.push({
66
175
  path: filePath,
67
176
  content,
68
- scope: "project"
177
+ scope: "project",
178
+ ...projectReader.ref ? { ref: projectReader.ref } : {}
69
179
  });
70
180
  break;
71
181
  }
@@ -73,8 +183,8 @@ function loadAgentInstructions(projectPath, configDirName = DEFAULT_CONFIG_DIR)
73
183
  }
74
184
  return sources;
75
185
  }
76
- function getStaticallyLoadedInstructionPaths(projectPath) {
77
- return loadAgentInstructions(projectPath).map((source) => normalize(source.path));
186
+ function getStaticallyLoadedInstructionPaths(projectPath, configDirName = DEFAULT_CONFIG_DIR, projectReader) {
187
+ return loadAgentInstructions(projectPath, configDirName, projectReader).map((source) => normalize(source.path));
78
188
  }
79
189
  /**
80
190
  * Format loaded instructions into a string for the system prompt.
@@ -82,10 +192,10 @@ function getStaticallyLoadedInstructionPaths(projectPath) {
82
192
  function formatAgentInstructions(sources) {
83
193
  if (sources.length === 0) return "";
84
194
  return `\n# Agent Instructions\n\n${sources.map((source) => {
85
- return `<!-- ${source.scope === "global" ? "Global" : "Project"} instructions from ${source.path} -->\n${source.content}`;
195
+ return `<!-- ${source.scope === "global" ? "Global" : "Project"} instructions from ${source.ref ? `${source.path} (at ref ${source.ref})` : source.path} -->\n${source.content}`;
86
196
  }).join("\n\n")}\n`;
87
197
  }
88
198
  //#endregion
89
- export { formatAgentInstructions, getStaticallyLoadedInstructionPaths, loadAgentInstructions };
199
+ export { createGitRefInstructionReader, createGitRefReminderReader, formatAgentInstructions, getStaticallyLoadedInstructionPaths, loadAgentInstructions };
90
200
 
91
201
  //# sourceMappingURL=agent-instructions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent-instructions.js","names":[],"sources":["../../../src/agents/prompts/agent-instructions.ts"],"sourcesContent":["/**\n * Load project and global agent instruction files (AGENTS.md, CLAUDE.md).\n * Prefers AGENTS.md over CLAUDE.md when multiple exist at the same location.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, normalize } from 'node:path';\nimport { DEFAULT_CONFIG_DIR } from '../../constants.js';\n\n// Filenames to check, in order of preference\nconst INSTRUCTION_FILES = ['AGENTS.md', 'CLAUDE.md'];\n\n// Locations to scan (relative to project root or home)\nconst PROJECT_LOCATIONS = [\n '', // project root\n '.claude',\n '.mastracode',\n];\n\nconst GLOBAL_LOCATIONS = ['.claude', '.mastracode', '.config/claude', '.config/mastracode'];\n\nexport interface InstructionSource {\n path: string;\n content: string;\n scope: 'global' | 'project';\n}\n\n/**\n * Find the first existing instruction file at a given base path.\n * Prefers AGENTS.md over CLAUDE.md.\n */\nfunction findInstructionFile(basePath: string): string | null {\n for (const filename of INSTRUCTION_FILES) {\n const fullPath = join(basePath, filename);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Load all agent instruction files from global and project locations.\n * Returns an array of instruction sources, with global ones first.\n */\nexport function loadAgentInstructions(projectPath: string, configDirName = DEFAULT_CONFIG_DIR): InstructionSource[] {\n const sources: InstructionSource[] = [];\n const home = homedir();\n\n // Derive location arrays from the base constants, substituting the config dir name\n const projectLocations = PROJECT_LOCATIONS.map(loc => (loc === '.mastracode' ? configDirName : loc));\n const globalLocations = GLOBAL_LOCATIONS.map(loc => {\n if (loc === '.mastracode') return configDirName;\n // XDG-style path (~/.config/<name>): strip the leading dot since the\n // .config/ prefix already signals a hidden/config directory.\n if (loc === '.config/mastracode') return '.config/' + configDirName.replace(/^\\./, '');\n return loc;\n });\n\n // Load global instructions first\n for (const location of globalLocations) {\n const basePath = join(home, location);\n const filePath = findInstructionFile(basePath);\n if (filePath) {\n try {\n const content = readFileSync(filePath, 'utf-8').trim();\n if (content) {\n sources.push({ path: filePath, content, scope: 'global' });\n break; // Only use first found global instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n // Load project instructions\n for (const location of projectLocations) {\n const basePath = location ? join(projectPath, location) : projectPath;\n const filePath = findInstructionFile(basePath);\n if (filePath) {\n try {\n const content = readFileSync(filePath, 'utf-8').trim();\n if (content) {\n sources.push({ path: filePath, content, scope: 'project' });\n break; // Only use first found project instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return sources;\n}\n\nexport function getStaticallyLoadedInstructionPaths(projectPath: string): string[] {\n return loadAgentInstructions(projectPath).map(source => normalize(source.path));\n}\n\n/**\n * Format loaded instructions into a string for the system prompt.\n */\nexport function formatAgentInstructions(sources: InstructionSource[]): string {\n if (sources.length === 0) return '';\n\n const sections = sources.map(source => {\n const label = source.scope === 'global' ? 'Global' : 'Project';\n return `<!-- ${label} instructions from ${source.path} -->\\n${source.content}`;\n });\n\n return `\\n# Agent Instructions\\n\\n${sections.join('\\n\\n')}\\n`;\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,oBAAoB,CAAC,aAAa,WAAW;AAGnD,MAAM,oBAAoB;CACxB;CACA;CACA;AACF;AAEA,MAAM,mBAAmB;CAAC;CAAW;CAAe;CAAkB;AAAoB;;;;;AAY1F,SAAS,oBAAoB,UAAiC;CAC5D,KAAK,MAAM,YAAY,mBAAmB;EACxC,MAAM,WAAW,KAAK,UAAU,QAAQ;EACxC,IAAI,WAAW,QAAQ,GACrB,OAAO;CAEX;CACA,OAAO;AACT;;;;;AAMA,SAAgB,sBAAsB,aAAqB,gBAAgB,oBAAyC;CAClH,MAAM,UAA+B,CAAC;CACtC,MAAM,OAAO,QAAQ;CAGrB,MAAM,mBAAmB,kBAAkB,KAAI,QAAQ,QAAQ,gBAAgB,gBAAgB,GAAI;CACnG,MAAM,kBAAkB,iBAAiB,KAAI,QAAO;EAClD,IAAI,QAAQ,eAAe,OAAO;EAGlC,IAAI,QAAQ,sBAAsB,OAAO,aAAa,cAAc,QAAQ,OAAO,EAAE;EACrF,OAAO;CACT,CAAC;CAGD,KAAK,MAAM,YAAY,iBAAiB;EAEtC,MAAM,WAAW,oBADA,KAAK,MAAM,QACgB,CAAC;EAC7C,IAAI,UACF,IAAI;GACF,MAAM,UAAU,aAAa,UAAU,OAAO,CAAC,CAAC,KAAK;GACrD,IAAI,SAAS;IACX,QAAQ,KAAK;KAAE,MAAM;KAAU;KAAS,OAAO;IAAS,CAAC;IACzD;GACF;EACF,QAAQ,CAER;CAEJ;CAGA,KAAK,MAAM,YAAY,kBAAkB;EAEvC,MAAM,WAAW,oBADA,WAAW,KAAK,aAAa,QAAQ,IAAI,WACb;EAC7C,IAAI,UACF,IAAI;GACF,MAAM,UAAU,aAAa,UAAU,OAAO,CAAC,CAAC,KAAK;GACrD,IAAI,SAAS;IACX,QAAQ,KAAK;KAAE,MAAM;KAAU;KAAS,OAAO;IAAU,CAAC;IAC1D;GACF;EACF,QAAQ,CAER;CAEJ;CAEA,OAAO;AACT;AAEA,SAAgB,oCAAoC,aAA+B;CACjF,OAAO,sBAAsB,WAAW,CAAC,CAAC,KAAI,WAAU,UAAU,OAAO,IAAI,CAAC;AAChF;;;;AAKA,SAAgB,wBAAwB,SAAsC;CAC5E,IAAI,QAAQ,WAAW,GAAG,OAAO;CAOjC,OAAO,6BALU,QAAQ,KAAI,WAAU;EAErC,OAAO,QADO,OAAO,UAAU,WAAW,WAAW,UAChC,qBAAqB,OAAO,KAAK,QAAQ,OAAO;CACvE,CAE2C,CAAC,CAAC,KAAK,MAAM,EAAE;AAC5D"}
1
+ {"version":3,"file":"agent-instructions.js","names":[],"sources":["../../../src/agents/prompts/agent-instructions.ts"],"sourcesContent":["/**\n * Load project and global agent instruction files (AGENTS.md, CLAUDE.md).\n * Prefers AGENTS.md over CLAUDE.md when multiple exist at the same location.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, normalize, relative, sep } from 'node:path';\nimport { DEFAULT_CONFIG_DIR } from '../../constants.js';\n\n// Filenames to check, in order of preference\nconst INSTRUCTION_FILES = ['AGENTS.md', 'CLAUDE.md'];\n\n// Locations to scan (relative to project root or home)\nconst PROJECT_LOCATIONS = [\n '', // project root\n '.claude',\n '.mastracode',\n];\n\nconst GLOBAL_LOCATIONS = ['.claude', '.mastracode', '.config/claude', '.config/mastracode'];\n\nexport interface InstructionSource {\n path: string;\n content: string;\n scope: 'global' | 'project';\n /** Git ref the content was read from, when not read off the working tree. */\n ref?: string;\n}\n\n/**\n * Reads project-scope instruction files. The default implementation reads the\n * working tree via `fs`; alternative readers can serve content from another\n * source (e.g. a trusted git ref) while keeping working-tree paths as the\n * addressing scheme.\n */\nexport interface InstructionFileReader {\n exists(path: string): boolean;\n read(path: string): string;\n /** Git ref backing this reader, recorded on the loaded sources. */\n ref?: string;\n}\n\nconst fsInstructionReader: InstructionFileReader = {\n exists: path => existsSync(path),\n read: path => readFileSync(path, 'utf-8'),\n};\n\n/**\n * Create a reader that serves instruction files from a git ref instead of the\n * working tree. Paths are still addressed as working-tree paths under\n * `projectPath`; content comes from `git show <ref>:<relpath>` so an untrusted\n * checkout (e.g. a PR branch under review) cannot influence what is loaded.\n * Tries `origin/<ref>` first (remote truth), then the local ref. Any git\n * failure (missing ref, missing file, no repo) reports the file as absent.\n */\nexport function createGitRefInstructionReader(projectPath: string, ref: string): InstructionFileReader {\n const toRelative = (path: string): string | null => {\n const rel = relative(projectPath, path);\n if (!rel || rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n };\n const show = (path: string): string | null => {\n const rel = toRelative(path);\n if (rel === null) return null;\n for (const candidate of [`origin/${ref}`, ref]) {\n try {\n return execFileSync('git', ['-C', projectPath, 'show', `${candidate}:${rel}`], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n maxBuffer: 1024 * 1024,\n });\n } catch {\n // Ref or file missing at this candidate — try the next one.\n }\n }\n return null;\n };\n return {\n ref,\n exists: path => show(path) !== null,\n read: path => {\n const content = show(path);\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n };\n}\n\n/**\n * Reader for the reactive reminder channel (AgentsMDInjector) that serves\n * paths under `projectPath` from a trusted git ref. Paths outside the project\n * fall back to the operator machine's filesystem (those are trusted); paths\n * inside the project are only ever resolved against the ref, never the\n * working tree, so an untrusted checkout cannot feed content in.\n */\nexport function createGitRefReminderReader(\n projectPath: string,\n ref: string,\n): {\n pathExists: (path: string) => boolean;\n isDirectory: (path: string) => boolean;\n readFile: (path: string) => string;\n} {\n const gitReader = createGitRefInstructionReader(projectPath, ref);\n const toRelative = (path: string): string | null => {\n const rel = relative(projectPath, normalize(path));\n if (rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n };\n const objectType = (rel: string): string | null => {\n if (rel === '') return 'tree'; // project root\n for (const candidate of [`origin/${ref}`, ref]) {\n try {\n return execFileSync('git', ['-C', projectPath, 'cat-file', '-t', `${candidate}:${rel}`], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n } catch {\n // Ref or object missing at this candidate — try the next one.\n }\n }\n return null;\n };\n return {\n pathExists: path => {\n const rel = toRelative(path);\n if (rel === null) return existsSync(path);\n return objectType(rel) !== null;\n },\n isDirectory: path => {\n const rel = toRelative(path);\n if (rel === null) {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n }\n return objectType(rel) === 'tree';\n },\n readFile: path => {\n const rel = toRelative(path);\n if (rel === null) return readFileSync(path, 'utf-8');\n return gitReader.read(path);\n },\n };\n}\n\n/**\n * Find the first existing instruction file at a given base path.\n * Prefers AGENTS.md over CLAUDE.md.\n */\nfunction findInstructionFile(basePath: string, reader: InstructionFileReader = fsInstructionReader): string | null {\n for (const filename of INSTRUCTION_FILES) {\n const fullPath = join(basePath, filename);\n if (reader.exists(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Load all agent instruction files from global and project locations.\n * Returns an array of instruction sources, with global ones first.\n *\n * `projectReader` controls where project-scope content comes from (defaults to\n * the working tree). Global instructions always read the operator machine's\n * filesystem.\n */\nexport function loadAgentInstructions(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: InstructionFileReader = fsInstructionReader,\n): InstructionSource[] {\n const sources: InstructionSource[] = [];\n const home = homedir();\n\n // Derive location arrays from the base constants, substituting the config dir name\n const projectLocations = PROJECT_LOCATIONS.map(loc => (loc === '.mastracode' ? configDirName : loc));\n const globalLocations = GLOBAL_LOCATIONS.map(loc => {\n if (loc === '.mastracode') return configDirName;\n // XDG-style path (~/.config/<name>): strip the leading dot since the\n // .config/ prefix already signals a hidden/config directory.\n if (loc === '.config/mastracode') return '.config/' + configDirName.replace(/^\\./, '');\n return loc;\n });\n\n // Load global instructions first\n for (const location of globalLocations) {\n const basePath = join(home, location);\n const filePath = findInstructionFile(basePath);\n if (filePath) {\n try {\n const content = readFileSync(filePath, 'utf-8').trim();\n if (content) {\n sources.push({ path: filePath, content, scope: 'global' });\n break; // Only use first found global instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n // Load project instructions\n for (const location of projectLocations) {\n const basePath = location ? join(projectPath, location) : projectPath;\n const filePath = findInstructionFile(basePath, projectReader);\n if (filePath) {\n try {\n const content = projectReader.read(filePath).trim();\n if (content) {\n sources.push({\n path: filePath,\n content,\n scope: 'project',\n ...(projectReader.ref ? { ref: projectReader.ref } : {}),\n });\n break; // Only use first found project instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return sources;\n}\n\nexport function getStaticallyLoadedInstructionPaths(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader?: InstructionFileReader,\n): string[] {\n return loadAgentInstructions(projectPath, configDirName, projectReader).map(source => normalize(source.path));\n}\n\n/**\n * Format loaded instructions into a string for the system prompt.\n */\nexport function formatAgentInstructions(sources: InstructionSource[]): string {\n if (sources.length === 0) return '';\n\n const sections = sources.map(source => {\n const label = source.scope === 'global' ? 'Global' : 'Project';\n const origin = source.ref ? `${source.path} (at ref ${source.ref})` : source.path;\n return `<!-- ${label} instructions from ${origin} -->\\n${source.content}`;\n });\n\n return `\\n# Agent Instructions\\n\\n${sections.join('\\n\\n')}\\n`;\n}\n"],"mappings":";;;;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ts","sourceRoot":"","sources":["../../../src/agents/prompts/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAG3C,OAAO,KAAK,EAAE,aAAa,IAAI,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAUpF,MAAM,WAAW,aAAc,SAAQ,IAAI,CAAC,iBAAiB,EAAE,cAAc,CAAC;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB;AAQD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAmD1D"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAG3C,OAAO,KAAK,EAAE,aAAa,IAAI,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAUpF,MAAM,WAAW,aAAc,SAAQ,IAAI,CAAC,iBAAiB,EAAE,cAAc,CAAC;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB;AAQD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAiE1D"}
@@ -3,7 +3,7 @@ import { planModePrompt } from "./plan.js";
3
3
  import { fastModePrompt } from "./fast.js";
4
4
  import { hasTavilyKey } from "../../tools/web-search.js";
5
5
  import "../../tools/index.js";
6
- import { formatAgentInstructions, loadAgentInstructions } from "./agent-instructions.js";
6
+ import { createGitRefInstructionReader, formatAgentInstructions, loadAgentInstructions } from "./agent-instructions.js";
7
7
  import { modelSpecificPrompts } from "./model.js";
8
8
  import { buildToolGuidance } from "./tool-guidance.js";
9
9
  import { buildBasePrompt } from "@mastra/core/coding-agent";
@@ -45,9 +45,15 @@ function buildFullPrompt(ctx) {
45
45
  const modeSpecific = (typeof entry === "function" ? entry(ctx) : entry) ?? "";
46
46
  const modelSpecific = ctx.modelId ? modelSpecificPrompts[ctx.modelId] ?? "" : "";
47
47
  const configDir = ctx.state?.configDir;
48
+ const untrustedCheckout = ctx.state?.untrustedCheckout === true;
49
+ const baseRef = typeof ctx.state?.baseRef === "string" ? ctx.state.baseRef : void 0;
50
+ const projectReader = untrustedCheckout ? baseRef ? createGitRefInstructionReader(ctx.workingDir, baseRef) : {
51
+ exists: () => false,
52
+ read: () => ""
53
+ } : void 0;
48
54
  return [
49
55
  base,
50
- formatAgentInstructions(loadAgentInstructions(ctx.workingDir, configDir)).trim(),
56
+ formatAgentInstructions(loadAgentInstructions(ctx.workingDir, configDir, projectReader)).trim(),
51
57
  modelSpecific.trim(),
52
58
  modeSpecific.trim()
53
59
  ].filter(Boolean).join("\n\n");
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/prompts/index.ts"],"sourcesContent":["/**\n * Prompt system — exports the prompt builder and mode-specific prompts.\n */\n\nexport { buildModePrompt, buildModePromptFn } from './build.js';\nexport { planModePrompt } from './plan.js';\nexport { fastModePrompt } from './fast.js';\n\nimport { buildBasePrompt } from '@mastra/core/coding-agent';\nimport type { PromptContext as BasePromptContext } from '@mastra/core/coding-agent';\nimport { hasTavilyKey } from '../../tools/index.js';\nimport { loadAgentInstructions, formatAgentInstructions } from './agent-instructions.js';\nimport { buildModePromptFn } from './build.js';\nimport { fastModePrompt } from './fast.js';\nimport { modelSpecificPrompts } from './model.js';\nimport { planModePrompt } from './plan.js';\nimport { buildToolGuidance } from './tool-guidance.js';\n\n// Extended prompt context that includes runtime information\nexport interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {\n modeId: string;\n state?: any;\n currentDate: string;\n workingDir: string;\n}\n\nconst modePrompts: Record<string, string | ((ctx: PromptContext) => string)> = {\n build: buildModePromptFn,\n plan: planModePrompt,\n fast: fastModePrompt,\n};\n\n/**\n * Build the full system prompt for a given mode and context.\n * Combines the base prompt with mode-specific instructions.\n */\nexport function buildFullPrompt(ctx: PromptContext): string {\n // Determine whether web search tools are available\n const modelId = ctx.modelId;\n const hasWebSearch = hasTavilyKey() || (!!modelId && modelId.startsWith('anthropic/'));\n\n // Collect per-tool deny rules so guidance omits denied tools\n const deniedTools = new Set<string>();\n const permRules = ctx.state?.permissionRules as { tools?: Record<string, string> } | undefined;\n if (permRules?.tools) {\n for (const [name, policy] of Object.entries(permRules.tools)) {\n if (policy === 'deny') deniedTools.add(name);\n }\n }\n\n // Build mode-aware tool guidance\n const toolGuidance = buildToolGuidance(ctx.modeId, { hasWebSearch, deniedTools });\n\n // Map new context to base context\n const baseCtx: BasePromptContext = {\n projectPath: ctx.workingDir,\n projectName: ctx.projectName || 'unknown',\n gitBranch: ctx.gitBranch,\n platform: process.platform,\n commonBinaries: ctx.commonBinaries,\n date: ctx.currentDate,\n mode: ctx.modeId,\n modelId: ctx.modelId,\n activePlan: ctx.state?.activePlan,\n toolGuidance,\n };\n\n const base = buildBasePrompt(baseCtx);\n const entry = modePrompts[ctx.modeId] || modePrompts.build;\n const modeSpecific = (typeof entry === 'function' ? entry(ctx) : entry) ?? '';\n const modelSpecific = ctx.modelId\n ? (modelSpecificPrompts[ctx.modelId as keyof typeof modelSpecificPrompts] ?? '')\n : '';\n\n // The current task list is carried on the agent state-signal lane (see\n // TaskStateProcessor) rather than injected into the cached system prompt. This\n // keeps the prompt prefix stable across task updates (preserving prompt cache)\n // while still surviving observational-memory truncation.\n\n // Load and inject agent instructions from AGENTS.md/CLAUDE.md files\n const configDir = ctx.state?.configDir as string | undefined;\n const instructionSources = loadAgentInstructions(ctx.workingDir, configDir);\n const instructionsSection = formatAgentInstructions(instructionSources);\n\n const sections = [base, instructionsSection.trim(), modelSpecific.trim(), modeSpecific.trim()].filter(Boolean);\n\n return sections.join('\\n\\n');\n}\n"],"mappings":";;;;;;;;;;AA0BA,MAAM,cAAyE;CAC7E,OAAO;CACP,MAAM;CACN,MAAM;AACR;;;;;AAMA,SAAgB,gBAAgB,KAA4B;CAE1D,MAAM,UAAU,IAAI;CACpB,MAAM,eAAe,aAAa,KAAM,CAAC,CAAC,WAAW,QAAQ,WAAW,YAAY;CAGpF,MAAM,8BAAc,IAAI,IAAY;CACpC,MAAM,YAAY,IAAI,OAAO;CAC7B,IAAI,WAAW,OACR;OAAA,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,UAAU,KAAK,GACzD,IAAI,WAAW,QAAQ,YAAY,IAAI,IAAI;CAAA;CAK/C,MAAM,eAAe,kBAAkB,IAAI,QAAQ;EAAE;EAAc;CAAY,CAAC;CAgBhF,MAAM,OAAO,gBAAgB;EAZ3B,aAAa,IAAI;EACjB,aAAa,IAAI,eAAe;EAChC,WAAW,IAAI;EACf,UAAU,QAAQ;EAClB,gBAAgB,IAAI;EACpB,MAAM,IAAI;EACV,MAAM,IAAI;EACV,SAAS,IAAI;EACb,YAAY,IAAI,OAAO;EACvB;CAGiC,CAAC;CACpC,MAAM,QAAQ,YAAY,IAAI,WAAW,YAAY;CACrD,MAAM,gBAAgB,OAAO,UAAU,aAAa,MAAM,GAAG,IAAI,UAAU;CAC3E,MAAM,gBAAgB,IAAI,UACrB,qBAAqB,IAAI,YAAiD,KAC3E;CAQJ,MAAM,YAAY,IAAI,OAAO;CAM7B,OAFiB;EAAC;EAFU,wBADD,sBAAsB,IAAI,YAAY,SACI,CAE3B,CAAC,CAAC,KAAK;EAAG,cAAc,KAAK;EAAG,aAAa,KAAK;CAAC,CAAC,CAAC,OAAO,OAExF,CAAC,CAAC,KAAK,MAAM;AAC7B"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/prompts/index.ts"],"sourcesContent":["/**\n * Prompt system — exports the prompt builder and mode-specific prompts.\n */\n\nexport { buildModePrompt, buildModePromptFn } from './build.js';\nexport { planModePrompt } from './plan.js';\nexport { fastModePrompt } from './fast.js';\n\nimport { buildBasePrompt } from '@mastra/core/coding-agent';\nimport type { PromptContext as BasePromptContext } from '@mastra/core/coding-agent';\nimport { hasTavilyKey } from '../../tools/index.js';\nimport { loadAgentInstructions, formatAgentInstructions, createGitRefInstructionReader } from './agent-instructions.js';\nimport { buildModePromptFn } from './build.js';\nimport { fastModePrompt } from './fast.js';\nimport { modelSpecificPrompts } from './model.js';\nimport { planModePrompt } from './plan.js';\nimport { buildToolGuidance } from './tool-guidance.js';\n\n// Extended prompt context that includes runtime information\nexport interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {\n modeId: string;\n state?: any;\n currentDate: string;\n workingDir: string;\n}\n\nconst modePrompts: Record<string, string | ((ctx: PromptContext) => string)> = {\n build: buildModePromptFn,\n plan: planModePrompt,\n fast: fastModePrompt,\n};\n\n/**\n * Build the full system prompt for a given mode and context.\n * Combines the base prompt with mode-specific instructions.\n */\nexport function buildFullPrompt(ctx: PromptContext): string {\n // Determine whether web search tools are available\n const modelId = ctx.modelId;\n const hasWebSearch = hasTavilyKey() || (!!modelId && modelId.startsWith('anthropic/'));\n\n // Collect per-tool deny rules so guidance omits denied tools\n const deniedTools = new Set<string>();\n const permRules = ctx.state?.permissionRules as { tools?: Record<string, string> } | undefined;\n if (permRules?.tools) {\n for (const [name, policy] of Object.entries(permRules.tools)) {\n if (policy === 'deny') deniedTools.add(name);\n }\n }\n\n // Build mode-aware tool guidance\n const toolGuidance = buildToolGuidance(ctx.modeId, { hasWebSearch, deniedTools });\n\n // Map new context to base context\n const baseCtx: BasePromptContext = {\n projectPath: ctx.workingDir,\n projectName: ctx.projectName || 'unknown',\n gitBranch: ctx.gitBranch,\n platform: process.platform,\n commonBinaries: ctx.commonBinaries,\n date: ctx.currentDate,\n mode: ctx.modeId,\n modelId: ctx.modelId,\n activePlan: ctx.state?.activePlan,\n toolGuidance,\n };\n\n const base = buildBasePrompt(baseCtx);\n const entry = modePrompts[ctx.modeId] || modePrompts.build;\n const modeSpecific = (typeof entry === 'function' ? entry(ctx) : entry) ?? '';\n const modelSpecific = ctx.modelId\n ? (modelSpecificPrompts[ctx.modelId as keyof typeof modelSpecificPrompts] ?? '')\n : '';\n\n // The current task list is carried on the agent state-signal lane (see\n // TaskStateProcessor) rather than injected into the cached system prompt. This\n // keeps the prompt prefix stable across task updates (preserving prompt cache)\n // while still surviving observational-memory truncation.\n\n // Load and inject agent instructions from AGENTS.md/CLAUDE.md files.\n // Untrusted checkouts (e.g. a PR branch under review) never read\n // project-scope files off the working tree: their AGENTS.md is\n // attacker-writable and would otherwise land in the system prompt as\n // trusted configuration. When the session carries a trusted base ref, the\n // project instructions are served from that ref instead (`git show`);\n // without one, project-scope files are skipped entirely. Global (operator\n // machine) instructions always load.\n const configDir = ctx.state?.configDir as string | undefined;\n const untrustedCheckout = ctx.state?.untrustedCheckout === true;\n const baseRef = typeof ctx.state?.baseRef === 'string' ? ctx.state.baseRef : undefined;\n const projectReader = untrustedCheckout\n ? baseRef\n ? createGitRefInstructionReader(ctx.workingDir, baseRef)\n : { exists: () => false, read: () => '' }\n : undefined;\n const instructionSources = loadAgentInstructions(ctx.workingDir, configDir, projectReader);\n const instructionsSection = formatAgentInstructions(instructionSources);\n\n const sections = [base, instructionsSection.trim(), modelSpecific.trim(), modeSpecific.trim()].filter(Boolean);\n\n return sections.join('\\n\\n');\n}\n"],"mappings":";;;;;;;;;;AA0BA,MAAM,cAAyE;CAC7E,OAAO;CACP,MAAM;CACN,MAAM;AACR;;;;;AAMA,SAAgB,gBAAgB,K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spaceFilesystem {
45
45
  /**
46
46
  * Resolve a workspace path to an absolute path inside the sandbox, enforcing
47
47
  * that it stays within the workdir.
48
+ *
49
+ * Accepts both workspace-relative paths (`src/foo.ts`, `/src/foo.ts`) and
50
+ * absolute sandbox paths that already live under the workdir — the agent's
51
+ * prompt advertises the workdir as its working directory, so tools are
52
+ * routinely called with fully-qualified paths like `<workdir>/src/foo.ts`.
48
53
  */
49
54
  private resolve;
50
55
  resolveAbsolutePath(inputPath: string): string | undefined;
@@ -53,6 +58,11 @@ export declare class SandboxFilesystem implements WorkspaceFilesystem {
53
58
  * Lexical guard catches `..` traversal, but a symlink inside the workdir can
54
59
  * still point outside it. After resolving a path that refers to an existing
55
60
  * entry, verify its realpath is still contained in the workdir.
61
+ *
62
+ * Canonicalization tries `realpath`, then `readlink -f` (GNU/busybox), then
63
+ * `cd && pwd -P` for directories — covering GNU hosts, macOS/BSD, and
64
+ * busybox. If the path exists but cannot be canonicalized we fail CLOSED:
65
+ * returning without a check would let a symlink bypass containment.
56
66
  */
57
67
  private assertContainedRealpath;
58
68
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox-filesystem.d.ts","sourceRoot":"","sources":["../../src/agents/sandbox-filesystem.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,KAAK,EACV,WAAW,EACX,WAAW,EACX,SAAS,EACT,QAAQ,EACR,cAAc,EACd,WAAW,EACX,cAAc,EACd,WAAW,EACX,aAAa,EACb,mBAAmB,EACnB,YAAY,EACb,MAAM,wBAAwB,CAAC;AAEhC,iDAAiD;AACjD,MAAM,WAAW,oBAAoB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,oDAAoD;AACpD,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI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