@mastra/code-sdk 1.19.0-alpha.1 → 1.19.0-alpha.11

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 (74) hide show
  1. package/dist/acp/runtime.d.ts.map +1 -1
  2. package/dist/acp/runtime.js +1 -0
  3. package/dist/acp/runtime.js.map +1 -1
  4. package/dist/agent-connections/tools.d.ts.map +1 -1
  5. package/dist/agent-connections/tools.js +67 -2
  6. package/dist/agent-connections/tools.js.map +1 -1
  7. package/dist/agents/fastembed-subprocess.d.ts +31 -0
  8. package/dist/agents/fastembed-subprocess.d.ts.map +1 -0
  9. package/dist/agents/fastembed-subprocess.js +202 -0
  10. package/dist/agents/fastembed-subprocess.js.map +1 -0
  11. package/dist/agents/instructions.d.ts +5 -2
  12. package/dist/agents/instructions.d.ts.map +1 -1
  13. package/dist/agents/instructions.js +6 -4
  14. package/dist/agents/instructions.js.map +1 -1
  15. package/dist/agents/mastracode-gateway.d.ts.map +1 -1
  16. package/dist/agents/mastracode-gateway.js +2 -2
  17. package/dist/agents/mastracode-gateway.js.map +1 -1
  18. package/dist/agents/memory.d.ts.map +1 -1
  19. package/dist/agents/memory.js +4 -6
  20. package/dist/agents/memory.js.map +1 -1
  21. package/dist/agents/model.d.ts.map +1 -1
  22. package/dist/agents/model.js +10 -5
  23. package/dist/agents/model.js.map +1 -1
  24. package/dist/agents/modes/build.js +1 -1
  25. package/dist/agents/modes/build.js.map +1 -1
  26. package/dist/agents/modes/plan.js +1 -1
  27. package/dist/agents/modes/plan.js.map +1 -1
  28. package/dist/agents/prompts/agent-instructions.d.ts +24 -1
  29. package/dist/agents/prompts/agent-instructions.d.ts.map +1 -1
  30. package/dist/agents/prompts/agent-instructions.js +386 -41
  31. package/dist/agents/prompts/agent-instructions.js.map +1 -1
  32. package/dist/agents/prompts/index.d.ts +3 -1
  33. package/dist/agents/prompts/index.d.ts.map +1 -1
  34. package/dist/agents/prompts/index.js +16 -5
  35. package/dist/agents/prompts/index.js.map +1 -1
  36. package/dist/agents/prompts/plan.d.ts +2 -0
  37. package/dist/agents/prompts/plan.d.ts.map +1 -1
  38. package/dist/agents/prompts/plan.js +10 -8
  39. package/dist/agents/prompts/plan.js.map +1 -1
  40. package/dist/agents/sandbox-filesystem.d.ts +25 -0
  41. package/dist/agents/sandbox-filesystem.d.ts.map +1 -1
  42. package/dist/agents/sandbox-filesystem.js +47 -6
  43. package/dist/agents/sandbox-filesystem.js.map +1 -1
  44. package/dist/auth/account-rotation-processor.d.ts +23 -0
  45. package/dist/auth/account-rotation-processor.d.ts.map +1 -1
  46. package/dist/auth/account-rotation-processor.js +63 -1
  47. package/dist/auth/account-rotation-processor.js.map +1 -1
  48. package/dist/auth/index.js +2 -2
  49. package/dist/auth/storage.d.ts +8 -0
  50. package/dist/auth/storage.d.ts.map +1 -1
  51. package/dist/auth/storage.js +37 -3
  52. package/dist/auth/storage.js.map +1 -1
  53. package/dist/experimental-agent.d.ts +8 -0
  54. package/dist/experimental-agent.d.ts.map +1 -1
  55. package/dist/experimental-agent.js +12 -1
  56. package/dist/experimental-agent.js.map +1 -1
  57. package/dist/headless/cli.d.ts.map +1 -1
  58. package/dist/headless/cli.js +2 -1
  59. package/dist/headless/cli.js.map +1 -1
  60. package/dist/index.d.ts +2 -0
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +21 -9
  63. package/dist/index.js.map +1 -1
  64. package/dist/onboarding/settings.d.ts +4 -0
  65. package/dist/onboarding/settings.d.ts.map +1 -1
  66. package/dist/onboarding/settings.js +6 -2
  67. package/dist/onboarding/settings.js.map +1 -1
  68. package/dist/schedules/scheduler.d.ts.map +1 -1
  69. package/dist/schedules/scheduler.js +3 -2
  70. package/dist/schedules/scheduler.js.map +1 -1
  71. package/dist/utils/token-estimator.d.ts.map +1 -1
  72. package/dist/utils/token-estimator.js +2 -1
  73. package/dist/utils/token-estimator.js.map +1 -1
  74. package/package.json +11 -11
@@ -1,8 +1,10 @@
1
1
  import { DEFAULT_CONFIG_DIR } from "../../constants.js";
2
2
  import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from "path";
3
+ import { createHash } from "crypto";
3
4
  import { existsSync, readFileSync, realpathSync, statSync } from "fs";
4
- import { execFileSync } from "child_process";
5
+ import { execFileSync, spawn } from "child_process";
5
6
  import { homedir } from "os";
7
+ import { readFile, realpath, stat } from "fs/promises";
6
8
  // src/agents/prompts/agent-instructions.ts
