@imenam/mcp-organizer 1.0.21 → 1.0.22

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 (44) hide show
  1. package/README.md +15 -11
  2. package/dist/shared/logic/documents.d.ts +2 -4
  3. package/dist/shared/logic/documents.js +6 -11
  4. package/dist/shared/schemas/agent-tools.schema.d.ts +133 -7
  5. package/dist/shared/schemas/agent-tools.schema.js +52 -7
  6. package/dist/shared/schemas/documents-api.schema.d.ts +0 -2
  7. package/dist/shared/schemas/documents-api.schema.js +0 -2
  8. package/dist/src/agent-api/attachments.d.ts +2 -0
  9. package/dist/src/agent-api/attachments.js +96 -0
  10. package/dist/src/agent-api/documents.d.ts +1 -1
  11. package/dist/src/agent-api/documents.js +9 -33
  12. package/dist/src/agent-api/files.d.ts +35 -0
  13. package/dist/src/agent-api/files.js +86 -0
  14. package/dist/src/agent-api/router.d.ts +2 -2
  15. package/dist/src/agent-api/router.js +5 -4
  16. package/dist/src/agent-api/tasks.js +5 -8
  17. package/dist/src/agent-api/types.d.ts +4 -2
  18. package/dist/src/core/agent-files.d.ts +41 -0
  19. package/dist/src/core/agent-files.js +102 -0
  20. package/dist/src/core/agent.d.ts +3 -1
  21. package/dist/src/core/agent.js +14 -3
  22. package/dist/src/core/document-text.d.ts +3 -2
  23. package/dist/src/core/document-text.js +3 -2
  24. package/dist/src/core/documents.js +0 -1
  25. package/dist/src/core/history.d.ts +3 -1
  26. package/dist/src/core/history.js +28 -11
  27. package/dist/src/core/requests.d.ts +9 -4
  28. package/dist/src/core/requests.js +21 -10
  29. package/dist/src/core/snapshots.d.ts +3 -3
  30. package/dist/src/core/snapshots.js +3 -1
  31. package/dist/src/gui-api.js +2 -2
  32. package/dist/src/mcp/client.d.ts +7 -4
  33. package/dist/src/mcp/client.js +31 -4
  34. package/dist/src/mcp/start.d.ts +1 -1
  35. package/dist/src/mcp/start.js +6 -6
  36. package/dist/src/mcp/tools.d.ts +11 -0
  37. package/dist/src/mcp/tools.js +55 -4
  38. package/dist/src/mcp/upload.d.ts +22 -0
  39. package/dist/src/mcp/upload.js +79 -0
  40. package/dist/src/server/app.js +38 -4
  41. package/gui/dist/assets/{index-DbzcjyaW.js → index-C1f7hOcM.js} +2 -2
  42. package/gui/dist/assets/{index-Dvf5Yo0e.css → index-CfMiwPSL.css} +1 -1
  43. package/gui/dist/index.html +2 -2
  44. package/package.json +3 -1
