@imenam/mcp-organizer 1.0.7 → 1.0.9

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 (58) hide show
  1. package/README.md +107 -28
  2. package/dist/shared/schemas/admin-api.schema.d.ts +92 -0
  3. package/dist/shared/schemas/admin-api.schema.js +46 -1
  4. package/dist/shared/schemas/agent-api.schema.d.ts +31 -4
  5. package/dist/shared/schemas/agent-api.schema.js +16 -4
  6. package/dist/shared/schemas/agent-tools.schema.d.ts +14 -0
  7. package/dist/shared/schemas/agent-tools.schema.js +12 -1
  8. package/dist/shared/schemas/api.schema.d.ts +17 -0
  9. package/dist/shared/schemas/api.schema.js +9 -0
  10. package/dist/shared/schemas/entities.schema.d.ts +63 -0
  11. package/dist/shared/schemas/entities.schema.js +47 -1
  12. package/dist/shared/schemas/enums.schema.d.ts +19 -1
  13. package/dist/shared/schemas/enums.schema.js +8 -0
  14. package/dist/shared/schemas/instructions-api.schema.d.ts +42 -0
  15. package/dist/shared/schemas/instructions-api.schema.js +25 -0
  16. package/dist/shared/schemas/tasks-api.schema.d.ts +5 -0
  17. package/dist/shared/schemas/tasks-api.schema.js +2 -0
  18. package/dist/shared/schemas/views-api.schema.d.ts +139 -0
  19. package/dist/shared/schemas/views-api.schema.js +33 -0
  20. package/dist/src/agent-api/requests.js +4 -2
  21. package/dist/src/cli/setup.d.ts +9 -6
  22. package/dist/src/cli/setup.js +108 -35
  23. package/dist/src/core/admin.d.ts +21 -1
  24. package/dist/src/core/admin.js +68 -0
  25. package/dist/src/core/agent-instructions.d.ts +6 -0
  26. package/dist/src/core/agent-instructions.js +43 -0
  27. package/dist/src/core/agent.d.ts +2 -0
  28. package/dist/src/core/agent.js +16 -2
  29. package/dist/src/core/board-views.d.ts +12 -0
  30. package/dist/src/core/board-views.js +84 -0
  31. package/dist/src/core/migrations.js +71 -0
  32. package/dist/src/core/requests.d.ts +21 -10
  33. package/dist/src/core/requests.js +54 -39
  34. package/dist/src/core/spaces.d.ts +7 -1
  35. package/dist/src/core/spaces.js +29 -0
  36. package/dist/src/core/store.d.ts +48 -5
  37. package/dist/src/core/store.js +213 -16
  38. package/dist/src/core/tasks.js +1 -0
  39. package/dist/src/deploy/env-render.d.ts +1 -1
  40. package/dist/src/deploy/env-render.js +2 -0
  41. package/dist/src/gui-api.d.ts +12 -1
  42. package/dist/src/gui-api.js +56 -6
  43. package/dist/src/mcp/start.d.ts +1 -1
  44. package/dist/src/mcp/start.js +4 -4
  45. package/dist/src/mcp/tools.js +13 -3
  46. package/dist/src/server/claude-processes.d.ts +26 -0
  47. package/dist/src/server/claude-processes.js +72 -0
  48. package/dist/src/server/claude-stream.d.ts +39 -0
  49. package/dist/src/server/claude-stream.js +111 -0
  50. package/dist/src/server/runner.d.ts +40 -0
  51. package/dist/src/server/runner.js +157 -24
  52. package/dist/src/server/start.js +19 -1
  53. package/gui/dist/assets/index--vL3hM-5.js +70 -0
  54. package/gui/dist/assets/index-D0rq0343.css +1 -0
  55. package/gui/dist/index.html +2 -2
  56. package/package.json +1 -1
  57. package/gui/dist/assets/index-DuoSNpBr.js +0 -70
  58. package/gui/dist/assets/index-duxL0fvO.css +0 -1
