@imenam/mcp-organizer 1.0.20 → 1.0.21

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 (106) hide show
  1. package/README.md +103 -29
  2. package/dist/shared/logic/attachments.d.ts +28 -0
  3. package/dist/shared/logic/attachments.js +52 -0
  4. package/dist/shared/logic/documents.d.ts +22 -0
  5. package/dist/shared/logic/documents.js +38 -0
  6. package/dist/shared/logic/line-diff.d.ts +13 -0
  7. package/dist/shared/logic/line-diff.js +66 -0
  8. package/dist/shared/logic/notes.d.ts +12 -0
  9. package/dist/shared/logic/notes.js +23 -0
  10. package/dist/shared/logic/timer.d.ts +69 -0
  11. package/dist/shared/logic/timer.js +87 -0
  12. package/dist/shared/schemas/agent-api.schema.d.ts +10 -29
  13. package/dist/shared/schemas/agent-api.schema.js +4 -15
  14. package/dist/shared/schemas/agent-tools.schema.d.ts +522 -2
  15. package/dist/shared/schemas/agent-tools.schema.js +111 -6
  16. package/dist/shared/schemas/api.schema.d.ts +7 -0
  17. package/dist/shared/schemas/api.schema.js +6 -0
  18. package/dist/shared/schemas/documents-api.schema.d.ts +49 -0
  19. package/dist/shared/schemas/documents-api.schema.js +38 -0
  20. package/dist/shared/schemas/entities.schema.d.ts +107 -54
  21. package/dist/shared/schemas/entities.schema.js +81 -10
  22. package/dist/shared/schemas/enums.schema.d.ts +19 -3
  23. package/dist/shared/schemas/enums.schema.js +8 -2
  24. package/dist/shared/schemas/gui-api.schema.d.ts +1 -0
  25. package/dist/shared/schemas/gui-api.schema.js +2 -0
  26. package/dist/shared/schemas/history-api.schema.d.ts +961 -0
  27. package/dist/shared/schemas/history-api.schema.js +104 -0
  28. package/dist/shared/schemas/notes-api.schema.d.ts +54 -0
  29. package/dist/shared/schemas/notes-api.schema.js +38 -0
  30. package/dist/shared/schemas/notifications-api.schema.d.ts +12 -0
  31. package/dist/shared/schemas/notifications-api.schema.js +4 -1
  32. package/dist/shared/schemas/tasks-api.schema.d.ts +39 -0
  33. package/dist/shared/schemas/tasks-api.schema.js +5 -0
  34. package/dist/shared/schemas/timers-api.schema.d.ts +119 -0
  35. package/dist/shared/schemas/timers-api.schema.js +44 -0
  36. package/dist/shared/schemas/views-api.schema.d.ts +16 -0
  37. package/dist/shared/schemas/views-api.schema.js +4 -2
  38. package/dist/src/agent-api/documents.d.ts +3 -0
  39. package/dist/src/agent-api/documents.js +66 -0
  40. package/dist/src/agent-api/history.d.ts +3 -0
  41. package/dist/src/agent-api/history.js +103 -0
  42. package/dist/src/agent-api/notes.d.ts +3 -0
  43. package/dist/src/agent-api/notes.js +39 -0
  44. package/dist/src/agent-api/requests.js +2 -1
  45. package/dist/src/agent-api/router.js +5 -1
  46. package/dist/src/agent-api/tasks.js +17 -6
  47. package/dist/src/agent-api/timers.d.ts +2 -0
  48. package/dist/src/agent-api/timers.js +170 -0
  49. package/dist/src/agent-api/types.d.ts +3 -0
  50. package/dist/src/agent-api/views.js +15 -30
  51. package/dist/src/cli/backup.js +3 -3
  52. package/dist/src/core/accounts.d.ts +12 -5
  53. package/dist/src/core/accounts.js +28 -10
  54. package/dist/src/core/agent.d.ts +27 -3
  55. package/dist/src/core/agent.js +118 -1
  56. package/dist/src/core/attachments.d.ts +6 -3
  57. package/dist/src/core/attachments.js +9 -4
  58. package/dist/src/core/board-views.js +4 -4
  59. package/dist/src/core/document-text.d.ts +17 -0
  60. package/dist/src/core/document-text.js +118 -0
  61. package/dist/src/core/documents.d.ts +22 -0
  62. package/dist/src/core/documents.js +168 -0
  63. package/dist/src/core/history-events.d.ts +34 -0
  64. package/dist/src/core/history-events.js +236 -0
  65. package/dist/src/core/history.js +33 -3
  66. package/dist/src/core/migrations.js +153 -0
  67. package/dist/src/core/notes.d.ts +23 -0
  68. package/dist/src/core/notes.js +78 -0
  69. package/dist/src/core/notifications.d.ts +48 -5
  70. package/dist/src/core/notifications.js +209 -33
  71. package/dist/src/core/password-reset.d.ts +37 -0
  72. package/dist/src/core/password-reset.js +56 -0
  73. package/dist/src/core/requests.d.ts +4 -3
  74. package/dist/src/core/requests.js +5 -4
  75. package/dist/src/core/snapshots.d.ts +3 -3
  76. package/dist/src/core/snapshots.js +3 -1
  77. package/dist/src/core/space-history.d.ts +18 -0
  78. package/dist/src/core/space-history.js +86 -0
  79. package/dist/src/core/spaces.d.ts +1 -1
  80. package/dist/src/core/spaces.js +4 -4
  81. package/dist/src/core/store.d.ts +154 -11
  82. package/dist/src/core/store.js +479 -52
  83. package/dist/src/core/task-history.d.ts +9 -5
  84. package/dist/src/core/task-history.js +17 -25
  85. package/dist/src/core/tasks.d.ts +2 -2
  86. package/dist/src/core/tasks.js +13 -2
  87. package/dist/src/core/timers.d.ts +33 -0
  88. package/dist/src/core/timers.js +101 -0
  89. package/dist/src/core/versions.d.ts +22 -0
  90. package/dist/src/core/versions.js +106 -0
  91. package/dist/src/gui-api.d.ts +4 -1
  92. package/dist/src/gui-api.js +85 -6
  93. package/dist/src/mcp/start.d.ts +1 -1
  94. package/dist/src/mcp/start.js +12 -7
  95. package/dist/src/mcp/tools.js +129 -3
  96. package/dist/src/server/app.d.ts +4 -2
  97. package/dist/src/server/app.js +21 -5
  98. package/dist/src/server/login-limiter.d.ts +27 -1
  99. package/dist/src/server/login-limiter.js +31 -1
  100. package/dist/src/server/start.js +1 -0
  101. package/gui/dist/assets/index-DbzcjyaW.js +104 -0
  102. package/gui/dist/assets/index-Dvf5Yo0e.css +1 -0
  103. package/gui/dist/index.html +2 -2
  104. package/package.json +1 -1
  105. package/gui/dist/assets/index-9c9BlfUi.js +0 -99
  106. package/gui/dist/assets/index-DH23A5aa.css +0 -1