@@ -0,0 +1,96 @@
1
+ import { AddAttachmentBodySchema, AttachmentAddedDataSchema, AttachmentDetailDataSchema, GetAttachmentQuerySchema } from "../../shared/schemas/agent-tools.schema.js";
2
+ import { attachmentImageMarkdown } from "../../shared/logic/attachments.js";
3
+ import { actFor, actingRequest, ago, byteSize, directSpace, resolveTask, taskData, taskKey, taskUpdateSummary, userLabel } from "../core/agent.js";
4
+ import { NotFoundError, OrganizerError } from "../core/errors.js";
5
+ import { newId } from "../core/ids.js";
6
+ import { readFile, readingOf } from "./files.js";
7
+ import { parseInput, respond } from "./types.js";
8
+ /**
9
+ * Pièces jointes des tâches de l'espace du jeton : lecture (image montrée à
10
+ * l'agent, texte d'un PDF, d'un fichier texte ou Word) et envoi d'un fichier
11
+ * que le mode MCP lit sur sa machine.
12
+ */
13
+ /** Référence d'une pièce jointe dans un texte : miniature pour une image, nom du fichier sinon. */
14
+ function attachmentReference(filename, mime, id) {
15
+ return mime.toLowerCase().startsWith("image/") ? attachmentImageMarkdown(filename, id) : `\`${filename.replace(/`/g, "'")}\``;
16
+ }
17
+ export const attachmentRoutes = [
18
+ {
19
+ method: "GET",
20
+ path: "/attachments/:id",
21
+ handle: async ({ store, attachments }, { agent, params, query }) => {
22
+ const input = parseInput(GetAttachmentQuerySchema, query);
23
+ const space = agent.space;
24
+ const id = params.id.trim();
25
+ const attachment = store.findAttachment(id);
26
+ const task = attachment ? store.findTask(attachment.taskId) : null;
27
+ if (!attachment || !task || task.spaceId !== space.id) {
28
+ throw new NotFoundError(`Attachment ${id} not found in "${space.name}". Take the id of an attachment from get_task, or from a reference attachment:<id> in a text of a task.`);
29
+ }
30
+ const uploader = store.findUser(attachment.uploaderId);
31
+ const uploadedBy = uploader ? userLabel(uploader) : "a former member";
32
+ const key = taskKey(store, task);
33
+ const header = `Attachment ${attachment.id} "${attachment.filename}" (${attachment.mime}, ${byteSize(attachment.size)}) of task ${key} "${task.title}", uploaded by ${uploadedBy} ${ago(attachment.createdAt)}.`;
34
+ const reading = readingOf(attachment.filename, attachment.mime);
35
+ if (!reading) {
36
+ throw new OrganizerError(`Attachment ${attachment.id} "${attachment.filename}" is a ${attachment.mime} file: get_attachment opens images, PDF files, text files (txt, md, csv, json, yaml, xml…) and Word files (.docx). Rely on its name and on the surrounding text, or ask its author what it contains.`);
37
+ }
38
+ const what = `attachment ${attachment.id} "${attachment.filename}"`;
39
+ const read = await readFile(reading, attachment.filename, attachments.read(attachment), input.part, what, (part) => `get_attachment with part ${part}`);
40
+ const data = {
41
+ attachment: { id: attachment.id, filename: attachment.filename, mime: attachment.mime, size: attachment.size, taskKey: key, uploadedBy, createdAt: attachment.createdAt },
42
+ ...read.fields,
43
+ };
44
+ return { ...respond(AttachmentDetailDataSchema, [header, "", ...read.lines].join("\n"), data), images: read.images };
45
+ },
46
+ },
47
+ {
48
+ method: "POST",
49
+ path: "/tasks/:ref/attachments",
50
+ handle: ({ store, attachments }, { agent, params, body }) => {
51
+ const input = parseInput(AddAttachmentBodySchema, body);
52
+ const comment = input.comment?.trim();
53
+ const content = Buffer.from(input.file.content);
54
+ const { filename, mime } = input.file;
55
+ // Refus avant l'écriture du fichier : demande invalide ou tâche hors de l'espace.
56
+ check(store, agent, input.request_id, params.ref);
57
+ const id = newId();
58
+ const storagePath = attachments.write(id, content);
59
+ try {
60
+ const { task, commentId } = actFor(store, agent, input.request_id, (tx, space) => {
61
+ const task = resolveTask(tx.store, space, params.ref);
62
+ const attachment = tx.createAttachment({ id, taskId: task.id, filename, mime, size: content.length, storagePath });
63
+ tx.recordAgentAction({ entityType: "attachment", entityId: id, operation: "create", before: null, after: attachment, summary: `Pièce jointe ajoutée : ${filename}`, taskId: task.id });
64
+ const reference = attachmentReference(filename, mime, id);
65
+ if (input.append_to_description) {
66
+ const before = tx.store.taskSnapshot(task.id);
67
+ const current = before.description.replace(/\s+$/, "");
68
+ tx.updateTask(task.id, { description: current === "" ? reference : `${current}\n\n${reference}` });
69
+ const after = tx.store.taskSnapshot(task.id);
70
+ tx.recordAgentAction({ entityType: "task", entityId: task.id, operation: "update", before, after, summary: taskUpdateSummary(tx.store, before, after).summary, taskId: task.id });
71
+ }
72
+ let commentId = null;
73
+ if (comment !== undefined && comment !== "") {
74
+ const added = tx.addComment(task.id, `${comment}\n\n${reference}`);
75
+ tx.recordAgentAction({ entityType: "comment", entityId: added.id, operation: "create", before: null, after: added, summary: "Commentaire ajouté", taskId: task.id });
76
+ commentId = added.id;
77
+ }
78
+ return { task, commentId };
79
+ });
80
+ const where = [commentId ? `shown in comment ${commentId}` : null, input.append_to_description ? "referenced at the end of the description" : null].filter((part) => part !== null);
81
+ return respond(AttachmentAddedDataSchema, `Attached "${filename}" (${mime}, ${byteSize(content.length)}) to ${taskKey(store, task)} (attachment id ${id})${where.length > 0 ? `, ${where.join(" and ")}` : ""}.`, { task: taskData(store, store.getTask(task.id)), attachment: { id, filename, mime, size: content.length }, commentId, inDescription: input.append_to_description });
82
+ }
83
+ catch (err) {
84
+ attachments.remove([storagePath]);
85
+ throw err;
86
+ }
87
+ },
88
+ },
89
+ ];
90
+ /** Vérifie, sans rien écrire, que l'agent peut écrire pour la demande et que la tâche est dans l'espace du jeton. */
91
+ function check(store, agent, requestId, ref) {
92
+ if (requestId === undefined)
93
+ resolveTask(store, directSpace(store, agent), ref);
94
+ else
95
+ resolveTask(store, actingRequest(store, agent, requestId).space, ref);
96
+ }
@@ -1,3 +1,3 @@
1
1
  import { type AgentRoute } from "./types.js";
2
- /** Documents de référence de l'espace du jeton, en lecture seule : liste et lecture par parties. */
2
+ /** Documents de référence de l'espace du jeton, en lecture seule : liste, lecture du texte par parties, image montrée à l'agent. */
3
3
  export declare const documentRoutes: AgentRoute[];
@@ -1,9 +1,9 @@
1
1
  import { DocumentDetailDataSchema, GetDocumentQuerySchema, ListDocumentsDataSchema, NoQuerySchema } from "../../shared/schemas/agent-tools.schema.js";
2
+ import { documentFormatOf } from "../../shared/logic/documents.js";
2
3
  import { ago, byteSize, documentData, documentLine, resolveDocument } from "../core/agent.js";
3
- import { DocumentTextError, documentText, splitParts } from "../core/document-text.js";
4
- import { OrganizerError } from "../core/errors.js";
4
+ import { readFile } from "./files.js";
5
5
  import { parseInput, respond } from "./types.js";