@@ -2,21 +2,25 @@ import { ActivateRequestSchema, ChangePasswordRequestSchema, CreateSpaceRequestS
2
2
  import { schemaVersion } from "./core/migrations.js";
3
3
  import { ForbiddenError, InvariantError, NotFoundError, OrganizerError, UnauthorizedError } from "./core/errors.js";
4
4
  import { authenticate, changePassword, login, logout, redeemAccessLink, resolveAccessLink, updateDisplayName } from "./core/accounts.js";
5
- import { acceptReceivedInvitation, createSharedSpace, declineReceivedInvitation, deleteSpace, inviteToSpace, leaveSpace, listMembers, listReceivedInvitations, listSpaces, removeMember, renameSpace, resendInvitation, revokeInvitation, } from "./core/spaces.js";
5
+ import { acceptReceivedInvitation, createSharedSpace, declineReceivedInvitation, deleteSpace, inviteToSpace, leaveSpace, listMembers, listMemberSuggestions, listReceivedInvitations, listSpaces, removeMember, renameSpace, resendInvitation, revokeInvitation, } from "./core/spaces.js";
6
6
  import { addChecklistItem, addComment, createTask, deleteAttachment, deleteChecklistItem, deleteComment, deleteTask, downloadAttachment, getBoard, getTaskDetail, listChanges, moveChecklistItem, moveTask, setAssignees, setTags, updateChecklistItem, updateComment, updateTask, uploadAttachment, } from "./core/tasks.js";
7
7
  import { addCheckpoint, deleteCheckpoint, moveCheckpoint, saveReviewDraft, setTestResult, submitReview, updateCheckpoint } from "./core/test-tasks.js";
8
8
  import { AddChecklistItemRequestSchema, CheckpointTextRequestSchema, CommentRequestSchema, CreateTaskRequestSchema, MoveAfterRequestSchema, MoveTaskRequestSchema, ReviewDraftRequestSchema, SetAssigneesRequestSchema, SetTagsRequestSchema, SetTestResultRequestSchema, SubmitReviewRequestSchema, TaskFiltersSchema, UpdateChecklistItemRequestSchema, UpdateTaskRequestSchema, UploadAttachmentRequestSchema, } from "../shared/schemas/tasks-api.schema.js";
9
9
  import { getSettings, getSpaceNotificationSettings, listNotifications, markAllNotificationsRead, markNotificationRead, unreadCount, updateSettings, updateSpaceNotificationSettings } from "./core/notifications.js";
10
10
  import { NotificationListQuerySchema, UpdateSettingsRequestSchema, UpdateSpaceNotificationSettingsRequestSchema } from "../shared/schemas/notifications-api.schema.js";
11
- import { cancelRequest, createRequest, getRequest, listRequests, releaseRequest, undoAction, undoRequest, updateRequest } from "./core/requests.js";
11
+ import { cancelRequest, createRequest, getRequest, listRequests, relaunchRequest, stopRequest, undoAction, undoRequest, updateRequest } from "./core/requests.js";
12
12
  import { listTaskVersions, restoreTaskVersion } from "./core/task-history.js";
13
13
  import { CreateRequestSchema, UpdateRequestSchema } from "../shared/schemas/agent-api.schema.js";
14
+ import { createBoardView, deleteBoardView, listBoardViews, updateBoardView } from "./core/board-views.js";
15
+ import { CreateBoardViewRequestSchema, UpdateBoardViewRequestSchema } from "../shared/schemas/views-api.schema.js";
14
16
  import { createIdea, delegatePromotion, listIdeas, promoteIdea, setIdeaArchived } from "./core/ideas.js";
15
17
  import { CreateIdeaRequestSchema, PromoteIdeaRequestSchema, UpdateIdeaRequestSchema } from "../shared/schemas/ideas-api.schema.js";
16
18
  import { createAgentToken, listAgentTokens, revokeAgentToken } from "./core/agent-tokens.js";
17
19
  import { CreateTokenRequestSchema } from "../shared/schemas/tokens-api.schema.js";
18
- import { listAdminSpaces, processQueueNow, requireAdmin, setRunnerAllowed } from "./core/admin.js";
19
- import { SetRunnerAllowedRequestSchema } from "../shared/schemas/admin-api.schema.js";
20
+ import { getRunnerSettings, listAdminSpaces, processQueueNow, requireAdmin, runnerUsage, setRunnerAllowed, setRunnerSettings } from "./core/admin.js";
21
+ import { RunnerSettingsSchema, RunnerUsageQuerySchema, SetRunnerAllowedRequestSchema } from "../shared/schemas/admin-api.schema.js";
22
+ import { getSiteInstructions, getSpaceInstructions, setSiteInstructions, setSpaceInstructions } from "./core/agent-instructions.js";
23
+ import { SetAgentInstructionsRequestSchema } from "../shared/schemas/instructions-api.schema.js";
20
24
  import { TranscriptionError } from "./core/transcription.js";
21
25
  import { MAX_TRANSCRIPTION_BYTES, TranscribeRequestSchema } from "../shared/schemas/transcription-api.schema.js";
22
26
  /** Erreur d'une requête de la GUI, avec la nature qui fixe son code HTTP. */
@@ -163,6 +167,7 @@ route("DELETE", "/spaces/:spaceId", (ctx, { user, params }) => {
163
167
  return { body: ok };
164
168
  });
165
169
  route("GET", "/spaces/:spaceId/members", (ctx, { user, params }) => ({ body: listMembers(ctx.store, user.id, params.spaceId, now(ctx)) }));
170
+ route("GET", "/spaces/:spaceId/member-suggestions", (ctx, { user, params }) => ({ body: listMemberSuggestions(ctx.store, user.id, params.spaceId) }));
166
171
  route("DELETE", "/spaces/:spaceId/members/:userId", (ctx, { user, params }) => {
167
172
  removeMember(ctx.store, user.id, params.spaceId, params.userId);
168
173
  return { body: ok };
@@ -190,6 +195,18 @@ route("POST", "/invitations/:invitationId/decline", (ctx, { user, params }) => {
190
195
  declineReceivedInvitation(ctx.store, user.id, params.invitationId);
191
196
  return { body: ok };
192
197
  });
198
+ // --- Vues du tableau de bord --------------------------------------------------------
199
+ route("GET", "/spaces/:spaceId/views", (ctx, { user, params }) => ({ body: listBoardViews(ctx.store, user.id, params.spaceId) }));
200
+ route("POST", "/spaces/:spaceId/views", (ctx, { user, request, params }) => ({
201
+ body: createBoardView(ctx.store, user.id, params.spaceId, parseBody(CreateBoardViewRequestSchema, request.body)),
202
+ }));
203
+ route("PATCH", "/views/:viewId", (ctx, { user, request, params }) => ({
204
+ body: updateBoardView(ctx.store, user.id, params.viewId, parseBody(UpdateBoardViewRequestSchema, request.body)),
205
+ }));
206
+ route("DELETE", "/views/:viewId", (ctx, { user, params }) => {
207
+ deleteBoardView(ctx.store, user.id, params.viewId);
208
+ return { body: ok };
209
+ });
193
210
  // --- Tâches -----------------------------------------------------------------------
194
211
  route("GET", "/spaces/:spaceId/tasks", (ctx, { user, request, params }) => {
195
212
  const parsed = TaskFiltersSchema.safeParse(request.query);
@@ -289,7 +306,7 @@ route("POST", "/ideas/:ideaId/promote", (ctx, { user, request, params }) => ({
289
306
  }));
290
307
  route("POST", "/ideas/:ideaId/delegate", (ctx, { user, params }) => ({ body: delegatePromotion(ctx.store, user.id, params.ideaId) }));
291
308
  // --- File de l'agent et historique -------------------------------------------------
292
- route("GET", "/spaces/:spaceId/requests", (ctx, { user, params }) => ({ body: listRequests(ctx.store, user.id, params.spaceId, ctx.runner.status.disabledReason, now(ctx)) }));
309
+ route("GET", "/spaces/:spaceId/requests", (ctx, { user, params }) => ({ body: listRequests(ctx.store, user.id, params.spaceId, { disabledReason: ctx.runner.status.disabledReason, failure: ctx.runner.lastFailure(params.spaceId), session: ctx.runner.currentSession(params.spaceId) }, now(ctx)) }));
293
310
  route("POST", "/spaces/:spaceId/requests", (ctx, { user, request, params }) => ({
294
311
  body: createRequest(ctx.store, user.id, params.spaceId, parseBody(CreateRequestSchema, request.body)),
295
312
  }));
@@ -298,7 +315,8 @@ route("PATCH", "/requests/:requestId", (ctx, { user, request, params }) => ({
298
315
  body: updateRequest(ctx.store, user.id, params.requestId, parseBody(UpdateRequestSchema, request.body).text),
299
316
  }));
300
317
  route("POST", "/requests/:requestId/cancel", (ctx, { user, params }) => ({ body: cancelRequest(ctx.store, user.id, params.requestId) }));
301
- route("POST", "/requests/:requestId/release", (ctx, { user, params }) => ({ body: releaseRequest(ctx.store, user.id, params.requestId) }));
318
+ route("POST", "/requests/:requestId/stop", (ctx, { user, params }) => ({ body: stopRequest(ctx.store, user.id, params.requestId, ctx.runner.stopSession) }));
319
+ route("POST", "/requests/:requestId/relaunch", (ctx, { user, params }) => ({ body: relaunchRequest(ctx.store, user.id, params.requestId) }));
302
320
  route("POST", "/requests/:requestId/undo", (ctx, { user, params }) => ({ body: undoRequest(ctx.store, user.id, params.requestId) }));
303
321
  route("POST", "/agent-actions/:actionId/undo", (ctx, { user, params }) => ({ body: undoAction(ctx.store, user.id, params.actionId) }));
304
322
  route("GET", "/tasks/:taskId/versions", (ctx, { user, params }) => ({ body: listTaskVersions(ctx.store, user.id, params.taskId) }));
@@ -330,6 +348,10 @@ route("GET", "/spaces/:spaceId/notification-settings", (ctx, { user, params }) =
330
348
  route("PUT", "/spaces/:spaceId/notification-settings", (ctx, { user, request, params }) => ({
331
349
  body: updateSpaceNotificationSettings(ctx.store, ctx, user.id, params.spaceId, parseBody(UpdateSpaceNotificationSettingsRequestSchema, request.body)),
332
350
  }));
351
+ route("GET", "/spaces/:spaceId/agent-instructions", (ctx, { user, params }) => ({ body: getSpaceInstructions(ctx.store, user.id, params.spaceId) }));
352
+ route("PUT", "/spaces/:spaceId/agent-instructions", (ctx, { user, request, params }) => ({
353
+ body: setSpaceInstructions(ctx.store, user.id, params.spaceId, parseBody(SetAgentInstructionsRequestSchema, request.body).text),
354
+ }));
333
355
  // --- Jetons d'agent ---------------------------------------------------------------
334
356
  route("GET", "/tokens", (ctx, { user }) => ({ body: listAgentTokens(ctx.store, user.id, now(ctx)) }));
335
357
  route("POST", "/tokens", (ctx, { user, request }) => {
@@ -348,10 +370,38 @@ route("POST", "/spaces/:spaceId/runner/run", (ctx, { user, params }) => {
348
370
  throw new ApiError("unavailable", `Runner désactivé : ${ctx.runner.status.disabledReason}`);
349
371
  return { body: processQueueNow(ctx.store, user.id, params.spaceId, runNow) };
350
372
  });
373
+ route("POST", "/spaces/:spaceId/runner/stop", (ctx, { user, params }) => {
374
+ requireAdmin(ctx.store, user.id);
375
+ const stopSession = ctx.runner.stopSession;
376
+ if (!stopSession)
377
+ throw new ApiError("unavailable", `Runner désactivé : ${ctx.runner.status.disabledReason}`);
378
+ const abortedRequests = stopSession(params.spaceId, user.id);
379
+ if (abortedRequests === null)
380
+ throw new InvariantError("Aucune session du runner ne tourne dans cet espace.");
381
+ return { body: { abortedRequests } };
382
+ });
383
+ route("GET", "/admin/runner/settings", (ctx, { user }) => ({ body: getRunnerSettings(ctx.store, user.id) }));
384
+ route("PUT", "/admin/runner/settings", (ctx, { user, request }) => ({
385
+ body: setRunnerSettings(ctx.store, user.id, parseBody(RunnerSettingsSchema, request.body)),
386
+ }));
387
+ route("GET", "/admin/runner/usage", (ctx, { user, request }) => {
388
+ const parsed = RunnerUsageQuerySchema.safeParse(request.query);
389
+ if (!parsed.success)
390
+ throw new ApiError("invalid", "days : un nombre de jours entre 1 et 90.");
391
+ return { body: runnerUsage(ctx.store, user.id, parsed.data.days, now(ctx)) };
392
+ });
393
+ route("POST", "/admin/runner/kill-all", async (ctx, { user }) => {
394
+ requireAdmin(ctx.store, user.id);
395
+ return { body: await ctx.runner.killAll(user.id) };
396
+ });
351
397
  route("PUT", "/admin/spaces/:spaceId/runner", (ctx, { user, request, params }) => {
352
398
  const input = parseBody(SetRunnerAllowedRequestSchema, request.body);
353
399
  return { body: setRunnerAllowed(ctx.store, user.id, params.spaceId, input.allowed) };
354
400
  });
401
+ route("GET", "/admin/agent-instructions", (ctx, { user }) => ({ body: getSiteInstructions(ctx.store, user.id) }));
402
+ route("PUT", "/admin/agent-instructions", (ctx, { user, request }) => ({
403
+ body: setSiteInstructions(ctx.store, user.id, parseBody(SetAgentInstructionsRequestSchema, request.body).text),
404
+ }));
355
405
  // --- Dictée ------------------------------------------------------------------------
356
406
  route("POST", "/transcribe", async (ctx, { request }) => {
357
407
  const input = parseBody(TranscribeRequestSchema, request.body);
@@ -1,6 +1,6 @@
1
1
  import { type SiteConnection } from "./client.js";
2
2
  /** Présentation du serveur transmise au client MCP : concepts et déroulé. */
3
- export declare const INSTRUCTIONS = "mcp-organizer connects you to an organizer site: a multi-user task manager where people organize tasks in a web app and queue requests for the AI. You, the connected agent, process those requests when the user asks you to. The site never calls an LLM: you are the intelligence.\n\nYour token covers exactly one space, with the rights of the user who created the token. Every tool works on that space.\n\nConcepts:\n- A **space** holds tasks and an idea box. A user's **personal space** is private; a **shared space** has one owner and members.\n- A **task** has a title, a markdown description, a status (todo, doing, review, done), a priority (low, medium, high, critical), assignees and tags. Tasks nest on two levels: task > sub-task > sub-sub-task. A task is either standard (with a checklist) or a test (with checkpoints that each tester marks ok, ko, blocked or untested).\n- A **request** is something a member of your space asked the AI: an idea, a remark, a test review, a message or an idea promotion. It is pending, then processing once you claim it (only your token can then act for it), then done (with your reply) or failed (with the reason).\n- A **batch** is the set of actions you perform for one request. Every action is logged with its before and after state and with your token, and users can undo one action or the whole batch.\n- The **scope** of your work is the space of your token: you see and process the requests of all its members, and you never act outside it.\n\nWork loop, when the user asks you to process the queue:\n1. list_requests to see the pending requests of your space.\n2. claim_request on the oldest one: it becomes processing for you and you get its context (text, author, context task, for a message the previous exchanges of its author, task tree, members, recent ideas). get_context shows the space at any time.\n3. Read what you need with get_task and search_tasks.\n4. Act with create_task, update_task, set_assignees, set_tags, edit_checklist, add_comment, create_idea, update_idea, promote_idea \u2014 always passing the request_id. Each write is one undoable action of the batch.\n5. complete_request with a short reply in the author's language (or fail_request with the reason), then go back to step 1 until no request is pending.\nWhen the queue is empty, tell the user.\n\nNotifications: call enable_notifications once at the start of the session and arm the watcher it hands you with Monitor, whatever the command (behind mcp-http-gateway, the gateway relay answers in place of this server and gives its own watcher command). Each request that becomes pending in your space then arrives on its own as one line (kind, author, excerpt, request id), even while you are idle: process it with the work loop above, starting with claim_request. The host stops that watcher after 30 minutes at most: each time it tells you the watcher expired, re-arm it at once with the same Monitor call; otherwise notifications stop for good. A line \"notifications stopped\" means the site refused the token, and a line \"[gateway-watch] \u2026 la veille \u00E9choue\" means the gateway watcher keeps failing: tell the user. wait_for_requests is the waiting tool of the watcher: you do not need to call it.\n\nHow to handle each kind of request:\n- **idea**: classify it. If it belongs to an existing task or sub-task, attach it there (sub-task, checklist item or comment). If it is actionable and important enough, create a task (or sub-task) with a fitting priority. Otherwise, put it in the idea box with create_idea. Prefer existing tasks over duplicates.\n- **test_review**: feed the tester's findings back into the existing tasks (status, checklist, comments, priority of the affected tasks), or create a task for each problem that has none.\n- **remark** and **message**: do whatever is useful \u2014 answer, update or create tasks, comment \u2014 and say what you did in the reply.\n- **idea_promotion**: turn the context idea into a well-formed task with promote_idea.\n\nRules: write titles, descriptions and replies in the language of the users; keep the reply short and factual. Errors tell you what to do next; an error about the token (missing, revoked, expired, owner no longer a member) cannot be fixed by retrying: tell the user.";
3
+ export declare const INSTRUCTIONS = "mcp-organizer connects you to an organizer site: a multi-user task manager where people organize tasks in a web app and queue requests for the AI. You, the connected agent, process those requests when the user asks you to. The site never calls an LLM: you are the intelligence.\n\nYour token covers exactly one space, with the rights of the user who created the token. Every tool works on that space.\n\nConcepts:\n- A **space** holds tasks and an idea box. A user's **personal space** is private; a **shared space** has one owner and members.\n- A **task** has a title, a markdown description, a status (todo, doing, review, done), a priority (low, medium, high, critical), assignees and tags. Tasks nest on two levels: task > sub-task > sub-sub-task. A task is either standard (with a checklist) or a test (with checkpoints that each tester marks ok, ko, blocked or untested).\n- A **request** is something a member of your space asked the AI: an idea, a remark, a test review, a message or an idea promotion. It is pending, then processing once you claim it (only your token can then act for it), then done (with your reply and the points left to its author) or failed (with the reason).\n- A **batch** is the set of actions you perform for one request. Every action is logged with its before and after state and with your token, and users can undo one action or the whole batch.\n- The **scope** of your work is the space of your token: you see and process the requests of all its members, and you never act outside it.\n\nWork loop, when the user asks you to process the queue:\n1. list_requests to see the pending requests of your space.\n2. claim_request on the oldest one: it becomes processing for you and you get its context (text, author, context task, for a message the previous exchanges of its author, task tree, members, recent ideas), along with the custom instructions of the site and of the space, which you follow. get_context shows the space at any time.\n3. Read what you need with get_task and search_tasks.\n4. Act with create_task, update_task, set_assignees, set_tags, edit_checklist, add_comment, create_idea, update_idea, promote_idea \u2014 always passing the request_id. Each write is one undoable action of the batch.\n5. complete_request with a short reply in the author's language and, in follow_ups, every point the author still has to handle (or fail_request with the reason), then go back to step 1 until no request is pending.\nWhen the queue is empty, tell the user.\n\nNotifications: call enable_notifications once at the start of the session and arm the watcher it hands you with Monitor, whatever the command (behind mcp-http-gateway, the gateway relay answers in place of this server and gives its own watcher command). Each request that becomes pending in your space then arrives on its own as one line (kind, author, excerpt, request id), even while you are idle: process it with the work loop above, starting with claim_request. The host stops that watcher after 30 minutes at most: each time it tells you the watcher expired, re-arm it at once with the same Monitor call; otherwise notifications stop for good. A line \"notifications stopped\" means the site refused the token, and a line \"[gateway-watch] \u2026 la veille \u00E9choue\" means the gateway watcher keeps failing: tell the user. wait_for_requests is the waiting tool of the watcher: you do not need to call it.\n\nHow to handle each kind of request:\n- **idea**: classify it. If it belongs to an existing task or sub-task, attach it there (sub-task, checklist item or comment). If it is actionable and important enough, create a task (or sub-task) with a fitting priority. Otherwise, put it in the idea box with create_idea. Prefer existing tasks over duplicates.\n- **test_review**: feed the tester's findings back into the existing tasks (status, checklist, comments, priority of the affected tasks), or create a task for each problem that has none.\n- **remark** and **message**: do whatever is useful \u2014 answer, update or create tasks, comment \u2014 and say what you did in the reply.\n- **idea_promotion**: turn the context idea into a well-formed task with promote_idea.\n\nRules: write titles, descriptions and replies in the language of the users; keep the reply short and factual (markdown is rendered); never bury in the reply something the author must act on: it belongs in follow_ups. Errors tell you what to do next; an error about the token (missing, revoked, expired, owner no longer a member) cannot be fixed by retrying: tell the user.";
4
4
  /**
5
5
  * Connexion au site d'après `ORGANIZER_URL` et `ORGANIZER_TOKEN` ; une valeur
6
6
  * absente ou invalide, ou une URL http vers une autre machine, est une `ConfigError`.
@@ -16,16 +16,16 @@ Your token covers exactly one space, with the rights of the user who created the
16
16
  Concepts:
17
17
  - A **space** holds tasks and an idea box. A user's **personal space** is private; a **shared space** has one owner and members.
18
18
  - A **task** has a title, a markdown description, a status (todo, doing, review, done), a priority (low, medium, high, critical), assignees and tags. Tasks nest on two levels: task > sub-task > sub-sub-task. A task is either standard (with a checklist) or a test (with checkpoints that each tester marks ok, ko, blocked or untested).
19
- - A **request** is something a member of your space asked the AI: an idea, a remark, a test review, a message or an idea promotion. It is pending, then processing once you claim it (only your token can then act for it), then done (with your reply) or failed (with the reason).
19
+ - A **request** is something a member of your space asked the AI: an idea, a remark, a test review, a message or an idea promotion. It is pending, then processing once you claim it (only your token can then act for it), then done (with your reply and the points left to its author) or failed (with the reason).
20
20
  - A **batch** is the set of actions you perform for one request. Every action is logged with its before and after state and with your token, and users can undo one action or the whole batch.
21
21
  - The **scope** of your work is the space of your token: you see and process the requests of all its members, and you never act outside it.
22
22
 
23
23
  Work loop, when the user asks you to process the queue:
24
24
  1. list_requests to see the pending requests of your space.
25
- 2. claim_request on the oldest one: it becomes processing for you and you get its context (text, author, context task, for a message the previous exchanges of its author, task tree, members, recent ideas). get_context shows the space at any time.
25
+ 2. claim_request on the oldest one: it becomes processing for you and you get its context (text, author, context task, for a message the previous exchanges of its author, task tree, members, recent ideas), along with the custom instructions of the site and of the space, which you follow. get_context shows the space at any time.
26
26
  3. Read what you need with get_task and search_tasks.
27
27
  4. Act with create_task, update_task, set_assignees, set_tags, edit_checklist, add_comment, create_idea, update_idea, promote_idea — always passing the request_id. Each write is one undoable action of the batch.
28
- 5. complete_request with a short reply in the author's language (or fail_request with the reason), then go back to step 1 until no request is pending.
28
+ 5. complete_request with a short reply in the author's language and, in follow_ups, every point the author still has to handle (or fail_request with the reason), then go back to step 1 until no request is pending.
29
29
  When the queue is empty, tell the user.
30
30
 
31
31
  Notifications: call enable_notifications once at the start of the session and arm the watcher it hands you with Monitor, whatever the command (behind mcp-http-gateway, the gateway relay answers in place of this server and gives its own watcher command). Each request that becomes pending in your space then arrives on its own as one line (kind, author, excerpt, request id), even while you are idle: process it with the work loop above, starting with claim_request. The host stops that watcher after 30 minutes at most: each time it tells you the watcher expired, re-arm it at once with the same Monitor call; otherwise notifications stop for good. A line "notifications stopped" means the site refused the token, and a line "[gateway-watch] … la veille échoue" means the gateway watcher keeps failing: tell the user. wait_for_requests is the waiting tool of the watcher: you do not need to call it.
@@ -36,7 +36,7 @@ How to handle each kind of request:
36
36
  - **remark** and **message**: do whatever is useful — answer, update or create tasks, comment — and say what you did in the reply.
37
37
  - **idea_promotion**: turn the context idea into a well-formed task with promote_idea.
38
38
 
39
- Rules: write titles, descriptions and replies in the language of the users; keep the reply short and factual. Errors tell you what to do next; an error about the token (missing, revoked, expired, owner no longer a member) cannot be fixed by retrying: tell the user.`;
39
+ Rules: write titles, descriptions and replies in the language of the users; keep the reply short and factual (markdown is rendered); never bury in the reply something the author must act on: it belongs in follow_ups. Errors tell you what to do next; an error about the token (missing, revoked, expired, owner no longer a member) cannot be fixed by retrying: tell the user.`;
40
40
  /** Hôtes de la machine locale, seuls admis en http. */
41
41
  const LOCAL_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
42
42
  /** Variable d'environnement non vide, ou null. */
@@ -1,6 +1,6 @@
1
1
  import { REQUEST_STATUSES, TASK_PRIORITIES, TASK_STATUSES, TASK_TYPES } from "../../shared/schemas/enums.schema.js";
2
2
  import { MAX_TAG_LENGTH, MAX_TASK_TITLE_LENGTH } from "../../shared/schemas/tasks-api.schema.js";
3
- import { MAX_CHECKLIST_ITEM_LENGTH, MAX_CHECKLIST_OPERATIONS, MAX_COMMENT_LENGTH, MAX_IDEA_LENGTH, MAX_REASON_LENGTH, MAX_REPLY_LENGTH, MAX_REQUEST_LIST_LIMIT, MAX_SEARCH_LIMIT, } from "../../shared/schemas/agent-tools.schema.js";
3
+ import { MAX_CHECKLIST_ITEM_LENGTH, MAX_CHECKLIST_OPERATIONS, MAX_COMMENT_LENGTH, MAX_FOLLOW_UP_LENGTH, MAX_FOLLOW_UPS, MAX_IDEA_LENGTH, MAX_REASON_LENGTH, MAX_REPLY_LENGTH, MAX_REQUEST_LIST_LIMIT, MAX_SEARCH_LIMIT, } from "../../shared/schemas/agent-tools.schema.js";
4
4
  /** Argument d'appel d'outil inutilisable pour former la requête. */
5
5
  export class ToolArgumentError extends Error {
6
6
  constructor(message) {
@@ -285,12 +285,22 @@ export const AGENT_TOOLS = [
285
285
  path: "requests/{request_id}/complete",
286
286
  definition: {
287
287
  name: "complete_request",
288
- description: "Finish a processing request with your reply to its author: one or two sentences in the author's language saying what you did (tasks created or changed, where the idea went) or answering their message. The reply is shown in the assistant panel and on the Agent page, next to the actions of the batch. Call it last.",
288
+ description: "Finish a processing request with your reply to its author: a short markdown report in the author's language saying what you did (tasks created or changed, where the idea went) or answering their message. Put in follow_ups every point the author still has to handle themselves (a decision to make, a person to assign, something you could not do or understand); leave it empty when everything is done. The Agent page shows the request in green when follow_ups is empty and in orange with these points otherwise. Call it last.",
289
289
  inputSchema: {
290
290
  type: "object",
291
291
  properties: {
292
292
  request_id: { type: "string", description: "Id of the request you claimed." },
293
- reply: { type: "string", maxLength: MAX_REPLY_LENGTH, description: "Short report for the author." },
293
+ reply: {
294
+ type: "string",
295
+ maxLength: MAX_REPLY_LENGTH,
296
+ description: "Short markdown report for the author: one sentence, or a short bullet list of the changes with task keys (ORG-12). Do not repeat the follow-ups here.",
297
+ },
298
+ follow_ups: {
299
+ type: "array",
300
+ maxItems: MAX_FOLLOW_UPS,
301
+ items: { type: "string", maxLength: MAX_FOLLOW_UP_LENGTH },
302
+ description: "What the author still has to do, one short actionable sentence each. Empty or omitted when everything is handled.",
303
+ },
294
304
  },
295
305
  required: ["request_id", "reply"],
296
306
  additionalProperties: false,
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Processus Claude Code de la machine du site, quelle que soit leur origine :
3
+ * binaire natif (`claude`, `claude.exe`, `…/claude/versions/<version>`) ou
4
+ * paquet npm (`@anthropic-ai/claude-code`). Sert à l'arrêt d'urgence, qui
5
+ * les tue tous.
6
+ */
7
+ export interface ClaudeProcess {
8
+ pid: number;
9
+ command: string;
10
+ }
11
+ /** Accès au système, remplacé dans les tests. */
12
+ export interface ProcessSystem {
13
+ list(): ClaudeProcess[];
14
+ kill(pid: number): void;
15
+ wait(ms: number): Promise<void>;
16
+ }
17
+ /** Vrai si la ligne de commande est celle d'un processus Claude Code. */
18
+ export declare function isClaudeCommand(command: string): boolean;
19
+ /** Tue un processus et ses descendants, sans délai de grâce. */
20
+ export declare function killProcessTree(pid: number): void;
21
+ export declare const SYSTEM: ProcessSystem;
22
+ /** Tue tous les processus Claude Code, puis rend leur nombre et ceux qui tournent encore. */
23
+ export declare function killAllClaude(system?: ProcessSystem): Promise<{
24
+ killed: number;
25
+ remaining: ClaudeProcess[];
26
+ }>;
@@ -0,0 +1,72 @@
1
+ import { spawnSync } from "node:child_process";
2
+ /** Premier mot d'une ligne de commande, guillemets retirés. */
3
+ function executable(command) {
4
+ const trimmed = command.trim();
5
+ if (trimmed.startsWith('"'))
6
+ return trimmed.slice(1, trimmed.indexOf('"', 1) === -1 ? undefined : trimmed.indexOf('"', 1));
7
+ return trimmed.split(/\s+/)[0] ?? "";
8
+ }
9
+ /** Vrai si la ligne de commande est celle d'un processus Claude Code. */
10
+ export function isClaudeCommand(command) {
11
+ const name = executable(command).split(/[\\/]/).pop()?.toLowerCase() ?? "";
12
+ if (name === "claude" || name === "claude.exe")
13
+ return true;
14
+ const normalized = command.replace(/\\/g, "/");
15
+ return normalized.includes("@anthropic-ai/claude-code") || normalized.includes("/claude/versions/");
16
+ }
17
+ /** Lignes de commande des processus de la machine : `ps` sous Unix, CIM sous Windows. */
18
+ function listProcesses() {
19
+ if (process.platform === "win32") {
20
+ const script = 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId)`t$(if ($_.CommandLine) { $_.CommandLine } else { $_.ExecutablePath })" }';
21
+ const result = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", windowsHide: true });
22
+ if (result.status !== 0)
23
+ throw new Error(`Cannot list the processes: ${result.stderr || result.error?.message}`);
24
+ return parse(result.stdout, "\t");
25
+ }
26
+ const result = spawnSync("ps", ["-eo", "pid=,args="], { encoding: "utf8" });
27
+ if (result.status !== 0)
28
+ throw new Error(`Cannot list the processes: ${result.stderr || result.error?.message}`);
29
+ return parse(result.stdout, null);
30
+ }
31
+ function parse(output, separator) {
32
+ const processes = [];
33
+ for (const line of output.split(/\r?\n/)) {
34
+ const match = separator === null ? /^\s*(\d+)\s+(.*)$/.exec(line) : /^(\d+)\t(.*)$/.exec(line);
35
+ if (match && match[2].trim() !== "")
36
+ processes.push({ pid: Number(match[1]), command: match[2].trim() });
37
+ }
38
+ return processes;
39
+ }
40
+ /** Tue un processus et ses descendants, sans délai de grâce. */
41
+ export function killProcessTree(pid) {
42
+ if (process.platform === "win32") {
43
+ spawnSync("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true });
44
+ return;
45
+ }
46
+ try {
47
+ process.kill(-pid, "SIGKILL");
48
+ }
49
+ catch {
50
+ try {
51
+ process.kill(pid, "SIGKILL");
52
+ }
53
+ catch {
54
+ // Le processus est déjà terminé.
55
+ }
56
+ }
57
+ }
58
+ export const SYSTEM = {
59
+ list: () => listProcesses().filter((entry) => entry.pid !== process.pid && isClaudeCommand(entry.command)),
60
+ kill: killProcessTree,
61
+ wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
62
+ };
63
+ /** Délai laissé au système avant de vérifier qu'aucun processus Claude Code ne tourne plus. */
64
+ const SETTLE_MS = 500;
65
+ /** Tue tous les processus Claude Code, puis rend leur nombre et ceux qui tournent encore. */
66
+ export async function killAllClaude(system = SYSTEM) {
67
+ const found = system.list();
68
+ for (const entry of found)
69
+ system.kill(entry.pid);
70
+ await system.wait(SETTLE_MS);
71
+ return { killed: found.length, remaining: system.list() };
72
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Lecture de la sortie `--output-format stream-json` d'une session du
3
+ * runner : une ligne JSON par évènement. Elle donne ce qu'il faut journaliser,
4
+ * le modèle, les tokens consommés (cumulés message par message, ce qui vaut
5
+ * aussi pour une session tuée avant sa fin) et le message final (`result`),
6
+ * qui porte l'issue, le nombre de tours et le coût annoncé par Claude Code.
7
+ */
8
+ export interface SessionTokens {
9
+ inputTokens: number;
10
+ outputTokens: number;
11
+ cacheReadTokens: number;
12
+ cacheCreationTokens: number;
13
+ }
14
+ /** Message final d'une session ; ses champs sont lus sans présumer de leur présence. */
15
+ export interface SessionResult {
16
+ subtype: string | null;
17
+ isError: boolean;
18
+ text: string | null;
19
+ turns: number | null;
20
+ costUsd: number | null;
21
+ tokens: SessionTokens | null;
22
+ }
23
+ export declare class SessionStream {
24
+ model: string | null;
25
+ result: SessionResult | null;
26
+ /** Dernier texte lisible écrit par Claude Code : ligne brute, message de l'assistant ou texte du résultat. */
27
+ lastText: string | null;
28
+ private readonly usageByMessage;
29
+ private readonly pending;
30
+ /** Lit un morceau de sortie ; rend les lignes à journaliser. */
31
+ feed(source: "stdout" | "stderr", chunk: string): string[];
32
+ /** Lit ce qui reste après la fin du processus. */
33
+ flush(): string[];
34
+ /** Tokens de la session : ceux du message final, sinon la somme des messages de l'assistant. */
35
+ tokens(): SessionTokens;
36
+ private line;
37
+ private assistant;
38
+ private finish;
39
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Lecture de la sortie `--output-format stream-json` d'une session du
3
+ * runner : une ligne JSON par évènement. Elle donne ce qu'il faut journaliser,
4
+ * le modèle, les tokens consommés (cumulés message par message, ce qui vaut
5
+ * aussi pour une session tuée avant sa fin) et le message final (`result`),
6
+ * qui porte l'issue, le nombre de tours et le coût annoncé par Claude Code.
7
+ */
8
+ const count = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.round(value) : 0);
9
+ function tokensOf(usage) {
10
+ if (!usage || typeof usage !== "object")
11
+ return null;
12
+ return {
13
+ inputTokens: count(usage.input_tokens),
14
+ outputTokens: count(usage.output_tokens),
15
+ cacheReadTokens: count(usage.cache_read_input_tokens),
16
+ cacheCreationTokens: count(usage.cache_creation_input_tokens),
17
+ };
18
+ }
19
+ export class SessionStream {
20
+ model = null;
21
+ result = null;
22
+ /** Dernier texte lisible écrit par Claude Code : ligne brute, message de l'assistant ou texte du résultat. */
23
+ lastText = null;
24
+ usageByMessage = new Map();
25
+ pending = new Map();
26
+ /** Lit un morceau de sortie ; rend les lignes à journaliser. */
27
+ feed(source, chunk) {
28
+ const text = (this.pending.get(source) ?? "") + chunk;
29
+ const lines = text.split(/\r?\n/);
30
+ this.pending.set(source, lines.pop() ?? "");
31
+ return lines.flatMap((line) => this.line(line));
32
+ }
33
+ /** Lit ce qui reste après la fin du processus. */
34
+ flush() {
35
+ const rest = [...this.pending.values()];
36
+ this.pending.clear();
37
+ return rest.flatMap((line) => this.line(line));
38
+ }
39
+ /** Tokens de la session : ceux du message final, sinon la somme des messages de l'assistant. */
40
+ tokens() {
41
+ if (this.result?.tokens)
42
+ return this.result.tokens;
43
+ const total = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0 };
44
+ for (const usage of this.usageByMessage.values()) {
45
+ total.inputTokens += usage.inputTokens;
46
+ total.outputTokens += usage.outputTokens;
47
+ total.cacheReadTokens += usage.cacheReadTokens;
48
+ total.cacheCreationTokens += usage.cacheCreationTokens;
49
+ }
50
+ return total;
51
+ }
52
+ line(raw) {
53
+ const line = raw.trim();
54
+ if (line === "")
55
+ return [];
56
+ let event;
57
+ try {
58
+ event = JSON.parse(line);
59
+ }
60
+ catch {
61
+ this.lastText = line;
62
+ return [line];
63
+ }
64
+ if (!event || typeof event !== "object")
65
+ return [];
66
+ if (event.type === "system" && event.subtype === "init") {
67
+ if (typeof event.model === "string")
68
+ this.model = event.model;
69
+ return [`model ${this.model ?? "?"}`];
70
+ }
71
+ if (event.type === "assistant")
72
+ return this.assistant(event.message ?? {});
73
+ if (event.type === "result")
74
+ return this.finish(event);
75
+ return [];
76
+ }
77
+ assistant(message) {
78
+ if (typeof message.model === "string")
79
+ this.model ??= message.model;
80
+ const usage = tokensOf(message.usage);
81
+ if (usage && typeof message.id === "string")
82
+ this.usageByMessage.set(message.id, usage);
83
+ const lines = [];
84
+ for (const block of Array.isArray(message.content) ? message.content : []) {
85
+ if (block?.type === "text" && typeof block.text === "string" && block.text.trim()) {
86
+ const text = block.text.trim();
87
+ this.lastText = text;
88
+ lines.push(text);
89
+ }
90
+ else if (block?.type === "tool_use" && typeof block.name === "string") {
91
+ lines.push(`→ ${block.name}`);
92
+ }
93
+ }
94
+ return lines;
95
+ }
96
+ finish(event) {
97
+ const text = typeof event.result === "string" && event.result.trim() ? event.result.trim() : Array.isArray(event.errors) && typeof event.errors[0] === "string" ? event.errors[0] : null;
98
+ this.result = {
99
+ subtype: typeof event.subtype === "string" ? event.subtype : null,
100
+ isError: event.is_error === true,
101
+ text,
102
+ turns: typeof event.num_turns === "number" ? count(event.num_turns) : null,
103
+ costUsd: typeof event.total_cost_usd === "number" && event.total_cost_usd >= 0 ? event.total_cost_usd : null,
104
+ tokens: tokensOf(event.usage),
105
+ };
106
+ if (text)
107
+ this.lastText = text;
108
+ const cost = this.result.costUsd === null ? "cost unknown" : `$${this.result.costUsd.toFixed(4)}`;
109
+ return [`result ${this.result.subtype ?? "?"}, ${this.result.turns ?? "?"} turn(s), ${cost}`];
110
+ }
111
+ }
@@ -1,6 +1,7 @@
1
1
  import type { Logger } from "../core/logger.js";
2
2
  import type { Store } from "../core/store.js";
3
3
  import type { RunnerStatus } from "../../shared/schemas/admin-api.schema.js";
4
+ import type { RunnerFailure } from "../../shared/schemas/agent-api.schema.js";
4
5
  /** Consigne de la session. Les `instructions` du serveur MCP organizer décrivent les concepts et la boucle de travail. */
5
6
  export declare const SESSION_PROMPT: string;
6
7
  export interface RunnerConfig {
@@ -15,6 +16,10 @@ export interface RunnerConfig {
15
16
  /** Dossier des sessions : configurations MCP éphémères, dossier courant de Claude Code. */
16
17
  workDir: string;
17
18
  }
19
+ /** Vrai si une session du runner peut joindre le site écoutant sur `host`, en http sur la machine. */
20
+ export declare function isRunnerHost(host: string): boolean;
21
+ /** Dossier personnel et de configuration de Claude Code pour le runner, sous le répertoire de données. */
22
+ export declare function runnerClaudeDir(dataDir: string): string;
18
23
  /** Configuration du runner d'après l'environnement, ou la raison de sa désactivation. */
19
24
  export declare function runnerFromEnv(env: NodeJS.ProcessEnv, site: {
20
25
  host: string;
@@ -35,17 +40,52 @@ export declare class SiteRunner {
35
40
  private readonly forced;
36
41
  private running;
37
42
  private child;
43
+ /** Session en cours : son espace et son début. */
44
+ private session;
45
+ /** La session en cours a été arrêtée par un administrateur : sa fin n'est pas un échec. */
46
+ private stopRequested;
47
+ /** Dernière session de chaque espace, quand elle a échoué. */
48
+ private readonly failures;
38
49
  private readonly unsubscribe;
39
50
  constructor(store: Store, config: RunnerConfig, logger: Logger);
40
51
  /** S'abonne aux demandes et aux autorisations, et planifie les espaces autorisés qui ont déjà des demandes. */
41
52
  start(): void;
42
53
  /** Arrête la session en cours et ne planifie plus rien. */
43
54
  stop(): void;
55
+ /** Session du runner en cours dans l'espace, null quand aucune n'y tourne. */
56
+ currentSession(spaceId: string): {
57
+ startedAt: string;
58
+ } | null;
59
+ /**
60
+ * Arrête la session en cours dans l'espace, au nom de l'administrateur
61
+ * `userId` : son jeton est invalidé, son processus tué avec ses descendants,
62
+ * et les demandes qu'elle avait prises sont stoppées. L'espace n'est pas
63
+ * repris ; une nouvelle demande relance une session. Rend le nombre de
64
+ * demandes stoppées, ou null quand aucune session n'y tourne.
65
+ */
66
+ stopSession(spaceId: string, userId: string): number | null;
67
+ /**
68
+ * Arrêt d'urgence du runner : la session en cours est arrêtée comme par
69
+ * `stopSession`, et aucun espace planifié n'est repris. Rend le nombre de
70
+ * demandes stoppées, dans tous les espaces.
71
+ */
72
+ abortAll(userId: string): number;
73
+ private killSession;
74
+ /** Dernière session du runner dans l'espace, quand elle a échoué ; null dès qu'une nouvelle session démarre. */
75
+ lastFailure(spaceId: string): RunnerFailure | null;
44
76
  /** Planifie une session pour traiter la file de l'espace une fois, même si le runner n'y est pas autorisé. */
45
77
  runNow(spaceId: string): void;
46
78
  /** Planifie une session pour l'espace ; un espace en cours de session est repris après elle. */
47
79
  schedule(spaceId: string): void;
48
80
  private drain;
49
81
  private runSession;
82
+ /** Enregistre le relevé de la session : issue, modèle, tours, tokens et coût annoncé par Claude Code. */
83
+ private record;
84
+ /**
85
+ * Lance la session avec ses limites : tours et budget appliqués par Claude
86
+ * Code, durée appliquée par le site, qui tue alors la session avec ses
87
+ * descendants. Rend son issue, et la raison de son arrêt quand ce n'est ni
88
+ * une fin normale ni un arrêt par un administrateur.
89
+ */
50
90
  private spawnClaude;
51
91
  }