@agllama/mcp 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +26 -4
  2. package/dist/__tests__/api-client.download.test.d.ts +2 -0
  3. package/dist/__tests__/api-client.download.test.d.ts.map +1 -0
  4. package/dist/__tests__/api-client.download.test.js +105 -0
  5. package/dist/__tests__/api-client.download.test.js.map +1 -0
  6. package/dist/__tests__/batch-search.test.d.ts +2 -0
  7. package/dist/__tests__/batch-search.test.d.ts.map +1 -0
  8. package/dist/__tests__/batch-search.test.js +186 -0
  9. package/dist/__tests__/batch-search.test.js.map +1 -0
  10. package/dist/api-client.d.ts +42 -1
  11. package/dist/api-client.d.ts.map +1 -1
  12. package/dist/api-client.js +111 -2
  13. package/dist/api-client.js.map +1 -1
  14. package/dist/hosted/__tests__/toolSurface.test.js +7 -5
  15. package/dist/hosted/__tests__/toolSurface.test.js.map +1 -1
  16. package/dist/hosted/toolSurface.d.ts +1 -1
  17. package/dist/hosted/toolSurface.d.ts.map +1 -1
  18. package/dist/hosted/toolSurface.js +12 -15
  19. package/dist/hosted/toolSurface.js.map +1 -1
  20. package/dist/server.d.ts.map +1 -1
  21. package/dist/server.js +8 -1
  22. package/dist/server.js.map +1 -1
  23. package/dist/tools/__tests__/downloadAttachment.test.d.ts +2 -0
  24. package/dist/tools/__tests__/downloadAttachment.test.d.ts.map +1 -0
  25. package/dist/tools/__tests__/downloadAttachment.test.js +128 -0
  26. package/dist/tools/__tests__/downloadAttachment.test.js.map +1 -0
  27. package/dist/tools/__tests__/specAttachments.test.d.ts +2 -0
  28. package/dist/tools/__tests__/specAttachments.test.d.ts.map +1 -0
  29. package/dist/tools/__tests__/specAttachments.test.js +416 -0
  30. package/dist/tools/__tests__/specAttachments.test.js.map +1 -0
  31. package/dist/tools/attachments.d.ts +38 -20
  32. package/dist/tools/attachments.d.ts.map +1 -1
  33. package/dist/tools/attachments.js +322 -102
  34. package/dist/tools/attachments.js.map +1 -1
  35. package/dist/tools/backlog.d.ts +2 -2
  36. package/dist/tools/batch-search.d.ts +53 -0
  37. package/dist/tools/batch-search.d.ts.map +1 -0
  38. package/dist/tools/batch-search.js +147 -0
  39. package/dist/tools/batch-search.js.map +1 -0
  40. package/dist/tools/help.d.ts.map +1 -1
  41. package/dist/tools/help.js +20 -9
  42. package/dist/tools/help.js.map +1 -1
  43. package/dist/tools/index.d.ts +1 -0
  44. package/dist/tools/index.d.ts.map +1 -1
  45. package/dist/tools/index.js +1 -0
  46. package/dist/tools/index.js.map +1 -1
  47. package/dist/tools/issues.d.ts +58 -58
  48. package/dist/tools/notificationRules.d.ts +4 -4
  49. package/dist/tools/organizations.d.ts +2 -2
  50. package/dist/tools/plans.d.ts.map +1 -1
  51. package/dist/tools/plans.js +32 -0
  52. package/dist/tools/plans.js.map +1 -1
  53. package/dist/tools/projectErrors.d.ts +2 -2
  54. package/dist/tools/projects.d.ts +2 -2
  55. package/dist/tools/prompts.d.ts +12 -12
  56. package/dist/tools/roadmap.d.ts +4 -4
  57. package/dist/tools/search.d.ts +3 -3
  58. package/dist/tools/search.d.ts.map +1 -1
  59. package/dist/tools/search.js +1 -1
  60. package/dist/tools/search.js.map +1 -1
  61. package/dist/tools/skills.d.ts +15 -15
  62. package/dist/tools/sprints.d.ts +2 -2
  63. package/dist/tools/triage.d.ts +6 -6
  64. package/dist/tools/workflowStatus.d.ts +2 -2
  65. package/dist/types.d.ts +55 -0
  66. package/dist/types.d.ts.map +1 -1
  67. package/dist/types.js.map +1 -1
  68. package/package.json +1 -1
@@ -46,31 +46,87 @@ const MIME_MAP = {
46
46
  '.zip': 'application/zip',
47
47
  };
48
48
  const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