7
9
  /**
8
10
  * Load project and global agent instruction files (AGENTS.md, CLAUDE.md).
@@ -46,36 +48,124 @@ function createProjectPathResolver(projectPath) {
46
48
  }
47
49
  };
48
50
  }
51
+ const GIT_OBJECT_CACHE_MAX_CHARS = 16777216;
52
+ const gitObjectOutputs = /* @__PURE__ */ new Map();
53
+ let gitObjectCacheChars = 0;
54
+ function gitObjectRead(projectPath, args, matchesId = () => true) {
55
+ const key = args.join("\0");
56
+ const cached = gitObjectOutputs.get(key);
57
+ if (cached !== void 0) return cached;
58
+ try {
59
+ const raw = execFileSync("git", [
60
+ "--no-replace-objects",
61
+ "-C",
62
+ projectPath,
63
+ "--literal-pathspecs",
64
+ ...args
65
+ ], {
66
+ stdio: [
67
+ "ignore",
68
+ "pipe",
69
+ "ignore"
70
+ ],
71
+ maxBuffer: 1048576
72
+ });
73
+ if (!matchesId(raw)) return null;
74
+ const output = raw.toString("utf-8");
75
+ gitObjectOutputs.set(key, output);
76
+ gitObjectCacheChars += key.length + output.length;
77
+ for (const [oldest, evicted] of gitObjectOutputs) {
78
+ if (gitObjectCacheChars <= GIT_OBJECT_CACHE_MAX_CHARS) break;
79
+ gitObjectOutputs.delete(oldest);
80
+ gitObjectCacheChars -= oldest.length + evicted.length;
81
+ }
82
+ return output;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+ function blobMatchesId(id, content) {
88
+ return createHash(id.length === 40 ? "sha1" : "sha256").update(`blob ${content.length}\0`).update(content).digest("hex") === id;
89
+ }
90
+ function createGitRefLookup(projectPath, ref) {
91
+ let trees;
92
+ const resolveTrees = () => {
93
+ if ([...ref].some((char) => char <= " " || char === "")) return [];
94
+ try {
95
+ const output = execFileSync("git", [
96
+ "-C",
97
+ projectPath,
98
+ "cat-file",
99
+ "--batch-check=%(objectname)"
100
+ ], {
101
+ encoding: "utf-8",
102
+ input: `origin/${ref}^{tree}\n${ref}^{tree}\n`,
103
+ stdio: [
104
+ "pipe",
105
+ "pipe",
106
+ "ignore"
107
+ ]
108
+ });
109
+ return [...new Set(output.split("\n").filter((line) => /^[0-9a-f]+$/.test(line)))];
110
+ } catch {
111
+ return [];
112
+ }
113
+ };
114
+ const entryAt = (tree, rel) => {
115
+ let entry = [
116
+ "",
117
+ "tree",
118
+ tree
119
+ ];
120
+ for (const name of rel.split("/")) {
121
+ if (entry[1] !== "tree") return [];
122
+ entry = gitObjectRead(projectPath, [
123
+ "ls-tree",
124
+ "--full-tree",
125
+ entry[2],
126
+ "--",
127
+ name
128
+ ])?.split(/\s/) ?? [];
129
+ }
130
+ return entry;
131
+ };
132
+ return {
133
+ type: (rel) => {
134
+ for (const tree of trees ??= resolveTrees()) {
135
+ const [, type] = entryAt(tree, rel);
136
+ if (type) return type;
137
+ }
138
+ return null;
139
+ },
140
+ show: (rel) => {
141
+ for (const tree of trees ??= resolveTrees()) {
142
+ const [, type, blob] = entryAt(tree, rel);
143
+ if (type !== "blob" || !blob) continue;
144
+ const content = gitObjectRead(projectPath, [
145
+ "cat-file",
146
+ "blob",
147
+ blob
148
+ ], (raw) => blobMatchesId(blob, raw));
149
+ if (content !== null) return content;
150
+ }
151
+ return null;
152
+ }
153
+ };
154
+ }
49
155
  /**
50
156
  * Create a reader that serves instruction files from a git ref instead of the
51
157
  * working tree. Paths are still addressed as working-tree paths under
52
- * `projectPath`; content comes from `git show <ref>:<relpath>` so an untrusted
158
+ * `projectPath`; content comes from the blob at `<ref>:<relpath>` so an untrusted
53
159
  * checkout (e.g. a PR branch under review) cannot influence what is loaded.
54
160
  * Tries `origin/<ref>` first (remote truth), then the local ref. Any git
55
161
  * failure (missing ref, missing file, no repo) reports the file as absent.
56
162
  */
57
163
  function createGitRefInstructionReader(projectPath, ref) {
58
164
  const toRelative = createProjectPathResolver(projectPath);
165
+ const lookup = createGitRefLookup(projectPath, ref);
59
166
  const show = (path) => {
60
167
  const rel = toRelative(path);
61
- if (!rel) return null;
62
- for (const candidate of [`origin/${ref}`, ref]) try {
63
- return execFileSync("git", [
64
- "-C",
65
- projectPath,
66
- "show",
67
- `${candidate}:${rel}`
68
- ], {
69
- encoding: "utf-8",
70
- stdio: [
71
- "ignore",
72
- "pipe",
73
- "ignore"
74
- ],
75
- maxBuffer: 1048576
76
- });
77
- } catch {}
78
- return null;
168
+ return rel ? lookup.show(rel) : null;
79
169
  };
80
170
  return {
81
171
  ref,
@@ -95,28 +185,12 @@ function createGitRefInstructionReader(projectPath, ref) {
95
185
  * working tree, so an untrusted checkout cannot feed content in.
96
186
  */
97
187
  function createGitRefReminderReader(projectPath, ref) {
98
- const gitReader = createGitRefInstructionReader(projectPath, ref);
99
188
  const toRelative = createProjectPathResolver(projectPath);
100
189
  const canonicalRoot = realpathOrResolved(projectPath);
190
+ const lookup = createGitRefLookup(projectPath, ref);
101
191
  const objectType = (rel) => {
102
192
  if (rel === "") return "tree";
103
- for (const candidate of [`origin/${ref}`, ref]) try {
104
- return execFileSync("git", [
105
- "-C",
106
- projectPath,
107
- "cat-file",
108
- "-t",
109
- `${candidate}:${rel}`
110
- ], {
111
- encoding: "utf-8",
112
- stdio: [
113
- "ignore",
114
- "pipe",
115
- "ignore"
116
- ]
117
- }).trim();
118
- } catch {}
119
- return null;
193
+ return lookup.type(rel);
120
194
  };
121
195
  return {
122
196
  pathExists: (path) => {
@@ -134,8 +208,11 @@ function createGitRefReminderReader(projectPath, ref) {
134
208
  return objectType(rel) === "tree";
135
209
  },
136
210
  readFile: (path) => {
137
- if (toRelative(path) === null) return readFileSync(path, "utf-8");
138
- return gitReader.read(path);
211
+ const rel = toRelative(path);
212
+ if (rel === null) return readFileSync(path, "utf-8");
213
+ const content = rel ? lookup.show(rel) : null;
214
+ if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);
215
+ return content;
139
216
  },
140
217
  getPathIdentity: (path) => {
141
218
  const rel = toRelative(path);
@@ -143,6 +220,274 @@ function createGitRefReminderReader(projectPath, ref) {
143
220
  }
144
221
  };
145
222
  }
223
+ const pendingGitObjects = /* @__PURE__ */ new Map();
224
+ function gitAsync(args, input) {
225
+ return new Promise((resolveOutput) => {
226
+ let child;
227
+ try {
228
+ child = spawn("git", args, { stdio: [
229
+ input === void 0 ? "ignore" : "pipe",
230
+ "pipe",
231
+ "ignore"
232
+ ] });
233
+ } catch {
234
+ resolveOutput(null);
235
+ return;
236
+ }
237
+ const chunks = [];
238
+ let size = 0;
239
+ let failed = false;
240
+ child.stdout?.on("data", (chunk) => {
241
+ size += chunk.length;
242
+ if (size > 1048576) {
243
+ failed = true;
244
+ child.kill();
245
+ } else chunks.push(chunk);
246
+ });
247
+ child.on("error", () => {
248
+ failed = true;
249
+ });
250
+ child.on("close", (code) => resolveOutput(!failed && code === 0 ? Buffer.concat(chunks) : null));
251
+ if (input !== void 0) {
252
+ child.stdin?.on("error", () => {
253
+ failed = true;
254
+ });
255
+ child.stdin?.end(input);
256
+ }
257
+ });
258
+ }
259
+ async function gitObjectReadAsync(projectPath, args, matchesId = () => true) {
260
+ const key = args.join("\0");
261
+ const cached = gitObjectOutputs.get(key);
262
+ if (cached !== void 0) return cached;
263
+ const pendingKey = `${projectPath}\0${key}`;
264
+ let pending = pendingGitObjects.get(pendingKey);
265
+ if (!pending) {
266
+ pending = (async () => {
267
+ const raw = await gitAsync([
268
+ "--no-replace-objects",
269
+ "-C",
270
+ projectPath,
271
+ "--literal-pathspecs",
272
+ ...args
273
+ ]);
274
+ if (!raw || !matchesId(raw)) return null;
275
+ const output = raw.toString("utf-8");
276
+ gitObjectOutputs.set(key, output);
277
+ gitObjectCacheChars += key.length + output.length;
278
+ for (const [oldest, evicted] of gitObjectOutputs) {
279
+ if (gitObjectCacheChars <= GIT_OBJECT_CACHE_MAX_CHARS) break;
280
+ gitObjectOutputs.delete(oldest);
281
+ gitObjectCacheChars -= oldest.length + evicted.length;
282
+ }
283
+ return output;
284
+ })();
285
+ pendingGitObjects.set(pendingKey, pending);
286
+ pending.then(() => pendingGitObjects.delete(pendingKey), () => pendingGitObjects.delete(pendingKey));
287
+ }
288
+ return pending;
289
+ }
290
+ async function realpathOrResolvedAsync(path) {
291
+ try {
292
+ return await realpath(path);
293
+ } catch {
294
+ return resolve(path);
295
+ }
296
+ }
297
+ async function createProjectPathResolverAsync(projectPath) {
298
+ const canonicalRoot = await realpathOrResolvedAsync(projectPath);
299
+ return async (path) => {
300
+ const rel = relative(projectPath, path);
301
+ if (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)) return rel.split(sep).join("/");
302
+ let ancestor = resolve(path);
303
+ let projectRelativePath = null;
304
+ while (true) {
305
+ if (await realpathOrResolvedAsync(ancestor) === canonicalRoot) projectRelativePath = relative(ancestor, path).split(sep).join("/");
306
+ const parent = dirname(ancestor);
307
+ if (parent === ancestor) return projectRelativePath;
308
+ ancestor = parent;
309
+ }
310
+ };
311
+ }
312
+ function createGitRefLookupAsync(projectPath, ref) {
313
+ let trees;
314
+ const resolveTrees = async () => {
315
+ if ([...ref].some((char) => char <= " " || char === "")) return [];
316
+ const raw = await gitAsync([
317
+ "-C",
318
+ projectPath,
319
+ "cat-file",
320
+ "--batch-check=%(objectname)"
321
+ ], `origin/${ref}^{tree}\n${ref}^{tree}\n`);
322
+ return raw ? [...new Set(raw.toString("utf-8").split("\n").filter((line) => /^[0-9a-f]+$/.test(line)))] : [];
323
+ };
324
+ const entryAt = async (tree, rel) => {
325
+ let entry = [
326
+ "",
327
+ "tree",
328
+ tree
329
+ ];
330
+ for (const name of rel.split("/")) {
331
+ if (entry[1] !== "tree") return [];
332
+ entry = (await gitObjectReadAsync(projectPath, [
333
+ "ls-tree",
334
+ "--full-tree",
335
+ entry[2],
336
+ "--",
337
+ name
338
+ ]))?.split(/\s/) ?? [];
339
+ }
340
+ return entry;
341
+ };
342
+ return {
343
+ type: async (rel) => {
344
+ for (const tree of await (trees ??= resolveTrees())) {
345
+ const [, type] = await entryAt(tree, rel);
346
+ if (type) return type;
347
+ }
348
+ return null;
349
+ },
350
+ show: async (rel) => {
351
+ for (const tree of await (trees ??= resolveTrees())) {
352
+ const [, type, blob] = await entryAt(tree, rel);
353
+ if (type !== "blob" || !blob) continue;
354
+ const content = await gitObjectReadAsync(projectPath, [
355
+ "cat-file",
356
+ "blob",
357
+ blob
358
+ ], (raw) => blobMatchesId(blob, raw));
359
+ if (content !== null) return content;
360
+ }
361
+ return null;
362
+ }
363
+ };
364
+ }
365
+ async function createGitRefInstructionReaderAsync(projectPath, ref) {
366
+ const toRelative = await createProjectPathResolverAsync(projectPath);
367
+ const lookup = createGitRefLookupAsync(projectPath, ref);
368
+ const show = async (path) => {
369
+ const rel = await toRelative(path);
370
+ return rel ? lookup.show(rel) : null;
371
+ };
372
+ return {
373
+ ref,
374
+ exists: async (path) => await show(path) !== null,
375
+ read: async (path) => {
376
+ const content = await show(path);
377
+ if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);
378
+ return content;
379
+ }
380
+ };
381
+ }
382
+ function createGitRefReminderReaderAsync(projectPath, ref) {
383
+ const toRelative = createProjectPathResolverAsync(projectPath);
384
+ const canonicalRoot = realpathOrResolvedAsync(projectPath);
385
+ const lookup = createGitRefLookupAsync(projectPath, ref);
386
+ const objectType = (rel) => rel === "" ? Promise.resolve("tree") : lookup.type(rel);
387
+ return {
388
+ pathExists: async (path) => {
389
+ const rel = await (await toRelative)(path);
390
+ if (rel === null) try {
391
+ await stat(path);
392
+ return true;
393
+ } catch {
394
+ return false;
395
+ }
396
+ return await objectType(rel) !== null;
397
+ },
398
+ isDirectory: async (path) => {
399
+ const rel = await (await toRelative)(path);
400
+ if (rel === null) try {
401
+ return (await stat(path)).isDirectory();
402
+ } catch {
403
+ return false;
404
+ }
405
+ return await objectType(rel) === "tree";
406
+ },
407
+ readFile: async (path) => {
408
+ const rel = await (await toRelative)(path);
409
+ if (rel === null) return readFile(path, "utf-8");
410
+ const content = rel ? await lookup.show(rel) : null;
411
+ if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);
412
+ return content;
413
+ },
414
+ getPathIdentity: async (path) => {
415
+ const rel = await (await toRelative)(path);
416
+ return rel === null ? realpathOrResolvedAsync(path) : join(await canonicalRoot, rel);
417
+ }
418
+ };
419
+ }
420
+ const fsInstructionReaderAsync = {
421
+ exists: async (path) => {
422
+ try {
423
+ await stat(path);
424
+ return true;
425
+ } catch {
426
+ return false;
427
+ }
428
+ },
429
+ read: (path) => readFile(path, "utf-8")
430
+ };
431
+ async function loadAgentInstructionsAsync(projectPath, configDirName = DEFAULT_CONFIG_DIR, projectReader = fsInstructionReaderAsync, { skipGlobal = false } = {}) {
432
+ const sources = [];
433
+ const projectLocations = PROJECT_LOCATIONS.map((loc) => loc === ".mastracode" ? configDirName : loc);
434
+ const globalLocations = skipGlobal ? [] : GLOBAL_LOCATIONS.map((loc) => {
435
+ if (loc === ".mastracode") return configDirName;
436
+ if (loc === ".config/mastracode") return ".config/" + configDirName.replace(/^\./, "");
437
+ return loc;
438
+ });
439
+ for (const location of globalLocations) {
440
+ const base = join(homedir(), location);
441
+ for (const filename of INSTRUCTION_FILES) {
442
+ const path = join(base, filename);
443
+ if (!await fsInstructionReaderAsync.exists(path)) continue;
444
+ try {
445
+ const content = (await fsInstructionReaderAsync.read(path)).trim();
446
+ if (content) {
447
+ sources.push({
448
+ path,
449
+ content,
450
+ scope: "global"
451
+ });
452
+ break;
453
+ }
454
+ } catch {}
455
+ break;
456
+ }
457
+ if (sources.length) break;
458
+ }
459
+ for (const location of projectLocations) {
460
+ const base = location ? join(projectPath, location) : projectPath;
461
+ for (const filename of INSTRUCTION_FILES) {
462
+ const path = join(base, filename);
463
+ if (!await projectReader.exists(path)) continue;
464
+ try {
465
+ const content = (await projectReader.read(path)).trim();
466
+ if (content) {
467
+ sources.push({
468
+ path,
469
+ content,
470
+ scope: "project",
471
+ ...projectReader.ref ? { ref: projectReader.ref } : {}
472
+ });
473
+ break;
474
+ }
475
+ } catch {}
476
+ break;
477
+ }
478
+ if (sources.some((source) => source.scope === "project")) break;
479
+ }
480
+ return sources;
481
+ }
482
+ async function loadSessionInstructionsAsync({ workingDir, instructionRoots, configDir, untrustedCheckout = false, baseRef, skipGlobal = false }) {
483
+ const [primary, ...others] = sessionInstructionRoots(workingDir, instructionRoots);
484
+ const sources = await loadAgentInstructionsAsync(primary, configDir, untrustedCheckout ? baseRef ? await createGitRefInstructionReaderAsync(primary, baseRef) : {
485
+ exists: async () => false,
486
+ read: async () => ""
487
+ } : void 0, { skipGlobal });
488
+ if (!untrustedCheckout) for (const root of others) sources.push(...await loadAgentInstructionsAsync(root, configDir, void 0, { skipGlobal: true }));
489
+ return sources;
490
+ }
146
491
  /**
147
492
  * Find the first existing instruction file at a given base path.
148
493
  * Prefers AGENTS.md over CLAUDE.md.
@@ -269,6 +614,6 @@ function formatAgentInstructions(sources) {
269
614
  const sections = sources.map(formatInstructionSource);
270
615
  return `\n${AGENT_INSTRUCTIONS_HEADING}\n\n${sections.join("\n\n")}\n`;
271
616
  }
272
- export { AGENT_INSTRUCTIONS_HEADING, createGitRefInstructionReader, createGitRefReminderReader, formatAgentInstructions, formatInstructionSource, getStaticallyLoadedInstructionPaths, instructionSourcePaths, loadAgentInstructions, loadSessionInstructions, sessionInstructionRoots };
617
+ export { AGENT_INSTRUCTIONS_HEADING, createGitRefInstructionReader, createGitRefInstructionReaderAsync, createGitRefReminderReader, createGitRefReminderReaderAsync, formatAgentInstructions, formatInstructionSource, getStaticallyLoadedInstructionPaths, instructionSourcePaths, loadAgentInstructions, loadAgentInstructionsAsync, loadSessionInstructions, loadSessionInstructionsAsync, sessionInstructionRoots };
273
618
 
274
619
  //# 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 { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, normalize, relative, resolve, 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\nfunction realpathOrResolved(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return resolve(path);\n }\n}\n\nfunction createProjectPathResolver(projectPath: string): (path: string) => string | null {\n const canonicalRoot = realpathOrResolved(projectPath);\n return path => {\n const rel = relative(projectPath, path);\n if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)) return rel.split(sep).join('/');\n\n // Match an alias of the project root, not the target of a checkout-controlled\n // descendant symlink. Missing descendants must still resolve against the ref.\n let ancestor = resolve(path);\n let projectRelativePath: string | null = null;\n while (true) {\n if (realpathOrResolved(ancestor) === canonicalRoot) {\n projectRelativePath = relative(ancestor, path).split(sep).join('/');\n }\n const parent = dirname(ancestor);\n if (parent === ancestor) return projectRelativePath;\n ancestor = parent;\n }\n };\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 = createProjectPathResolver(projectPath);\n const show = (path: string): string | null => {\n const rel = toRelative(path);\n if (!rel) 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 getPathIdentity: (path: string) => string;\n} {\n const gitReader = createGitRefInstructionReader(projectPath, ref);\n const toRelative = createProjectPathResolver(projectPath);\n const canonicalRoot = realpathOrResolved(projectPath);\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 getPathIdentity: path => {\n const rel = toRelative(path);\n // Only canonicalize the project root: checkout symlinks do not define\n // file identity in the trusted ref, including files missing on disk.\n return rel === null ? realpathOrResolved(path) : join(canonicalRoot, rel);\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 read the operator machine's\n * filesystem, unless `skipGlobal` keeps them out entirely.\n */\nexport function loadAgentInstructions(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: InstructionFileReader = fsInstructionReader,\n { skipGlobal = false }: { skipGlobal?: boolean } = {},\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 = skipGlobal\n ? []\n : 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 instructionSourcePaths(loadAgentInstructions(projectPath, configDirName, projectReader), [projectPath]);\n}\n\n/**\n * Directories a session's project instructions load from: the host's\n * `instructionRoots` (resolved against the working directory, the session's\n * own checkout first) when it sets any, else the working directory itself.\n */\nexport function sessionInstructionRoots(workingDir: string, instructionRoots?: readonly string[]): string[] {\n if (!instructionRoots?.length) return [workingDir];\n return [...new Set(instructionRoots.map(root => resolve(workingDir, root)))];\n}\n\n/**\n * The instruction files a session's system prompt carries. Global files load\n * once (unless `skipGlobal`), then each instruction root's project files, in\n * root order. An untrusted checkout never reads project files off the working\n * tree: with a `baseRef` the first root (the session's own checkout) is served\n * from that ref and the other roots are skipped; without one no project files\n * load.\n */\nexport function loadSessionInstructions({\n workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout = false,\n baseRef,\n skipGlobal = false,\n}: {\n workingDir: string;\n instructionRoots?: readonly string[];\n configDir?: string;\n untrustedCheckout?: boolean;\n baseRef?: string;\n skipGlobal?: boolean;\n}): InstructionSource[] {\n const [primary, ...others] = sessionInstructionRoots(workingDir, instructionRoots);\n const primaryReader = untrustedCheckout\n ? baseRef\n ? createGitRefInstructionReader(primary!, baseRef)\n : { exists: () => false, read: () => '' }\n : undefined;\n const sources = loadAgentInstructions(primary!, configDir, primaryReader, { skipGlobal });\n if (untrustedCheckout) return sources;\n for (const root of others) {\n sources.push(...loadAgentInstructions(root, configDir, undefined, { skipGlobal: true }));\n }\n return sources;\n}\n\n/**\n * Paths of loaded instruction sources, each project source also under its\n * root's canonical path, so reactive reminders never repeat a file the\n * system prompt already carries.\n */\nexport function instructionSourcePaths(sources: InstructionSource[], roots: readonly string[]): string[] {\n return sources.flatMap(source => {\n const path = normalize(source.path);\n if (source.scope !== 'project') return [path];\n const root = roots.find(candidate => {\n const rel = relative(candidate, path);\n return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);\n });\n if (!root) return [path];\n const canonicalPath = join(realpathOrResolved(root), relative(root, path));\n return path === canonicalPath ? [path] : [path, canonicalPath];\n });\n}\n\n/** Heading the agent-instructions block is introduced by in the system prompt. */\nexport const AGENT_INSTRUCTIONS_HEADING = '# Agent Instructions';\n\n/**\n * Format a single instruction source as it appears in the system prompt.\n *\n * Exported so callers that attribute prompt cost per source (the `/context`\n * audit) measure the exact block that is sent rather than reconstructing it.\n */\nexport function formatInstructionSource(source: InstructionSource): string {\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/**\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(formatInstructionSource);\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AAI,CAAC,MAAM,OAAO,CAAC,IAAI;EACvB,MAAM,gBAAgB,KAAK,mBAAmB,IAAI,GAAG,SAAS,MAAM,IAAI,CAAC;EACzE,OAAO,SAAS,gBAAgB,CAAC,IAAI,IAAI,CAAC,MAAM,aAAa;CAC/D,CAAC;AACH;;AAGA,MAAa,6BAA6B;;;;;;;AAQ1C,SAAgB,wBAAwB,QAAmC;CAGzE,OAAO,QAFO,OAAO,UAAU,WAAW,WAAW,UAEhC,qBADN,OAAO,MAAM,GAAG,OAAO,KAAK,WAAW,OAAO,IAAI,KAAK,OAAO,KAC5B,QAAQ,OAAO;AAClE;;;;AAKA,SAAgB,wBAAwB,SAAsC;CAC5E,IAAI,QAAQ,WAAW,GAAG,OAAO;CAEjC,MAAM,WAAW,QAAQ,IAAI,uBAAuB;CAEpD,OAAO,KAAK,2BAA2B,MAAM,SAAS,KAAK,MAAM,EAAE;AACrE"}
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, spawn } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';\nimport { readFile, realpath, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, normalize, relative, resolve, 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\nfunction realpathOrResolved(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return resolve(path);\n }\n}\n\nfunction createProjectPathResolver(projectPath: string): (path: string) => string | null {\n const canonicalRoot = realpathOrResolved(projectPath);\n return path => {\n const rel = relative(projectPath, path);\n if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)) return rel.split(sep).join('/');\n\n // Match an alias of the project root, not the target of a checkout-controlled\n // descendant symlink. Missing descendants must still resolve against the ref.\n let ancestor = resolve(path);\n let projectRelativePath: string | null = null;\n while (true) {\n if (realpathOrResolved(ancestor) === canonicalRoot) {\n projectRelativePath = relative(ancestor, path).split(sep).join('/');\n }\n const parent = dirname(ancestor);\n if (parent === ancestor) return projectRelativePath;\n ancestor = parent;\n }\n };\n}\n\n// Keys count towards the limit too: a path a folder lacks is cached as an empty listing.\nconst GIT_OBJECT_CACHE_MAX_CHARS = 16 * 1024 * 1024;\nconst gitObjectOutputs = new Map<string, string>();\nlet gitObjectCacheChars = 0;\n\n// The cache is shared by every checkout in the process, so a read is kept only once it is known to\n// match its id: git checks the tree it is asked to list, and `matchesId` covers what git does not check.\n// A blobless clone fetches file content over the network, so a failed read is never cached.\nfunction gitObjectRead(\n projectPath: string,\n args: string[],\n matchesId: (output: Buffer) => boolean = () => true,\n): string | null {\n const key = args.join('\\0');\n const cached = gitObjectOutputs.get(key);\n if (cached !== undefined) return cached;\n try {\n const raw = execFileSync('git', ['--no-replace-objects', '-C', projectPath, '--literal-pathspecs', ...args], {\n stdio: ['ignore', 'pipe', 'ignore'],\n maxBuffer: 1024 * 1024,\n });\n if (!matchesId(raw)) return null;\n const output = raw.toString('utf-8');\n gitObjectOutputs.set(key, output);\n gitObjectCacheChars += key.length + output.length;\n for (const [oldest, evicted] of gitObjectOutputs) {\n if (gitObjectCacheChars <= GIT_OBJECT_CACHE_MAX_CHARS) break;\n gitObjectOutputs.delete(oldest);\n gitObjectCacheChars -= oldest.length + evicted.length;\n }\n return output;\n } catch {\n return null;\n }\n}\n\nfunction blobMatchesId(id: string, content: Buffer): boolean {\n const hash = createHash(id.length === 40 ? 'sha1' : 'sha256');\n return hash.update(`blob ${content.length}\\0`).update(content).digest('hex') === id;\n}\n\nfunction createGitRefLookup(projectPath: string, ref: string) {\n // Resolved on first use and kept, so a lookup reads the ref as it stood then: build one per model step.\n let trees: string[] | undefined;\n const resolveTrees = (): string[] => {\n // A ref name never holds a space or control character, and each line of the batch below names\n // one object, so a line break in `ref` would add names of its own, such as the checkout's `HEAD`.\n if ([...ref].some(char => char <= ' ' || char === '\\x7f')) return [];\n try {\n const output = execFileSync('git', ['-C', projectPath, 'cat-file', '--batch-check=%(objectname)'], {\n encoding: 'utf-8',\n input: `origin/${ref}^{tree}\\n${ref}^{tree}\\n`,\n stdio: ['pipe', 'pipe', 'ignore'],\n });\n return [...new Set(output.split('\\n').filter(line => /^[0-9a-f]+$/.test(line)))];\n } catch {\n return [];\n }\n };\n // One folder level per call: git hash-checks the tree it lists, not the trees it walks through.\n const entryAt = (tree: string, rel: string): string[] => {\n let entry = ['', 'tree', tree];\n for (const name of rel.split('/')) {\n if (entry[1] !== 'tree') return [];\n entry = gitObjectRead(projectPath, ['ls-tree', '--full-tree', entry[2]!, '--', name])?.split(/\\s/) ?? [];\n }\n return entry;\n };\n return {\n type: (rel: string): string | null => {\n for (const tree of (trees ??= resolveTrees())) {\n const [, type] = entryAt(tree, rel);\n if (type) return type;\n }\n return null;\n },\n show: (rel: string): string | null => {\n for (const tree of (trees ??= resolveTrees())) {\n const [, type, blob] = entryAt(tree, rel);\n if (type !== 'blob' || !blob) continue;\n const content = gitObjectRead(projectPath, ['cat-file', 'blob', blob], raw => blobMatchesId(blob, raw));\n if (content !== null) return content;\n }\n return null;\n },\n };\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 the blob at `<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 = createProjectPathResolver(projectPath);\n const lookup = createGitRefLookup(projectPath, ref);\n const show = (path: string): string | null => {\n const rel = toRelative(path);\n return rel ? lookup.show(rel) : 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 getPathIdentity: (path: string) => string;\n} {\n const toRelative = createProjectPathResolver(projectPath);\n const canonicalRoot = realpathOrResolved(projectPath);\n const lookup = createGitRefLookup(projectPath, ref);\n const objectType = (rel: string): string | null => {\n if (rel === '') return 'tree'; // project root\n return lookup.type(rel);\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 const content = rel ? lookup.show(rel) : null;\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n getPathIdentity: path => {\n const rel = toRelative(path);\n // Only canonicalize the project root: checkout symlinks do not define\n // file identity in the trusted ref, including files missing on disk.\n return rel === null ? realpathOrResolved(path) : join(canonicalRoot, rel);\n },\n };\n}\n\n// Keep in-flight object reads shared across concurrent prompt and reminder lookups.\nconst pendingGitObjects = new Map<string, Promise<string | null>>();\n\nfunction gitAsync(args: string[], input?: string): Promise<Buffer | null> {\n return new Promise(resolveOutput => {\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn('git', args, { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'] });\n } catch {\n resolveOutput(null);\n return;\n }\n const chunks: Buffer[] = [];\n let size = 0;\n let failed = false;\n child.stdout?.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (size > 1024 * 1024) {\n failed = true;\n child.kill();\n } else chunks.push(chunk);\n });\n child.on('error', () => {\n failed = true;\n });\n child.on('close', code => resolveOutput(!failed && code === 0 ? Buffer.concat(chunks) : null));\n if (input !== undefined) {\n child.stdin?.on('error', () => {\n failed = true;\n });\n child.stdin?.end(input);\n }\n });\n}\n\nasync function gitObjectReadAsync(\n projectPath: string,\n args: string[],\n matchesId: (raw: Buffer) => boolean = () => true,\n): Promise<string | null> {\n const key = args.join('\\0');\n const cached = gitObjectOutputs.get(key);\n if (cached !== undefined) return cached;\n const pendingKey = `${projectPath}\\0${key}`;\n let pending = pendingGitObjects.get(pendingKey);\n if (!pending) {\n pending = (async () => {\n const raw = await gitAsync(['--no-replace-objects', '-C', projectPath, '--literal-pathspecs', ...args]);\n if (!raw || !matchesId(raw)) return null;\n const output = raw.toString('utf-8');\n gitObjectOutputs.set(key, output);\n gitObjectCacheChars += key.length + output.length;\n for (const [oldest, evicted] of gitObjectOutputs) {\n if (gitObjectCacheChars <= GIT_OBJECT_CACHE_MAX_CHARS) break;\n gitObjectOutputs.delete(oldest);\n gitObjectCacheChars -= oldest.length + evicted.length;\n }\n return output;\n })();\n pendingGitObjects.set(pendingKey, pending);\n void pending.then(\n () => pendingGitObjects.delete(pendingKey),\n () => pendingGitObjects.delete(pendingKey),\n );\n }\n return pending;\n}\n\nasync function realpathOrResolvedAsync(path: string): Promise<string> {\n try {\n return await realpath(path);\n } catch {\n return resolve(path);\n }\n}\n\nasync function createProjectPathResolverAsync(projectPath: string): Promise<(path: string) => Promise<string | null>> {\n const canonicalRoot = await realpathOrResolvedAsync(projectPath);\n return async path => {\n const rel = relative(projectPath, path);\n if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)) return rel.split(sep).join('/');\n let ancestor = resolve(path);\n let projectRelativePath: string | null = null;\n while (true) {\n if ((await realpathOrResolvedAsync(ancestor)) === canonicalRoot) {\n projectRelativePath = relative(ancestor, path).split(sep).join('/');\n }\n const parent = dirname(ancestor);\n if (parent === ancestor) return projectRelativePath;\n ancestor = parent;\n }\n };\n}\n\nfunction createGitRefLookupAsync(projectPath: string, ref: string) {\n let trees: Promise<string[]> | undefined;\n const resolveTrees = async (): Promise<string[]> => {\n if ([...ref].some(char => char <= ' ' || char === '\\x7f')) return [];\n const raw = await gitAsync(\n ['-C', projectPath, 'cat-file', '--batch-check=%(objectname)'],\n `origin/${ref}^{tree}\\n${ref}^{tree}\\n`,\n );\n return raw\n ? [\n ...new Set(\n raw\n .toString('utf-8')\n .split('\\n')\n .filter(line => /^[0-9a-f]+$/.test(line)),\n ),\n ]\n : [];\n };\n const entryAt = async (tree: string, rel: string): Promise<string[]> => {\n let entry = ['', 'tree', tree];\n for (const name of rel.split('/')) {\n if (entry[1] !== 'tree') return [];\n entry =\n (await gitObjectReadAsync(projectPath, ['ls-tree', '--full-tree', entry[2]!, '--', name]))?.split(/\\s/) ?? [];\n }\n return entry;\n };\n return {\n type: async (rel: string): Promise<string | null> => {\n for (const tree of await (trees ??= resolveTrees())) {\n const [, type] = await entryAt(tree, rel);\n if (type) return type;\n }\n return null;\n },\n show: async (rel: string): Promise<string | null> => {\n for (const tree of await (trees ??= resolveTrees())) {\n const [, type, blob] = await entryAt(tree, rel);\n if (type !== 'blob' || !blob) continue;\n const content = await gitObjectReadAsync(projectPath, ['cat-file', 'blob', blob], raw =>\n blobMatchesId(blob, raw),\n );\n if (content !== null) return content;\n }\n return null;\n },\n };\n}\n\nexport async function createGitRefInstructionReaderAsync(\n projectPath: string,\n ref: string,\n): Promise<AsyncInstructionFileReader> {\n const toRelative = await createProjectPathResolverAsync(projectPath);\n const lookup = createGitRefLookupAsync(projectPath, ref);\n const show = async (path: string) => {\n const rel = await toRelative(path);\n return rel ? lookup.show(rel) : null;\n };\n return {\n ref,\n exists: async path => (await show(path)) !== null,\n read: async path => {\n const content = await show(path);\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n };\n}\n\nexport function createGitRefReminderReaderAsync(projectPath: string, ref: string) {\n const toRelative = createProjectPathResolverAsync(projectPath);\n const canonicalRoot = realpathOrResolvedAsync(projectPath);\n const lookup = createGitRefLookupAsync(projectPath, ref);\n const objectType = (rel: string) => (rel === '' ? Promise.resolve('tree') : lookup.type(rel));\n return {\n pathExists: async (path: string) => {\n const rel = await (await toRelative)(path);\n if (rel === null) {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n }\n return (await objectType(rel)) !== null;\n },\n isDirectory: async (path: string) => {\n const rel = await (await toRelative)(path);\n if (rel === null) {\n try {\n return (await stat(path)).isDirectory();\n } catch {\n return false;\n }\n }\n return (await objectType(rel)) === 'tree';\n },\n readFile: async (path: string) => {\n const rel = await (await toRelative)(path);\n if (rel === null) return readFile(path, 'utf-8');\n const content = rel ? await lookup.show(rel) : null;\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n getPathIdentity: async (path: string) => {\n const rel = await (await toRelative)(path);\n return rel === null ? realpathOrResolvedAsync(path) : join(await canonicalRoot, rel);\n },\n };\n}\n\nexport interface AsyncInstructionFileReader {\n exists(path: string): Promise<boolean>;\n read(path: string): Promise<string>;\n ref?: string;\n}\n\nconst fsInstructionReaderAsync: AsyncInstructionFileReader = {\n exists: async path => {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n },\n read: path => readFile(path, 'utf-8'),\n};\n\nexport async function loadAgentInstructionsAsync(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: AsyncInstructionFileReader = fsInstructionReaderAsync,\n { skipGlobal = false }: { skipGlobal?: boolean } = {},\n): Promise<InstructionSource[]> {\n const sources: InstructionSource[] = [];\n const projectLocations = PROJECT_LOCATIONS.map(loc => (loc === '.mastracode' ? configDirName : loc));\n const globalLocations = skipGlobal\n ? []\n : GLOBAL_LOCATIONS.map(loc => {\n if (loc === '.mastracode') return configDirName;\n if (loc === '.config/mastracode') return '.config/' + configDirName.replace(/^\\./, '');\n return loc;\n });\n for (const location of globalLocations) {\n const base = join(homedir(), location);\n for (const filename of INSTRUCTION_FILES) {\n const path = join(base, filename);\n if (!(await fsInstructionReaderAsync.exists(path))) continue;\n try {\n const content = (await fsInstructionReaderAsync.read(path)).trim();\n if (content) {\n sources.push({ path, content, scope: 'global' });\n break;\n }\n } catch {\n /* Skip unreadable instructions. */\n }\n break;\n }\n if (sources.length) break;\n }\n for (const location of projectLocations) {\n const base = location ? join(projectPath, location) : projectPath;\n for (const filename of INSTRUCTION_FILES) {\n const path = join(base, filename);\n if (!(await projectReader.exists(path))) continue;\n try {\n const content = (await projectReader.read(path)).trim();\n if (content) {\n sources.push({ path, content, scope: 'project', ...(projectReader.ref ? { ref: projectReader.ref } : {}) });\n break;\n }\n } catch {\n /* Skip unreadable instructions. */\n }\n break;\n }\n if (sources.some(source => source.scope === 'project')) break;\n }\n return sources;\n}\n\nexport async function loadSessionInstructionsAsync({\n workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout = false,\n baseRef,\n skipGlobal = false,\n}: {\n workingDir: string;\n instructionRoots?: readonly string[];\n configDir?: string;\n untrustedCheckout?: boolean;\n baseRef?: string;\n skipGlobal?: boolean;\n}): Promise<InstructionSource[]> {\n const [primary, ...others] = sessionInstructionRoots(workingDir, instructionRoots);\n const reader = untrustedCheckout\n ? baseRef\n ? await createGitRefInstructionReaderAsync(primary!, baseRef)\n : { exists: async () => false, read: async () => '' }\n : undefined;\n const sources = await loadAgentInstructionsAsync(primary!, configDir, reader, { skipGlobal });\n if (!untrustedCheckout) {\n for (const root of others)\n sources.push(...(await loadAgentInstructionsAsync(root, configDir, undefined, { skipGlobal: true })));\n }\n return sources;\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 read the operator machine's\n * filesystem, unless `skipGlobal` keeps them out entirely.\n */\nexport function loadAgentInstructions(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: InstructionFileReader = fsInstructionReader,\n { skipGlobal = false }: { skipGlobal?: boolean } = {},\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 = skipGlobal\n ? []\n : 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 instructionSourcePaths(loadAgentInstructions(projectPath, configDirName, projectReader), [projectPath]);\n}\n\n/**\n * Directories a session's project instructions load from: the host's\n * `instructionRoots` (resolved against the working directory, the session's\n * own checkout first) when it sets any, else the working directory itself.\n */\nexport function sessionInstructionRoots(workingDir: string, instructionRoots?: readonly string[]): string[] {\n if (!instructionRoots?.length) return [workingDir];\n return [...new Set(instructionRoots.map(root => resolve(workingDir, root)))];\n}\n\n/**\n * The instruction files a session's system prompt carries. Global files load\n * once (unless `skipGlobal`), then each instruction root's project files, in\n * root order. An untrusted checkout never reads project files off the working\n * tree: with a `baseRef` the first root (the session's own checkout) is served\n * from that ref and the other roots are skipped; without one no project files\n * load.\n */\nexport function loadSessionInstructions({\n workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout = false,\n baseRef,\n skipGlobal = false,\n}: {\n workingDir: string;\n instructionRoots?: readonly string[];\n configDir?: string;\n untrustedCheckout?: boolean;\n baseRef?: string;\n skipGlobal?: boolean;\n}): InstructionSource[] {\n const [primary, ...others] = sessionInstructionRoots(workingDir, instructionRoots);\n const primaryReader = untrustedCheckout\n ? baseRef\n ? createGitRefInstructionReader(primary!, baseRef)\n : { exists: () => false, read: () => '' }\n : undefined;\n const sources = loadAgentInstructions(primary!, configDir, primaryReader, { skipGlobal });\n if (untrustedCheckout) return sources;\n for (const root of others) {\n sources.push(...loadAgentInstructions(root, configDir, undefined, { skipGlobal: true }));\n }\n return sources;\n}\n\n/**\n * Paths of loaded instruction sources, each project source also under its\n * root's canonical path, so reactive reminders never repeat a file the\n * system prompt already carries.\n */\nexport function instructionSourcePaths(sources: InstructionSource[], roots: readonly string[]): string[] {\n return sources.flatMap(source => {\n const path = normalize(source.path);\n if (source.scope !== 'project') return [path];\n const root = roots.find(candidate => {\n const rel = relative(candidate, path);\n return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);\n });\n if (!root) return [path];\n const canonicalPath = join(realpathOrResolved(root), relative(root, path));\n return path === canonicalPath ? [path] : [path, canonicalPath];\n });\n}\n\n/** Heading the agent-instructions block is introduced by in the system prompt. */\nexport const AGENT_INSTRUCTIONS_HEADING = '# Agent Instructions';\n\n/**\n * Format a single instruction source as it appears in the system prompt.\n *\n * Exported so callers that attribute prompt cost per source (the `/context`\n * audit) measure the exact block that is sent rather than reconstructing it.\n */\nexport function formatInstructionSource(source: InstructionSource): string {\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/**\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(formatInstructionSource);\n\n return `\\n${AGENT_INSTRUCTIONS_HEADING}\\n\\n${sections.join('\\n\\n')}\\n`;\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAM,oBAAoB,CAAC,aAAa,WAAW;AAGnD,MAAM,oBAAoB;CACxB;C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EACvE,CAAC;EACD,IAAI,CAAC,MAAM,OAAO,CAAC,IAAI;EACvB,MAAM,gBAAgB,KAAK,mBAAmB,IAAI,GAAG,SAAS,MAAM,IAAI,CAAC;EACzE,OAAO,SAAS,gBAAgB,CAAC,IAAI,IAAI,CAAC,MAAM,aAAa;CAC/D,CAAC;AACH;;AAGA,MAAa,6BAA6B;;;;;;;AAQ1C,SAAgB,wBAAwB,QAAmC;CAGzE,OAAO,QAFO,OAAO,UAAU,WAAW,WAAW,UAEhC,qBADN,OAAO,MAAM,GAAG,OAAO,KAAK,WAAW,OAAO,IAAI,KAAK,OAAO,KAC5B,QAAQ,OAAO;AAClE;;;;AAKA,SAAgB,wBAAwB,SAAsC;CAC5E,IAAI,QAAQ,WAAW,GAAG,OAAO;CAEjC,MAAM,WAAW,QAAQ,IAAI,uBAAuB;CAEpD,OAAO,KAAK,2BAA2B,MAAM,SAAS,KAAK,MAAM,EAAE;AACrE"}
@@ -6,6 +6,7 @@ export { planModePrompt } from './plan.js';
6
6
  export { fastModePrompt } from './fast.js';
7
7
  import type { PromptContext as BasePromptContext } from '@mastra/core/coding-agent';
8
8
  import type { RequestContextReader } from '../../auth/account-routing-context.js';
9
+ import type { InstructionSource } from './agent-instructions.js';
9
10
  export interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {
10
11
  modeId: string;
11
12
  state?: any;
@@ -51,9 +52,10 @@ export declare function joinPromptSections(sections: PromptSection[]): string;
51
52
  * Combines the base prompt with mode-specific instructions.
52
53
  */
53
54
  export declare function buildFullPrompt(ctx: PromptContext): string;
55
+ export declare function buildFullPromptSectionsAsync(ctx: PromptContext): Promise<PromptSection[]>;
54
56
  /**
55
57
  * Build the system prompt as labeled sections. `buildFullPrompt` is the join of
56
58
  * these, so the two can never disagree about what the model receives.
57
59
  */
58
- export declare function buildFullPromptSections(ctx: PromptContext): PromptSection[];
60
+ export declare function buildFullPromptSections(ctx: PromptContext, loadedInstructions?: InstructionSource[]): PromptSection[];
59
61
  //#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