@imenam/mcp-organizer 1.0.33 → 1.0.35

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 (36) hide show
  1. package/README.md +35 -20
  2. package/dist/shared/schemas/agent-api.schema.d.ts +18 -0
  3. package/dist/shared/schemas/agent-api.schema.js +12 -1
  4. package/dist/shared/schemas/agent-tools.schema.d.ts +15 -1
  5. package/dist/shared/schemas/agent-tools.schema.js +22 -1
  6. package/dist/shared/schemas/entities.schema.d.ts +32 -0
  7. package/dist/shared/schemas/entities.schema.js +26 -0
  8. package/dist/shared/schemas/notifications-api.schema.d.ts +8 -0
  9. package/dist/shared/schemas/notifications-api.schema.js +4 -1
  10. package/dist/shared/schemas/tasks-api.schema.d.ts +9 -1
  11. package/dist/shared/schemas/tasks-api.schema.js +5 -2
  12. package/dist/src/agent-api/attachments.js +85 -50
  13. package/dist/src/agent-api/requests.js +2 -0
  14. package/dist/src/cli/backup.js +4 -3
  15. package/dist/src/core/agent.d.ts +3 -1
  16. package/dist/src/core/agent.js +18 -2
  17. package/dist/src/core/migrations.js +24 -0
  18. package/dist/src/core/notifications.js +2 -1
  19. package/dist/src/core/request-attachments.d.ts +33 -0
  20. package/dist/src/core/request-attachments.js +100 -0
  21. package/dist/src/core/requests.d.ts +14 -2
  22. package/dist/src/core/requests.js +67 -5
  23. package/dist/src/core/spaces.js +1 -1
  24. package/dist/src/core/store.d.ts +35 -2
  25. package/dist/src/core/store.js +101 -6
  26. package/dist/src/core/tasks.d.ts +2 -2
  27. package/dist/src/core/tasks.js +13 -3
  28. package/dist/src/gui-api.js +16 -2
  29. package/dist/src/mcp/start.d.ts +1 -1
  30. package/dist/src/mcp/start.js +4 -2
  31. package/dist/src/mcp/tools.js +27 -3
  32. package/gui/dist/assets/index-B6cGTeVR.js +106 -0
  33. package/gui/dist/assets/{index-kNRY_0Gs.css → index-BuYH_-i4.css} +1 -1
  34. package/gui/dist/index.html +2 -2
  35. package/package.json +1 -1
  36. package/gui/dist/assets/index-CLW9PAC7.js +0 -104
@@ -92,6 +92,16 @@ export declare const TaskOpenModeSchema: z.ZodEnum<{
92
92
  preview: "preview";
93
93
  }>;
94
94
  export type TaskOpenMode = z.infer<typeof TaskOpenModeSchema>;
95
+ /**
96
+ * Libellé des boutons de référence à une tâche dans les textes : son numéro
97
+ * (« Task 41 »), ou son titre courant.
98
+ */
99
+ export declare const TASK_LINK_LABELS: readonly ["key", "title"];
100
+ export declare const TaskLinkLabelSchema: z.ZodEnum<{
101
+ key: "key";
102
+ title: "title";
103
+ }>;
104
+ export type TaskLinkLabel = z.infer<typeof TaskLinkLabelSchema>;
95
105
  /** Préférences de notification : assignation et commentaire, dans l'application et par e-mail. */
96
106
  export declare const NotificationPreferencesSchema: z.ZodObject<{
97
107
  notifyAssignApp: z.ZodBoolean;
@@ -135,6 +145,10 @@ export declare const UserSettingsSchema: z.ZodObject<{
135
145
  page: "page";
136
146
  preview: "preview";
137
147
  }>;
148
+ taskLinkLabel: z.ZodEnum<{
149
+ key: "key";
150
+ title: "title";
151
+ }>;
138
152
  }, z.core.$strip>;
139
153
  export type UserSettings = z.infer<typeof UserSettingsSchema>;
140
154
  /** Préférences de notification d'un utilisateur propres à un espace ; elles remplacent celles du compte dans cet espace. */
@@ -366,6 +380,22 @@ export declare const AttachmentSchema: z.ZodObject<{
366
380
  createdAt: z.ZodISODateTime;
367
381
  }, z.core.$strip>;
368
382
  export type Attachment = z.infer<typeof AttachmentSchema>;