49
+ /** Business spec files (SOWs, signed documents). Matches the API's per-file cap. */
50
+ const MAX_SPEC_FILE_SIZE = 25 * 1024 * 1024; // 25MB
51
+ const TARGET_FIELDS = {
52
+ orgSlug: z.string().optional().describe('Org slug (session default)'),
53
+ projectKey: z.string().optional().describe('Project key (session default). Issues only'),
54
+ issueKey: z.string().optional().describe('Issue key (e.g., "PROJ-123"). Provide this OR specId'),
55
+ specId: z.string().optional().describe('Business spec ID. Provide this OR issueKey'),
56
+ };
57
+ /** Every attachment tool acts on exactly one of: an issue, a business spec. */
58
+ async function resolveTarget(input) {
59
+ if (input.issueKey && input.specId) {
60
+ return { error: 'Provide either issueKey or specId, not both.' };
61
+ }
62
+ if (!input.issueKey && !input.specId) {
63
+ return { error: 'Provide issueKey (for an issue) or specId (for a business spec).' };
64
+ }
65
+ if (input.specId) {
66
+ const context = await resolveOrg(input.orgSlug);
67
+ if ('error' in context)
68
+ return context;
69
+ return { kind: 'spec', orgSlug: context.orgSlug, specId: input.specId, label: `spec ${input.specId}` };
70
+ }
71
+ const context = await resolveOrgProject(input);
72
+ if ('error' in context)
73
+ return context;
74
+ return {
75
+ kind: 'issue',
76
+ orgSlug: context.orgSlug,
77
+ projectKey: context.projectKey,
78
+ issueKey: input.issueKey,
79
+ label: input.issueKey,
80
+ };
81
+ }
82
+ /** Never throws: a failed usage record must not fail the tool. */
83
+ async function recordCall(toolName, target) {
84
+ try {
85
+ await getApiClient().recordToolCall(toolName, target.kind === 'issue'
86
+ ? { orgSlug: target.orgSlug, projectKey: target.projectKey }
87
+ : { orgSlug: target.orgSlug, specId: target.specId });
88
+ }
89
+ catch {
90
+ // Ignore recording errors
91
+ }
92
+ }
93
+ function downloadUrlFor(target, attachmentId) {
94
+ const client = getApiClient();
95
+ return target.kind === 'issue'
96
+ ? client.getAttachmentDownloadUrl(target.orgSlug, target.projectKey, target.issueKey, attachmentId)
97
+ : client.getSpecAttachmentDownloadUrl(target.orgSlug, target.specId, attachmentId);
98
+ }
99
+ /** `{ issueKey }` or `{ specId }`, spread into a tool result. */
100
+ function targetRef(target) {
101
+ return target.kind === 'issue' ? { issueKey: target.issueKey } : { specId: target.specId };
102
+ }
49
103
  // ============================================
50
104
  // Attach File
51
105
  // ============================================
52
106
  export const attachFileToolName = 'llama_attach_file';
53
- export const attachFileToolDescription = `Upload local files to an issue. Max 10MB. Images, docs, archives supported.`;
107
+ export const attachFileToolDescription = `Upload local files to an issue (issueKey, max 10MB each) or a business spec (specId, max 25MB each). Images, PDFs, Office docs, text, archives. On a spec, setAsSpecDocument makes the file the spec document shown in the spec viewer.`;
54
108
  export const attachFileToolSchema = z.object({
55
- orgSlug: z.string().optional().describe('Org slug (session default)'),
56
- projectKey: z.string().optional().describe('Project key (session default)'),
57
- issueKey: z.string().describe('Issue key (e.g., "PROJ-123")'),
109
+ ...TARGET_FIELDS,
58
110
  filePaths: z.array(z.string()).min(1).describe('Absolute file paths to upload'),
59
- embedInDescription: z.boolean().optional().describe('If true, appends markdown image/link references to the issue description for uploaded files'),
111
+ embedInDescription: z.boolean().optional().describe('Issues only. If true, appends markdown image/link references to the issue description for uploaded files'),
112
+ setAsSpecDocument: z.boolean().optional().describe('Specs only. If true, the first file becomes the spec document (e.g. the SOW PDF), replacing any current one'),
60
113
  });
