@imenam/mcp-organizer 1.0.3 → 1.0.8
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.
- package/README.md +154 -26
- package/dist/shared/schemas/admin-api.schema.d.ts +193 -0
- package/dist/shared/schemas/admin-api.schema.js +84 -0
- package/dist/shared/schemas/agent-api.schema.d.ts +27 -0
- package/dist/shared/schemas/agent-api.schema.js +14 -0
- package/dist/shared/schemas/agent-tools.schema.d.ts +48 -0
- package/dist/shared/schemas/agent-tools.schema.js +14 -1
- package/dist/shared/schemas/api.schema.d.ts +2 -0
- package/dist/shared/schemas/api.schema.js +2 -0
- package/dist/shared/schemas/entities.schema.d.ts +88 -1
- package/dist/shared/schemas/entities.schema.js +65 -3
- package/dist/shared/schemas/enums.schema.d.ts +19 -1
- package/dist/shared/schemas/enums.schema.js +8 -0
- package/dist/shared/schemas/instructions-api.schema.d.ts +42 -0
- package/dist/shared/schemas/instructions-api.schema.js +25 -0
- package/dist/shared/schemas/notifications-api.schema.d.ts +31 -0
- package/dist/shared/schemas/notifications-api.schema.js +22 -1
- package/dist/shared/schemas/tasks-api.schema.d.ts +2 -0
- package/dist/shared/schemas/views-api.schema.d.ts +139 -0
- package/dist/shared/schemas/views-api.schema.js +33 -0
- package/dist/src/agent-api/requests.js +6 -3
- package/dist/src/cli/set-admin.d.ts +1 -0
- package/dist/src/cli/set-admin.js +45 -0
- package/dist/src/cli/setup.d.ts +9 -6
- package/dist/src/cli/setup.js +108 -35
- package/dist/src/core/accounts.js +2 -1
- package/dist/src/core/admin.d.ts +38 -0
- package/dist/src/core/admin.js +130 -0
- package/dist/src/core/agent-instructions.d.ts +6 -0
- package/dist/src/core/agent-instructions.js +43 -0
- package/dist/src/core/agent-tokens.d.ts +9 -1
- package/dist/src/core/agent-tokens.js +25 -2
- package/dist/src/core/agent.d.ts +7 -0
- package/dist/src/core/agent.js +38 -1
- package/dist/src/core/board-views.d.ts +12 -0
- package/dist/src/core/board-views.js +84 -0
- package/dist/src/core/migrations.js +435 -344
- package/dist/src/core/notifications.d.ts +7 -1
- package/dist/src/core/notifications.js +32 -1
- package/dist/src/core/requests.d.ts +8 -2
- package/dist/src/core/requests.js +6 -5
- package/dist/src/core/store.d.ts +77 -5
- package/dist/src/core/store.js +340 -46
- package/dist/src/deploy/env-render.d.ts +1 -1
- package/dist/src/deploy/env-render.js +2 -0
- package/dist/src/gui-api.d.ts +17 -0
- package/dist/src/gui-api.js +73 -4
- package/dist/src/index.js +8 -1
- package/dist/src/mcp/start.d.ts +1 -1
- package/dist/src/mcp/start.js +4 -4
- package/dist/src/mcp/tools.js +14 -4
- package/dist/src/server/claude-processes.d.ts +26 -0
- package/dist/src/server/claude-processes.js +72 -0
- package/dist/src/server/claude-stream.d.ts +39 -0
- package/dist/src/server/claude-stream.js +111 -0
- package/dist/src/server/runner.d.ts +91 -0
- package/dist/src/server/runner.js +355 -0
- package/dist/src/server/start.js +26 -0
- package/gui/dist/assets/index-BX6iBj41.js +70 -0
- package/gui/dist/assets/index-CXzkYy4P.css +1 -0
- package/gui/dist/index.html +2 -2
- package/package.json +3 -2
- package/gui/dist/assets/index-BVN0agCc.css +0 -1
- package/gui/dist/assets/index-DI1_kr81.js +0 -70
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* variables gérées absentes du fichier sont ajoutées à la fin.
|
|
8
8
|
*/
|
|
9
9
|
/** Variables écrites par le setup, dans l'ordre d'un fichier neuf. */
|
|
10
|
-
export declare const MANAGED_ENV_KEYS: readonly ["ORGANIZER_PUBLIC_URL", "ORGANIZER_BASE_PATH", "PORT", "HOST", "ORGANIZER_TRUST_PROXY", "MCP_ORGANIZER_DATA_DIR", "GROQ_API_KEY", "ORGANIZER_TRANSCRIBE_MODEL", "SMTP_URL", "MAIL_FROM"];
|
|
10
|
+
export declare const MANAGED_ENV_KEYS: readonly ["ORGANIZER_PUBLIC_URL", "ORGANIZER_BASE_PATH", "PORT", "HOST", "ORGANIZER_TRUST_PROXY", "MCP_ORGANIZER_DATA_DIR", "GROQ_API_KEY", "ORGANIZER_TRANSCRIBE_MODEL", "SMTP_URL", "MAIL_FROM", "ORGANIZER_RUNNER_CLAUDE"];
|
|
11
11
|
export type ManagedEnvKey = (typeof MANAGED_ENV_KEYS)[number];
|
|
12
12
|
/**
|
|
13
13
|
* Variables d'amorçage du premier compte : le setup crée le compte en base et
|
|
@@ -18,6 +18,7 @@ export const MANAGED_ENV_KEYS = [
|
|
|
18
18
|
"ORGANIZER_TRANSCRIBE_MODEL",
|
|
19
19
|
"SMTP_URL",
|
|
20
20
|
"MAIL_FROM",
|
|
21
|
+
"ORGANIZER_RUNNER_CLAUDE",
|
|
21
22
|
];
|
|
22
23
|
/**
|
|
23
24
|
* Variables d'amorçage du premier compte : le setup crée le compte en base et
|
|
@@ -51,6 +52,7 @@ const COMMENTS = {
|
|
|
51
52
|
ORGANIZER_PUBLIC_URL: "# URL ouverte par les utilisateurs, derrière nginx.",
|
|
52
53
|
PORT: "# Écoute du site ; nginx le joint à cette adresse.",
|
|
53
54
|
MCP_ORGANIZER_DATA_DIR: "# Base SQLite, pièces jointes et journaux.",
|
|
55
|
+
ORGANIZER_RUNNER_CLAUDE: "# Claude Code du runner, connecté pour le compte du site.",
|
|
54
56
|
GROQ_API_KEY: "# Dictée vocale (Groq).",
|
|
55
57
|
SMTP_URL: "# Envoi des e-mails (invitations, notifications).",
|
|
56
58
|
};
|
package/dist/src/gui-api.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type ApiRequestData, type ApiResponseData, type ApiErrorKind } from "../shared/schemas/gui-api.schema.js";
|
|
2
|
+
import { type RunnerFailure } from "../shared/schemas/agent-api.schema.js";
|
|
3
|
+
import { type KillAllResponse, type RunnerStatus } from "../shared/schemas/admin-api.schema.js";
|
|
2
4
|
import type { AttachmentStorage } from "./core/attachments.js";
|
|
3
5
|
import type { Mailer } from "./core/mail.js";
|
|
4
6
|
import type { Store } from "./core/store.js";
|
|
@@ -26,6 +28,21 @@ export interface GuiApiContext {
|
|
|
26
28
|
attachments: AttachmentStorage;
|
|
27
29
|
/** Dictée vocale (API Groq). */
|
|
28
30
|
transcriber: Transcriber;
|
|
31
|
+
/** Runner du site : son état, et le lancement d'une session ponctuelle (null quand il est désactivé). */
|
|
32
|
+
runner: {
|
|
33
|
+
status: RunnerStatus;
|
|
34
|
+
runNow: ((spaceId: string) => void) | null;
|
|
35
|
+
/** Dernière session du runner dans un espace, quand elle a échoué. */
|
|
36
|
+
lastFailure: (spaceId: string) => RunnerFailure | null;
|
|
37
|
+
/** Session du runner en cours dans un espace. */
|
|
38
|
+
currentSession: (spaceId: string) => {
|
|
39
|
+
startedAt: string;
|
|
40
|
+
} | null;
|
|
41
|
+
/** Arrête la session en cours dans un espace ; rend les demandes passées en échec, null sans session (null quand le runner est désactivé). */
|
|
42
|
+
stopSession: ((spaceId: string, userId: string) => number | null) | null;
|
|
43
|
+
/** Arrêt d'urgence : tue tous les processus Claude Code de la machine du site. */
|
|
44
|
+
killAll: (userId: string) => Promise<KillAllResponse>;
|
|
45
|
+
};
|
|
29
46
|
/** Horloge, imposée par les tests. */
|
|
30
47
|
now?: () => Date;
|
|
31
48
|
}
|
package/dist/src/gui-api.js
CHANGED
|
@@ -6,15 +6,21 @@ import { acceptReceivedInvitation, createSharedSpace, declineReceivedInvitation,
|
|
|
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
|
-
import { getSettings, listNotifications, markAllNotificationsRead, markNotificationRead, unreadCount, updateSettings } from "./core/notifications.js";
|
|
10
|
-
import { NotificationListQuerySchema, UpdateSettingsRequestSchema } from "../shared/schemas/notifications-api.schema.js";
|
|
9
|
+
import { getSettings, getSpaceNotificationSettings, listNotifications, markAllNotificationsRead, markNotificationRead, unreadCount, updateSettings, updateSpaceNotificationSettings } from "./core/notifications.js";
|
|
10
|
+
import { NotificationListQuerySchema, UpdateSettingsRequestSchema, UpdateSpaceNotificationSettingsRequestSchema } from "../shared/schemas/notifications-api.schema.js";
|
|
11
11
|
import { cancelRequest, createRequest, getRequest, listRequests, releaseRequest, 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";
|
|
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";
|
|
18
24
|
import { TranscriptionError } from "./core/transcription.js";
|
|
19
25
|
import { MAX_TRANSCRIPTION_BYTES, TranscribeRequestSchema } from "../shared/schemas/transcription-api.schema.js";
|
|
20
26
|
/** Erreur d'une requête de la GUI, avec la nature qui fixe son code HTTP. */
|
|
@@ -89,7 +95,7 @@ function parseBody(schema, body) {
|
|
|
89
95
|
return parsed.data;
|
|
90
96
|
}
|
|
91
97
|
function publicUser(user) {
|
|
92
|
-
return { id: user.id, email: user.email, displayName: user.displayName, status: user.status };
|
|
98
|
+
return { id: user.id, email: user.email, displayName: user.displayName, status: user.status, isAdmin: user.isAdmin };
|
|
93
99
|
}
|
|
94
100
|
const ok = { ok: true };
|
|
95
101
|
/** Taille lisible d'un nombre d'octets, en Mo. */
|
|
@@ -188,6 +194,18 @@ route("POST", "/invitations/:invitationId/decline", (ctx, { user, params }) => {
|
|
|
188
194
|
declineReceivedInvitation(ctx.store, user.id, params.invitationId);
|
|
189
195
|
return { body: ok };
|
|
190
196
|
});
|
|
197
|
+
// --- Vues du tableau de bord --------------------------------------------------------
|
|
198
|
+
route("GET", "/spaces/:spaceId/views", (ctx, { user, params }) => ({ body: listBoardViews(ctx.store, user.id, params.spaceId) }));
|
|
199
|
+
route("POST", "/spaces/:spaceId/views", (ctx, { user, request, params }) => ({
|
|
200
|
+
body: createBoardView(ctx.store, user.id, params.spaceId, parseBody(CreateBoardViewRequestSchema, request.body)),
|
|
201
|
+
}));
|
|
202
|
+
route("PATCH", "/views/:viewId", (ctx, { user, request, params }) => ({
|
|
203
|
+
body: updateBoardView(ctx.store, user.id, params.viewId, parseBody(UpdateBoardViewRequestSchema, request.body)),
|
|
204
|
+
}));
|
|
205
|
+
route("DELETE", "/views/:viewId", (ctx, { user, params }) => {
|
|
206
|
+
deleteBoardView(ctx.store, user.id, params.viewId);
|
|
207
|
+
return { body: ok };
|
|
208
|
+
});
|
|
191
209
|
// --- Tâches -----------------------------------------------------------------------
|
|
192
210
|
route("GET", "/spaces/:spaceId/tasks", (ctx, { user, request, params }) => {
|
|
193
211
|
const parsed = TaskFiltersSchema.safeParse(request.query);
|
|
@@ -287,7 +305,7 @@ route("POST", "/ideas/:ideaId/promote", (ctx, { user, request, params }) => ({
|
|
|
287
305
|
}));
|
|
288
306
|
route("POST", "/ideas/:ideaId/delegate", (ctx, { user, params }) => ({ body: delegatePromotion(ctx.store, user.id, params.ideaId) }));
|
|
289
307
|
// --- File de l'agent et historique -------------------------------------------------
|
|
290
|
-
route("GET", "/spaces/:spaceId/requests", (ctx, { user, params }) => ({ body: listRequests(ctx.store, user.id, params.spaceId, now(ctx)) }));
|
|
308
|
+
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)) }));
|
|
291
309
|
route("POST", "/spaces/:spaceId/requests", (ctx, { user, request, params }) => ({
|
|
292
310
|
body: createRequest(ctx.store, user.id, params.spaceId, parseBody(CreateRequestSchema, request.body)),
|
|
293
311
|
}));
|
|
@@ -322,6 +340,16 @@ route("GET", "/settings", (ctx, { user }) => ({ body: getSettings(ctx.store, ctx
|
|
|
322
340
|
route("PUT", "/settings", (ctx, { user, request }) => ({
|
|
323
341
|
body: updateSettings(ctx.store, ctx, user.id, parseBody(UpdateSettingsRequestSchema, request.body)),
|
|
324
342
|
}));
|
|
343
|
+
route("GET", "/spaces/:spaceId/notification-settings", (ctx, { user, params }) => ({
|
|
344
|
+
body: getSpaceNotificationSettings(ctx.store, ctx, user.id, params.spaceId),
|
|
345
|
+
}));
|
|
346
|
+
route("PUT", "/spaces/:spaceId/notification-settings", (ctx, { user, request, params }) => ({
|
|
347
|
+
body: updateSpaceNotificationSettings(ctx.store, ctx, user.id, params.spaceId, parseBody(UpdateSpaceNotificationSettingsRequestSchema, request.body)),
|
|
348
|
+
}));
|
|
349
|
+
route("GET", "/spaces/:spaceId/agent-instructions", (ctx, { user, params }) => ({ body: getSpaceInstructions(ctx.store, user.id, params.spaceId) }));
|
|
350
|
+
route("PUT", "/spaces/:spaceId/agent-instructions", (ctx, { user, request, params }) => ({
|
|
351
|
+
body: setSpaceInstructions(ctx.store, user.id, params.spaceId, parseBody(SetAgentInstructionsRequestSchema, request.body).text),
|
|
352
|
+
}));
|
|
325
353
|
// --- Jetons d'agent ---------------------------------------------------------------
|
|
326
354
|
route("GET", "/tokens", (ctx, { user }) => ({ body: listAgentTokens(ctx.store, user.id, now(ctx)) }));
|
|
327
355
|
route("POST", "/tokens", (ctx, { user, request }) => {
|
|
@@ -331,6 +359,47 @@ route("POST", "/tokens", (ctx, { user, request }) => {
|
|
|
331
359
|
return { body: createAgentToken(ctx.store, user.id, input, ctx.publicUrl, now(ctx)) };
|
|
332
360
|
});
|
|
333
361
|
route("POST", "/tokens/:tokenId/revoke", (ctx, { user, params }) => ({ body: revokeAgentToken(ctx.store, user.id, params.tokenId, now(ctx)) }));
|
|
362
|
+
// --- Administration ----------------------------------------------------------------
|
|
363
|
+
route("GET", "/admin/spaces", (ctx, { user }) => ({ body: listAdminSpaces(ctx.store, user.id, ctx.runner.status) }));
|
|
364
|
+
route("POST", "/spaces/:spaceId/runner/run", (ctx, { user, params }) => {
|
|
365
|
+
requireAdmin(ctx.store, user.id);
|
|
366
|
+
const runNow = ctx.runner.runNow;
|
|
367
|
+
if (!runNow)
|
|
368
|
+
throw new ApiError("unavailable", `Runner désactivé : ${ctx.runner.status.disabledReason}`);
|
|
369
|
+
return { body: processQueueNow(ctx.store, user.id, params.spaceId, runNow) };
|
|
370
|
+
});
|
|
371
|
+
route("POST", "/spaces/:spaceId/runner/stop", (ctx, { user, params }) => {
|
|
372
|
+
requireAdmin(ctx.store, user.id);
|
|
373
|
+
const stopSession = ctx.runner.stopSession;
|
|
374
|
+
if (!stopSession)
|
|
375
|
+
throw new ApiError("unavailable", `Runner désactivé : ${ctx.runner.status.disabledReason}`);
|
|
376
|
+
const abortedRequests = stopSession(params.spaceId, user.id);
|
|
377
|
+
if (abortedRequests === null)
|
|
378
|
+
throw new InvariantError("Aucune session du runner ne tourne dans cet espace.");
|
|
379
|
+
return { body: { abortedRequests } };
|
|
380
|
+
});
|
|
381
|
+
route("GET", "/admin/runner/settings", (ctx, { user }) => ({ body: getRunnerSettings(ctx.store, user.id) }));
|
|
382
|
+
route("PUT", "/admin/runner/settings", (ctx, { user, request }) => ({
|
|
383
|
+
body: setRunnerSettings(ctx.store, user.id, parseBody(RunnerSettingsSchema, request.body)),
|
|
384
|
+
}));
|
|
385
|
+
route("GET", "/admin/runner/usage", (ctx, { user, request }) => {
|
|
386
|
+
const parsed = RunnerUsageQuerySchema.safeParse(request.query);
|
|
387
|
+
if (!parsed.success)
|
|
388
|
+
throw new ApiError("invalid", "days : un nombre de jours entre 1 et 90.");
|
|
389
|
+
return { body: runnerUsage(ctx.store, user.id, parsed.data.days, now(ctx)) };
|
|
390
|
+
});
|
|
391
|
+
route("POST", "/admin/runner/kill-all", async (ctx, { user }) => {
|
|
392
|
+
requireAdmin(ctx.store, user.id);
|
|
393
|
+
return { body: await ctx.runner.killAll(user.id) };
|
|
394
|
+
});
|
|
395
|
+
route("PUT", "/admin/spaces/:spaceId/runner", (ctx, { user, request, params }) => {
|
|
396
|
+
const input = parseBody(SetRunnerAllowedRequestSchema, request.body);
|
|
397
|
+
return { body: setRunnerAllowed(ctx.store, user.id, params.spaceId, input.allowed) };
|
|
398
|
+
});
|
|
399
|
+
route("GET", "/admin/agent-instructions", (ctx, { user }) => ({ body: getSiteInstructions(ctx.store, user.id) }));
|
|
400
|
+
route("PUT", "/admin/agent-instructions", (ctx, { user, request }) => ({
|
|
401
|
+
body: setSiteInstructions(ctx.store, user.id, parseBody(SetAgentInstructionsRequestSchema, request.body).text),
|
|
402
|
+
}));
|
|
334
403
|
// --- Dictée ------------------------------------------------------------------------
|
|
335
404
|
route("POST", "/transcribe", async (ctx, { request }) => {
|
|
336
405
|
const input = parseBody(TranscribeRequestSchema, request.body);
|
package/dist/src/index.js
CHANGED
|
@@ -12,6 +12,9 @@ Usage :
|
|
|
12
12
|
mcp-organizer --server Site web : interface, API et base de données, sur HOST:PORT.
|
|
13
13
|
mcp-organizer --set-user [email] [--name="Prénom Nom"] [--non-interactive]
|
|
14
14
|
Crée un compte ou remplace son mot de passe.
|
|
15
|
+
mcp-organizer --set-admin <email> [--revoke]
|
|
16
|
+
Accorde (ou retire) le rôle d'administrateur du site à un compte actif.
|
|
17
|
+
Le premier compte créé est administrateur d'office.
|
|
15
18
|
mcp-organizer --setup [options] Installe le site : .env, unité systemd, bloc nginx, premier compte
|
|
16
19
|
(interactif, ou --non-interactive ; --setup --help pour les options).
|
|
17
20
|
mcp-organizer --backup <fichier> [--force]
|
|
@@ -33,7 +36,7 @@ Le mode MCP exige ORGANIZER_URL (URL publique du site, en https hors de la machi
|
|
|
33
36
|
et ORGANIZER_TOKEN (jeton d'agent), fournis par son environnement.
|
|
34
37
|
Voir le README pour la liste complète des variables.`;
|
|
35
38
|
/** Commandes qui ouvrent la base du site ; toute autre invocation démarre le mode MCP. */
|
|
36
|
-
const SITE_COMMANDS = ["--server", "--set-user", "--setup", "--backup"];
|
|
39
|
+
const SITE_COMMANDS = ["--server", "--set-user", "--set-admin", "--setup", "--backup"];
|
|
37
40
|
async function main() {
|
|
38
41
|
const argv = process.argv.slice(2);
|
|
39
42
|
if (argv.includes("--setup") && (argv.includes("--help") || argv.includes("-h"))) {
|
|
@@ -87,6 +90,10 @@ async function main() {
|
|
|
87
90
|
const [{ runSetUser }, { resolveDataDir }] = await Promise.all([import("./cli/set-user.js"), import("./core/data-dir.js")]);
|
|
88
91
|
process.exit(await runSetUser(args, resolveDataDir(rootDir)));
|
|
89
92
|
}
|
|
93
|
+
if (args.includes("--set-admin")) {
|
|
94
|
+
const [{ runSetAdmin }, { resolveDataDir }] = await Promise.all([import("./cli/set-admin.js"), import("./core/data-dir.js")]);
|
|
95
|
+
process.exit(await runSetAdmin(args, resolveDataDir(rootDir)));
|
|
96
|
+
}
|
|
90
97
|
if (args.includes("--backup")) {
|
|
91
98
|
const [{ runBackup }, { resolveDataDir }] = await Promise.all([import("./cli/backup.js"), import("./core/data-dir.js")]);
|
|
92
99
|
process.exit(await runBackup(args, resolveDataDir(rootDir)));
|
package/dist/src/mcp/start.d.ts
CHANGED
|
@@ -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, 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`.
|
package/dist/src/mcp/start.js
CHANGED
|
@@ -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, 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. */
|
package/dist/src/mcp/tools.js
CHANGED
|
@@ -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) {
|
|
@@ -35,7 +35,7 @@ export const AGENT_TOOLS = [
|
|
|
35
35
|
path: "requests/{request_id}/claim",
|
|
36
36
|
definition: {
|
|
37
37
|
name: "claim_request",
|
|
38
|
-
description: "Claim a pending request before working on it: it becomes processing for your token only (no other agent can take it or act for it) and you get its full context — text, author, context task or idea, the task tree of your space with keys, statuses, priorities and assignees, its members and recent ideas. Every write tool then needs this request_id.",
|
|
38
|
+
description: "Claim a pending request before working on it: it becomes processing for your token only (no other agent can take it or act for it) and you get its full context — text, author, context task or idea, for a message the previous exchanges of its author (their requests and your replies), the task tree of your space with keys, statuses, priorities and assignees, its members and recent ideas. Every write tool then needs this request_id.",
|
|
39
39
|
inputSchema: {
|
|
40
40
|
type: "object",
|
|
41
41
|
properties: { request_id: { type: "string", description: "Id of a pending request, from list_requests." } },
|
|
@@ -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:
|
|
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: {
|
|
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
|
+
}
|