6
- /** Documents de référence de l'espace du jeton, en lecture seule : liste et lecture par parties. */
6
+ /** Documents de référence de l'espace du jeton, en lecture seule : liste, lecture du texte par parties, image montrée à l'agent. */
7
7
  export const documentRoutes = [
8
8
  {
9
9
  method: "GET",
@@ -23,44 +23,20 @@ export const documentRoutes = [
23
23
  {
24
24
  method: "GET",
25
25
  path: "/documents/:ref",
26
- handle: ({ store, attachments }, { agent, params, query }) => {
26
+ handle: async ({ store, attachments }, { agent, params, query }) => {
27
27
  const input = parseInput(GetDocumentQuerySchema, query);
28
28
  const document = resolveDocument(store, agent.space, params.ref);
29
29
  const data = documentData(store, document);
30
+ const format = documentFormatOf(document.filename);
31
+ if (!format)
32
+ throw new Error(`Document ${document.id} has an unsupported file name: ${document.filename}.`);
30
33
  const replaced = document.version > 1 ? `, version ${document.version} uploaded by ${data.updatedBy} ${ago(document.updatedAt)}` : `, version 1`;
31
34
  const header = [
32
35
  `Document ${document.id} "${document.filename}" (${data.format}, ${byteSize(document.size)}), uploaded by ${data.uploadedBy} ${ago(document.createdAt)}${replaced}.`,
33
36
  `Description: ${document.description.trim() === "" ? "(none)" : document.description}`,
34
37
  ];
35
- if (!data.readable) {
36
- const text = [
37
- ...header,
38
- "",
39
- `You cannot read the content of this ${data.format} file: the organizer only extracts the text of text files (txt, md, csv, json, yaml, xml…) and Word files (.docx). Rely on its name and description, and when you need its content, ask a member (in your reply or a comment) to upload a text, markdown or Word version.`,
40
- ].join("\n");
41
- return respond(DocumentDetailDataSchema, text, { document: data, part: 1, partCount: 1, text: null });
42
- }
43
- let content;
44
- try {
45
- content = documentText(document.filename, attachments.readPath(document.storagePath)) ?? "";
46
- }
47
- catch (err) {
48
- if (err instanceof DocumentTextError)
49
- throw new OrganizerError(`The text of document ${document.id} "${document.filename}" cannot be read (invalid UTF-8 text or damaged Word file). Ask a member to upload it again.`);
50
- throw err;
51
- }
52
- const parts = splitParts(content);
53
- if (input.part > parts.length)
54
- throw new OrganizerError(`Document "${document.filename}" has ${parts.length} part(s): pass a part between 1 and ${parts.length}.`);
55
- const position = parts.length > 1 ? `Part ${input.part} of ${parts.length}:` : "Content:";
56
- const next = input.part < parts.length ? `\n\n(Next: get_document with part ${input.part + 1}.)` : "";
57
- const body = content.trim() === "" ? "(empty)" : parts[input.part - 1];
58
- return respond(DocumentDetailDataSchema, [...header, "", position, body].join("\n") + next, {
59
- document: data,
60
- part: input.part,
61
- partCount: parts.length,
62
- text: parts[input.part - 1],
63
- });
38
+ const read = await readFile(format.reading, document.filename, attachments.readPath(document.storagePath), input.part, `document ${document.id} "${document.filename}"`, (part) => `get_document with part ${part}`);
39
+ return { ...respond(DocumentDetailDataSchema, [...header, "", ...read.lines].join("\n"), { document: data, ...read.fields }), images: read.images };
64
40
  },
65
41
  },
66
42
  ];
@@ -0,0 +1,35 @@
1
+ import type { AgentImageContent } from "../../shared/schemas/agent-tools.schema.js";
2
+ import { type DocumentReading } from "../../shared/logic/documents.js";
3
+ /**
4
+ * Lecture d'un fichier par l'agent, commune à get_document et get_attachment :
5
+ * une image jointe à la réponse, le texte d'un PDF, d'un fichier texte ou
6
+ * d'un fichier Word, découpé en parties.
7
+ */
8
+ /** Contenu lu : texte de la réponse (sans en-tête), données et images à montrer. */
9
+ export interface FileReading {
10
+ lines: string[];
11
+ fields: {
12
+ kind: DocumentReading;
13
+ part: number;
14
+ partCount: number;
15
+ text: string | null;
16
+ image: {
17
+ mimeType: string;
18
+ width: number;
19
+ height: number;
20
+ converted: boolean;
21
+ } | null;
22
+ pdf: {
23
+ pages: number;
24
+ hasText: boolean;
25
+ } | null;
26
+ };
27
+ images: AgentImageContent[];
28
+ }
29
+ /** Façon de lire un fichier d'après son type MIME et son nom ; null pour un format que l'agent n'ouvre pas. */
30
+ export declare function readingOf(filename: string, mime: string): DocumentReading | null;
31
+ /**
32
+ * Lit un fichier : `what` le désigne dans les messages (`document X "nom"`),
33
+ * `next` est l'appel qui lit la partie suivante.
34
+ */
35
+ export declare function readFile(reading: DocumentReading, filename: string, content: Buffer, part: number, what: string, next: (part: number) => string): Promise<FileReading>;
@@ -0,0 +1,86 @@
1
+ import { documentFormatOf } from "../../shared/logic/documents.js";
2
+ import { pdfPagesText, pdfText, prepareImage } from "../core/agent-files.js";
3
+ import { DocumentTextError, documentText, splitParts } from "../core/document-text.js";
4
+ import { OrganizerError } from "../core/errors.js";
5
+ /** Façon de lire un fichier d'après son type MIME et son nom ; null pour un format que l'agent n'ouvre pas. */
6
+ export function readingOf(filename, mime) {
7
+ const normalized = mime.toLowerCase().split(";")[0].trim();
8
+ if (normalized.startsWith("image/"))
9
+ return "image";
10
+ if (normalized === "application/pdf")
11
+ return "pdf";
12
+ return documentFormatOf(filename)?.reading ?? null;
13
+ }
14
+ /**
15
+ * Lit un fichier : `what` le désigne dans les messages (`document X "nom"`),
16
+ * `next` est l'appel qui lit la partie suivante.
17
+ */
18
+ export async function readFile(reading, filename, content, part, what, next) {
19
+ if (reading === "image") {
20
+ if (part !== 1)
21
+ throw new OrganizerError(`${capitalize(what)} is an image: it has a single part, pass part 1.`);
22
+ let image;
23
+ try {
24
+ image = await prepareImage(content);
25
+ }
26
+ catch (err) {
27
+ if (err instanceof OrganizerError)
28
+ throw new OrganizerError(`The image of ${what} cannot be shown: ${err.message}`);
29
+ throw err;
30
+ }
31
+ const note = image.converted ? ` It was converted to ${image.width}×${image.height} px (${image.mimeType}) to fit the limits of the Claude API.` : "";
32
+ return {
33
+ lines: [`The image follows (${image.width}×${image.height} px).${note}`],
34
+ fields: { kind: "image", part: 1, partCount: 1, text: null, image: { mimeType: image.mimeType, width: image.width, height: image.height, converted: image.converted }, pdf: null },
35
+ images: [{ data: image.data, mimeType: image.mimeType }],
36
+ };
37
+ }
38
+ let text;
39
+ let pdf = null;
40
+ if (reading === "pdf") {
41
+ let extracted;
42
+ try {
43
+ extracted = await pdfText(content);
44
+ }
45
+ catch (err) {
46
+ if (err instanceof OrganizerError)
47
+ throw new OrganizerError(`${capitalize(what)}: ${err.message} Ask a member to upload it again.`);
48
+ throw err;
49
+ }
50
+ pdf = { pages: extracted.pages.length, hasText: extracted.hasText };
51
+ if (!extracted.hasText) {
52
+ if (part !== 1)
53
+ throw new OrganizerError(`${capitalize(what)} has no text: pass part 1.`);
54
+ return {
55
+ lines: [
56
+ `This PDF has ${extracted.pages.length} page(s) but no text layer: it contains only images (a scan or a photo, for instance), so no text can be extracted. Ask a member for a text version, or for screenshots of the relevant pages pasted into a task.`,
57
+ ],
58
+ fields: { kind: "pdf", part: 1, partCount: 1, text: null, image: null, pdf },
59
+ images: [],
60
+ };
61
+ }
62
+ text = pdfPagesText(extracted);
63
+ }
64
+ else {
65
+ try {
66
+ text = documentText(filename, content) ?? "";
67
+ }
68
+ catch (err) {
69
+ if (err instanceof DocumentTextError)
70
+ throw new OrganizerError(`The text of ${what} cannot be read (invalid UTF-8 text or damaged Word file). Ask a member to upload it again.`);
71
+ throw err;
72
+ }
73
+ }
74
+ const parts = splitParts(text);
75
+ if (part > parts.length)
76
+ throw new OrganizerError(`${capitalize(what)} has ${parts.length} part(s): pass a part between 1 and ${parts.length}.`);
77
+ const position = parts.length > 1 ? `Part ${part} of ${parts.length}:` : "Content:";
78
+ const body = text.trim() === "" ? "(empty)" : parts[part - 1];
79
+ const lines = [pdf ? `PDF of ${pdf.pages} page(s), extracted text.` : null, position, body].filter((line) => line !== null);
80
+ if (part < parts.length)
81
+ lines.push("", `(Next: ${next(part + 1)}.)`);
82
+ return { lines, fields: { kind: reading, part, partCount: parts.length, text: parts[part - 1], image: null, pdf }, images: [] };
83
+ }
84
+ function capitalize(text) {
85
+ return text.charAt(0).toUpperCase() + text.slice(1);
86
+ }
@@ -1,3 +1,3 @@
1
1
  import type { AgentApiContext, AgentApiRequest, AgentApiResponse } from "./types.js";
2
- /** Traite une requête de l'API agent ; une erreur est levée telle quelle, avec la nature qui fixe son code HTTP. */
3
- export declare function handleAgentRequest(ctx: AgentApiContext, request: AgentApiRequest): AgentApiResponse;
2
+ /** Traite une requête de l'API agent ; une erreur est rejetée telle quelle, avec la nature qui fixe son code HTTP. */
3
+ export declare function handleAgentRequest(ctx: AgentApiContext, request: AgentApiRequest): Promise<AgentApiResponse>;
@@ -5,6 +5,7 @@ import { questionRoutes } from "./questions.js";
5
5
  import { ideaRoutes } from "./ideas.js";
6
6
  import { noteRoutes } from "./notes.js";
7
7
  import { documentRoutes } from "./documents.js";
8
+ import { attachmentRoutes } from "./attachments.js";
8
9
  import { historyRoutes } from "./history.js";
9
10
  import { notificationRoutes } from "./notifications.js";
10
11
  import { requestRoutes } from "./requests.js";
@@ -19,7 +20,7 @@ function compile(route) {
19
20
  });
20
21
  return { route, pattern: new RegExp(`^${source}$`), keys };
21
22
  }
22
- const ROUTES = [...requestRoutes, ...taskRoutes, ...checklistRoutes, ...questionRoutes, ...ideaRoutes, ...noteRoutes, ...documentRoutes, ...historyRoutes, ...viewRoutes, ...timerRoutes, ...notificationRoutes].map(compile);
23
+ const ROUTES = [...requestRoutes, ...taskRoutes, ...checklistRoutes, ...questionRoutes, ...ideaRoutes, ...noteRoutes, ...documentRoutes, ...attachmentRoutes, ...historyRoutes, ...viewRoutes, ...timerRoutes, ...notificationRoutes].map(compile);
23
24
  /** Segment de chemin décodé ; un encodage `%` invalide est une erreur 400. */
24
25
  function decodeSegment(raw) {
25
26
  try {
@@ -29,8 +30,8 @@ function decodeSegment(raw) {
29
30
  throw new OrganizerError(`Invalid URL: a path segment is badly encoded (${raw}).`);
30
31
  }
31
32
  }
32
- /** Traite une requête de l'API agent ; une erreur est levée telle quelle, avec la nature qui fixe son code HTTP. */
33
- export function handleAgentRequest(ctx, request) {
33
+ /** Traite une requête de l'API agent ; une erreur est rejetée telle quelle, avec la nature qui fixe son code HTTP. */
34
+ export async function handleAgentRequest(ctx, request) {
34
35
  const now = ctx.now?.() ?? new Date();
35
36
  const agent = resolveAgentToken(ctx.store, request.bearer, now);
36
37
  for (const candidate of ROUTES) {
@@ -41,7 +42,7 @@ export function handleAgentRequest(ctx, request) {
41
42
  continue;
42
43
  const params = {};
43
44
  candidate.keys.forEach((key, index) => (params[key] = decodeSegment(match[index + 1])));
44
- return candidate.route.handle(ctx, { agent, params, query: request.query, body: request.body });
45
+ return await candidate.route.handle(ctx, { agent, params, query: request.query, body: request.body });
45
46
  }
46
47
  throw new NotFoundError(`Unknown agent API route: ${request.method} /api/agent${request.path}. Update @imenam/mcp-organizer so that the MCP mode and the site agree.`);
47
48
  }
@@ -1,14 +1,14 @@
1
1
  import { AddCommentBodySchema, CommentDataSchema, ContextDataSchema, CreateTaskBodySchema, NoQuerySchema, SearchTasksDataSchema, SearchTasksQuerySchema, SetAssigneesBodySchema, SetTagsBodySchema, TaskDataSchema, TaskDetailDataSchema, UpdateTaskBodySchema, } from "../../shared/schemas/agent-tools.schema.js";
2
2
  import { attachmentImages } from "../../shared/logic/attachments.js";
3
3
  import { combinedResult } from "../../shared/logic/test-summary.js";
4
- import { actFor, ago, assigneesSummary, createdTaskSummary, ideaData, documentData, memberData, recentIdeas, requireText, resolveMembers, resolveTask, spaceContextLines, spaceData, taskData, taskKey, taskUpdateSummary, treeData, userLabel, } from "../core/agent.js";
4
+ import { actFor, ago, attachmentLines, assigneesSummary, createdTaskSummary, ideaData, documentData, memberData, recentIdeas, requireText, resolveMembers, resolveTask, spaceContextLines, spaceData, taskData, taskKey, taskUpdateSummary, treeData, userLabel, } from "../core/agent.js";
5
5
  import { OrganizerError } from "../core/errors.js";
6
6
  import { questionData, questionLines, questionsOf } from "./questions.js";
7
7
  import { parseInput, respond } from "./types.js";
8
- /** Mention des images jointes qu'un texte référence, ajoutée à sa ligne : ` [images: nom (attachment id), …]`. */
8
+ /** Mention des images jointes qu'un texte référence, ajoutée à sa ligne : ` [images: nom (attachment id), …; open with get_attachment]`. */
9
9
  function imageNote(text) {
10
10
  const images = attachmentImages(text);
11
- return images.length === 0 ? "" : ` [images: ${images.map((image) => `${image.name} (attachment ${image.id})`).join(", ")}]`;
11
+ return images.length === 0 ? "" : ` [images: ${images.map((image) => `${image.name} (attachment ${image.id})`).join(", ")}; open with get_attachment]`;
12
12
  }
13
13
  /** Espace du jeton et ses tâches : contexte, lecture, recherche, création, modification, assignés, tags, commentaires. */
14
14
  /** Nombre de commentaires récents affichés par get_task. */
@@ -105,11 +105,8 @@ export const taskRoutes = [
105
105
  lines.push(`- ${comment.requestId ? "agent" : name(comment.authorId)}, ${ago(comment.createdAt)}: ${comment.body}${imageNote(comment.body)}`);
106
106
  }
107
107
  const attachments = store.listAttachments(task.id);
108
- if (attachments.length > 0) {
109
- lines.push("", "Attachments:");
110
- for (const attachment of attachments)
111
- lines.push(`- ${attachment.filename} (${attachment.mime}, ${attachment.size} bytes, id ${attachment.id})`);
112
- }
108
+ if (attachments.length > 0)
109
+ lines.push("", ...attachmentLines(store, task));
113
110
  return respond(TaskDetailDataSchema, lines.join("\n"), {
114
111
  task: summary,
115
112
  description: task.description,
@@ -2,6 +2,7 @@ import type { z } from "zod";
2
2
  import type { AgentCaller } from "../core/agent.js";
3
3
  import type { Store } from "../core/store.js";
4
4
  import type { AttachmentStorage } from "../core/attachments.js";
5
+ import type { AgentImageContent } from "../../shared/schemas/agent-tools.schema.js";
5
6
  /** Dépendances de l'API agent. */
6
7
  export interface AgentApiContext {
7
8
  store: Store;
@@ -20,10 +21,11 @@ export interface AgentApiRequest {
20
21
  /** Jeton de l'en-tête `Authorization: Bearer`, null sans en-tête. */
21
22
  bearer: string | null;
22
23
  }
23
- /** Réponse réussie : texte rédigé pour l'agent et données structurées. */
24
+ /** Réponse réussie : texte rédigé pour l'agent, données structurées et images montrées à l'agent. */
24
25
  export interface AgentApiResponse {
25
26
  text: string;
26
27
  data: unknown;
28
+ images?: AgentImageContent[];
27
29
  }
28
30
  /** Appel d'une route : agent authentifié, paramètres de chemin, requête et corps. */
29
31
  export interface AgentCall {
@@ -36,7 +38,7 @@ export interface AgentRoute {
36
38
  method: "GET" | "POST" | "PUT" | "PATCH";
37
39
  /** Chemin sous `/api/agent`, avec `:nom` pour un paramètre. */
38
40
  path: string;
39
- handle: (ctx: AgentApiContext, call: AgentCall) => AgentApiResponse;
41
+ handle: (ctx: AgentApiContext, call: AgentCall) => AgentApiResponse | Promise<AgentApiResponse>;
40
42
  }
41
43
  /** Données validées par `schema` ; une donnée invalide est une erreur qui liste les problèmes. */
42
44
  export declare function parseInput<S extends z.ZodType>(schema: S, value: unknown): z.infer<S>;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Contenu des fichiers ouverts par l'agent : une image préparée pour l'API de
3
+ * Claude (format PNG, JPEG, GIF ou WebP, côté long et poids bornés, quitte à
4
+ * la redimensionner et la recompresser) et le texte d'un PDF, page par page.
5
+ * sharp et unpdf se chargent à la première utilisation : le mode MCP ne les
6
+ * charge jamais.
7
+ */
8
+ /** Côté long maximal d'une image envoyée à l'agent, en pixels : limite de l'API de Claude quand une conversation dépasse 20 images. */
9
+ export declare const MAX_IMAGE_SIDE = 2000;
10
+ /** Poids maximal d'une image envoyée à l'agent, encodée en base64 : limite de l'API de Claude. */
11
+ export declare const MAX_IMAGE_BASE64_BYTES: number;
12
+ /** Image prête pour un bloc de contenu MCP. */
13
+ export interface AgentImage {
14
+ /** Contenu encodé en base64. */
15
+ data: string;
16
+ mimeType: string;
17
+ width: number;
18
+ height: number;
19
+ /** Vrai si l'image a été redimensionnée, recompressée ou convertie. */
20
+ converted: boolean;
21
+ }
22
+ /** Texte d'un PDF : une entrée par page ; `hasText` est faux pour un PDF sans couche texte (scan). */
23
+ export interface PdfText {
24
+ pages: string[];
25
+ hasText: boolean;
26
+ }
27
+ /**
28
+ * Image prête pour l'agent. Une image déjà dans un format de l'API, dans les
29
+ * limites de côté et de poids, part telle quelle ; sinon elle est réduite au
30
+ * côté maximal, puis encodée en PNG, ou en JPEG de qualité décroissante et de
31
+ * taille décroissante jusqu'à tenir dans le poids maximal. Une image animée
32
+ * est réduite à sa première image, une photo orientée par EXIF redressée.
33
+ */
34
+ export declare function prepareImage(content: Buffer, limits?: {
35
+ maxSide?: number;
36
+ maxBase64Bytes?: number;
37
+ }): Promise<AgentImage>;
38
+ /** Texte d'un PDF, page par page, lignes reconstituées ; un PDF illisible ou chiffré est une erreur explicite. */
39
+ export declare function pdfText(content: Buffer): Promise<PdfText>;
40
+ /** Texte d'un PDF mis en forme pour l'agent : chaque page précédée de `--- Page N ---`. */
41
+ export declare function pdfPagesText(text: PdfText): string;
@@ -0,0 +1,102 @@
1
+ import { OrganizerError } from "./errors.js";
2
+ /**
3
+ * Contenu des fichiers ouverts par l'agent : une image préparée pour l'API de
4
+ * Claude (format PNG, JPEG, GIF ou WebP, côté long et poids bornés, quitte à
5
+ * la redimensionner et la recompresser) et le texte d'un PDF, page par page.
6
+ * sharp et unpdf se chargent à la première utilisation : le mode MCP ne les
7
+ * charge jamais.
8
+ */
9
+ /** Côté long maximal d'une image envoyée à l'agent, en pixels : limite de l'API de Claude quand une conversation dépasse 20 images. */
10
+ export const MAX_IMAGE_SIDE = 2000;
11
+ /** Poids maximal d'une image envoyée à l'agent, encodée en base64 : limite de l'API de Claude. */
12
+ export const MAX_IMAGE_BASE64_BYTES = 5 * 1024 * 1024;
13
+ /** Formats d'image acceptés tels quels par l'API de Claude, par nom de format sharp. */
14
+ const API_IMAGE_TYPES = { png: "image/png", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
15
+ async function loadSharp() {
16
+ try {
17
+ return (await import("sharp")).default;
18
+ }
19
+ catch (err) {
20
+ throw new OrganizerError(`The organizer site cannot process images: the sharp library does not load (${err?.message ?? err}). The administrator of the site must reinstall its dependencies (npm install) on this machine.`);
21
+ }
22
+ }
23
+ const base64Length = (bytes) => Math.ceil(bytes / 3) * 4;
24
+ /**
25
+ * Image prête pour l'agent. Une image déjà dans un format de l'API, dans les
26
+ * limites de côté et de poids, part telle quelle ; sinon elle est réduite au
27
+ * côté maximal, puis encodée en PNG, ou en JPEG de qualité décroissante et de
28
+ * taille décroissante jusqu'à tenir dans le poids maximal. Une image animée
29
+ * est réduite à sa première image, une photo orientée par EXIF redressée.
30
+ */
31
+ export async function prepareImage(content, limits = {}) {
32
+ const maxSide = limits.maxSide ?? MAX_IMAGE_SIDE;
33
+ const maxBase64 = limits.maxBase64Bytes ?? MAX_IMAGE_BASE64_BYTES;
34
+ const sharp = await loadSharp();
35
+ let metadata;
36
+ try {
37
+ metadata = await sharp(content).metadata();
38
+ }
39
+ catch (err) {
40
+ throw new OrganizerError(`The file is not an image the organizer can decode (${err?.message ?? err}).`);
41
+ }
42
+ const width = metadata.width ?? 0;
43
+ const height = metadata.height ?? 0;
44
+ if (width === 0 || height === 0)
45
+ throw new OrganizerError("The file is not an image the organizer can decode (no dimensions).");
46
+ const apiType = metadata.format ? API_IMAGE_TYPES[metadata.format] : undefined;
47
+ const animated = (metadata.pages ?? 1) > 1;
48
+ const rotated = (metadata.orientation ?? 1) !== 1;
49
+ if (apiType && !animated && !rotated && Math.max(width, height) <= maxSide && base64Length(content.length) <= maxBase64) {
50
+ return { data: content.toString("base64"), mimeType: apiType, width, height, converted: false };
51
+ }
52
+ const scale = Math.min(1, maxSide / Math.max(width, height));
53
+ const attempts = [{ scale, format: "png", quality: 100 }];
54
+ for (const factor of [1, 0.75, 0.5, 0.35, 0.25]) {
55
+ for (const quality of [85, 70, 55])
56
+ attempts.push({ scale: scale * factor, format: "jpeg", quality });
57
+ }
58
+ try {
59
+ for (const attempt of attempts) {
60
+ const side = Math.max(1, Math.round(Math.max(width, height) * attempt.scale));
61
+ let pipeline = sharp(content).rotate().resize({ width: side, height: side, fit: "inside", withoutEnlargement: true });
62
+ pipeline = attempt.format === "png" ? pipeline.png({ compressionLevel: 9 }) : pipeline.flatten({ background: "#ffffff" }).jpeg({ quality: attempt.quality, mozjpeg: true });
63
+ const { data, info } = await pipeline.toBuffer({ resolveWithObject: true });
64
+ if (base64Length(data.length) <= maxBase64) {
65
+ return { data: data.toString("base64"), mimeType: attempt.format === "png" ? "image/png" : "image/jpeg", width: info.width, height: info.height, converted: true };
66
+ }
67
+ }
68
+ }
69
+ catch (err) {
70
+ throw new OrganizerError(`The organizer cannot convert this image (${err?.message ?? err}).`);
71
+ }
72
+ throw new OrganizerError(`The image cannot be reduced under ${Math.round(maxBase64 / (1024 * 1024))} MB, even at a quarter of its size.`);
73
+ }
74
+ /** Texte d'un PDF, page par page, lignes reconstituées ; un PDF illisible ou chiffré est une erreur explicite. */
75
+ export async function pdfText(content) {
76
+ let unpdf;
77
+ try {
78
+ unpdf = await import("unpdf");
79
+ }
80
+ catch (err) {
81
+ throw new OrganizerError(`The organizer site cannot read PDF files: the unpdf library does not load (${err?.message ?? err}). The administrator of the site must reinstall its dependencies (npm install) on this machine.`);
82
+ }
83
+ let pages;
84
+ try {
85
+ const pdf = await unpdf.getDocumentProxy(new Uint8Array(content));
86
+ try {
87
+ pages = (await unpdf.extractText(pdf, { mergePages: false })).text;
88
+ }
89
+ finally {
90
+ await pdf.loadingTask.destroy();
91
+ }
92
+ }
93
+ catch (err) {
94
+ throw new OrganizerError(`The PDF file cannot be read (${err?.message ?? err}): it is damaged or protected by a password.`);
95
+ }
96
+ const cleaned = pages.map((page) => page.replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim());
97
+ return { pages: cleaned, hasText: cleaned.some((page) => page !== "") };
98
+ }
99
+ /** Texte d'un PDF mis en forme pour l'agent : chaque page précédée de `--- Page N ---`. */
100
+ export function pdfPagesText(text) {
101
+ return text.pages.map((page, index) => `--- Page ${index + 1} of ${text.pages.length} ---\n${page === "" ? "(no text on this page)" : page}`).join("\n\n");
102
+ }
@@ -79,13 +79,15 @@ export declare function requestThread(store: Store, request: AgentRequest): Comm
79
79
  export declare function previousSuites(store: Store, origin: AgentRequest, request: AgentRequest): AgentRequest[];
80
80
  /** Contexte complet d'une demande, renvoyé par claim_request. */
81
81
  export declare function requestContext(store: Store, agent: AgentCaller, request: AgentRequest): string;
82
+ /** Pièces jointes d'une tâche, avec la façon de les ouvrir ; aucune ligne pour une tâche sans pièce jointe. */
83
+ export declare function attachmentLines(store: Store, task: Task): string[];
82
84
  /** Instructions personnalisées de l'agent pour une demande de l'espace : celles du site, puis celles de l'espace. */
83
85
  export declare function instructionLines(store: Store, space: Space): string[];
84
86
  /** Idées actives récentes de la boîte à idées d'un espace. */
85
87
  export declare function recentIdeas(store: Store, space: Space): Idea[];
86
88
  /** Taille lisible d'un nombre d'octets, pour l'agent. */
87
89
  export declare function byteSize(bytes: number): string;
88
- /** Ligne d'un document : identifiant, nom, format, taille, version, lisibilité et description. */
90
+ /** Ligne d'un document : identifiant, nom, format, taille, version et description. */
89
91
  export declare function documentLine(store: Store, document: SpaceDocument): string;
90
92
  /** Documents de référence d'un espace, pour claim_request et get_context. */
91
93
  export declare function documentContextLines(store: Store, space: Space): string[];
@@ -344,6 +344,8 @@ export function requestContext(store, agent, request) {
344
344
  if (task) {
345
345
  const space = store.getSpace(task.spaceId);
346
346
  lines.push(`Context task: ${space.keyPrefix}-${task.number} "${task.title}" [${task.status}, ${task.priority}${task.type === "test" ? ", test" : ""}] (id ${task.id})${space.id !== target.id ? ` in space "${space.name}" (out of your reach)` : ""}.`);
347
+ if (space.id === target.id)
348
+ lines.push(...attachmentLines(store, task));
347
349
  if (task.type === "test" && request.kind === "test_review") {
348
350
  const checkpoints = store.listCheckpoints(task.id);
349
351
  const results = store.listTestResults(task.id).filter((result) => result.testerId === request.authorId);
@@ -379,6 +381,16 @@ export function requestContext(store, agent, request) {
379
381
  lines.push("", "Next: read with get_task / search_tasks, act with the write tools (pass this request_id), then call complete_request with a short reply in the author's language, and follow_ups for what the author still has to do.");
380
382
  return lines.join("\n");
381
383
  }
384
+ /** Pièces jointes d'une tâche, avec la façon de les ouvrir ; aucune ligne pour une tâche sans pièce jointe. */
385
+ export function attachmentLines(store, task) {
386
+ const attachments = store.listAttachments(task.id);
387
+ if (attachments.length === 0)
388
+ return [];
389
+ return [
390
+ `Attachments of ${taskKey(store, task)} — open one with get_attachment (images are shown to you, PDF files come as text) when it helps, for example a screenshot of a failed checkpoint or one cited in a comment:`,
391
+ ...attachments.map((attachment) => `- ${attachment.filename} (${attachment.mime}, ${byteSize(attachment.size)}, id ${attachment.id})`),
392
+ ];
393
+ }
382
394
  /** Instructions personnalisées de l'agent pour une demande de l'espace : celles du site, puis celles de l'espace. */
383
395
  export function instructionLines(store, space) {
384
396
  const site = store.findAgentInstructions(null);
@@ -407,12 +419,12 @@ export function byteSize(bytes) {
407
419
  return `${(bytes / 1024).toFixed(1)} KB`;
408
420
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
409
421
  }
410
- /** Ligne d'un document : identifiant, nom, format, taille, version, lisibilité et description. */
422
+ /** Ligne d'un document : identifiant, nom, format, taille, version et description. */
411
423
  export function documentLine(store, document) {
412
424
  const data = documentData(store, document);
413
425
  const description = data.description.trim().replace(/\s+/g, " ");
414
426
  const shown = description.length > 200 ? `${description.slice(0, 200)}…` : description;
415
- return `- ${data.id} "${data.filename}" (${data.format}, ${byteSize(data.size)}, version ${data.version}, updated ${ago(data.updatedAt)}${data.readable ? "" : ", content not readable"})${shown ? ` — ${shown}` : ""}`;
427
+ return `- ${data.id} "${data.filename}" (${data.format}, ${byteSize(data.size)}, version ${data.version}, updated ${ago(data.updatedAt)})${shown ? ` — ${shown}` : ""}`;
416
428
  }
417
429
  /** Documents de référence d'un espace, pour claim_request et get_context. */
418
430
  export function documentContextLines(store, space) {
@@ -516,7 +528,6 @@ export function documentData(store, document) {
516
528
  mime: document.mime,
517
529
  size: document.size,
518
530
  version: document.version,
519
- readable: format.reading !== "none",
520
531
  uploadedBy: userNameOf(store, document.uploaderId),
521
532
  updatedBy: userNameOf(store, document.updatedBy),
522
533
  createdAt: document.createdAt,
@@ -2,7 +2,8 @@ import { OrganizerError } from "./errors.js";
2
2
  /**
3
3
  * Texte d'un document pour l'agent : le contenu d'un fichier texte décodé en
4
4
  * UTF-8, ou le texte des paragraphes d'un fichier Word (.docx), lu dans
5
- * l'archive sans dépendance. Les autres formats n'ont pas de texte.
5
+ * l'archive sans dépendance. Le texte d'un PDF et les images se lisent de
6
+ * façon asynchrone (voir `agent-files.ts`).
6
7
  */
7
8
  /** Longueur d'une partie d'un document lu par morceaux, en caractères. */
8
9
  export declare const DOCUMENT_PART_LENGTH = 20000;
@@ -11,7 +12,7 @@ export declare class DocumentTextError extends OrganizerError {
11
12
  }
12
13
  /** Contenu décompressé d'une entrée d'une archive zip, ou null si l'archive ne la contient pas. */
13
14
  export declare function readZipEntry(archive: Buffer, entryName: string): Buffer | null;
14
- /** Texte d'un document lisible par l'agent ; null pour un format dont l'agent ne lit pas le contenu. */
15
+ /** Texte d'un fichier texte ou Word ; null pour un PDF ou une image. */
15
16
  export declare function documentText(filename: string, content: Buffer): string | null;
16
17
  /** Découpe un texte en parties d'au plus `size` caractères, coupées de préférence en fin de ligne. */
17
18
  export declare function splitParts(text: string, size?: number): string[];