@@ -2,15 +2,19 @@ import { NotFoundError } from "./errors.js";
2
2
  import { requireMember } from "./spaces.js";
3
3
  /**
4
4
  * Notifications (assignation, commentaire, demande traitée avec des points à
5
- * régler) et préférences. Les notifications
6
- * sont créées par le store dans la transaction de l'événement ; leurs e-mails
7
- * partent après la validation, et l'issue de chaque envoi est enregistrée.
5
+ * régler) et préférences. Les notifications sont créées par le store dans la
6
+ * transaction de l'événement ; leurs e-mails partent après la validation, et
7
+ * l'issue de chaque envoi est enregistrée.
8
8
  */
9
9
  const asUser = (userId) => ({ type: "user", userId });
10
10
  /** Longueur maximale de l'extrait d'un commentaire. */
11
11
  const EXCERPT_LENGTH = 120;
12
12
  /** Nom de l'agent dans les phrases des notifications. */
13
13
  const AGENT_NAME = "L'agent";
14
+ /** Délai maximal pendant lequel les e-mails d'un lot de l'agent attendent la clôture de sa demande. */
15
+ export const AGENT_EMAIL_MAX_DELAY_MS = 15 * 60_000;
16
+ /** Pied des e-mails de notification. */
17
+ const UNSUBSCRIBE = "Ces e-mails se désactivent dans les Paramètres de mcp-organizer.";
14
18
  function publicBase(publicUrl) {
15
19
  return publicUrl?.trim().replace(/\/+$/, "") || null;
16
20
  }
@@ -34,81 +38,182 @@ function actorName(store, notification) {
34
38
  const actor = store.findUser(notification.actorId);
35
39
  return actor ? (actor.displayName ?? actor.email) : null;
36
40
  }
41
+ function userName(store, userId) {
42
+ const user = store.findUser(userId);
43
+ return user ? (user.displayName ?? user.email) : "un ancien membre";
44
+ }
45
+ /** Vrai si l'e-mail de la notification attend la fin du lot de l'agent qui l'a créée. */
46
+ function batched(notification) {
47
+ return notification.actorType === "agent" && notification.requestId !== null;
48
+ }
37
49
  /**
38
- * Envoi des e-mails de notification. Abonné au store, il reçoit les
39
- * notifications dont le destinataire veut un e-mail après la validation de
40
- * la mutation qui les a créées, envoie chaque e-mail et enregistre son issue
41
- * (`emailedAt` ou `emailError`).
50
+ * Envoi des e-mails de notification. Le store marque en base les
51
+ * notifications à envoyer par e-mail ; après chaque mutation qui peut en
52
+ * rendre prêtes, au démarrage et à l'échéance du prochain lot, l'envoi
53
+ * parcourt celles en attente :
54
+ *
55
+ * - celle d'une action d'un utilisateur part aussitôt, seule ;
56
+ * - celles de l'agent sont regroupées par destinataire et par lot (la demande
57
+ * pour laquelle il agit) : un seul e-mail part quand la demande quitte
58
+ * `processing` (traitée, échouée, libérée), ou au plus tard `maxDelayMs`
59
+ * après la plus ancienne notification du groupe.
60
+ *
61
+ * L'issue de l'envoi (`emailedAt` ou `emailError`) est enregistrée sur chaque
62
+ * notification de l'e-mail, ce qui lève son attente. Une notification encore
63
+ * en attente à l'arrêt du site part au démarrage suivant.
42
64
  */