61
114
  export async function executeAttachFile(input) {
62
115
  try {
63
- const context = await resolveOrgProject(input);
64
- if ('error' in context) {
65
- return JSON.stringify({ success: false, error: context.error });
116
+ const target = await resolveTarget(input);
117
+ if ('error' in target) {
118
+ return JSON.stringify({ success: false, error: target.error });
66
119
  }
67
- const client = getApiClient();
68
- try {
69
- await client.recordToolCall('llama_attach_file', { orgSlug: context.orgSlug, projectKey: context.projectKey });
120
+ if (target.kind === 'spec' && input.embedInDescription) {
121
+ return JSON.stringify({ success: false, error: 'embedInDescription applies to issues only.' });
70
122
  }
71
- catch {
72
- // Ignore recording errors
123
+ if (target.kind === 'issue' && input.setAsSpecDocument) {
124
+ return JSON.stringify({ success: false, error: 'setAsSpecDocument applies to business specs only (use specId).' });
73
125
  }
126
+ const client = getApiClient();
127
+ await recordCall('llama_attach_file', target);
128
+ const maxFileSize = target.kind === 'spec' ? MAX_SPEC_FILE_SIZE : MAX_FILE_SIZE;
129
+ const maxLabel = `${maxFileSize / 1024 / 1024}MB`;
74
130
  // Validate all files before uploading any
75
131
  const validatedFiles = [];
76
132
  for (const filePath of input.filePaths) {
@@ -92,10 +148,10 @@ export async function executeAttachFile(input) {
92
148
  if (!stat.isFile()) {
93
149
  return JSON.stringify({ success: false, error: `Not a file: ${filePath}` });
94
150
  }
95
- if (stat.size > MAX_FILE_SIZE) {
151
+ if (stat.size > maxFileSize) {
96
152
  return JSON.stringify({
97
153
  success: false,
98
- error: `File too large (${(stat.size / 1024 / 1024).toFixed(1)}MB > 10MB limit): ${filePath}`,
154
+ error: `File too large (${(stat.size / 1024 / 1024).toFixed(1)}MB > ${maxLabel} limit): ${filePath}`,
99
155
  });
100
156
  }
101
157
  // Check MIME type
@@ -117,18 +173,30 @@ export async function executeAttachFile(input) {
117
173
  // Upload each file
118
174
  const results = [];
119
175
  const errors = [];
120
- for (const file of validatedFiles) {
176
+ for (const [index, file] of validatedFiles.entries()) {
121
177
  try {
122
178
  const buffer = await fs.readFile(file.filePath);
123
- const attachment = await client.uploadAttachmentBuffer(context.orgSlug, context.projectKey, input.issueKey, file.fileName, buffer, file.mimeType);
124
- const downloadUrl = client.getAttachmentDownloadUrl(context.orgSlug, context.projectKey, input.issueKey, attachment.id);
125
- results.push({
126
- fileName: file.fileName,
127
- size: file.size,
128
- attachmentId: attachment.id,
129
- downloadUrl,
130
- mimeType: file.mimeType,
131
- });
179
+ if (target.kind === 'spec') {
180
+ const attachment = await client.uploadSpecAttachmentBuffer(target.orgSlug, target.specId, file.fileName, buffer, file.mimeType, { isPrimary: input.setAsSpecDocument === true && index === 0 });
181
+ results.push({
182
+ fileName: file.fileName,
183
+ size: file.size,
184
+ attachmentId: attachment.id,
185
+ downloadUrl: downloadUrlFor(target, attachment.id),
186
+ mimeType: file.mimeType,
187
+ isSpecDocument: attachment.isPrimary,
188
+ });
189
+ }
190
+ else {
191
+ const attachment = await client.uploadAttachmentBuffer(target.orgSlug, target.projectKey, target.issueKey, file.fileName, buffer, file.mimeType);
192
+ results.push({
193
+ fileName: file.fileName,
194
+ size: file.size,
195
+ attachmentId: attachment.id,
196
+ downloadUrl: downloadUrlFor(target, attachment.id),
197
+ mimeType: file.mimeType,
198
+ });
199
+ }
132
200
  }
133
201
  catch (err) {
134
202
  errors.push({
@@ -144,10 +212,10 @@ export async function executeAttachFile(input) {
144
212
  errors,
145
213
  });
146
214
  }
147
- // Embed in description if requested
148
- if (input.embedInDescription && results.length > 0) {
215
+ // Embed in description if requested (issues only, checked above)
216
+ if (target.kind === 'issue' && input.embedInDescription && results.length > 0) {
149
217
  try {
150
- const issue = await client.getIssue(context.orgSlug, context.projectKey, input.issueKey);
218
+ const issue = await client.getIssue(target.orgSlug, target.projectKey, target.issueKey);
151
219
  const existingDesc = issue.description || '';
152
220
  const markdownLines = results.map((r) => {
153
221
  if (r.mimeType.startsWith('image/')) {
@@ -157,7 +225,7 @@ export async function executeAttachFile(input) {
157
225
  });
158
226
  const separator = existingDesc.length > 0 ? '\n\n' : '';
159
227
  const newDescription = existingDesc + separator + markdownLines.join('\n\n');
160
- await client.updateIssue(context.orgSlug, context.projectKey, input.issueKey, {
228
+ await client.updateIssue(target.orgSlug, target.projectKey, target.issueKey, {
161
229
  description: newDescription,
162
230
  });
163
231
  }
@@ -165,7 +233,7 @@ export async function executeAttachFile(input) {
165
233
  // Don't fail the whole operation if embed fails
166
234
  return JSON.stringify({
167
235
  success: true,
168
- message: `Uploaded ${results.length} file(s) to ${input.issueKey} (but failed to embed in description)`,
236
+ message: `Uploaded ${results.length} file(s) to ${target.label} (but failed to embed in description)`,
169
237
  attachments: results,
170
238
  ...(errors.length > 0 ? { errors } : {}),
171
239
  });
@@ -173,7 +241,7 @@ export async function executeAttachFile(input) {
173
241
  }
174
242
  return JSON.stringify({
175
243
  success: true,
176
- message: `Uploaded ${results.length} file(s) to ${input.issueKey}${input.embedInDescription ? ' and embedded in description' : ''}`,
244
+ message: `Uploaded ${results.length} file(s) to ${target.label}${input.embedInDescription ? ' and embedded in description' : ''}`,
177
245
  attachments: results,
178
246
  ...(errors.length > 0 ? { errors } : {}),
179
247
  });
@@ -186,29 +254,39 @@ export async function executeAttachFile(input) {
186
254
  // List Attachments
187
255
  // ============================================
188
256
  export const listAttachmentsToolName = 'llama_list_attachments';
189
- export const listAttachmentsToolDescription = `List all attachments on an issue.`;
257
+ export const listAttachmentsToolDescription = `List all attachments on an issue (issueKey) or a business spec (specId). On a spec, isSpecDocument marks the file that is the spec itself.`;
190
258
  export const listAttachmentsToolSchema = z.object({
191
- orgSlug: z.string().optional().describe('Org slug (session default)'),
192
- projectKey: z.string().optional().describe('Project key (session default)'),
193
- issueKey: z.string().describe('Issue key (e.g., "PROJ-123")'),
259
+ ...TARGET_FIELDS,
194
260
  });
195
261
  export async function executeListAttachments(input) {
196
262
  try {
197
- const context = await resolveOrgProject(input);
198
- if ('error' in context) {
199
- return JSON.stringify({ success: false, error: context.error });
263
+ const target = await resolveTarget(input);
264
+ if ('error' in target) {
265
+ return JSON.stringify({ success: false, error: target.error });
200
266
  }
201
267
  const client = getApiClient();
202
- try {
203
- await client.recordToolCall('llama_list_attachments', { orgSlug: context.orgSlug, projectKey: context.projectKey });
204
- }
205
- catch {
206
- // Ignore recording errors
268
+ await recordCall('llama_list_attachments', target);
269
+ if (target.kind === 'spec') {
270
+ const attachments = await client.listSpecAttachments(target.orgSlug, target.specId);
271
+ return JSON.stringify({
272
+ success: true,
273
+ specId: target.specId,
274
+ count: attachments.length,
275
+ attachments: attachments.map((a) => ({
276
+ id: a.id,
277
+ fileName: a.originalName,
278
+ fileSize: a.fileSize,
279
+ mimeType: a.mimeType,
280
+ isSpecDocument: a.isPrimary,
281
+ uploadedBy: a.uploadedBy?.name ?? null,
282
+ createdAt: a.createdAt,
283
+ })),
284
+ });
207
285
  }
208
- const attachments = await client.listAttachments(context.orgSlug, context.projectKey, input.issueKey);
286
+ const attachments = await client.listAttachments(target.orgSlug, target.projectKey, target.issueKey);
209
287
  return JSON.stringify({
210
288
  success: true,
211
- issueKey: input.issueKey,
289
+ issueKey: target.issueKey,
212
290
  count: attachments.length,
213
291
  attachments: attachments.map((a) => ({
214
292
  id: a.id,
@@ -228,30 +306,28 @@ export async function executeListAttachments(input) {
228
306
  // Delete Attachment
229
307
  // ============================================
230
308
  export const deleteAttachmentToolName = 'llama_delete_attachment';
231
- export const deleteAttachmentToolDescription = `Delete an attachment from an issue.`;
309
+ export const deleteAttachmentToolDescription = `Delete an attachment from an issue (issueKey) or a business spec (specId).`;
232
310
  export const deleteAttachmentToolSchema = z.object({
233
- orgSlug: z.string().optional().describe('Org slug (session default)'),
234
- projectKey: z.string().optional().describe('Project key (session default)'),
235
- issueKey: z.string().describe('Issue key (e.g., "PROJ-123")'),
311
+ ...TARGET_FIELDS,
236
312
  attachmentId: z.string().describe('Attachment ID to delete'),
237
313
  });
238
314
  export async function executeDeleteAttachment(input) {
239
315
  try {
240
- const context = await resolveOrgProject(input);
241
- if ('error' in context) {
242
- return JSON.stringify({ success: false, error: context.error });
316
+ const target = await resolveTarget(input);
317
+ if ('error' in target) {
318
+ return JSON.stringify({ success: false, error: target.error });
243
319
  }
244
320
  const client = getApiClient();
245
- try {
246
- await client.recordToolCall('llama_delete_attachment', { orgSlug: context.orgSlug, projectKey: context.projectKey });
321
+ await recordCall('llama_delete_attachment', target);
322
+ if (target.kind === 'spec') {
323
+ await client.deleteSpecAttachment(target.orgSlug, target.specId, input.attachmentId);
247
324
  }
248
- catch {
249
- // Ignore recording errors
325
+ else {
326
+ await client.deleteAttachment(target.orgSlug, target.projectKey, target.issueKey, input.attachmentId);
250
327
  }
251
- await client.deleteAttachment(context.orgSlug, context.projectKey, input.issueKey, input.attachmentId);
252
328
  return JSON.stringify({
253
329
  success: true,
254
- message: `Deleted attachment ${input.attachmentId} from ${input.issueKey}`,
330
+ message: `Deleted attachment ${input.attachmentId} from ${target.label}`,
255
331
  });
256
332
  }
257
333
  catch (error) {
@@ -269,52 +345,185 @@ const TEXT_MIME_TYPES = new Set([
269
345
  'application/json', 'application/xml', 'application/javascript',
270
346
  ]);
271
347
  const SKIPPED_MIME_PREFIXES = ['video/', 'audio/'];
348
+ /** Text and other non-image files. Images use MAX_IMAGE_EMBEDDED_SIZE. */
272
349
  const MAX_EMBEDDED_SIZE = 1024 * 1024; // 1MB
350
+ /** Retina screenshots are often over 1MB. Above this, return metadata only. */
351
+ const MAX_IMAGE_EMBEDDED_SIZE = 5 * 1024 * 1024; // 5MB
352
+ /** Largest file `saveTo` writes to disk. Matches the API's upload ceiling. */
353
+ const MAX_SAVED_SIZE = 50 * 1024 * 1024; // 50MB
354
+ function embeddedSizeLimit(mimeType) {
355
+ return IMAGE_MIME_TYPES.has(mimeType) ? MAX_IMAGE_EMBEDDED_SIZE : MAX_EMBEDDED_SIZE;
356
+ }
357
+ function formatMegabytes(bytes) {
358
+ return `${bytes / (1024 * 1024)}MB`;
359
+ }
360
+ const SAVE_TO_HINT = 'Pass saveTo (an absolute local directory) to save the file to disk, then read it from savedPath.';
361
+ /**
362
+ * Extension a saved attachment gets, chosen by its type. Never taken from the
363
+ * uploaded name: whoever uploaded the file picked that name.
364
+ */
365
+ const SAVE_EXTENSION_BY_MIME = {
366
+ 'image/jpeg': '.jpg',
367
+ 'image/png': '.png',
368
+ 'image/gif': '.gif',
369
+ 'image/webp': '.webp',
370
+ 'application/pdf': '.pdf',
371
+ 'application/msword': '.doc',
372
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
373
+ 'application/vnd.ms-excel': '.xls',
374
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
375
+ 'text/plain': '.txt',
376
+ 'text/markdown': '.md',
377
+ 'text/csv': '.csv',
378
+ 'application/json': '.json',
379
+ 'application/zip': '.zip',
380
+ 'application/x-zip-compressed': '.zip',
381
+ 'video/webm': '.webm',
382
+ 'video/mp4': '.mp4',
383
+ };
384
+ const MAX_SAVE_NAME_ATTEMPTS = 20;
385
+ /**
386
+ * The on-disk name for a saved attachment: `<readable stem>-<id><.ext>`.
387
+ *
388
+ * An attachment's name is chosen by its uploader, who may be anyone able to
389
+ * file feedback, and the directory is often an agent's working directory. A
390
+ * file saved under its uploaded name could land as `CLAUDE.md`, `.npmrc`,
391
+ * `.envrc` or `run.sh` and be picked up by the next tool that reads that
392
+ * directory. So the uploaded name contributes only a readable stem:
393
+ * - letters, digits, space, `_` and `-` survive; everything else, dots
394
+ * included, becomes `_` (no dotfiles, no path separators of either OS, no
395
+ * characters Windows refuses);
396
+ * - the attachment id is always appended, so the result can never equal a
397
+ * well-known file name or a Windows device name;
398
+ * - the extension comes from the type, from a fixed list.
399
+ */
400
+ function savedFileName(originalName, mimeType, attachmentId, attempt) {
401
+ const ext = SAVE_EXTENSION_BY_MIME[mimeType.toLowerCase().split(';')[0].trim()] ?? '.bin';
402
+ const base = originalName.split(/[\\/]/).pop() ?? '';
403
+ const stem = base
404
+ .replace(/\.[^.]*$/, '')
405
+ .replace(/[^A-Za-z0-9 _-]/g, '_')
406
+ .replace(/^[\s_-]+/, '')
407
+ .slice(0, 80)
408
+ .trim() || 'attachment';
409
+ const idPart = attachmentId.replace(/[^A-Za-z0-9]/g, '').slice(-8) || 'file';
410
+ const counter = attempt === 0 ? '' : `-${attempt + 1}`;
411
+ return `${stem}-${idPart}${counter}${ext}`;
412
+ }
413
+ /**
414
+ * Write a downloaded attachment into `directory`. Every write is exclusive
415
+ * (`wx`): an existing file, or a symlink sitting at the target name, is never
416
+ * written through. A name already taken gets a numbered sibling instead.
417
+ */
418
+ async function saveAttachment(directory, originalName, mimeType, attachmentId, buffer) {
419
+ for (let attempt = 0; attempt < MAX_SAVE_NAME_ATTEMPTS; attempt++) {
420
+ const target = path.join(directory, savedFileName(originalName, mimeType, attachmentId, attempt));
421
+ try {
422
+ await fs.writeFile(target, buffer, { flag: 'wx' });
423
+ return target;
424
+ }
425
+ catch (err) {
426
+ if (err.code !== 'EEXIST')
427
+ throw err;
428
+ }
429
+ }
430
+ throw new Error(`Could not save the file: ${MAX_SAVE_NAME_ATTEMPTS} copies already exist in ${directory}`);
431
+ }
273
432
  export const downloadAttachmentToolName = 'llama_download_attachment';
274
- export const downloadAttachmentToolDescription = `Download and view an attachment. Images are returned visually, text files as readable content. Skips video/audio (use llama_get_transcription instead). Files >1MB return metadata only.`;
433
+ export const downloadAttachmentToolDescription = `Download and view an attachment on an issue (issueKey) or a business spec (specId). Images are returned visually (up to ${formatMegabytes(MAX_IMAGE_EMBEDDED_SIZE)}), text files as readable content (up to ${formatMegabytes(MAX_EMBEDDED_SIZE)}). PDFs, Office files and anything larger: pass saveTo (a local directory) to save the file and read it from disk. Skips video/audio (use llama_get_transcription instead).`;
275
434
  export const downloadAttachmentToolSchema = z.object({
276
- orgSlug: z.string().optional().describe('Org slug (session default)'),
277
- projectKey: z.string().optional().describe('Project key (session default)'),
278
- issueKey: z.string().describe('Issue key (e.g., "PROJ-123")'),
435
+ ...TARGET_FIELDS,
279
436
  attachmentId: z.string().describe('Attachment ID (from llama_list_attachments)'),
437
+ saveTo: z.string().optional().describe('Absolute path of an existing local directory. The file is written there (any type, up to 50MB) under a generated name and its path returned as savedPath. Not available on the hosted connector'),
280
438
  });
439
+ function textBlock(payload) {
440
+ return [{ type: 'text', text: JSON.stringify(payload) }];
441
+ }
281
442
  export async function executeDownloadAttachment(input) {
282
443
  try {
283
- const context = await resolveOrgProject(input);
284
- if ('error' in context) {
285
- return [{ type: 'text', text: JSON.stringify({ success: false, error: context.error }) }];
444
+ const target = await resolveTarget(input);
445
+ if ('error' in target) {
446
+ return textBlock({ success: false, error: target.error });
286
447
  }
287
448
  const client = getApiClient();
288
- try {
289
- await client.recordToolCall('llama_download_attachment', {
290
- orgSlug: context.orgSlug, projectKey: context.projectKey,
291
- });
292
- }
293
- catch {
294
- // Ignore recording errors
449
+ if (input.saveTo !== undefined) {
450
+ // On the hosted connector this code runs inside the API server: a
451
+ // "local directory" there would be the server's own disk.
452
+ if (client.isHosted) {
453
+ return textBlock({ success: false, error: 'saveTo is not available on the hosted connector: there is no local disk to save to.' });
454
+ }
455
+ if (!path.isAbsolute(input.saveTo)) {
456
+ return textBlock({ success: false, error: `saveTo must be an absolute path: ${input.saveTo}` });
457
+ }
458
+ // A `..` path segment, not the substring: "C:\\work\\v1..2" is a real directory.
459
+ if (input.saveTo.split(/[\\/]/).includes('..')) {
460
+ return textBlock({ success: false, error: `Path traversal not allowed: ${input.saveTo}` });
461
+ }
462
+ let stat;
463
+ try {
464
+ stat = await fs.stat(input.saveTo);
465
+ }
466
+ catch {
467
+ return textBlock({ success: false, error: `saveTo directory not found: ${input.saveTo}` });
468
+ }
469
+ if (!stat.isDirectory()) {
470
+ return textBlock({ success: false, error: `saveTo is not a directory: ${input.saveTo}` });
471
+ }
295
472
  }
296
- const downloadUrl = client.getAttachmentDownloadUrl(context.orgSlug, context.projectKey, input.issueKey, input.attachmentId);
473
+ await recordCall('llama_download_attachment', target);
474
+ const downloadUrl = downloadUrlFor(target, input.attachmentId);
297
475
  // Fetch attachment metadata to check MIME type and size before downloading
298
- const allAttachments = await client.listAttachments(context.orgSlug, context.projectKey, input.issueKey);
476
+ const allAttachments = target.kind === 'issue'
477
+ ? await client.listAttachments(target.orgSlug, target.projectKey, target.issueKey)
478
+ : await client.listSpecAttachments(target.orgSlug, target.specId);
299
479
  const attachmentMeta = allAttachments.find((a) => a.id === input.attachmentId);
300
480
  if (!attachmentMeta) {
301
- return [{ type: 'text', text: JSON.stringify({ success: false, error: `Attachment ${input.attachmentId} not found on ${input.issueKey}` }) }];
481
+ return textBlock({ success: false, error: `Attachment ${input.attachmentId} not found on ${target.label}` });
302
482
  }
303
483
  const metaMimeType = attachmentMeta.mimeType;
304
484
  const metaFileSize = attachmentMeta.fileSize;
485
+ const ref = targetRef(target);
486
+ const download = () => target.kind === 'issue'
487
+ ? client.downloadAttachment(target.orgSlug, target.projectKey, target.issueKey, input.attachmentId)
488
+ : client.downloadSpecAttachment(target.orgSlug, target.specId, input.attachmentId);
489
+ // Save to disk: any type, no embed limits. The caller reads it from there.
490
+ if (input.saveTo !== undefined) {
491
+ if (metaFileSize > MAX_SAVED_SIZE) {
492
+ return textBlock({
493
+ success: false,
494
+ error: `File too large to save (${(metaFileSize / 1024 / 1024).toFixed(1)}MB > ${formatMegabytes(MAX_SAVED_SIZE)} limit).`,
495
+ });
496
+ }
497
+ const { buffer, contentType } = await download();
498
+ const savedPath = await saveAttachment(input.saveTo, attachmentMeta.originalName, metaMimeType, input.attachmentId, buffer);
499
+ return textBlock({
500
+ success: true,
501
+ attachmentId: input.attachmentId,
502
+ ...ref,
503
+ fileName: attachmentMeta.originalName,
504
+ contentType,
505
+ fileSize: buffer.length,
506
+ savedPath,
507
+ note: 'Saved to disk. Read the file at savedPath.',
508
+ });
509
+ }
305
510
  // Skip video/audio — automatically include transcription if available
306
511
  if (SKIPPED_MIME_PREFIXES.some((p) => metaMimeType.startsWith(p))) {
307
512
  const result = {
308
513
  success: true,
309
514
  attachmentId: input.attachmentId,
310
- issueKey: input.issueKey,
515
+ ...ref,
311
516
  fileName: attachmentMeta.originalName,
312
517
  contentType: metaMimeType,
313
518
  fileSize: metaFileSize,
314
519
  };
520
+ if (target.kind === 'spec') {
521
+ result.note = `${metaMimeType} file — no transcription available.`;
522
+ return textBlock(result);
523
+ }
315
524
  // Try to fetch transcription for this specific attachment
316
525
  try {
317
- const transcriptions = await client.getTranscriptions(context.orgSlug, context.projectKey, input.issueKey);
526
+ const transcriptions = await client.getTranscriptions(target.orgSlug, target.projectKey, target.issueKey);
318
527
  const match = transcriptions.find((t) => t.id === input.attachmentId);
319
528
  if (match?.transcription) {
320
529
  const t = match.transcription;
@@ -332,30 +541,44 @@ export async function executeDownloadAttachment(input) {
332
541
  catch {
333
542
  result.note = `${metaMimeType} file — could not fetch transcription.`;
334
543
  }
335
- return [{ type: 'text', text: JSON.stringify(result) }];
544
+ return textBlock(result);
545
+ }
546
+ const canSave = !client.isHosted;
547
+ // Size guard: don't download files we will not embed. Images get a
548
+ // higher cap than text — a screenshot the caller cannot see is useless.
549
+ const embedLimit = embeddedSizeLimit(metaMimeType);
550
+ if (metaFileSize > embedLimit) {
551
+ return textBlock({
552
+ success: true,
553
+ attachmentId: input.attachmentId,
554
+ ...ref,
555
+ fileName: attachmentMeta.originalName,
556
+ contentType: metaMimeType,
557
+ fileSize: metaFileSize,
558
+ downloadUrl,
559
+ note: `File too large to embed (${(metaFileSize / 1024 / 1024).toFixed(1)}MB > ${formatMegabytes(embedLimit)} limit). ${canSave ? SAVE_TO_HINT : 'Use the download URL to access it.'}`,
560
+ });
336
561
  }
337
- // Size guard: don't download large files
338
- if (metaFileSize > MAX_EMBEDDED_SIZE) {
339
- return [{
340
- type: 'text',
341
- text: JSON.stringify({
342
- success: true,
343
- attachmentId: input.attachmentId,
344
- issueKey: input.issueKey,
345
- fileName: attachmentMeta.originalName,
346
- contentType: metaMimeType,
347
- fileSize: metaFileSize,
348
- downloadUrl,
349
- note: `File too large to embed (${(metaFileSize / 1024 / 1024).toFixed(1)}MB > 1MB limit). Use the download URL to access it.`,
350
- }),
351
- }];
562
+ // A binary type is never embedded, so do not pull its bytes just to drop them.
563
+ const embeddable = IMAGE_MIME_TYPES.has(metaMimeType) || TEXT_MIME_TYPES.has(metaMimeType) || metaMimeType.startsWith('text/');
564
+ if (!embeddable) {
565
+ return textBlock({
566
+ success: true,
567
+ attachmentId: input.attachmentId,
568
+ ...ref,
569
+ fileName: attachmentMeta.originalName,
570
+ contentType: metaMimeType,
571
+ fileSize: metaFileSize,
572
+ downloadUrl,
573
+ note: `Binary file (${metaMimeType}) cannot be displayed inline. ${canSave ? SAVE_TO_HINT : 'Use the download URL to access it.'}`,
574
+ });
352
575
  }
353
576
  // Download the file
354
- const { buffer, contentType } = await client.downloadAttachment(context.orgSlug, context.projectKey, input.issueKey, input.attachmentId);
577
+ const { buffer, contentType } = await download();
355
578
  const metadata = {
356
579
  success: true,
357
580
  attachmentId: input.attachmentId,
358
- issueKey: input.issueKey,
581
+ ...ref,
359
582
  contentType,
360
583
  fileSize: buffer.length,
361
584
  downloadUrl,
@@ -375,13 +598,10 @@ export async function executeDownloadAttachment(input) {
375
598
  ];
376
599
  }
377
600
  // Other binary (PDF, docx, zip, etc.): can't embed, provide link
378
- return [{
379
- type: 'text',
380
- text: JSON.stringify({
381
- ...metadata,
382
- note: `Binary file (${contentType}) cannot be displayed inline. Use the download URL to access it.`,
383
- }),
384
- }];
601
+ return textBlock({
602
+ ...metadata,
603
+ note: `Binary file (${contentType}) cannot be displayed inline. ${canSave ? SAVE_TO_HINT : 'Use the download URL to access it.'}`,
604
+ });
385
605
  }
386
606
  catch (error) {
387
607
  return [{ type: 'text', text: formatError(error, 'download attachment') }];