383
+ /**
384
+ * Image jointe à une demande à l'agent : déposée par son auteur pendant la
385
+ * saisie (`requestId` null), puis rattachée à la demande qui la référence.
386
+ */
387
+ export declare const RequestAttachmentSchema: z.ZodObject<{
388
+ id: z.ZodString;
389
+ spaceId: z.ZodString;
390
+ requestId: z.ZodNullable<z.ZodString>;
391
+ uploaderId: z.ZodString;
392
+ filename: z.ZodString;
393
+ mime: z.ZodString;
394
+ size: z.ZodNumber;
395
+ storagePath: z.ZodString;
396
+ createdAt: z.ZodISODateTime;
397
+ }, z.core.$strip>;
398
+ export type RequestAttachment = z.infer<typeof RequestAttachmentSchema>;
369
399
  export declare const IdeaSchema: z.ZodObject<{
370
400
  id: z.ZodString;
371
401
  spaceId: z.ZodString;
@@ -504,6 +534,8 @@ export declare const AgentRequestSchema: z.ZodObject<{
504
534
  cancelledBy: z.ZodNullable<z.ZodString>;
505
535
  stoppedAt: z.ZodNullable<z.ZodISODateTime>;
506
536
  stoppedBy: z.ZodNullable<z.ZodString>;
537
+ dismissedAt: z.ZodNullable<z.ZodISODateTime>;
538
+ dismissedBy: z.ZodNullable<z.ZodString>;
507
539
  }, z.core.$strip>;
508
540
  export type AgentRequest = z.infer<typeof AgentRequestSchema>;
509
541
  /**
@@ -81,6 +81,12 @@ export const SidebarModeSchema = z.enum(SIDEBAR_MODES);
81
81
  */
82
82
  export const TASK_OPEN_MODES = ["page", "preview"];
83
83
  export const TaskOpenModeSchema = z.enum(TASK_OPEN_MODES);
84
+ /**
85
+ * Libellé des boutons de référence à une tâche dans les textes : son numéro
86
+ * (« Task 41 »), ou son titre courant.
87
+ */
88
+ export const TASK_LINK_LABELS = ["key", "title"];
89
+ export const TaskLinkLabelSchema = z.enum(TASK_LINK_LABELS);
84
90
  /** Préférences de notification : assignation et commentaire, dans l'application et par e-mail. */
85
91
  export const NotificationPreferencesSchema = z.object({
86
92
  notifyAssignApp: z.boolean(),
@@ -109,6 +115,8 @@ export const UserSettingsSchema = NotificationPreferencesSchema.extend({
109
115
  sidebarMode: SidebarModeSchema,
110
116
  /** Ouverture d'une tâche par un clic simple sur sa carte, sur tous les appareils de l'utilisateur. */
111
117
  taskOpenMode: TaskOpenModeSchema,
118
+ /** Libellé des boutons de référence à une tâche, sur tous les appareils de l'utilisateur. */
119
+ taskLinkLabel: TaskLinkLabelSchema,
112
120
  });
113
121
  /** Préférences de notification d'un utilisateur propres à un espace ; elles remplacent celles du compte dans cet espace. */
114
122
  export const SpaceNotificationSettingsSchema = NotificationPreferencesSchema.extend({
@@ -277,6 +285,21 @@ export const AttachmentSchema = z.object({
277
285
  storagePath: z.string().min(1),
278
286
  createdAt: TimestampSchema,
279
287
  });
288
+ /**
289
+ * Image jointe à une demande à l'agent : déposée par son auteur pendant la
290
+ * saisie (`requestId` null), puis rattachée à la demande qui la référence.
291
+ */
292
+ export const RequestAttachmentSchema = z.object({
293
+ id: IdSchema,
294
+ spaceId: IdSchema,
295
+ requestId: IdSchema.nullable(),
296
+ uploaderId: IdSchema,
297
+ filename: z.string().min(1),
298
+ mime: z.string().min(1),
299
+ size: z.number().int().min(0),
300
+ storagePath: z.string().min(1),
301
+ createdAt: TimestampSchema,
302
+ });
280
303
  export const IdeaSchema = z.object({
281
304
  id: IdSchema,
282
305
  spaceId: IdSchema,
@@ -383,6 +406,9 @@ export const AgentRequestSchema = z.object({
383
406
  /** Arrêt du traitement par l'auteur ou un administrateur : la demande est alors `failed`. */
384
407
  stoppedAt: TimestampSchema.nullable(),
385
408
  stoppedBy: IdSchema.nullable(),
409
+ /** Demande en échec retirée de la liste « En attente » par un membre de son espace. */
410
+ dismissedAt: TimestampSchema.nullable(),
411
+ dismissedBy: IdSchema.nullable(),
386
412
  });
387
413
  /**
388
414
  * Point que l'auteur d'une demande doit régler, laissé par l'agent en la
@@ -101,6 +101,10 @@ export declare const SettingsResponseSchema: z.ZodObject<{
101
101
  page: "page";
102
102
  preview: "preview";
103
103
  }>;
104
+ taskLinkLabel: z.ZodEnum<{
105
+ key: "key";
106
+ title: "title";
107
+ }>;
104
108
  email: z.ZodObject<{
105
109
  enabled: z.ZodBoolean;
106
110
  reason: z.ZodNullable<z.ZodString>;
@@ -135,6 +139,10 @@ export declare const UpdateSettingsRequestSchema: z.ZodObject<{
135
139
  page: "page";
136
140
  preview: "preview";
137
141
  }>>;
142
+ taskLinkLabel: z.ZodOptional<z.ZodEnum<{
143
+ key: "key";
144
+ title: "title";
145
+ }>>;
138
146
  }, z.core.$strict>;
139
147
  export type UpdateSettingsRequest = z.infer<typeof UpdateSettingsRequestSchema>;
140
148
  /**
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { ActorTypeSchema, NotificationTypeSchema } from "./enums.schema.js";
3
- import { AssistantHistorySchema, EmailDigestSchema, IdSchema, NotificationPreferencesSchema, PomodoroSettingsSchema, SidebarModeSchema, TaskOpenModeSchema, TimestampSchema } from "./entities.schema.js";
3
+ import { AssistantHistorySchema, EmailDigestSchema, IdSchema, NotificationPreferencesSchema, PomodoroSettingsSchema, SidebarModeSchema, TaskLinkLabelSchema, TaskOpenModeSchema, TimestampSchema } from "./entities.schema.js";
4
4
  /** Corps des requêtes et des réponses des notifications et des paramètres de la GUI. */
5
5
  /** Nombre de notifications renvoyées par défaut, et au plus, par page. */
6
6
  export const NOTIFICATIONS_PAGE_SIZE = 20;
@@ -65,6 +65,8 @@ export const SettingsResponseSchema = z.object({
65
65
  sidebarMode: SidebarModeSchema,
66
66
  /** Ouverture d'une tâche par un clic simple sur sa carte : en pleine page ou dans l'aperçu latéral. */
67
67
  taskOpenMode: TaskOpenModeSchema,
68
+ /** Libellé des boutons de référence à une tâche : son numéro ou son titre. */
69
+ taskLinkLabel: TaskLinkLabelSchema,
68
70
  /** Envoi des e-mails de notification : `reason` dit pourquoi il n'a pas lieu. */
69
71
  email: z.object({ enabled: z.boolean(), reason: z.string().nullable() }),
70
72
  /** Dictée vocale : `reason` dit pourquoi elle est indisponible. */
@@ -83,6 +85,7 @@ export const UpdateSettingsRequestSchema = z
83
85
  emailDigestMinutes: EmailDigestSchema.optional(),
84
86
  sidebarMode: SidebarModeSchema.optional(),
85
87
  taskOpenMode: TaskOpenModeSchema.optional(),
88
+ taskLinkLabel: TaskLinkLabelSchema.optional(),
86
89
  })
87
90
  .strict()
88
91
  .refine((patch) => Object.values(patch).some((value) => value !== undefined), "Aucune modification demandée.");
@@ -229,7 +229,10 @@ export declare const TaskRefSchema: z.ZodObject<{
229
229
  title: z.ZodString;
230
230
  }, z.core.$strip>;
231
231
  export type TaskRef = z.infer<typeof TaskRefSchema>;
232
- /** Tâche désignée par une clé (`GET task-keys/:key`), avec son statut. */
232
+ /**
233
+ * Tâche désignée par une clé (`GET task-keys/:key`), avec son statut et ses
234
+ * ancêtres, du premier niveau au parent direct (vide pour une tâche de premier niveau).
235
+ */
233
236
  export declare const TaskKeyTargetSchema: z.ZodObject<{
234
237
  id: z.ZodString;
235
238
  key: z.ZodString;
@@ -240,6 +243,11 @@ export declare const TaskKeyTargetSchema: z.ZodObject<{
240
243
  review: "review";
241
244
  todo: "todo";
242
245
  }>;
246
+ ancestors: z.ZodArray<z.ZodObject<{
247
+ id: z.ZodString;
248
+ key: z.ZodString;
249
+ title: z.ZodString;
250
+ }, z.core.$strip>>;
243
251
  }, z.core.$strip>;
244
252
  export type TaskKeyTarget = z.infer<typeof TaskKeyTargetSchema>;
245
253
  /** `GET task-keys/:key` : espace du texte où la clé est écrite, préféré parmi ceux qui portent son préfixe. */
@@ -97,8 +97,11 @@ export const TaskViewSchema = z.object({
97
97
  version: z.number().int(),
98
98
  });
99
99
  export const TaskRefSchema = z.object({ id: IdSchema, key: z.string(), title: z.string() });
100
- /** Tâche désignée par une clé (`GET task-keys/:key`), avec son statut. */
101
- export const TaskKeyTargetSchema = TaskRefSchema.extend({ status: TaskStatusSchema });
100
+ /**
101
+ * Tâche désignée par une clé (`GET task-keys/:key`), avec son statut et ses
102
+ * ancêtres, du premier niveau au parent direct (vide pour une tâche de premier niveau).
103
+ */
104
+ export const TaskKeyTargetSchema = TaskRefSchema.extend({ status: TaskStatusSchema, ancestors: z.array(TaskRefSchema) });
102
105
  /** `GET task-keys/:key` : espace du texte où la clé est écrite, préféré parmi ceux qui portent son préfixe. */
103
106
  export const TaskKeyQuerySchema = z.object({ spaceId: IdSchema.optional() }).strict();
104
107
  export const ChecklistItemViewSchema = z.object({ id: IdSchema, text: z.string(), done: z.boolean(), position: PositionSchema });
@@ -1,4 +1,4 @@
1
- import { AddAttachmentBodySchema, AttachmentAddedDataSchema, AttachmentDetailDataSchema, GetAttachmentQuerySchema } from "../../shared/schemas/agent-tools.schema.js";
1
+ import { AddAttachmentBodySchema, AttachmentAddedDataSchema, AttachmentDetailDataSchema, CopyAttachmentBodySchema, GetAttachmentQuerySchema } from "../../shared/schemas/agent-tools.schema.js";
2
2
  import { attachmentImageMarkdown } from "../../shared/logic/attachments.js";
3
3
  import { actFor, actingRequest, ago, byteSize, directSpace, resolveTask, taskData, taskKey, taskUpdateSummary, userLabel } from "../core/agent.js";
4
4
  import { NotFoundError, OrganizerError } from "../core/errors.js";
@@ -6,14 +6,69 @@ import { newId } from "../core/ids.js";
6
6
  import { readFile, readingOf } from "./files.js";
7
7
  import { parseInput, respond } from "./types.js";
8
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.
9
+ * Pièces jointes des tâches et images des demandes de l'espace du jeton :
10
+ * lecture (image montrée à l'agent, texte d'un PDF, d'un fichier texte ou
11
+ * Word), envoi d'un fichier que le mode MCP lit sur sa machine, et copie sur
12
+ * une tâche d'une image de demande ou d'une pièce jointe d'une autre tâche.
12
13
  */
13
14
  /** Référence d'une pièce jointe dans un texte : miniature pour une image, nom du fichier sinon. */
14
15
  function attachmentReference(filename, mime, id) {
15
16
  return mime.toLowerCase().startsWith("image/") ? attachmentImageMarkdown(filename, id) : `\`${filename.replace(/`/g, "'")}\``;
16
17
  }
18
+ /** Pièce jointe d'une tâche ou image d'une demande de l'espace ; une image encore en brouillon ou d'un autre espace est introuvable. */
19
+ function findSpaceFile(store, space, id) {
20
+ const attachment = store.findAttachment(id);
21
+ const task = attachment ? store.findTask(attachment.taskId) : null;
22
+ if (attachment && task && task.spaceId === space.id) {
23
+ return { ...attachment, owner: { taskKey: taskKey(store, task), taskTitle: task.title, requestId: null } };
24
+ }
25
+ const image = store.findRequestAttachment(id);
26
+ if (image && image.spaceId === space.id && image.requestId !== null) {
27
+ return { ...image, owner: { taskKey: null, taskTitle: null, requestId: image.requestId } };
28
+ }
29
+ return null;
30
+ }
31
+ /**
32
+ * Joint à une tâche un fichier dont le contenu est donné : pièce jointe,
33
+ * commentaire et ajout à la description éventuels, chacun une action du lot.
34
+ * Le fichier écrit est effacé si l'écriture échoue.
35
+ */
36
+ function attachToTask(store, attachments, agent, target, file) {
37
+ const comment = target.comment?.trim();
38
+ const { filename, mime, content } = file;
39
+ // Refus avant l'écriture du fichier : demande invalide ou tâche hors de l'espace.
40
+ check(store, agent, target.requestId, target.ref);
41
+ const id = newId();
42
+ const storagePath = attachments.write(id, content);
43
+ try {
44
+ const { task, commentId } = actFor(store, agent, target.requestId, (tx, space) => {
45
+ const task = resolveTask(tx.store, space, target.ref);
46
+ const attachment = tx.createAttachment({ id, taskId: task.id, filename, mime, size: content.length, storagePath });
47
+ tx.recordAgentAction({ entityType: "attachment", entityId: id, operation: "create", before: null, after: attachment, summary: `Pièce jointe ajoutée : ${filename}`, taskId: task.id });
48
+ const reference = attachmentReference(filename, mime, id);
49
+ if (target.appendToDescription) {
50
+ const before = tx.store.taskSnapshot(task.id);
51
+ const current = before.description.replace(/\s+$/, "");
52
+ tx.updateTask(task.id, { description: current === "" ? reference : `${current}\n\n${reference}` });
53
+ const after = tx.store.taskSnapshot(task.id);
54
+ tx.recordAgentAction({ entityType: "task", entityId: task.id, operation: "update", before, after, summary: taskUpdateSummary(tx.store, before, after).summary, taskId: task.id });
55
+ }
56
+ let commentId = null;
57
+ if (comment !== undefined && comment !== "") {
58
+ const added = tx.addComment(task.id, `${comment}\n\n${reference}`);
59
+ tx.recordAgentAction({ entityType: "comment", entityId: added.id, operation: "create", before: null, after: added, summary: "Commentaire ajouté", taskId: task.id });
60
+ commentId = added.id;
61
+ }
62
+ return { task, commentId };
63
+ });
64
+ const where = [commentId ? `shown in comment ${commentId}` : null, target.appendToDescription ? "referenced at the end of the description" : null].filter((part) => part !== null);
65
+ 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: target.appendToDescription });
66
+ }
67
+ catch (err) {
68
+ attachments.remove([storagePath]);
69
+ throw err;
70
+ }
71
+ }
17
72
  export const attachmentRoutes = [
18
73
  {
19
74
  method: "GET",
@@ -22,23 +77,22 @@ export const attachmentRoutes = [
22
77
  const input = parseInput(GetAttachmentQuerySchema, query);
23
78
  const space = agent.space;
24
79
  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.`);
80
+ const file = findSpaceFile(store, space, id);
81
+ if (!file) {
82
+ throw new NotFoundError(`Attachment ${id} not found in "${space.name}". Take the id of an attachment from get_task or claim_request, or from a reference attachment:<id> in a text of a task or a request.`);
29
83
  }
30
- const uploader = store.findUser(attachment.uploaderId);
84
+ const uploader = store.findUser(file.uploaderId);
31
85
  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);
86
+ const of = file.owner.requestId === null ? `of task ${file.owner.taskKey} "${file.owner.taskTitle}"` : `of request ${file.owner.requestId}`;
87
+ const header = `Attachment ${file.id} "${file.filename}" (${file.mime}, ${byteSize(file.size)}) ${of}, uploaded by ${uploadedBy} ${ago(file.createdAt)}.`;
88
+ const reading = readingOf(file.filename, file.mime);
35
89
  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.`);
90
+ throw new OrganizerError(`Attachment ${file.id} "${file.filename}" is a ${file.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
91
  }
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}`);
92
+ const what = `attachment ${file.id} "${file.filename}"`;
93
+ const read = await readFile(reading, file.filename, attachments.readPath(file.storagePath), input.part, what, (part) => `get_attachment with part ${part}`);
40
94
  const data = {
41
- attachment: { id: attachment.id, filename: attachment.filename, mime: attachment.mime, size: attachment.size, taskKey: key, uploadedBy, createdAt: attachment.createdAt },
95
+ attachment: { id: file.id, filename: file.filename, mime: file.mime, size: file.size, taskKey: file.owner.taskKey, requestId: file.owner.requestId, uploadedBy, createdAt: file.createdAt },
42
96
  ...read.fields,
43
97
  };
44
98
  return { ...respond(AttachmentDetailDataSchema, [header, "", ...read.lines].join("\n"), data), images: read.images };
@@ -49,41 +103,22 @@ export const attachmentRoutes = [
49
103
  path: "/tasks/:ref/attachments",
50
104
  handle: ({ store, attachments }, { agent, params, body }) => {
51
105
  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;
106
+ const target = { requestId: input.request_id, ref: params.ref, comment: input.comment, appendToDescription: input.append_to_description };
107
+ return attachToTask(store, attachments, agent, target, { filename: input.file.filename, mime: input.file.mime, content: Buffer.from(input.file.content) });
108
+ },
109
+ },
110
+ {
111
+ method: "POST",
112
+ path: "/tasks/:ref/attachments/copy",
113
+ handle: ({ store, attachments }, { agent, params, body }) => {
114
+ const input = parseInput(CopyAttachmentBodySchema, body);
115
+ const space = input.request_id === undefined ? directSpace(store, agent) : actingRequest(store, agent, input.request_id).space;
116
+ const source = findSpaceFile(store, space, input.attachment);
117
+ if (!source) {
118
+ throw new NotFoundError(`Attachment ${input.attachment} not found in "${space.name}". Take the id of an image of the request from claim_request, or of an attachment from get_task.`);
86
119
  }
120
+ const target = { requestId: input.request_id, ref: params.ref, comment: input.comment, appendToDescription: input.append_to_description };
121
+ return attachToTask(store, attachments, agent, target, { filename: source.filename, mime: source.mime, content: attachments.readPath(source.storagePath) });
87
122
  },
88
123
  },
89
124
  ];
@@ -1,4 +1,5 @@
1
1
  import { CheckFollowUpsBodySchema, CheckFollowUpsDataSchema, ClaimRequestBodySchema, ClaimRequestDataSchema, CompleteRequestBodySchema, FailRequestBodySchema, FinishRequestDataSchema, ListRequestsDataSchema, ListRequestsQuerySchema, ReportDirectBodySchema, } from "../../shared/schemas/agent-tools.schema.js";
2
+ import { attachmentsOfRequest } from "../core/request-attachments.js";
2
3
  import { actFor, agentActor, directSpace, ideaData, documentData, memberData, previousSuites, quote, recentIdeas, requestContext, requestData, requestHistory, requestLine, requestOfSpace, requestThread, spaceData, userLabel, treeData, } from "../core/agent.js";
3
4
  import { InvariantError, NotFoundError } from "../core/errors.js";
4
5
  import { parseInput, respond } from "./types.js";
@@ -63,6 +64,7 @@ export const requestRoutes = [
63
64
  tasks: treeData(store, agent.space),
64
65
  ideas: recentIdeas(store, agent.space).map((idea) => ideaData(store, idea)),
65
66
  documents: store.listDocuments(agent.space.id).map((document) => documentData(store, document)),
67
+ attachments: attachmentsOfRequest(store, request).map((attachment) => ({ id: attachment.id, filename: attachment.filename, mime: attachment.mime, size: attachment.size })),
66
68
  });
67
69
  },
68
70
  },
@@ -8,8 +8,9 @@ import { BUSY_TIMEOUT_MS, databasePath } from "../core/db.js";
8
8
  * en service ou non.
9
9
  *
10
10
  * La base est copiée par l'API de sauvegarde de SQLite, qui produit un
11
- * instantané cohérent même pendant les écritures du site. Les pièces jointes
12
- * et les documents d'espace référencés par cet instantané sont ensuite copiés dans le dossier
11
+ * instantané cohérent même pendant les écritures du site. Les pièces jointes,
12
+ * les images des demandes et les documents d'espace référencés par cet
13
+ * instantané sont ensuite copiés dans le dossier
13
14
  * `<fichier>.attachments/`, sous leur nom de stockage. Une pièce jointe
14
15
  * référencée mais introuvable fait échouer la sauvegarde, qui ne laisse alors
15
16
  * rien derrière elle. Une destination existante est refusée, sauf `--force`
@@ -73,7 +74,7 @@ export async function backupSite(dataDir, target, force) {
73
74
  const integrity = copy.pragma("integrity_check", { simple: true });
74
75
  if (integrity !== "ok")
75
76
  throw new Error(`La copie de la base est corrompue (integrity_check : ${String(integrity)}).`);
76
- storagePaths = copy.prepare("SELECT storage_path FROM attachments UNION ALL SELECT storage_path FROM documents ORDER BY storage_path").all().map((row) => row.storage_path);
77
+ storagePaths = copy.prepare("SELECT storage_path FROM attachments UNION ALL SELECT storage_path FROM request_attachments UNION ALL SELECT storage_path FROM documents ORDER BY storage_path").all().map((row) => row.storage_path);
77
78
  }
78
79
  finally {
79
80
  copy.close();
@@ -66,7 +66,7 @@ export declare function spaceTree(store: Store, space: Space): string[];
66
66
  export declare function memberLines(store: Store, space: Space): string[];
67
67
  /** Durée écoulée depuis `iso`, en anglais. */
68
68
  export declare function ago(iso: string, now?: Date): string;
69
- /** Résumé d'une demande pour list_requests. */
69
+ /** Résumé d'une demande pour list_requests : son texte, réduit au-delà de `REQUEST_LINE_EXCERPT` caractères à un extrait signalé comme tel. */
70
70
  export declare function requestLine(store: Store, agent: AgentCaller, request: AgentRequest): string;
71
71
  /**
72
72
  * Échanges précédents de l'auteur d'un message dans l'espace visé, du plus ancien
@@ -79,6 +79,8 @@ 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
+ /** Images d'une demande, avec la façon de les ouvrir et de les joindre à une tâche ; aucune ligne pour une demande sans image. */
83
+ export declare function requestAttachmentLines(store: Store, request: AgentRequest): string[];
82
84
  /** 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
85
  export declare function attachmentLines(store: Store, task: Task): string[];
84
86
  /** Instructions personnalisées de l'agent pour une demande de l'espace : celles du site, puis celles de l'espace. */
@@ -4,6 +4,7 @@ import { noteHash, noteIdOf, noteIdsIn } from "../../shared/logic/notes.js";
4
4
  import { documentFormatOf } from "../../shared/logic/documents.js";
5
5
  import { PRIORITY_LABELS, STATUS_LABELS, TYPE_LABELS } from "../../shared/logic/labels.js";
6
6
  import { summarizeTest } from "../../shared/logic/test-summary.js";
7
+ import { attachmentsOfRequest } from "./request-attachments.js";
7
8
  export function agentActor(agent, requestId) {
8
9
  return { type: "agent", requestId, tokenId: agent.token.id };
9
10
  }
@@ -236,7 +237,9 @@ export function ago(iso, now = new Date()) {
236
237
  }
237
238
  /** Nombre d'idées récentes listées dans le contexte d'une demande. */
238
239
  const CONTEXT_IDEAS = 15;
239
- /** Résumé d'une demande pour list_requests. */
240
+ /** Longueur maximale du texte d'une demande dans list_requests. */
241
+ const REQUEST_LINE_EXCERPT = 200;
242
+ /** Résumé d'une demande pour list_requests : son texte, réduit au-delà de `REQUEST_LINE_EXCERPT` caractères à un extrait signalé comme tel. */
240
243
  export function requestLine(store, agent, request) {
241
244
  const author = store.getUser(request.authorId);
242
245
  const task = request.contextTaskId === null ? null : store.findTask(request.contextTaskId);
@@ -246,7 +249,8 @@ export function requestLine(store, agent, request) {
246
249
  if (task)
247
250
  parts.push(`context ${taskKey(store, task)}`);
248
251
  const text = request.text.trim().replace(/\s+/g, " ");
249
- return `${parts.join(" — ")}\n "${text.length > 200 ? `${text.slice(0, 199)}…` : text}"`;
252
+ const excerpt = text.length > REQUEST_LINE_EXCERPT ? `"${text.slice(0, REQUEST_LINE_EXCERPT - 1)}…" (excerpt: claim_request gives the full text)` : `"${text}"`;
253
+ return `${parts.join(" — ")}\n ${excerpt}`;
250
254
  }
251
255
  /** Ce que l'agent doit faire d'une demande selon son type. */
252
256
  const KIND_GUIDANCE = {
@@ -377,10 +381,22 @@ export function requestContext(store, agent, request) {
377
381
  lines.push(...historyLines(store, previous));
378
382
  }
379
383
  lines.push("", "Text:", request.text, "");
384
+ lines.push(...requestAttachmentLines(store, request));
380
385
  lines.push(...spaceContextLines(store, target));
381
386
  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.");
382
387
  return lines.join("\n");
383
388
  }
389
+ /** Images d'une demande, avec la façon de les ouvrir et de les joindre à une tâche ; aucune ligne pour une demande sans image. */
390
+ export function requestAttachmentLines(store, request) {
391
+ const attachments = attachmentsOfRequest(store, request);
392
+ if (attachments.length === 0)
393
+ return [];
394
+ return [
395
+ "Images of the request, pasted by its author in the text as ![name](attachment:<id>): open each with get_attachment, and attach the ones that matter to the tasks you create or change with copy_attachment, so that a task reads without the request:",
396
+ ...attachments.map((attachment) => `- ${attachment.filename} (${attachment.mime}, ${byteSize(attachment.size)}, id ${attachment.id})`),
397
+ "",
398
+ ];
399
+ }
384
400
  /** 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
401
  export function attachmentLines(store, task) {
386
402
  const attachments = store.listAttachments(task.id);
@@ -791,6 +791,30 @@ export const MIGRATIONS = [
791
791
  // Ouverture d'une tâche par un clic simple sur sa carte : en pleine page ou dans l'aperçu latéral.
792
792
  `
793
793
  ALTER TABLE user_settings ADD COLUMN task_open_mode TEXT NOT NULL DEFAULT 'page' CHECK (task_open_mode IN ('page', 'preview'));
794
+ `,
795
+ // Demande en échec retirée de la liste « En attente » : quand, et par qui.
796
+ `
797
+ ALTER TABLE agent_requests ADD COLUMN dismissed_at TEXT;
798
+ ALTER TABLE agent_requests ADD COLUMN dismissed_by TEXT REFERENCES users(id) ON DELETE SET NULL;
799
+ `,
800
+ // Images jointes aux demandes à l'agent : déposées pendant la saisie (request_id NULL), rattachées à la demande à son envoi.
801
+ `
802
+ CREATE TABLE request_attachments (
803
+ id TEXT PRIMARY KEY,
804
+ space_id TEXT NOT NULL REFERENCES spaces(id) ON DELETE CASCADE,
805
+ request_id TEXT REFERENCES agent_requests(id) ON DELETE CASCADE,
806
+ uploader_id TEXT NOT NULL REFERENCES users(id),
807
+ filename TEXT NOT NULL,
808
+ mime TEXT NOT NULL,
809
+ size INTEGER NOT NULL CHECK (size >= 0),
810
+ storage_path TEXT NOT NULL,
811
+ created_at TEXT NOT NULL
812
+ );
813
+ CREATE INDEX request_attachments_space ON request_attachments(space_id, request_id);
814
+ `,
815
+ // Libellé des boutons de référence à une tâche dans les textes : son numéro ou son titre.
816
+ `
817
+ ALTER TABLE user_settings ADD COLUMN task_link_label TEXT NOT NULL DEFAULT 'key' CHECK (task_link_label IN ('key', 'title'));
794
818
  `,
795
819
  ];
796
820
  /** Version du schéma attendue par ce code. */
@@ -503,7 +503,7 @@ export function markAllNotificationsRead(store, userId) {
503
503
  return unreadCount(store, userId);
504
504
  }
505
505
  function settingsView(store, deps, userId) {
506
- const { notifyAssignApp, notifyAssignEmail, notifyCommentApp, notifyCommentEmail, notifyFollowUpApp, notifyFollowUpEmail, assistantHistory, pomodoro, emailDigestMinutes, sidebarMode, taskOpenMode, } = store.getUserSettings(userId);
506
+ const { notifyAssignApp, notifyAssignEmail, notifyCommentApp, notifyCommentEmail, notifyFollowUpApp, notifyFollowUpEmail, assistantHistory, pomodoro, emailDigestMinutes, sidebarMode, taskOpenMode, taskLinkLabel, } = store.getUserSettings(userId);
507
507
  const reason = notificationEmailBlocker(deps);
508
508
  return {
509
509
  notifyAssignApp,
@@ -517,6 +517,7 @@ function settingsView(store, deps, userId) {
517
517
  emailDigestMinutes,
518
518
  sidebarMode,
519
519
  taskOpenMode,
520
+ taskLinkLabel,
520
521
  email: { enabled: reason === null, reason },
521
522
  transcription: { enabled: deps.transcriber.enabled, reason: deps.transcriber.disabledReason },
522
523
  };
@@ -0,0 +1,33 @@
1
+ import type { AttachmentStorage } from "./attachments.js";
2
+ import type { Mutation, Store } from "./store.js";
3
+ import type { AgentRequest, RequestAttachment } from "../../shared/schemas/entities.schema.js";
4
+ import type { ApiFile } from "../../shared/schemas/gui-api.schema.js";
5
+ import { type AttachmentView, type UploadAttachmentRequest } from "../../shared/schemas/tasks-api.schema.js";
6
+ /**
7
+ * Images jointes aux demandes à l'agent. Un membre en dépose une pendant la
8
+ * saisie d'une demande : elle reste un brouillon, que lui seul voit et
9
+ * retire, jusqu'à l'envoi de la demande qui la référence
10
+ * (`![nom](attachment:<id>)`), à laquelle elle est alors rattachée ; les
11
+ * membres de l'espace la voient ensuite comme la demande. Un brouillon
12
+ * rattaché à aucune demande au bout de `DRAFT_LIFETIME_MS` est effacé au
13
+ * dépôt suivant.
14
+ */
15
+ /** Durée de vie d'une image déposée et rattachée à aucune demande. */
16
+ export declare const DRAFT_LIFETIME_MS: number;
17
+ export declare function requestAttachmentView(attachment: RequestAttachment): AttachmentView;
18
+ /**
19
+ * Dépose une image pour une demande en cours d'écriture dans l'espace
20
+ * `spaceId`, aux limites des pièces jointes des tâches ; les brouillons
21
+ * périmés de tous les espaces sont effacés au passage.
22
+ */
23
+ export declare function uploadRequestAttachment(store: Store, storage: AttachmentStorage, userId: string, spaceId: string, input: UploadAttachmentRequest, now?: Date): AttachmentView;
24
+ /** Contenu d'une image de demande, avec son type et son nom ; null si l'identifiant ne désigne aucune image de demande. */
25
+ export declare function downloadRequestAttachment(store: Store, storage: AttachmentStorage, userId: string, attachmentId: string): ApiFile | null;
26
+ /** Retire une image déposée par l'utilisateur pour une demande qu'il n'a pas encore envoyée. */
27
+ export declare function deleteRequestAttachment(store: Store, storage: AttachmentStorage, userId: string, attachmentId: string): void;
28
+ /** Identifiants des images référencées par un texte de demande, dans l'ordre du texte. */
29
+ export declare function referencedAttachmentIds(text: string): string[];
30
+ /** Rattache à une demande les images que son texte référence et que son auteur a déposées pour elle. */
31
+ export declare function linkReferencedAttachments(tx: Mutation, request: AgentRequest): void;
32
+ /** Images d'une demande pour l'agent : celles que son texte référence dans son espace, puis celles qui lui sont rattachées sans y être citées. */
33
+ export declare function attachmentsOfRequest(store: Store, request: AgentRequest): RequestAttachment[];