43
65
  export class NotificationMailer {
44
66
  store;
45
67
  deps;
46
68
  inFlight = new Set();
69
+ /** Notifications dont l'e-mail est en cours d'envoi. */
70
+ sending = new Set();
71
+ /** Notifications dont l'issue n'a pas pu être enregistrée : ignorées jusqu'au prochain démarrage. */
72
+ abandoned = new Set();
73
+ timer = null;
47
74
  constructor(store, deps) {
48
75
  this.store = store;
49
76
  this.deps = deps;
50
77
  }
51
- /** Abonne l'envoi aux mutations du store. */
78
+ get maxDelayMs() {
79
+ return this.deps.maxDelayMs ?? AGENT_EMAIL_MAX_DELAY_MS;
80
+ }
81
+ now() {
82
+ return (this.deps.now ?? Date.now)();
83
+ }
84
+ /** Abonne l'envoi aux mutations du store et envoie les e-mails déjà prêts. */
52
85
  attach() {
53
- this.store.setEmailListener((ids) => this.enqueue(ids));
86
+ this.store.setEmailListener(() => this.sweep());
87
+ this.sweep();
54
88
  return this;
55
89
  }
90
+ /** Désabonne l'envoi et annule l'échéance programmée. */
91
+ detach() {
92
+ this.store.setEmailListener(null);
93
+ this.clearTimer();
94
+ }
56
95
  /** Attend la fin des envois en cours. */
57
96
  async flush() {
58
97
  while (this.inFlight.size > 0)
59
98
  await Promise.all([...this.inFlight]);
60
99
  }
100
+ /** Envoie les e-mails prêts à partir et programme l'échéance du prochain lot en attente. */
101
+ sweep() {
102
+ this.clearTimer();
103
+ let pending;
104
+ try {
105
+ pending = this.store.listEmailPendingNotifications();
106
+ }
107
+ catch (err) {
108
+ this.deps.logError(`Listing the pending notification e-mails failed: ${err?.stack ?? err}`);
109
+ return;
110
+ }
111
+ const groups = new Map();
112
+ for (const notification of pending) {
113
+ if (this.sending.has(notification.id) || this.abandoned.has(notification.id))
114
+ continue;
115
+ const key = batched(notification) ? `${notification.userId} ${notification.requestId}` : notification.id;
116
+ const group = groups.get(key);
117
+ if (group)
118
+ group.push(notification);
119
+ else
120
+ groups.set(key, [notification]);
121
+ }
122
+ let next = Infinity;
123
+ for (const group of groups.values()) {
124
+ const deadline = Date.parse(group[0].createdAt) + this.maxDelayMs;
125
+ if (this.ready(group[0], deadline))
126
+ this.enqueue(group.map((notification) => notification.id));
127
+ else
128
+ next = Math.min(next, deadline);
129
+ }
130
+ if (next < Infinity) {
131
+ this.timer = setTimeout(() => this.sweep(), Math.max(0, next - this.now()));
132
+ this.timer.unref?.();
133
+ }
134
+ }
135
+ clearTimer() {
136
+ if (this.timer)
137
+ clearTimeout(this.timer);
138
+ this.timer = null;
139
+ }
140
+ /** Vrai si le groupe dont `first` est la plus ancienne notification peut partir. */
141
+ ready(first, deadline) {
142
+ if (!batched(first) || this.now() >= deadline)
143
+ return true;
144
+ const request = this.store.findAgentRequest(first.requestId);
145
+ return request === null || request.status !== "processing";
146
+ }
61
147
  enqueue(ids) {
62
- const delivery = this.deliver(ids).finally(() => this.inFlight.delete(delivery));
148
+ for (const id of ids)
149
+ this.sending.add(id);
150
+ const delivery = this.deliver(ids).finally(() => {
151
+ for (const id of ids)
152
+ this.sending.delete(id);
153
+ this.inFlight.delete(delivery);
154
+ });
63
155
  this.inFlight.add(delivery);
64
156
  }
157
+ /** Envoie un e-mail pour les notifications `ids`, d'un même destinataire, et enregistre son issue sur chacune. */
65
158
  async deliver(ids) {
66
- for (const id of ids) {
159
+ try {
160
+ const notifications = this.existing(ids);
161
+ if (notifications.length === 0)
162
+ return;
163
+ const outcome = await this.send(notifications);
164
+ // Une notification disparaît avec sa tâche ou son commentaire, éventuellement supprimés pendant l'envoi.
165
+ this.record(this.existing(ids), outcome);
166
+ }
167
+ catch (err) {
168
+ this.deps.logError(`E-mail of notification(s) ${ids.join(", ")} failed: ${err?.stack ?? err}`);
67
169
  try {
68
- const notification = this.store.findNotification(id);
69
- if (!notification)
70
- continue;
71
- const outcome = await this.send(notification);
72
- // La notification disparaît avec sa tâche ou son commentaire, éventuellement supprimés pendant l'envoi.
73
- if (!this.store.findNotification(id))
74
- continue;
75
- this.store.mutate(asUser(notification.userId), (tx) => tx.recordNotificationEmail(id, outcome));
170
+ this.record(this.existing(ids), { sent: false, reason: `L'envoi de l'e-mail a échoué : ${err?.message ?? err}` });
76
171
  }
77
- catch (err) {
78
- this.deps.logError(`E-mail of notification ${id} failed: ${err?.stack ?? err}`);
172
+ catch (recordErr) {
173
+ for (const id of ids)
174
+ this.abandoned.add(id);
175
+ this.deps.logError(`Recording the failed e-mail of notification(s) ${ids.join(", ")} failed: ${recordErr?.stack ?? recordErr}`);
79
176
  }
80
177
  }
81
178
  }
82
- async send(notification) {
179
+ existing(ids) {
180
+ return ids.map((id) => this.store.findNotification(id)).filter((notification) => notification !== null);
181
+ }
182
+ record(notifications, outcome) {
183
+ if (notifications.length === 0)
184
+ return;
185
+ this.store.mutate(asUser(notifications[0].userId), (tx) => {
186
+ for (const notification of notifications)
187
+ tx.recordNotificationEmail(notification.id, outcome);
188
+ });
189
+ }
190
+ async send(notifications) {
83
191
  const blocker = notificationEmailBlocker(this.deps);
84
192
  if (blocker)
85
193
  return { sent: false, reason: blocker };
86
- const recipient = this.store.getUser(notification.userId);
87
- const outcome = await this.deps.mailer.send(this.message(notification, recipient.email));
194
+ const recipient = this.store.getUser(notifications[0].userId);
195
+ const message = notifications.length === 1 ? this.message(notifications[0], recipient.email) : this.digest(notifications, recipient.email);
196
+ const outcome = await this.deps.mailer.send(message);
88
197
  return outcome.sent ? { sent: true } : { sent: false, reason: outcome.reason };
89
198
  }
90
199
  message(notification, to) {
91
- const base = publicBase(this.deps.publicUrl);
92
- const unsubscribe = "Ces e-mails se désactivent dans les Paramètres de mcp-organizer.";
93
200
  if (notification.taskId === null) {
94
201
  const request = this.store.getAgentRequest(notification.requestId ?? "");
95
202
  const space = this.store.getSpace(request.targetSpaceId);
96
- const points = this.store.listFollowUps(request.id).filter((point) => point.doneAt === null);
97
- const url = `${base}/#/agent/demande/${encodeURIComponent(request.id)}`;
203
+ const points = this.openPoints(request.id);
98
204
  return {
99
205
  to,
100
206
  subject: `${AGENT_NAME} a traité ta demande : ${pointsLabel(points.length)} à traiter de ton côté`,
101
207
  text: `${AGENT_NAME} a traité ta demande « ${excerpt(request.text)} » dans l'espace « ${space.name} ». Il reste à traiter de ton côté :\n\n${points
102
- .map((point) => `- ${point.text}`)
103
- .join("\n")}\n\nOuvrir la demande : ${url}\n\n${unsubscribe}\n`,
208
+ .map((point) => `- ${point}`)
209
+ .join("\n")}\n\nOuvrir la demande : ${this.requestUrl(request.id)}\n\n${UNSUBSCRIBE}\n`,
104
210
  };
105
211
  }
106
212
  const task = this.store.getTask(notification.taskId);
107
213
  const space = this.store.getSpace(task.spaceId);
108
214
  const key = `${space.keyPrefix}-${task.number}`;
109
215
  const who = actorName(this.store, notification) ?? AGENT_NAME;
110
- const url = `${base}/#/task/${encodeURIComponent(task.id)}`;
111
- const footer = `\n\nOuvrir la tâche : ${url}\n\n${unsubscribe}\n`;
216
+ const footer = `\n\nOuvrir la tâche : ${this.taskUrl(task.id)}\n\n${UNSUBSCRIBE}\n`;
112
217
  if (notification.type === "assigned") {
113
218
  return {
114
219
  to,
@@ -123,6 +228,76 @@ export class NotificationMailer {
123
228
  text: `${who} a commenté la tâche ${key} « ${task.title} » dans l'espace « ${space.name} » :\n\n${comment?.body ?? ""}${footer}`,
124
229
  };
125
230
  }
231
+ /**
232
+ * E-mail récapitulatif des notifications d'un lot de l'agent : la demande
233
+ * d'origine, chaque tâche concernée avec ce qui la touche et son lien, puis
234
+ * les points à traiter laissés à l'auteur de la demande.
235
+ */
236
+ digest(notifications, to) {
237
+ const request = this.store.findAgentRequest(notifications[0].requestId);
238
+ const byTask = new Map();
239
+ let followUps = null;
240
+ for (const notification of notifications) {
241
+ if (notification.taskId === null) {
242
+ followUps = notification;
243
+ continue;
244
+ }
245
+ const list = byTask.get(notification.taskId);
246
+ if (list)
247
+ list.push(notification);
248
+ else
249
+ byTask.set(notification.taskId, [notification]);
250
+ }
251
+ const space = this.store.getSpace(request?.targetSpaceId ?? this.store.getTask([...byTask.keys()][0]).spaceId);
252
+ const intro = !request
253
+ ? `${AGENT_NAME} a agi dans l'espace « ${space.name} ».`
254
+ : request.kind === "direct"
255
+ ? `${AGENT_NAME} a agi dans l'espace « ${space.name} » à la demande directe de ${userName(this.store, request.authorId)}.`
256
+ : `${AGENT_NAME} a agi dans l'espace « ${space.name} » pour la demande « ${excerpt(request.text)} » de ${userName(this.store, request.authorId)}.`;
257
+ const status = request?.status === "processing"
258
+ ? `\n${AGENT_NAME} n'a pas encore terminé cette demande.`
259
+ : request?.status === "failed"
260
+ ? `\nLa demande a échoué${request.failureReason ? ` : ${request.failureReason}` : "."}`
261
+ : "";
262
+ const sections = [];
263
+ for (const [taskId, list] of byTask) {
264
+ const task = this.store.getTask(taskId);
265
+ const lines = list.map((notification) => {
266
+ if (notification.type === "assigned")
267
+ return "- vous a assigné cette tâche";
268
+ const comment = notification.commentId === null ? null : this.store.findComment(notification.commentId);
269
+ const body = (comment?.body ?? "").trim().replace(/\r?\n/g, "\n ");
270
+ return body ? `- a commenté :\n ${body}` : "- a commenté";
271
+ });
272
+ sections.push(`${space.keyPrefix}-${task.number} « ${task.title} »\n${lines.join("\n")}\nOuvrir la tâche : ${this.taskUrl(task.id)}`);
273
+ }
274
+ if (followUps) {
275
+ const points = this.openPoints(followUps.requestId);
276
+ sections.push(`Il reste à traiter de ton côté :\n${points.map((point) => `- ${point}`).join("\n")}\nOuvrir la demande : ${this.requestUrl(followUps.requestId)}`);
277
+ }
278
+ return {
279
+ to,
280
+ subject: `${AGENT_NAME} : ${notificationsLabel(notifications.length)} dans l'espace « ${space.name} »`,
281
+ text: `${intro}${status}\n\n${sections.join("\n\n")}\n\n${UNSUBSCRIBE}\n`,
282
+ };
283
+ }
284
+ /** Textes des points encore ouverts d'une demande. */
285
+ openPoints(requestId) {
286
+ return this.store
287
+ .listFollowUps(requestId)
288
+ .filter((point) => point.doneAt === null)
289
+ .map((point) => point.text);
290
+ }
291
+ taskUrl(taskId) {
292
+ return `${publicBase(this.deps.publicUrl)}/#/task/${encodeURIComponent(taskId)}`;
293
+ }
294
+ requestUrl(requestId) {
295
+ return `${publicBase(this.deps.publicUrl)}/#/agent/demande/${encodeURIComponent(requestId)}`;
296
+ }
297
+ }
298
+ /** « 1 notification », « 3 notifications ». */
299
+ function notificationsLabel(count) {
300
+ return `${count} notification${count > 1 ? "s" : ""}`;
126
301
  }
127
302
  /** « 1 point », « 3 points ». */
128
303
  function pointsLabel(count) {
@@ -179,7 +354,7 @@ export function markAllNotificationsRead(store, userId) {
179
354
  return unreadCount(store, userId);
180
355
  }
181
356
  function settingsView(store, deps, userId) {
182
- const { notifyAssignApp, notifyAssignEmail, notifyCommentApp, notifyCommentEmail, notifyFollowUpApp, notifyFollowUpEmail, assistantHistory } = store.getUserSettings(userId);
357
+ const { notifyAssignApp, notifyAssignEmail, notifyCommentApp, notifyCommentEmail, notifyFollowUpApp, notifyFollowUpEmail, assistantHistory, pomodoro } = store.getUserSettings(userId);
183
358
  const reason = notificationEmailBlocker(deps);
184
359
  return {
185
360
  notifyAssignApp,
@@ -189,6 +364,7 @@ function settingsView(store, deps, userId) {
189
364
  notifyFollowUpApp,
190
365
  notifyFollowUpEmail,
191
366
  assistantHistory,
367
+ pomodoro,
192
368
  email: { enabled: reason === null, reason },
193
369
  transcription: { enabled: deps.transcriber.enabled, reason: deps.transcriber.disabledReason },
194
370
  };
@@ -0,0 +1,37 @@
1
+ import type { Mailer } from "./mail.js";
2
+ import type { Store } from "./store.js";
3
+ import type { User } from "../../shared/schemas/entities.schema.js";
4
+ /**
5
+ * Mot de passe oublié : une adresse reçoit par e-mail un lien de
6
+ * réinitialisation à usage unique, valable `RESET_LINK_TTL_MINUTES` minutes. La demande
7
+ * répond de la même façon que l'adresse ait un compte actif ou non : l'e-mail
8
+ * part en arrière-plan et son issue n'est écrite que dans le journal du site.
9
+ */
10
+ /** Journal du site, qui reçoit les demandes, les réinitialisations et les échecs d'envoi. */
11
+ export interface PasswordResetLog {
12
+ info: (message: string) => void;
13
+ error: (message: string) => void;
14
+ }
15
+ /** Dépendances de la réinitialisation du mot de passe. */
16
+ export interface PasswordResetDeps {
17
+ mailer: Mailer;
18
+ /** URL publique de la GUI (`ORGANIZER_PUBLIC_URL`), base du lien envoyé. */
19
+ publicUrl: string | undefined;
20
+ log: PasswordResetLog;
21
+ now?: () => Date;
22
+ }
23
+ /** Raison pour laquelle la réinitialisation par e-mail est indisponible sur le site, ou null. */
24
+ export declare function passwordResetBlocker(deps: Pick<PasswordResetDeps, "mailer" | "publicUrl">): string | null;
25
+ /**
26
+ * Traite une demande de réinitialisation pour `rawEmail`. Un compte actif
27
+ * reçoit un nouveau lien, qui remplace le précédent ; une adresse inconnue, un
28
+ * compte à activer ou désactivé ne reçoivent rien. `delivery` se résout une
29
+ * fois l'e-mail parti ou son échec journalisé ; l'appelant n'a pas à l'attendre.
30
+ */
31
+ export declare function requestPasswordReset(store: Store, deps: PasswordResetDeps, rawEmail: string): {
32
+ delivery: Promise<void>;
33
+ };
34
+ /** Journalise une réinitialisation faite et envoie l'e-mail de confirmation au compte. */
35
+ export declare function confirmPasswordReset(deps: PasswordResetDeps, user: User): {
36
+ delivery: Promise<void>;
37
+ };
@@ -0,0 +1,56 @@
1
+ import { accessLinkPath, issueAccessLink, normalizeEmail } from "./accounts.js";
2
+ import { OrganizerError } from "./errors.js";
3
+ import { RESET_LINK_TTL_MINUTES } from "../../shared/schemas/api.schema.js";
4
+ function publicBase(publicUrl) {
5
+ return publicUrl?.trim().replace(/\/+$/, "") || null;
6
+ }
7
+ /** Raison pour laquelle la réinitialisation par e-mail est indisponible sur le site, ou null. */
8
+ export function passwordResetBlocker(deps) {
9
+ const contact = "Demandez à l'administrateur du site de redéfinir votre mot de passe (commande --set-user).";
10
+ if (!deps.mailer.enabled)
11
+ return `Récupération du mot de passe indisponible : l'envoi d'e-mail n'est pas configuré sur ce site (${deps.mailer.disabledReason}). ${contact}`;
12
+ if (!publicBase(deps.publicUrl)) {
13
+ return `Récupération du mot de passe indisponible : ORGANIZER_PUBLIC_URL n'est pas défini dans la configuration du site, le lien ne peut pas figurer dans l'e-mail. ${contact}`;
14
+ }
15
+ return null;
16
+ }
17
+ /** Envoie un e-mail et journalise son issue. */
18
+ async function deliver(deps, to, subject, text, what) {
19
+ const outcome = await deps.mailer.send({ to, subject, text });
20
+ if (outcome.sent)
21
+ deps.log.info(`Password reset: ${what} sent to ${to}.`);
22
+ else
23
+ deps.log.error(`Password reset: ${what} to ${to} not sent: ${outcome.reason}`);
24
+ }
25
+ /**
26
+ * Traite une demande de réinitialisation pour `rawEmail`. Un compte actif
27
+ * reçoit un nouveau lien, qui remplace le précédent ; une adresse inconnue, un
28
+ * compte à activer ou désactivé ne reçoivent rien. `delivery` se résout une
29
+ * fois l'e-mail parti ou son échec journalisé ; l'appelant n'a pas à l'attendre.
30
+ */
31
+ export function requestPasswordReset(store, deps, rawEmail) {
32
+ const blocker = passwordResetBlocker(deps);
33
+ if (blocker)
34
+ throw new OrganizerError(blocker);
35
+ const email = normalizeEmail(rawEmail);
36
+ const now = deps.now?.() ?? new Date();
37
+ const user = store.findUserByEmail(email);
38
+ if (!user || user.status !== "active" || user.passwordHash === null) {
39
+ deps.log.info(`Password reset requested for ${email}: no active account, no e-mail sent.`);
40
+ return { delivery: Promise.resolve() };
41
+ }
42
+ const issued = store.mutate({ type: "user", userId: user.id }, (tx) => issueAccessLink(tx, user.id, "reset", null, now));
43
+ deps.log.info(`Password reset requested for ${email}: link issued, valid until ${issued.expiresAt}.`);
44
+ const url = `${publicBase(deps.publicUrl)}/${accessLinkPath(issued.token)}`;
45
+ const text = `Une réinitialisation du mot de passe de votre compte mcp-organizer (${email}) a été demandée.\n\n` +
46
+ `Pour choisir un nouveau mot de passe, ouvrez ce lien, valable ${RESET_LINK_TTL_MINUTES} minutes et une seule fois :\n${url}\n\n` +
47
+ "Si vous n'êtes pas à l'origine de cette demande, ignorez ce message : votre mot de passe reste inchangé.\n";
48
+ return { delivery: deliver(deps, email, "Réinitialisation de votre mot de passe", text, "reset link") };
49
+ }
50
+ /** Journalise une réinitialisation faite et envoie l'e-mail de confirmation au compte. */
51
+ export function confirmPasswordReset(deps, user) {
52
+ deps.log.info(`Password reset completed for ${user.email}: other sessions closed.`);
53
+ const text = `Le mot de passe de votre compte mcp-organizer (${user.email}) vient d'être modifié, et vos autres sessions ont été fermées.\n\n` +
54
+ "Si vous n'êtes pas à l'origine de ce changement, faites immédiatement une demande depuis « Mot de passe oublié ? » sur l'écran de connexion, puis prévenez l'administrateur du site.\n";
55
+ return { delivery: deliver(deps, user.email, "Votre mot de passe a été modifié", text, "confirmation") };
56
+ }
@@ -53,9 +53,10 @@ export declare function createSuite(store: Store, userId: string, requestId: str
53
53
  export declare function setFollowUpDone(store: Store, userId: string, followUpId: string, done: boolean): RequestView;
54
54
  export declare function getRequest(store: Store, userId: string, requestId: string): RequestView;
55
55
  /**
56
- * Demandes d'un espace, avec le nombre de demandes en attente et les jetons
57
- * actifs qui couvrent l'espace, chacun avec son dernier usage et la présence
58
- * de son veilleur de notifications.
56
+ * Demandes d'un espace, avec le nombre de demandes que l'agent n'a pas prises,
57
+ * celui des demandes qui attendent l'utilisateur, et les jetons actifs qui
58
+ * couvrent l'espace, chacun avec son dernier usage et la présence de son
59
+ * veilleur de notifications.
59
60
  */
60
61
  export declare function listRequests(store: Store, userId: string, spaceId: string, runner: {
61
62
  disabledReason: string | null;
@@ -238,9 +238,10 @@ export function getRequest(store, userId, requestId) {
238
238
  return requestView(store, userId, requireVisibleRequest(store, userId, requestId));
239
239
  }
240
240
  /**
241
- * Demandes d'un espace, avec le nombre de demandes en attente et les jetons
242
- * actifs qui couvrent l'espace, chacun avec son dernier usage et la présence
243
- * de son veilleur de notifications.
241
+ * Demandes d'un espace, avec le nombre de demandes que l'agent n'a pas prises,
242
+ * celui des demandes qui attendent l'utilisateur, et les jetons actifs qui
243
+ * couvrent l'espace, chacun avec son dernier usage et la présence de son
244
+ * veilleur de notifications.
244
245
  */
245
246
  export function listRequests(store, userId, spaceId, runner, now = new Date()) {
246
247
  const { space } = requireMember(store, spaceId, userId);
@@ -249,7 +250,7 @@ export function listRequests(store, userId, spaceId, runner, now = new Date()) {
249
250
  .listAgentTokensOfSpace(spaceId)
250
251
  .filter((token) => tokenState(store, token, now) === "active" && (!token.isRunner || space.runnerAllowed))
251
252
  .map((token) => ({ ...agentRef(store, token), lastUsedAt: token.lastUsedAt, listening: store.watchers.status(token.id).armed }));
252
- return { requests, pendingCount: store.countPendingRequestsOfSpace(spaceId), agents, runnerAllowed: space.runnerAllowed, runnerDisabledReason: runner.disabledReason, runnerFailure: runner.failure, runnerSession: runner.session };
253
+ return { requests, pendingCount: store.countPendingRequestsOfSpace(spaceId), waitingCount: store.countWaitingRequestsOfSpace(spaceId), agents, runnerAllowed: space.runnerAllowed, runnerDisabledReason: runner.disabledReason, runnerFailure: runner.failure, runnerSession: runner.session };
253
254
  }
254
255
  // --- Annulation -----------------------------------------------------------------
255
256
  /**
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import type { Store } from "./store.js";
3
3
  import type { EntityType } from "../../shared/schemas/enums.schema.js";
4
- import { type AgentAction, type BoardView, type ChecklistItem, type Comment, type FollowUp, type Idea, type QuestionSnapshot, type TaskSnapshot } from "../../shared/schemas/entities.schema.js";
4
+ import { type AgentAction, type BoardView, type ChecklistItem, type Comment, type FollowUp, type Idea, type QuestionSnapshot, type TaskSnapshot, type TimeSession } from "../../shared/schemas/entities.schema.js";
5
5
  /** Instantanés des entités que l'agent modifie : l'état avant et après chaque action de son lot. */
6
6
  /** Point de vérification avec les résultats saisis dessus. */
7
7
  export declare const CheckpointSnapshotSchema: z.ZodObject<{
@@ -24,9 +24,9 @@ export declare const CheckpointSnapshotSchema: z.ZodObject<{
24
24
  }, z.core.$strip>;
25
25
  export type CheckpointSnapshot = z.infer<typeof CheckpointSnapshotSchema>;
26
26
  /** Entités dont l'agent enregistre l'état avant et après chaque action. */
27
- export type TrackedEntityType = "task" | "checklist_item" | "task_question" | "test_checkpoint" | "comment" | "idea" | "board_view" | "follow_up";
27
+ export type TrackedEntityType = "task" | "checklist_item" | "task_question" | "test_checkpoint" | "comment" | "idea" | "board_view" | "follow_up" | "time_session";
28
28
  export declare function isTracked(entityType: EntityType): entityType is TrackedEntityType;
29
29
  /** Instantané courant d'une entité, ou null si elle n'existe pas. */
30
- export declare function snapshotOf(store: Store, entityType: TrackedEntityType, entityId: string): TaskSnapshot | ChecklistItem | QuestionSnapshot | CheckpointSnapshot | Comment | Idea | BoardView | FollowUp | null;
30
+ export declare function snapshotOf(store: Store, entityType: TrackedEntityType, entityId: string): TaskSnapshot | ChecklistItem | QuestionSnapshot | CheckpointSnapshot | Comment | Idea | BoardView | FollowUp | TimeSession | null;
31
31
  /** Tâche concernée par une action : la tâche elle-même, ou celle qui porte l'élément ; null pour une idée, une vue ou un point à régler. */
32
32
  export declare function taskIdOfAction(action: Pick<AgentAction, "entityType" | "entityId" | "before" | "after">): string | null;
@@ -3,7 +3,7 @@ import { TestCheckpointSchema, TestResultSchema } from "../../shared/schemas/ent
3
3
  /** Instantanés des entités que l'agent modifie : l'état avant et après chaque action de son lot. */
4
4
  /** Point de vérification avec les résultats saisis dessus. */
5
5
  export const CheckpointSnapshotSchema = TestCheckpointSchema.extend({ results: z.array(TestResultSchema) });
6
- const TRACKED = new Set(["task", "checklist_item", "task_question", "test_checkpoint", "comment", "idea", "board_view", "follow_up"]);
6
+ const TRACKED = new Set(["task", "checklist_item", "task_question", "test_checkpoint", "comment", "idea", "board_view", "follow_up", "time_session"]);
7
7
  export function isTracked(entityType) {
8
8
  return TRACKED.has(entityType);
9
9
  }
@@ -30,6 +30,8 @@ export function snapshotOf(store, entityType, entityId) {
30
30
  return store.findBoardView(entityId);
31
31
  case "follow_up":
32
32
  return store.findFollowUp(entityId);
33
+ case "time_session":
34
+ return store.findTimeSession(entityId);
33
35
  }
34
36
  }
35
37
  /** Tâche concernée par une action : la tâche elle-même, ou celle qui porte l'élément ; null pour une idée, une vue ou un point à régler. */
@@ -0,0 +1,18 @@
1
+ import type { HistoryFilters, Store } from "./store.js";
2
+ import type { RestoreTaskResponse, SpaceHistoryQuery, SpaceHistoryResponse } from "../../shared/schemas/history-api.schema.js";
3
+ /**
4
+ * Historique d'un espace : les événements de ses tâches, idées, membres,
5
+ * notes et documents, filtrés et paginés ; restauration d'une tâche supprimée.
6
+ */
7
+ /** Filtres du store d'après la requête : `agent` ou un identifiant d'utilisateur pour l'auteur. */
8
+ export declare function historyFilters(query: Pick<SpaceHistoryQuery, "actor" | "categories" | "since">): HistoryFilters;
9
+ /** Page d'événements d'un espace, du plus récent au plus ancien, avant le curseur `before`. */
10
+ export declare function listSpaceHistory(store: Store, userId: string, spaceId: string, query: SpaceHistoryQuery): SpaceHistoryResponse;
11
+ /**
12
+ * Restaure une tâche supprimée, à la demande d'un membre de son espace : la
13
+ * tâche reprend son dernier état, avec ses sous-tâches, ses éléments de
14
+ * checklist et ses points de vérification supprimés avec elle. Ses assignés
15
+ * qui ne sont plus membres de l'espace ne sont pas repris ; ses commentaires
16
+ * et pièces jointes, supprimés avec elle, ne reviennent pas.
17
+ */
18
+ export declare function restoreDeletedTask(store: Store, userId: string, taskId: string): RestoreTaskResponse;
@@ -0,0 +1,86 @@
1
+ import { InvariantError, NotFoundError } from "./errors.js";
2
+ import { entityTypesOf, HistoryContext, historyEvent } from "./history-events.js";
3
+ import { requireMember } from "./spaces.js";
4
+ import { ChecklistItemSchema, TestCheckpointSchema } from "../../shared/schemas/entities.schema.js";
5
+ /**
6
+ * Historique d'un espace : les événements de ses tâches, idées, membres,
7
+ * notes et documents, filtrés et paginés ; restauration d'une tâche supprimée.
8
+ */
9
+ /** Filtres du store d'après la requête : `agent` ou un identifiant d'utilisateur pour l'auteur. */
10
+ export function historyFilters(query) {
11
+ return {
12
+ actor: query.actor === undefined ? null : query.actor === "agent" ? { type: "agent" } : { type: "user", userId: query.actor },
13
+ entityTypes: query.categories === undefined ? null : entityTypesOf(query.categories),
14
+ since: query.since ?? null,
15
+ };
16
+ }
17
+ /** Page d'événements d'un espace, du plus récent au plus ancien, avant le curseur `before`. */
18
+ export function listSpaceHistory(store, userId, spaceId, query) {
19
+ requireMember(store, spaceId, userId);
20
+ return store.db.transaction(() => {
21
+ const filters = historyFilters(query);
22
+ const rows = store.listSpaceHistory(spaceId, filters, query.before ?? null, query.limit + 1);
23
+ const page = rows.slice(0, query.limit);
24
+ const ctx = new HistoryContext(store);
25
+ const events = page.map((row) => historyEvent(ctx, row, false)).filter((event) => event !== null);
26
+ return {
27
+ events,
28
+ total: store.countSpaceHistory(spaceId, filters),
29
+ nextBefore: rows.length > query.limit ? page[page.length - 1].version.seq : null,
30
+ authors: store.listMemberships(spaceId).map((membership) => {
31
+ const person = ctx.person(membership.userId);
32
+ return { id: membership.userId, name: person.name };
33
+ }),
34
+ };
35
+ })();
36
+ }
37
+ /**
38
+ * Restaure une tâche supprimée, à la demande d'un membre de son espace : la
39
+ * tâche reprend son dernier état, avec ses sous-tâches, ses éléments de
40
+ * checklist et ses points de vérification supprimés avec elle. Ses assignés
41
+ * qui ne sont plus membres de l'espace ne sont pas repris ; ses commentaires
42
+ * et pièces jointes, supprimés avec elle, ne reviennent pas.
43
+ */
44
+ export function restoreDeletedTask(store, userId, taskId) {
45
+ const latest = store.latestVersion("task", taskId);
46
+ if (!latest)
47
+ throw new NotFoundError("Tâche introuvable, ou vous n'êtes pas membre de son espace.");
48
+ requireMember(store, latest.spaceId, userId);
49
+ if (latest.snapshot !== null || store.findTask(taskId))
50
+ throw new InvariantError("Cette tâche existe : rien à restaurer.");
51
+ store.mutate({ type: "user", userId }, (tx) => restoreTree(tx, taskId, latest.createdAt));
52
+ return { task: new HistoryContext(store).task(taskId) };
53
+ }
54
+ /** Recrée la tâche `taskId` supprimée à la date `deletedAt`, et ce qui a été supprimé avec elle. */
55
+ function restoreTree(tx, taskId, deletedAt) {
56
+ const store = tx.store;
57
+ const snapshot = store.lastTaskSnapshot(taskId);
58
+ if (!snapshot)
59
+ throw new NotFoundError("Cette tâche n'a aucun état connu : restauration impossible.");
60
+ requireParent(tx, snapshot);
61
+ tx.restoreTask(snapshot);
62
+ const assignees = snapshot.assigneeIds.filter((id) => store.isMember(snapshot.spaceId, id));
63
+ if (assignees.length > 0)
64
+ tx.setAssignees(taskId, assignees, false);
65
+ const tags = snapshot.tagIds.flatMap((id) => store.findTag(id)?.name ?? []);
66
+ if (tags.length > 0)
67
+ tx.setTags(taskId, tags);
68
+ for (const removed of store.listDeletedAt(snapshot.spaceId, deletedAt)) {
69
+ if (removed.entityType === "checklist_item" && removed.taskId === taskId) {
70
+ tx.restoreChecklistItem(ChecklistItemSchema.parse(store.lastSnapshot("checklist_item", removed.entityId)));
71
+ }
72
+ else if (removed.entityType === "test_checkpoint" && removed.taskId === taskId) {
73
+ tx.restoreCheckpoint(TestCheckpointSchema.parse(store.lastSnapshot("test_checkpoint", removed.entityId)), []);
74
+ }
75
+ else if (removed.entityType === "task" && store.lastTaskSnapshot(removed.entityId)?.parentId === taskId) {
76
+ restoreTree(tx, removed.entityId, deletedAt);
77
+ }
78
+ }
79
+ }
80
+ /** La tâche parente d'une tâche à restaurer existe. */
81
+ function requireParent(tx, snapshot) {
82
+ if (snapshot.parentId === null || tx.store.findTask(snapshot.parentId))
83
+ return;
84
+ const parent = new HistoryContext(tx.store).task(snapshot.parentId);
85
+ throw new InvariantError(`La tâche parente${parent ? ` ${parent.key} « ${parent.title} »` : ""} est supprimée : restaurez-la d'abord.`);
86
+ }
@@ -32,7 +32,7 @@ export declare function createSharedSpace(store: Store, userId: string, input: {
32
32
  keyPrefix?: string;
33
33
  }): SpaceSummary;
34
34
  export declare function renameSpace(store: Store, userId: string, spaceId: string, name: string): SpaceSummary;
35
- /** Supprime un espace commun, son contenu et les fichiers de ses pièces jointes. */
35
+ /** Supprime un espace commun, son contenu et les fichiers de ses pièces jointes et de ses documents. */
36
36
  export declare function deleteSpace(store: Store, storage: AttachmentStorage, userId: string, spaceId: string): void;
37
37
  /** Membres (propriétaire d'abord) et invitations en attente d'un espace, pour un de ses membres. */
38
38
  export declare function listMembers(store: Store, userId: string, spaceId: string, now?: Date): MembersResponse;
@@ -68,15 +68,15 @@ export function renameSpace(store, userId, spaceId, name) {
68
68
  return summary(tx.renameSpace(spaceId, name), tx.store.findMembership(spaceId, userId));
69
69
  });
70
70
  }
71
- /** Supprime un espace commun, son contenu et les fichiers de ses pièces jointes. */
71
+ /** Supprime un espace commun, son contenu et les fichiers de ses pièces jointes et de ses documents. */
72
72
  export function deleteSpace(store, storage, userId, spaceId) {
73
73
  const removed = store.mutate({ type: "user", userId }, (tx) => {
74
74
  requireOwner(tx.store, spaceId, userId, "supprimer l'espace");
75
- const attachments = tx.store.listAttachmentsInSpace(spaceId);
75
+ const files = [...tx.store.listAttachmentsInSpace(spaceId), ...tx.store.listDocuments(spaceId)].map((file) => file.storagePath);
76
76
  tx.deleteSpace(spaceId);
77
- return attachments;
77
+ return files;
78
78
  });
79
- storage.remove(removed.map((attachment) => attachment.storagePath));
79
+ storage.remove(removed);
80
80
  }
81
81
  // --- Membres --------------------------------------------------------------------
82
82
  /** Membres (propriétaire d'abord) et invitations en attente d'un espace, pour un de ses membres. */