@runeya/runeya 2.0.96 → 2.0.97

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.
@@ -24,7 +24,7 @@ import {
24
24
  resetRelaunches,
25
25
  syncConversationFromClaudeTranscript,
26
26
  verifyJwt
27
- } from "./chunk-BV7A2N5C.js";
27
+ } from "./chunk-ANGVT3MX.js";
28
28
  import {
29
29
  agentManager,
30
30
  agentStore,
@@ -87,466 +87,98 @@ import { execFile } from "child_process";
87
87
  import { promisify } from "util";
88
88
  import { fileURLToPath as fileURLToPath2 } from "url";
89
89
 
90
- // ../../packages/ai-capabilities/src/capabilities.ts
91
- function toList(raw) {
92
- if (!raw) return [];
93
- const text = raw.trim();
94
- if (text.startsWith("[")) {
90
+ // ../../packages/mcp-server/src/launch.ts
91
+ import { fileURLToPath } from "url";
92
+ import { createRequire } from "module";
93
+ import { existsSync } from "fs";
94
+ function resolveMcpServerPath() {
95
+ try {
96
+ const req = createRequire(import.meta.url);
97
+ return req.resolve("@runeya/packages-mcp-server");
98
+ } catch {
99
+ }
100
+ const candidates = [
101
+ // Build packagé du CLI : dist/agent/index.js et dist/index.js côtoient
102
+ // dist/mcp-server/, copié là par le post-build.
103
+ new URL("../mcp-server/index.js", import.meta.url),
104
+ new URL("./mcp-server/index.js", import.meta.url),
105
+ // Monorepo, depuis un dist d'app.
106
+ new URL("../../../packages/mcp-server/dist/index.js", import.meta.url),
107
+ new URL("../../../../packages/mcp-server/dist/index.js", import.meta.url)
108
+ ];
109
+ for (const c of candidates) {
110
+ const p = fileURLToPath(c);
111
+ if (existsSync(p)) return p;
112
+ }
113
+ throw new Error("Could not locate @runeya/packages-mcp-server (built dist not found)");
114
+ }
115
+ function pickEnv(env2) {
116
+ return {
117
+ ...env2.RUNEYA_BASE_URL ? { RUNEYA_BASE_URL: env2.RUNEYA_BASE_URL } : {},
118
+ ...env2.RUNEYA_API_TOKEN ? { RUNEYA_API_TOKEN: env2.RUNEYA_API_TOKEN } : {},
119
+ ...env2.RUNEYA_PROJECT_ID ? { RUNEYA_PROJECT_ID: env2.RUNEYA_PROJECT_ID } : {},
120
+ ...env2.RUNEYA_ORG_ID ? { RUNEYA_ORG_ID: env2.RUNEYA_ORG_ID } : {}
121
+ };
122
+ }
123
+ function runeyaMcpConfig(env2) {
124
+ return JSON.stringify({
125
+ mcpServers: {
126
+ runeya: {
127
+ command: "node",
128
+ args: [resolveMcpServerPath()],
129
+ env: pickEnv(env2)
130
+ }
131
+ }
132
+ });
133
+ }
134
+ function codexMcpArgs(env2) {
135
+ const fields = [
136
+ `command=${tomlString("node")}`,
137
+ `args=[${tomlString(resolveMcpServerPath())}]`
138
+ ];
139
+ const entries = Object.entries(pickEnv(env2));
140
+ if (entries.length > 0) {
141
+ const inline = entries.map(([k, v]) => `${k}=${tomlString(v)}`).join(",");
142
+ fields.push(`env={${inline}}`);
143
+ }
144
+ return ["-c", `mcp_servers.runeya={${fields.join(",")}}`];
145
+ }
146
+ function tomlString(value) {
147
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/[\u0000-\u001f\u007f]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
148
+ return `"${escaped}"`;
149
+ }
150
+
151
+ // ../server/src/services/codex-sessions.ts
152
+ import { readdir } from "fs/promises";
153
+ import { homedir } from "os";
154
+ import { join } from "path";
155
+ var CODEX_SESSIONS_DIR = join(homedir(), ".codex", "sessions");
156
+ async function findCodexSessionFile(sessionId) {
157
+ const suffix = `-${sessionId}.jsonl`;
158
+ async function walk(dir) {
159
+ let entries;
95
160
  try {
96
- const parsed = JSON.parse(text);
97
- if (Array.isArray(parsed)) return parsed.map((v) => String(v).trim()).filter(Boolean);
161
+ entries = await readdir(dir, { withFileTypes: true });
98
162
  } catch {
163
+ return null;
164
+ }
165
+ for (const entry of entries) {
166
+ const full = join(dir, entry.name);
167
+ if (entry.isDirectory()) {
168
+ const found = await walk(full);
169
+ if (found) return found;
170
+ } else if (entry.name.endsWith(suffix)) {
171
+ return full;
172
+ }
99
173
  }
174
+ return null;
100
175
  }
101
- return text.split(",").map((v) => v.trim().replace(/^["'[]+|["'\]]+$/g, "")).filter(Boolean);
176
+ return walk(CODEX_SESSIONS_DIR);
102
177
  }
103
- function clearable(raw, parse2, key) {
104
- if (raw === void 0) return {};
105
- const text = String(raw).trim();
106
- if (!text || text === "null") return { [key]: null };
107
- return { [key]: parse2(text) };
108
- }
109
- var RUNEYA_CAPABILITIES = [
110
- {
111
- name: "list_services",
112
- description: "List all available services. Returns serviceId and agentId for each \u2014 use these exact fields in other calls.",
113
- route: "service.list",
114
- method: "GET",
115
- params: [],
116
- buildInput: () => void 0
117
- },
118
- {
119
- name: "get_service_status",
120
- description: "Get the current status (running, stopped, etc.) of a service.",
121
- route: "process.get",
122
- method: "GET",
123
- params: [
124
- { name: "serviceId", description: "The service ID", required: true },
125
- { name: "agentId", description: "The agent ID hosting this service", required: true }
126
- ],
127
- buildInput: (p) => ({ agentId: p.agentId, id: p.serviceId })
128
- },
129
- {
130
- name: "get_logs",
131
- description: "Get the recent buffered logs for a service.",
132
- route: "process.logs",
133
- method: "GET",
134
- params: [
135
- { name: "serviceId", description: "The service ID", required: true },
136
- { name: "agentId", description: "The agent ID hosting this service", required: true }
137
- ],
138
- buildInput: (p) => ({ agentId: p.agentId, processId: p.serviceId })
139
- },
140
- {
141
- name: "start_service",
142
- description: "Start a service on an agent.",
143
- route: "process.start",
144
- method: "POST",
145
- params: [
146
- { name: "serviceId", description: "The service ID to start", required: true },
147
- { name: "agentId", description: "The agent ID hosting this service", required: true }
148
- ],
149
- buildInput: (p) => ({ agentId: p.agentId, processId: p.serviceId }),
150
- destructive: true
151
- },
152
- {
153
- name: "stop_service",
154
- description: "Stop a running service on an agent.",
155
- route: "process.stop",
156
- method: "POST",
157
- params: [
158
- { name: "serviceId", description: "The service ID to stop", required: true },
159
- { name: "agentId", description: "The agent ID hosting this service", required: true }
160
- ],
161
- buildInput: (p) => ({ agentId: p.agentId, processId: p.serviceId }),
162
- destructive: true
163
- },
164
- {
165
- name: "restart_service",
166
- description: "Restart a service on an agent (stop \u2192 redeploy \u2192 start).",
167
- route: "process.restart",
168
- method: "POST",
169
- params: [
170
- { name: "serviceId", description: "The service ID to restart", required: true },
171
- { name: "agentId", description: "The agent ID hosting this service", required: true }
172
- ],
173
- buildInput: (p) => ({ agentId: p.agentId, processId: p.serviceId }),
174
- destructive: true
175
- },
176
- // ─── Utility ─────────────────────────────────────────────────────────────
177
- {
178
- name: "wait",
179
- description: "Wait for a given number of milliseconds before continuing.",
180
- route: "utility.wait",
181
- method: "POST",
182
- params: [
183
- { name: "ms", description: "Number of MILLISECONDS to wait. Convert from seconds: 1s=1000, 10s=10000, 1min=60000. Max 300000.", required: true }
184
- ],
185
- buildInput: (p) => ({ ms: Number(p.ms) }),
186
- usageHint: '"wait 5s" \u2192 wait(ms=5000), "pause 10 seconds" \u2192 wait(ms=10000), "attends 3 secondes" \u2192 wait(ms=3000). Always convert to milliseconds.'
187
- },
188
- // ─── Kanban ───────────────────────────────────────────────────────────────
189
- {
190
- name: "kanban_list_boards",
191
- description: "List the kanban boards of the organization. Returns the organizationId actually queried, the boardId to use in the other kanban tools, plus column and card counts. Cards themselves are not included \u2014 use kanban_get_board for those. An empty list means that organization really has no board: a failure to reach the cloud is reported as an error instead, never as an empty list.",
192
- route: "kanban.listBoards",
193
- method: "GET",
194
- params: [
195
- { name: "includeArchived", description: 'Set to "true" to include archived boards. Default: false.', required: false },
196
- { name: "organizationId", description: "Which organization to read. Optional: needed only when the account belongs to several and the error message asks for it.", required: false }
197
- ],
198
- buildInput: (p) => ({
199
- includeArchived: p.includeArchived === "true",
200
- ...p.organizationId ? { organizationId: p.organizationId } : {}
201
- })
202
- },
203
- {
204
- name: "kanban_get_board",
205
- description: "Read one kanban board: its columns, and the cards in each (id, title, markdown body, assignees, comment count, and attachment metadata \u2014 use kanban_download_attachment to fetch the bytes of a file). Use the exact column names it returns when moving or adding a card.",
206
- route: "kanban.getBoard",
207
- method: "GET",
208
- params: [
209
- { name: "boardId", description: "The kanban board ID, from kanban_list_boards", required: true }
210
- ],
211
- buildInput: (p) => ({ boardId: p.boardId })
212
- },
213
- {
214
- name: "kanban_get_card_comments",
215
- description: "Read the comment thread of one kanban card, newest last: who wrote each comment (ai or user, with the person's name), when, its text, and its attachments. The comments in your task context are a snapshot taken when the task started \u2014 call this to see anything written since, whenever someone tells you a comment was added or kanban_get_board reports a higher commentCount than you have.",
216
- route: "kanban.getCardComments",
217
- method: "GET",
218
- params: [
219
- { name: "boardId", description: "The kanban board ID", required: true },
220
- { name: "cardId", description: "The card ID whose comments to read", required: true },
221
- { name: "limit", description: "How many of the most recent comments to return (1-200). Default: 50.", required: false }
222
- ],
223
- buildInput: (p) => ({
224
- boardId: p.boardId,
225
- cardId: p.cardId,
226
- ...p.limit ? { limit: Number(p.limit) } : {}
227
- }),
228
- usageHint: '"le support a ajout\xE9 un commentaire" / "regarde les nouveaux commentaires" \u2192 kanban_get_card_comments(boardId, cardId). Never answer from the snapshot in your context when fresh comments are mentioned.'
229
- },
230
- {
231
- name: "kanban_search_cards",
232
- description: "Search kanban cards by free text, matched against their title, body and comments (accent- and case-insensitive). Archived cards are included. Searches every board of the organization unless boardId narrows it down.",
233
- route: "kanban.searchCards",
234
- method: "GET",
235
- params: [
236
- { name: "query", description: "Text to look for in card titles, bodies and comments", required: true },
237
- { name: "boardId", description: "Restrict the search to this board. Omit to search all boards.", required: false },
238
- { name: "limit", description: "Maximum number of cards to return (1-100). Default: 25.", required: false },
239
- { name: "organizationId", description: "Which organization to search. Optional: needed only when the account belongs to several and the error message asks for it.", required: false }
240
- ],
241
- buildInput: (p) => ({
242
- query: p.query,
243
- ...p.boardId ? { boardId: p.boardId } : {},
244
- ...p.limit ? { limit: Number(p.limit) } : {},
245
- ...p.organizationId ? { organizationId: p.organizationId } : {}
246
- })
247
- },
248
- {
249
- name: "kanban_download_attachment",
250
- description: "Download a kanban card attachment (image, PDF, any file) onto this machine and return its local path, so it can be opened with file-reading tools. Attachment ids come from the card context, from kanban_get_board, or from kanban_get_card_comments \u2014 a file attached to a comment downloads exactly like one attached to the card.",
251
- route: "kanban.downloadAttachment",
252
- method: "POST",
253
- params: [
254
- { name: "attachmentId", description: "The attachment ID, as listed on the card", required: true }
255
- ],
256
- buildInput: (p) => ({ attachmentId: p.attachmentId })
257
- },
258
- {
259
- name: "kanban_move_card",
260
- description: "Move a kanban card to another column. Use the exact column name.",
261
- route: "kanban.moveCard",
262
- method: "POST",
263
- params: [
264
- { name: "boardId", description: "The kanban board ID", required: true },
265
- { name: "cardId", description: "The card ID to move", required: true },
266
- { name: "targetColumn", description: "Exact name of the target column", required: true }
267
- ],
268
- buildInput: (p) => ({ boardId: p.boardId, cardId: p.cardId, targetColumn: p.targetColumn })
269
- },
270
- {
271
- name: "kanban_add_comment",
272
- description: "Add a comment to a kanban card.",
273
- route: "kanban.addComment",
274
- method: "POST",
275
- params: [
276
- { name: "boardId", description: "The kanban board ID", required: true },
277
- { name: "cardId", description: "The card ID", required: true },
278
- { name: "comment", description: "The comment text (markdown supported)", required: true }
279
- ],
280
- buildInput: (p) => ({ boardId: p.boardId, cardId: p.cardId, comment: p.comment })
281
- },
282
- {
283
- name: "kanban_get_card_links",
284
- description: "Read the filiation of a board: which card depends on which. Returns one entry per link (child card \u2194 parent card), plus the title, board, column, assignees and comment count of any linked card living on another board. Use it when a card context says it has a parent or sub-cards and you need their ids to read them.",
285
- route: "kanban.getCardLinks",
286
- method: "GET",
287
- params: [
288
- { name: "boardId", description: "The kanban board ID whose links to read", required: true }
289
- ],
290
- buildInput: (p) => ({ boardId: p.boardId })
291
- },
292
- {
293
- name: "kanban_set_card_parent",
294
- description: "Link a kanban card to a parent card, or detach it. The parent is the card the other one depends on \u2014 an epic and its tasks, a bug and its follow-ups. A card has at most one parent, and setting a new one replaces it. Omit parentCardId to detach. kanban_get_board reports the current filiation as parentCardId / childCardIds on each card.",
295
- route: "kanban.setCardParent",
296
- method: "POST",
297
- params: [
298
- { name: "boardId", description: "The kanban board ID of the card being linked", required: true },
299
- { name: "cardId", description: "The card that depends on the parent (the child)", required: true },
300
- { name: "parentCardId", description: "The parent card ID. Omit to detach the card from its parent.", required: false },
301
- { name: "parentBoardId", description: "The parent's board, when it lives on another board of the same organization. Defaults to boardId.", required: false }
302
- ],
303
- buildInput: (p) => ({
304
- boardId: p.boardId,
305
- cardId: p.cardId,
306
- ...p.parentCardId ? { parentCardId: p.parentCardId } : {},
307
- ...p.parentBoardId ? { parentBoardId: p.parentBoardId } : {}
308
- })
309
- },
310
- {
311
- name: "kanban_add_card",
312
- description: "Add a new card to a kanban column.",
313
- route: "kanban.addCard",
314
- method: "POST",
315
- params: [
316
- { name: "boardId", description: "The kanban board ID", required: true },
317
- { name: "column", description: "Exact name of the target column", required: true },
318
- { name: "title", description: "Card title", required: true },
319
- { name: "content", description: "Card content in markdown", required: false }
320
- ],
321
- buildInput: (p) => ({ boardId: p.boardId, column: p.column, title: p.title, content: p.content })
322
- },
323
- {
324
- name: "kanban_get_card",
325
- description: "Read one kanban card by id, including archived ones. Cheaper than fetching the whole board, and the only way to read a card that has been archived.",
326
- route: "kanban.getCard",
327
- method: "GET",
328
- params: [
329
- { name: "boardId", description: "The kanban board ID", required: true },
330
- { name: "cardId", description: "The card ID", required: true }
331
- ],
332
- buildInput: (p) => ({ boardId: p.boardId, cardId: p.cardId })
333
- },
334
- {
335
- name: "kanban_update_card",
336
- description: "Update an existing kanban card. Only the fields you pass are changed; passing null to priority, color or deadline clears it. Prefer this over creating a second card when something needs correcting.",
337
- route: "kanban.updateCard",
338
- method: "POST",
339
- params: [
340
- { name: "boardId", description: "The kanban board ID", required: true },
341
- { name: "cardId", description: "The card ID", required: true },
342
- { name: "title", description: "New title", required: false },
343
- { name: "content", description: "New card content, in markdown", required: false },
344
- { name: "priority", description: "Priority from 1 to 10, or null to clear it", required: false },
345
- { name: "color", description: "Card colour, or null to clear it", required: false },
346
- { name: "groups", description: "Labels, as a list of strings. Replaces the current ones.", required: false },
347
- { name: "deadline", description: "Due date as YYYY-MM-DD, or null to clear it", required: false },
348
- { name: "assignees", description: "User ids to assign, as a list. Replaces the current ones; use kanban_list_members to find the ids.", required: false }
349
- ],
350
- buildInput: (p) => ({
351
- boardId: p.boardId,
352
- cardId: p.cardId,
353
- ...p.title !== void 0 ? { title: p.title } : {},
354
- ...p.content !== void 0 ? { content: p.content } : {},
355
- // Tout arrive en chaîne : un modèle n'écrit pas des nombres, des listes
356
- // ni des `null` typés. `clearable` distingue « efface » de « ne touche
357
- // pas » — sans quoi vider une couleur serait impossible à exprimer, et
358
- // changer un titre risquerait de vider le reste.
359
- ...clearable(p.priority, (v) => Number(v), "priority"),
360
- ...clearable(p.color, (v) => v, "color"),
361
- ...clearable(p.deadline, (v) => v, "deadline"),
362
- ...p.groups !== void 0 ? { groups: toList(p.groups) } : {},
363
- ...p.assignees !== void 0 ? { assignees: toList(p.assignees) } : {}
364
- })
365
- },
366
- {
367
- name: "kanban_set_card_archived",
368
- description: "Archive a kanban card (it leaves the board but is not deleted) or bring it back. An unarchived card returns to the column it left.",
369
- route: "kanban.setCardArchived",
370
- method: "POST",
371
- params: [
372
- { name: "boardId", description: "The kanban board ID", required: true },
373
- { name: "cardId", description: "The card ID", required: true },
374
- { name: "archived", description: "true to archive, false to bring the card back", required: true }
375
- ],
376
- buildInput: (p) => ({ boardId: p.boardId, cardId: p.cardId, archived: p.archived === "true" })
377
- },
378
- {
379
- name: "kanban_list_members",
380
- description: "List the people of the organization who can be assigned to a card, with their ids. Needed before assigning anyone with kanban_update_card.",
381
- route: "kanban.listMembers",
382
- method: "GET",
383
- params: [
384
- { name: "organizationId", description: "Which organization. Optional: needed only when the account belongs to several and the error message asks for it.", required: false }
385
- ],
386
- buildInput: (p) => p.organizationId ? { organizationId: p.organizationId } : {}
387
- }
388
- ];
389
-
390
- // ../../packages/ai-capabilities/src/adapters/anthropic.ts
391
- function buildAnthropicTools(capabilities) {
392
- return capabilities.map((cap) => ({
393
- name: cap.name,
394
- description: cap.description,
395
- input_schema: {
396
- type: "object",
397
- properties: Object.fromEntries(
398
- cap.params.map((p) => [p.name, { type: "string", description: p.description }])
399
- ),
400
- required: cap.params.filter((p) => p.required).map((p) => p.name)
401
- }
402
- }));
403
- }
404
-
405
- // ../../packages/ai-capabilities/src/adapters/openai.ts
406
- function buildOpenAITools(capabilities) {
407
- return capabilities.map((cap) => ({
408
- type: "function",
409
- function: {
410
- name: cap.name,
411
- description: cap.description,
412
- parameters: {
413
- type: "object",
414
- properties: Object.fromEntries(
415
- cap.params.map((p) => [p.name, { type: "string", description: p.description }])
416
- ),
417
- required: cap.params.filter((p) => p.required).map((p) => p.name)
418
- }
419
- }
420
- }));
421
- }
422
-
423
- // ../../packages/ai-capabilities/src/adapters/prompt.ts
424
- function buildToolSafetyInstruction(capabilities) {
425
- const destructive = capabilities.filter((c) => c.destructive).map((c) => c.name);
426
- const withHints = capabilities.filter((c) => c.usageHint);
427
- const lines = ["## Tool use safety rules"];
428
- if (destructive.length > 0) {
429
- lines.push(`CRITICAL: Never call ${destructive.join(", ")} unless the user has EXPLICITLY and UNAMBIGUOUSLY requested it.`);
430
- lines.push(`- Only call destructive tools (${destructive.join(", ")}) when the user explicitly uses action words for a specific service.`);
431
- }
432
- if (withHints.length > 0) {
433
- lines.push("");
434
- lines.push("## Tool usage hints");
435
- for (const cap of withHints) {
436
- lines.push(`- ${cap.usageHint}`);
437
- }
438
- }
439
- return lines.join("\n");
440
- }
441
- function buildPromptDocs(baseUrl, token, capabilities) {
442
- if (!token) return "";
443
- const lines = [
444
- "## Runeya API",
445
- "",
446
- `Tu peux interagir avec Runeya via l'API HTTP tRPC ci-dessous.`,
447
- `Base URL : ${baseUrl}/api/trpc`,
448
- "Auth header : Authorization: Bearer $RUNEYA_API_TOKEN",
449
- ""
450
- ];
451
- const gets = capabilities.filter((c) => c.method === "GET");
452
- const posts = capabilities.filter((c) => c.method === "POST");
453
- if (gets.length > 0) {
454
- lines.push("### GET routes (param\xE8tres en query string ?input=<JSON encod\xE9>)", "");
455
- for (const cap of gets) {
456
- const example = cap.params.length > 0 ? `?input=${JSON.stringify(Object.fromEntries(cap.params.map((p) => [p.name === "serviceId" ? "id" : p.name, "..."])))}` : "";
457
- lines.push(`- \`${cap.route}${example}\` \u2014 ${cap.description}`);
458
- }
459
- lines.push("");
460
- }
461
- if (posts.length > 0) {
462
- lines.push("### POST routes (body JSON)", "");
463
- for (const cap of posts) {
464
- const bodyExample = cap.params.length > 0 ? JSON.stringify(Object.fromEntries(cap.params.map((p) => [p.name === "serviceId" ? "processId" : p.name, "..."]))) : "{}";
465
- lines.push(`- \`${cap.route}\` \u2014 \`${bodyExample}\``);
466
- }
467
- lines.push("");
468
- }
469
- const hints = capabilities.filter((c) => c.usageHint);
470
- if (hints.length > 0) {
471
- lines.push("### Usage hints", "");
472
- for (const cap of hints) {
473
- lines.push(`- ${cap.usageHint}`);
474
- }
475
- lines.push("");
476
- }
477
- lines.push(
478
- "### Exemple curl",
479
- "",
480
- "```bash",
481
- `curl -H "Authorization: Bearer $RUNEYA_API_TOKEN" \\`,
482
- ` "${baseUrl}/api/trpc/service.list"`,
483
- "",
484
- `curl -X POST -H "Authorization: Bearer $RUNEYA_API_TOKEN" \\`,
485
- ' -H "Content-Type: application/json" \\',
486
- ` -d '{"agentId":"local","processId":"my-service"}' \\`,
487
- ` "${baseUrl}/api/trpc/process.start"`,
488
- "```",
489
- "",
490
- 'La r\xE9ponse est de la forme `{"result":{"data":<r\xE9sultat>}}`.'
491
- );
492
- return lines.join("\n");
493
- }
494
-
495
- // ../../packages/ai-capabilities/src/trpc-caller.ts
496
- async function callTrpc(baseUrl, route, method, input, authToken) {
497
- const headers = {
498
- "Content-Type": "application/json",
499
- "Authorization": `Bearer ${authToken}`
500
- };
501
- const url = method === "GET" && input ? `${baseUrl}/api/trpc/${route}?input=${encodeURIComponent(JSON.stringify(input))}` : `${baseUrl}/api/trpc/${route}`;
502
- const res = await fetch(url, {
503
- method,
504
- headers,
505
- ...method === "POST" ? { body: JSON.stringify(input ?? {}) } : {},
506
- signal: AbortSignal.timeout(15e3)
507
- });
508
- const json = await res.json();
509
- if (json["error"]) throw new Error(JSON.stringify(json["error"]));
510
- const result = json["result"];
511
- return result?.["data"] ?? result ?? json;
512
- }
513
-
514
- // ../server/src/services/ai-runners/runeya-api-docs.ts
515
- function buildApiDocs(apiBaseUrl, apiToken) {
516
- return buildPromptDocs(apiBaseUrl, apiToken, RUNEYA_CAPABILITIES);
517
- }
518
-
519
- // ../server/src/services/codex-sessions.ts
520
- import { readdir } from "fs/promises";
521
- import { homedir } from "os";
522
- import { join } from "path";
523
- var CODEX_SESSIONS_DIR = join(homedir(), ".codex", "sessions");
524
- async function findCodexSessionFile(sessionId) {
525
- const suffix = `-${sessionId}.jsonl`;
526
- async function walk(dir) {
527
- let entries;
528
- try {
529
- entries = await readdir(dir, { withFileTypes: true });
530
- } catch {
531
- return null;
532
- }
533
- for (const entry of entries) {
534
- const full = join(dir, entry.name);
535
- if (entry.isDirectory()) {
536
- const found = await walk(full);
537
- if (found) return found;
538
- } else if (entry.name.endsWith(suffix)) {
539
- return full;
540
- }
541
- }
542
- return null;
543
- }
544
- return walk(CODEX_SESSIONS_DIR);
545
- }
546
- async function codexSessionExists(sessionId) {
547
- const { threadExists } = await import("./codex-thread-db-LE5FYDDA.js");
548
- if (threadExists(sessionId)) return true;
549
- return await findCodexSessionFile(sessionId) !== null;
178
+ async function codexSessionExists(sessionId) {
179
+ const { threadExists } = await import("./codex-thread-db-LE5FYDDA.js");
180
+ if (threadExists(sessionId)) return true;
181
+ return await findCodexSessionFile(sessionId) !== null;
550
182
  }
551
183
 
552
184
  // ../server/src/trpc/routers/chat.ts
@@ -1386,112 +1018,752 @@ var EnvironmentResolver = class {
1386
1018
  }
1387
1019
  return byKey;
1388
1020
  }
1389
- async resolveDag(environmentId, visited, project) {
1390
- if (visited.has(environmentId)) {
1391
- throw new Error(`Circular dependency detected in environment inheritance for ${environmentId}`);
1392
- }
1393
- const environment = await environmentStore.get(environmentId);
1394
- if (!environment) {
1395
- throw new Error(`Environment "${environmentId}" not found`);
1396
- }
1397
- visited.add(environmentId);
1398
- const effectiveParentIds = await this.getEffectiveParentIds(environment);
1399
- const parentResults = [];
1400
- for (const parentId of effectiveParentIds) {
1401
- const parentVisited = new Set(visited);
1402
- const parentResult = await this.resolveDag(parentId, parentVisited, project);
1403
- parentResults.push(parentResult);
1404
- }
1405
- const mergedVariables = {};
1406
- const sources = {};
1407
- for (const result of parentResults) {
1408
- for (const [varId, variable] of Object.entries(result.variables)) {
1409
- for (const [existingId, existingVar] of Object.entries(mergedVariables)) {
1410
- if (existingVar.key === variable.key && existingId !== varId) {
1411
- delete mergedVariables[existingId];
1412
- delete sources[existingId];
1413
- }
1414
- }
1415
- mergedVariables[varId] = variable;
1416
- sources[varId] = result.sources[varId] ?? sources[varId];
1417
- }
1418
- }
1419
- const parentEnv = {};
1420
- const parentSecretKeys = /* @__PURE__ */ new Set();
1421
- const parentKeySources = {};
1422
- for (const [varId, variable] of Object.entries(mergedVariables)) {
1423
- const slot = variable.value;
1424
- parentEnv[variable.key] = slot.pre + slot.value + slot.post;
1425
- if (slot.isSecret) {
1426
- parentSecretKeys.add(variable.key);
1427
- }
1428
- const source = sources[varId];
1429
- if (source) {
1430
- parentKeySources[variable.key] = { environmentId: source.environmentId, environmentName: source.environmentName };
1431
- }
1021
+ async resolveDag(environmentId, visited, project) {
1022
+ if (visited.has(environmentId)) {
1023
+ throw new Error(`Circular dependency detected in environment inheritance for ${environmentId}`);
1024
+ }
1025
+ const environment = await environmentStore.get(environmentId);
1026
+ if (!environment) {
1027
+ throw new Error(`Environment "${environmentId}" not found`);
1028
+ }
1029
+ visited.add(environmentId);
1030
+ const effectiveParentIds = await this.getEffectiveParentIds(environment);
1031
+ const parentResults = [];
1032
+ for (const parentId of effectiveParentIds) {
1033
+ const parentVisited = new Set(visited);
1034
+ const parentResult = await this.resolveDag(parentId, parentVisited, project);
1035
+ parentResults.push(parentResult);
1036
+ }
1037
+ const mergedVariables = {};
1038
+ const sources = {};
1039
+ for (const result of parentResults) {
1040
+ for (const [varId, variable] of Object.entries(result.variables)) {
1041
+ for (const [existingId, existingVar] of Object.entries(mergedVariables)) {
1042
+ if (existingVar.key === variable.key && existingId !== varId) {
1043
+ delete mergedVariables[existingId];
1044
+ delete sources[existingId];
1045
+ }
1046
+ }
1047
+ mergedVariables[varId] = variable;
1048
+ sources[varId] = result.sources[varId] ?? sources[varId];
1049
+ }
1050
+ }
1051
+ const parentEnv = {};
1052
+ const parentSecretKeys = /* @__PURE__ */ new Set();
1053
+ const parentKeySources = {};
1054
+ for (const [varId, variable] of Object.entries(mergedVariables)) {
1055
+ const slot = variable.value;
1056
+ parentEnv[variable.key] = slot.pre + slot.value + slot.post;
1057
+ if (slot.isSecret) {
1058
+ parentSecretKeys.add(variable.key);
1059
+ }
1060
+ const source = sources[varId];
1061
+ if (source) {
1062
+ parentKeySources[variable.key] = { environmentId: source.environmentId, environmentName: source.environmentName };
1063
+ }
1064
+ }
1065
+ const isInterpRef = (v) => /\{\{environment\.[^}]+\}\}/.test(v);
1066
+ for (const result of parentResults) {
1067
+ for (const [key, value] of Object.entries(result.parentEnv)) {
1068
+ const existingIsRef = key in parentEnv && isInterpRef(parentEnv[key]);
1069
+ const newIsConcrete = !isInterpRef(value);
1070
+ if (!(key in parentEnv) || existingIsRef && newIsConcrete) {
1071
+ parentEnv[key] = value;
1072
+ }
1073
+ }
1074
+ for (const key of result.parentSecretKeys) {
1075
+ parentSecretKeys.add(key);
1076
+ }
1077
+ for (const [key, source] of Object.entries(result.parentKeySources)) {
1078
+ if (!(key in parentKeySources)) {
1079
+ parentKeySources[key] = source;
1080
+ }
1081
+ }
1082
+ }
1083
+ for (const key of this.collectSecretKeys(mergedVariables, parentSecretKeys)) {
1084
+ parentSecretKeys.add(key);
1085
+ }
1086
+ const ownVariables = project ? project(environment.variables) : environment.variables;
1087
+ for (const [varId, variable] of Object.entries(ownVariables)) {
1088
+ let wasInherited = varId in mergedVariables;
1089
+ for (const [existingId, existingVar] of Object.entries(mergedVariables)) {
1090
+ if (existingVar.key === variable.key && existingId !== varId) {
1091
+ delete mergedVariables[existingId];
1092
+ delete sources[existingId];
1093
+ wasInherited = true;
1094
+ }
1095
+ }
1096
+ mergedVariables[varId] = variable;
1097
+ sources[varId] = {
1098
+ environmentId: environment.id,
1099
+ environmentName: environment.name,
1100
+ overridden: wasInherited
1101
+ };
1102
+ }
1103
+ return {
1104
+ variables: mergedVariables,
1105
+ sources,
1106
+ parentEnv,
1107
+ parentSecretKeys,
1108
+ parentKeySources
1109
+ };
1110
+ }
1111
+ };
1112
+ var environmentResolver = new EnvironmentResolver();
1113
+
1114
+ // ../../packages/ai-capabilities/src/capabilities.ts
1115
+ function toList(raw) {
1116
+ if (!raw) return [];
1117
+ const text = raw.trim();
1118
+ if (text.startsWith("[")) {
1119
+ try {
1120
+ const parsed = JSON.parse(text);
1121
+ if (Array.isArray(parsed)) return parsed.map((v) => String(v).trim()).filter(Boolean);
1122
+ } catch {
1123
+ }
1124
+ }
1125
+ return text.split(",").map((v) => v.trim().replace(/^["'[]+|["'\]]+$/g, "")).filter(Boolean);
1126
+ }
1127
+ function clearable(raw, parse2, key) {
1128
+ if (raw === void 0) return {};
1129
+ const text = String(raw).trim();
1130
+ if (!text || text === "null") return { [key]: null };
1131
+ return { [key]: parse2(text) };
1132
+ }
1133
+ function gitTarget(p) {
1134
+ return {
1135
+ ...p.serviceId ? { serviceId: p.serviceId } : {},
1136
+ ...p.projectId ? { projectId: p.projectId } : {},
1137
+ ...p.agentId ? { agentId: p.agentId } : {},
1138
+ ...p.orgId ? { orgId: p.orgId } : {}
1139
+ };
1140
+ }
1141
+ var RUNEYA_CAPABILITIES = [
1142
+ {
1143
+ name: "list_services",
1144
+ description: "List services, with the serviceId and agentId to use in other calls. Pass the projectId your context names to stay on the project the user is looking at, or another one from list_projects to look elsewhere. Called with no project, this can answer for every project of every organization on the machine \u2014 far more than the interface shows.",
1145
+ route: "service.list",
1146
+ method: "GET",
1147
+ params: [
1148
+ { name: "projectId", description: "Restrict to this project, from list_projects. Omit to list every service on the machine.", required: false },
1149
+ { name: "orgId", description: "Its organization. Needed only when the same project id exists in several.", required: false }
1150
+ ],
1151
+ buildInput: (p) => p.projectId ? { projectId: p.projectId, ...p.orgId ? { orgId: p.orgId } : {} } : void 0
1152
+ },
1153
+ {
1154
+ name: "get_service_status",
1155
+ description: "Get the current status (running, stopped, etc.) of a service. A service that has never been started on this agent has no process yet, and this answers 404 Process not found \u2014 that means STOPPED, not forbidden and not missing. Start it, or read its configuration with get_service.",
1156
+ route: "process.get",
1157
+ method: "GET",
1158
+ params: [
1159
+ { name: "serviceId", description: "The service ID", required: true },
1160
+ { name: "agentId", description: "The agent ID hosting this service", required: true }
1161
+ ],
1162
+ buildInput: (p) => ({ agentId: p.agentId, id: p.serviceId })
1163
+ },
1164
+ {
1165
+ name: "get_logs",
1166
+ description: "Get the recent buffered logs for a service.",
1167
+ route: "process.logs",
1168
+ method: "GET",
1169
+ params: [
1170
+ { name: "serviceId", description: "The service ID", required: true },
1171
+ { name: "agentId", description: "The agent ID hosting this service", required: true }
1172
+ ],
1173
+ buildInput: (p) => ({ agentId: p.agentId, processId: p.serviceId })
1174
+ },
1175
+ {
1176
+ name: "start_service",
1177
+ description: "Start a service on an agent.",
1178
+ route: "process.start",
1179
+ method: "POST",
1180
+ params: [
1181
+ { name: "serviceId", description: "The service ID to start", required: true },
1182
+ { name: "agentId", description: "The agent ID hosting this service", required: true }
1183
+ ],
1184
+ buildInput: (p) => ({ agentId: p.agentId, processId: p.serviceId }),
1185
+ destructive: true
1186
+ },
1187
+ {
1188
+ name: "stop_service",
1189
+ description: "Stop a running service on an agent.",
1190
+ route: "process.stop",
1191
+ method: "POST",
1192
+ params: [
1193
+ { name: "serviceId", description: "The service ID to stop", required: true },
1194
+ { name: "agentId", description: "The agent ID hosting this service", required: true }
1195
+ ],
1196
+ buildInput: (p) => ({ agentId: p.agentId, processId: p.serviceId }),
1197
+ destructive: true
1198
+ },
1199
+ {
1200
+ name: "restart_service",
1201
+ description: "Restart a service on an agent (stop \u2192 redeploy \u2192 start).",
1202
+ route: "process.restart",
1203
+ method: "POST",
1204
+ params: [
1205
+ { name: "serviceId", description: "The service ID to restart", required: true },
1206
+ { name: "agentId", description: "The agent ID hosting this service", required: true }
1207
+ ],
1208
+ buildInput: (p) => ({ agentId: p.agentId, processId: p.serviceId }),
1209
+ destructive: true
1210
+ },
1211
+ // ─── Utility ─────────────────────────────────────────────────────────────
1212
+ {
1213
+ name: "wait",
1214
+ description: "Wait for a given number of milliseconds before continuing.",
1215
+ route: "utility.wait",
1216
+ method: "POST",
1217
+ params: [
1218
+ { name: "ms", description: "Number of MILLISECONDS to wait. Convert from seconds: 1s=1000, 10s=10000, 1min=60000. Max 300000.", required: true }
1219
+ ],
1220
+ buildInput: (p) => ({ ms: Number(p.ms) }),
1221
+ usageHint: '"wait 5s" \u2192 wait(ms=5000), "pause 10 seconds" \u2192 wait(ms=10000), "attends 3 secondes" \u2192 wait(ms=3000). Always convert to milliseconds.'
1222
+ },
1223
+ // ─── Kanban ───────────────────────────────────────────────────────────────
1224
+ {
1225
+ name: "kanban_list_boards",
1226
+ description: "List the kanban boards of the organization. Returns the organizationId actually queried, the boardId to use in the other kanban tools, plus column and card counts. Cards themselves are not included \u2014 use kanban_get_board for those. An empty list means that organization really has no board: a failure to reach the cloud is reported as an error instead, never as an empty list.",
1227
+ route: "kanban.listBoards",
1228
+ method: "GET",
1229
+ params: [
1230
+ { name: "includeArchived", description: 'Set to "true" to include archived boards. Default: false.', required: false },
1231
+ { name: "organizationId", description: "Which organization to read. Optional: needed only when the account belongs to several and the error message asks for it.", required: false }
1232
+ ],
1233
+ buildInput: (p) => ({
1234
+ includeArchived: p.includeArchived === "true",
1235
+ ...p.organizationId ? { organizationId: p.organizationId } : {}
1236
+ })
1237
+ },
1238
+ {
1239
+ name: "kanban_get_board",
1240
+ description: "Read one kanban board: its columns, and the cards in each (id, title, markdown body, assignees, comment count, and attachment metadata \u2014 use kanban_download_attachment to fetch the bytes of a file). Use the exact column names it returns when moving or adding a card.",
1241
+ route: "kanban.getBoard",
1242
+ method: "GET",
1243
+ params: [
1244
+ { name: "boardId", description: "The kanban board ID, from kanban_list_boards", required: true }
1245
+ ],
1246
+ buildInput: (p) => ({ boardId: p.boardId })
1247
+ },
1248
+ {
1249
+ name: "kanban_get_card_comments",
1250
+ description: "Read the comment thread of one kanban card, newest last: who wrote each comment (ai or user, with the person's name), when, its text, and its attachments. The comments in your task context are a snapshot taken when the task started \u2014 call this to see anything written since, whenever someone tells you a comment was added or kanban_get_board reports a higher commentCount than you have.",
1251
+ route: "kanban.getCardComments",
1252
+ method: "GET",
1253
+ params: [
1254
+ { name: "boardId", description: "The kanban board ID", required: true },
1255
+ { name: "cardId", description: "The card ID whose comments to read", required: true },
1256
+ { name: "limit", description: "How many of the most recent comments to return (1-200). Default: 50.", required: false }
1257
+ ],
1258
+ buildInput: (p) => ({
1259
+ boardId: p.boardId,
1260
+ cardId: p.cardId,
1261
+ ...p.limit ? { limit: Number(p.limit) } : {}
1262
+ }),
1263
+ usageHint: '"le support a ajout\xE9 un commentaire" / "regarde les nouveaux commentaires" \u2192 kanban_get_card_comments(boardId, cardId). Never answer from the snapshot in your context when fresh comments are mentioned.'
1264
+ },
1265
+ {
1266
+ name: "kanban_search_cards",
1267
+ description: "Search kanban cards by free text, matched against their title, body and comments (accent- and case-insensitive). Archived cards are included. Searches every board of the organization unless boardId narrows it down.",
1268
+ route: "kanban.searchCards",
1269
+ method: "GET",
1270
+ params: [
1271
+ { name: "query", description: "Text to look for in card titles, bodies and comments", required: true },
1272
+ { name: "boardId", description: "Restrict the search to this board. Omit to search all boards.", required: false },
1273
+ { name: "limit", description: "Maximum number of cards to return (1-100). Default: 25.", required: false },
1274
+ { name: "organizationId", description: "Which organization to search. Optional: needed only when the account belongs to several and the error message asks for it.", required: false }
1275
+ ],
1276
+ buildInput: (p) => ({
1277
+ query: p.query,
1278
+ ...p.boardId ? { boardId: p.boardId } : {},
1279
+ ...p.limit ? { limit: Number(p.limit) } : {},
1280
+ ...p.organizationId ? { organizationId: p.organizationId } : {}
1281
+ })
1282
+ },
1283
+ {
1284
+ name: "kanban_download_attachment",
1285
+ description: "Download a kanban card attachment (image, PDF, any file) onto this machine and return its local path, so it can be opened with file-reading tools. Attachment ids come from the card context, from kanban_get_board, or from kanban_get_card_comments \u2014 a file attached to a comment downloads exactly like one attached to the card.",
1286
+ route: "kanban.downloadAttachment",
1287
+ method: "POST",
1288
+ params: [
1289
+ { name: "attachmentId", description: "The attachment ID, as listed on the card", required: true }
1290
+ ],
1291
+ buildInput: (p) => ({ attachmentId: p.attachmentId })
1292
+ },
1293
+ {
1294
+ name: "kanban_move_card",
1295
+ description: "Move a kanban card to another column. Use the exact column name.",
1296
+ route: "kanban.moveCard",
1297
+ method: "POST",
1298
+ params: [
1299
+ { name: "boardId", description: "The kanban board ID", required: true },
1300
+ { name: "cardId", description: "The card ID to move", required: true },
1301
+ { name: "targetColumn", description: "Exact name of the target column", required: true }
1302
+ ],
1303
+ buildInput: (p) => ({ boardId: p.boardId, cardId: p.cardId, targetColumn: p.targetColumn })
1304
+ },
1305
+ {
1306
+ name: "kanban_add_comment",
1307
+ description: "Add a comment to a kanban card.",
1308
+ route: "kanban.addComment",
1309
+ method: "POST",
1310
+ params: [
1311
+ { name: "boardId", description: "The kanban board ID", required: true },
1312
+ { name: "cardId", description: "The card ID", required: true },
1313
+ { name: "comment", description: "The comment text (markdown supported)", required: true }
1314
+ ],
1315
+ buildInput: (p) => ({ boardId: p.boardId, cardId: p.cardId, comment: p.comment })
1316
+ },
1317
+ {
1318
+ name: "kanban_get_card_links",
1319
+ description: "Read the filiation of a board: which card depends on which. Returns one entry per link (child card \u2194 parent card), plus the title, board, column, assignees and comment count of any linked card living on another board. Use it when a card context says it has a parent or sub-cards and you need their ids to read them.",
1320
+ route: "kanban.getCardLinks",
1321
+ method: "GET",
1322
+ params: [
1323
+ { name: "boardId", description: "The kanban board ID whose links to read", required: true }
1324
+ ],
1325
+ buildInput: (p) => ({ boardId: p.boardId })
1326
+ },
1327
+ {
1328
+ name: "kanban_set_card_parent",
1329
+ description: "Link a kanban card to a parent card, or detach it. The parent is the card the other one depends on \u2014 an epic and its tasks, a bug and its follow-ups. A card has at most one parent, and setting a new one replaces it. Omit parentCardId to detach. kanban_get_board reports the current filiation as parentCardId / childCardIds on each card.",
1330
+ route: "kanban.setCardParent",
1331
+ method: "POST",
1332
+ params: [
1333
+ { name: "boardId", description: "The kanban board ID of the card being linked", required: true },
1334
+ { name: "cardId", description: "The card that depends on the parent (the child)", required: true },
1335
+ { name: "parentCardId", description: "The parent card ID. Omit to detach the card from its parent.", required: false },
1336
+ { name: "parentBoardId", description: "The parent's board, when it lives on another board of the same organization. Defaults to boardId.", required: false }
1337
+ ],
1338
+ buildInput: (p) => ({
1339
+ boardId: p.boardId,
1340
+ cardId: p.cardId,
1341
+ ...p.parentCardId ? { parentCardId: p.parentCardId } : {},
1342
+ ...p.parentBoardId ? { parentBoardId: p.parentBoardId } : {}
1343
+ })
1344
+ },
1345
+ {
1346
+ name: "kanban_add_card",
1347
+ description: "Add a new card to a kanban column.",
1348
+ route: "kanban.addCard",
1349
+ method: "POST",
1350
+ params: [
1351
+ { name: "boardId", description: "The kanban board ID", required: true },
1352
+ { name: "column", description: "Exact name of the target column", required: true },
1353
+ { name: "title", description: "Card title", required: true },
1354
+ { name: "content", description: "Card content in markdown", required: false }
1355
+ ],
1356
+ buildInput: (p) => ({ boardId: p.boardId, column: p.column, title: p.title, content: p.content })
1357
+ },
1358
+ {
1359
+ name: "kanban_get_card",
1360
+ description: "Read one kanban card by id, including archived ones. Cheaper than fetching the whole board, and the only way to read a card that has been archived.",
1361
+ route: "kanban.getCard",
1362
+ method: "GET",
1363
+ params: [
1364
+ { name: "boardId", description: "The kanban board ID", required: true },
1365
+ { name: "cardId", description: "The card ID", required: true }
1366
+ ],
1367
+ buildInput: (p) => ({ boardId: p.boardId, cardId: p.cardId })
1368
+ },
1369
+ {
1370
+ name: "kanban_update_card",
1371
+ description: "Update an existing kanban card. Only the fields you pass are changed; passing null to priority, color or deadline clears it. Prefer this over creating a second card when something needs correcting.",
1372
+ route: "kanban.updateCard",
1373
+ method: "POST",
1374
+ params: [
1375
+ { name: "boardId", description: "The kanban board ID", required: true },
1376
+ { name: "cardId", description: "The card ID", required: true },
1377
+ { name: "title", description: "New title", required: false },
1378
+ { name: "content", description: "New card content, in markdown", required: false },
1379
+ { name: "priority", description: "Priority from 1 to 10, or null to clear it", required: false },
1380
+ { name: "color", description: "Card colour, or null to clear it", required: false },
1381
+ { name: "groups", description: "Labels, as a list of strings. Replaces the current ones.", required: false },
1382
+ { name: "deadline", description: "Due date as YYYY-MM-DD, or null to clear it", required: false },
1383
+ { name: "assignees", description: "User ids to assign, as a list. Replaces the current ones; use kanban_list_members to find the ids.", required: false }
1384
+ ],
1385
+ buildInput: (p) => ({
1386
+ boardId: p.boardId,
1387
+ cardId: p.cardId,
1388
+ ...p.title !== void 0 ? { title: p.title } : {},
1389
+ ...p.content !== void 0 ? { content: p.content } : {},
1390
+ // Tout arrive en chaîne : un modèle n'écrit pas des nombres, des listes
1391
+ // ni des `null` typés. `clearable` distingue « efface » de « ne touche
1392
+ // pas » — sans quoi vider une couleur serait impossible à exprimer, et
1393
+ // changer un titre risquerait de vider le reste.
1394
+ ...clearable(p.priority, (v) => Number(v), "priority"),
1395
+ ...clearable(p.color, (v) => v, "color"),
1396
+ ...clearable(p.deadline, (v) => v, "deadline"),
1397
+ ...p.groups !== void 0 ? { groups: toList(p.groups) } : {},
1398
+ ...p.assignees !== void 0 ? { assignees: toList(p.assignees) } : {}
1399
+ })
1400
+ },
1401
+ {
1402
+ name: "kanban_set_card_archived",
1403
+ description: "Archive a kanban card (it leaves the board but is not deleted) or bring it back. An unarchived card returns to the column it left.",
1404
+ route: "kanban.setCardArchived",
1405
+ method: "POST",
1406
+ params: [
1407
+ { name: "boardId", description: "The kanban board ID", required: true },
1408
+ { name: "cardId", description: "The card ID", required: true },
1409
+ { name: "archived", description: "true to archive, false to bring the card back", required: true }
1410
+ ],
1411
+ buildInput: (p) => ({ boardId: p.boardId, cardId: p.cardId, archived: p.archived === "true" })
1412
+ },
1413
+ {
1414
+ name: "kanban_list_members",
1415
+ description: "List the people of the organization who can be assigned to a card, with their ids. Needed before assigning anyone with kanban_update_card.",
1416
+ route: "kanban.listMembers",
1417
+ method: "GET",
1418
+ params: [
1419
+ { name: "organizationId", description: "Which organization. Optional: needed only when the account belongs to several and the error message asks for it.", required: false }
1420
+ ],
1421
+ buildInput: (p) => p.organizationId ? { organizationId: p.organizationId } : {}
1422
+ },
1423
+ // ─── Lecture seule ───────────────────────────────────────────────────────
1424
+ //
1425
+ // Tout ce qui se consulte sans rien changer. La création, la mise à jour et
1426
+ // la suppression restent hors MCP : elles s'ajouteront au cas par cas.
1427
+ //
1428
+ // Volontairement absentes, et à ne pas ajouter sans y regarder à deux fois,
1429
+ // parce qu'elles rendent un secret : `environment.list` / `get` / `resolve` /
1430
+ // `resolveFlat` (un `Environment` porte ses variables, valeurs comprises),
1431
+ // `apiKeys.list` / `reveal`, `setup.getEncryptionKeyHex` et `getOrgKeys`
1432
+ // (clés de chiffrement), `settings.get` et `settings.listAIProviders` (clés
1433
+ // de fournisseurs d'IA — `settings.getPaths` et `getNetwork`, eux, ne
1434
+ // rendent que des chemins et une adresse, d'où leur présence ci-dessous),
1435
+ // `cloudAuth.session`, `agent.getPassthroughEnv`. Un agent n'a pas besoin de
1436
+ // ces valeurs pour travailler, et ce qu'il lit finit dans une transcription.
1437
+ {
1438
+ name: "list_processes",
1439
+ description: "List every process across all agents with its current state (running, stopped, exit code, uptime). Use this to see the whole machine at once, rather than calling get_service_status service by service. An agent only learns about a service when it is first started, so this lists what is deployed, not what is configured: an empty list means nothing has been started, not that you cannot see them \u2014 list_services shows what exists.",
1440
+ route: "process.list",
1441
+ method: "GET",
1442
+ params: [],
1443
+ buildInput: () => void 0
1444
+ },
1445
+ {
1446
+ name: "get_service",
1447
+ description: "Read the full configuration of one service: its commands, ports, groups, runner, log sources and restart policy. list_services gives the ids.",
1448
+ route: "service.get",
1449
+ method: "GET",
1450
+ params: [
1451
+ { name: "serviceId", description: "The service ID", required: true }
1452
+ ],
1453
+ buildInput: (p) => ({ id: p.serviceId })
1454
+ },
1455
+ {
1456
+ name: "get_service_metrics",
1457
+ description: "Read the CPU and memory currently used by a running service.",
1458
+ route: "process.metrics",
1459
+ method: "GET",
1460
+ params: [
1461
+ { name: "serviceId", description: "The service ID", required: true },
1462
+ { name: "agentId", description: "The agent ID hosting this service", required: true }
1463
+ ],
1464
+ buildInput: (p) => ({ agentId: p.agentId, processId: p.serviceId })
1465
+ },
1466
+ {
1467
+ name: "list_agents",
1468
+ description: "List the agents connected to this Runeya, with their status and whether they run on this machine. Passphrases are never returned.",
1469
+ route: "agent.list",
1470
+ method: "GET",
1471
+ params: [],
1472
+ buildInput: () => void 0
1473
+ },
1474
+ {
1475
+ name: "list_projects",
1476
+ description: "List the projects known to this Runeya, with their ids and the services they hold.",
1477
+ route: "project.list",
1478
+ method: "GET",
1479
+ params: [],
1480
+ buildInput: () => void 0
1481
+ },
1482
+ {
1483
+ name: "get_project",
1484
+ description: "Read one project: its services, its active environment, its organization.",
1485
+ route: "project.get",
1486
+ method: "GET",
1487
+ params: [
1488
+ { name: "projectId", description: "The project ID, from list_projects", required: true },
1489
+ { name: "orgId", description: "Its organization. Needed only when the same project id exists in several.", required: false }
1490
+ ],
1491
+ buildInput: (p) => ({ id: p.projectId, ...p.orgId ? { orgId: p.orgId } : {} })
1492
+ },
1493
+ {
1494
+ name: "list_project_paths",
1495
+ description: "Where each project lives on this machine. Use it to find the directory to work in before reading or editing files.",
1496
+ route: "project.localPaths",
1497
+ method: "GET",
1498
+ params: [],
1499
+ buildInput: () => void 0
1500
+ },
1501
+ {
1502
+ name: "git_status",
1503
+ description: "Read the git working tree of a service or a project: staged, modified and untracked files, current branch, ahead/behind counts.",
1504
+ route: "git.status",
1505
+ method: "GET",
1506
+ params: [
1507
+ { name: "serviceId", description: "Target the repository of this service", required: false },
1508
+ { name: "projectId", description: "Target the repository of this project, when no service is given", required: false },
1509
+ { name: "agentId", description: "The agent hosting the repository", required: false },
1510
+ { name: "orgId", description: "Its organization, when a project id alone is ambiguous", required: false }
1511
+ ],
1512
+ buildInput: (p) => gitTarget(p)
1513
+ },
1514
+ {
1515
+ name: "git_log",
1516
+ description: "Read the recent commits of a service or project repository: hash, author, date, message.",
1517
+ route: "git.log",
1518
+ method: "GET",
1519
+ params: [
1520
+ { name: "serviceId", description: "Target the repository of this service", required: false },
1521
+ { name: "projectId", description: "Target the repository of this project, when no service is given", required: false },
1522
+ { name: "agentId", description: "The agent hosting the repository", required: false },
1523
+ { name: "orgId", description: "Its organization, when a project id alone is ambiguous", required: false },
1524
+ { name: "limit", description: "How many commits to return (1-200). Default: 50.", required: false }
1525
+ ],
1526
+ buildInput: (p) => ({ ...gitTarget(p), ...p.limit ? { limit: Number(p.limit) } : {} })
1527
+ },
1528
+ {
1529
+ name: "git_branches",
1530
+ description: "List the local and remote branches of a service or project repository.",
1531
+ route: "git.branches",
1532
+ method: "GET",
1533
+ params: [
1534
+ { name: "serviceId", description: "Target the repository of this service", required: false },
1535
+ { name: "projectId", description: "Target the repository of this project, when no service is given", required: false },
1536
+ { name: "agentId", description: "The agent hosting the repository", required: false },
1537
+ { name: "orgId", description: "Its organization, when a project id alone is ambiguous", required: false }
1538
+ ],
1539
+ buildInput: (p) => gitTarget(p)
1540
+ },
1541
+ {
1542
+ name: "git_diff",
1543
+ description: "Read the diff of a service or project repository \u2014 everything, or one file. Use it to see what changed before describing or reviewing it.",
1544
+ route: "git.diff",
1545
+ method: "GET",
1546
+ params: [
1547
+ { name: "serviceId", description: "Target the repository of this service", required: false },
1548
+ { name: "projectId", description: "Target the repository of this project, when no service is given", required: false },
1549
+ { name: "agentId", description: "The agent hosting the repository", required: false },
1550
+ { name: "orgId", description: "Its organization, when a project id alone is ambiguous", required: false },
1551
+ { name: "path", description: "Restrict the diff to this file path", required: false },
1552
+ { name: "staged", description: 'Set to "true" to read the staged diff instead of the working tree', required: false },
1553
+ { name: "untracked", description: 'Set to "true" to include untracked files', required: false }
1554
+ ],
1555
+ buildInput: (p) => ({
1556
+ ...gitTarget(p),
1557
+ ...p.path ? { path: p.path } : {},
1558
+ ...p.staged !== void 0 ? { staged: p.staged === "true" } : {},
1559
+ ...p.untracked !== void 0 ? { untracked: p.untracked === "true" } : {}
1560
+ })
1561
+ },
1562
+ {
1563
+ name: "list_docs",
1564
+ description: "List the markdown documentation files of a scope, as a tree. Pair it with read_doc to answer from the project's own docs rather than from guesswork.",
1565
+ route: "wiki.list",
1566
+ method: "GET",
1567
+ params: [
1568
+ { name: "scope", description: `"global" for this Runeya, or "service:<serviceId>" for one service's repository`, required: true }
1569
+ ],
1570
+ buildInput: (p) => ({ scope: p.scope })
1571
+ },
1572
+ {
1573
+ name: "read_doc",
1574
+ description: "Read one markdown documentation file. Paths come from list_docs; only .md and .markdown can be read.",
1575
+ route: "wiki.read",
1576
+ method: "GET",
1577
+ params: [
1578
+ { name: "scope", description: `"global" for this Runeya, or "service:<serviceId>" for one service's repository`, required: true },
1579
+ { name: "path", description: "Relative path of the file, as returned by list_docs", required: true }
1580
+ ],
1581
+ buildInput: (p) => ({ scope: p.scope, path: p.path })
1582
+ },
1583
+ {
1584
+ name: "get_server_logs",
1585
+ description: "Read Runeya's own recent log entries. Use it to explain why Runeya itself misbehaved \u2014 not to read a service's output, which is get_logs.",
1586
+ route: "diagnostics.recentLogs",
1587
+ method: "GET",
1588
+ params: [
1589
+ { name: "limit", description: "How many entries to return (1-2000). Default: 500.", required: false }
1590
+ ],
1591
+ buildInput: (p) => p.limit ? { limit: Number(p.limit) } : void 0
1592
+ },
1593
+ {
1594
+ name: "get_kanban_queue_state",
1595
+ description: "Read the state of the kanban task queue: what is running, what is waiting. Use it before queuing work, or to explain why a card has not started.",
1596
+ route: "kanbanQueue.getState",
1597
+ method: "GET",
1598
+ params: [],
1599
+ buildInput: () => void 0
1600
+ },
1601
+ {
1602
+ name: "export_project",
1603
+ description: "Read a project and every service it holds in one call, with secrets stripped out. Cheaper and safer than calling get_service for each service \u2014 prefer it whenever you need the whole picture of a project.",
1604
+ route: "project.export",
1605
+ method: "GET",
1606
+ params: [
1607
+ { name: "projectId", description: "The project ID, from list_projects", required: true },
1608
+ { name: "orgId", description: "Its organization. Needed only when the same project id exists in several.", required: false }
1609
+ ],
1610
+ buildInput: (p) => ({ id: p.projectId, ...p.orgId ? { orgId: p.orgId } : {} })
1611
+ },
1612
+ {
1613
+ name: "git_remotes",
1614
+ description: "List the git remotes of a service or project repository, with their URLs.",
1615
+ route: "git.remotes",
1616
+ method: "GET",
1617
+ params: [
1618
+ { name: "serviceId", description: "Target the repository of this service", required: false },
1619
+ { name: "projectId", description: "Target the repository of this project, when no service is given", required: false },
1620
+ { name: "agentId", description: "The agent hosting the repository", required: false },
1621
+ { name: "orgId", description: "Its organization, when a project id alone is ambiguous", required: false }
1622
+ ],
1623
+ buildInput: (p) => gitTarget(p)
1624
+ },
1625
+ {
1626
+ name: "git_stash_list",
1627
+ description: "List the stashes of a service or project repository. Useful before assuming work was lost: it may simply be stashed.",
1628
+ route: "git.stashList",
1629
+ method: "GET",
1630
+ params: [
1631
+ { name: "serviceId", description: "Target the repository of this service", required: false },
1632
+ { name: "projectId", description: "Target the repository of this project, when no service is given", required: false },
1633
+ { name: "agentId", description: "The agent hosting the repository", required: false },
1634
+ { name: "orgId", description: "Its organization, when a project id alone is ambiguous", required: false }
1635
+ ],
1636
+ buildInput: (p) => gitTarget(p)
1637
+ },
1638
+ {
1639
+ name: "get_runeya_version",
1640
+ description: "Read the version of Runeya running here, the latest published one, and whether this install is up to date. Use it before blaming a bug on the code: the machine may simply be behind.",
1641
+ route: "health.versionInfo",
1642
+ method: "GET",
1643
+ params: [],
1644
+ buildInput: () => void 0
1645
+ },
1646
+ {
1647
+ name: "get_runeya_paths",
1648
+ description: "Read where Runeya keeps its things on this machine: its launch directory, its data directory, and the machine-wide directory holding cloud projects.",
1649
+ route: "settings.getPaths",
1650
+ method: "GET",
1651
+ params: [],
1652
+ buildInput: () => void 0
1653
+ },
1654
+ {
1655
+ name: "get_network_info",
1656
+ description: "Read where this Runeya listens (host and port) and whether it is reachable from the local network, with the URLs to use. Use it to give someone a working link instead of guessing one.",
1657
+ route: "settings.getNetwork",
1658
+ method: "GET",
1659
+ params: [],
1660
+ buildInput: () => void 0
1661
+ },
1662
+ {
1663
+ name: "list_runeya_instances",
1664
+ description: "List every Runeya answering on this machine, this one included, with its port and directory. Use it when a port is taken or when two instances seem to disagree.",
1665
+ route: "diagnostics.instances",
1666
+ method: "GET",
1667
+ params: [],
1668
+ buildInput: () => void 0
1669
+ },
1670
+ {
1671
+ name: "get_cloud_status",
1672
+ description: "Say whether this Runeya is linked to a cloud account, and to which cloud. A kanban tool failing for lack of a cloud link is explained here.",
1673
+ route: "cloudAuth.status",
1674
+ method: "GET",
1675
+ params: [],
1676
+ buildInput: () => void 0
1677
+ }
1678
+ ];
1679
+
1680
+ // ../../packages/ai-capabilities/src/adapters/anthropic.ts
1681
+ function buildAnthropicTools(capabilities) {
1682
+ return capabilities.map((cap) => ({
1683
+ name: cap.name,
1684
+ description: cap.description,
1685
+ input_schema: {
1686
+ type: "object",
1687
+ properties: Object.fromEntries(
1688
+ cap.params.map((p) => [p.name, { type: "string", description: p.description }])
1689
+ ),
1690
+ required: cap.params.filter((p) => p.required).map((p) => p.name)
1432
1691
  }
1433
- const isInterpRef = (v) => /\{\{environment\.[^}]+\}\}/.test(v);
1434
- for (const result of parentResults) {
1435
- for (const [key, value] of Object.entries(result.parentEnv)) {
1436
- const existingIsRef = key in parentEnv && isInterpRef(parentEnv[key]);
1437
- const newIsConcrete = !isInterpRef(value);
1438
- if (!(key in parentEnv) || existingIsRef && newIsConcrete) {
1439
- parentEnv[key] = value;
1440
- }
1441
- }
1442
- for (const key of result.parentSecretKeys) {
1443
- parentSecretKeys.add(key);
1444
- }
1445
- for (const [key, source] of Object.entries(result.parentKeySources)) {
1446
- if (!(key in parentKeySources)) {
1447
- parentKeySources[key] = source;
1448
- }
1692
+ }));
1693
+ }
1694
+
1695
+ // ../../packages/ai-capabilities/src/adapters/openai.ts
1696
+ function buildOpenAITools(capabilities) {
1697
+ return capabilities.map((cap) => ({
1698
+ type: "function",
1699
+ function: {
1700
+ name: cap.name,
1701
+ description: cap.description,
1702
+ parameters: {
1703
+ type: "object",
1704
+ properties: Object.fromEntries(
1705
+ cap.params.map((p) => [p.name, { type: "string", description: p.description }])
1706
+ ),
1707
+ required: cap.params.filter((p) => p.required).map((p) => p.name)
1449
1708
  }
1450
1709
  }
1451
- for (const key of this.collectSecretKeys(mergedVariables, parentSecretKeys)) {
1452
- parentSecretKeys.add(key);
1453
- }
1454
- const ownVariables = project ? project(environment.variables) : environment.variables;
1455
- for (const [varId, variable] of Object.entries(ownVariables)) {
1456
- let wasInherited = varId in mergedVariables;
1457
- for (const [existingId, existingVar] of Object.entries(mergedVariables)) {
1458
- if (existingVar.key === variable.key && existingId !== varId) {
1459
- delete mergedVariables[existingId];
1460
- delete sources[existingId];
1461
- wasInherited = true;
1462
- }
1463
- }
1464
- mergedVariables[varId] = variable;
1465
- sources[varId] = {
1466
- environmentId: environment.id,
1467
- environmentName: environment.name,
1468
- overridden: wasInherited
1469
- };
1710
+ }));
1711
+ }
1712
+
1713
+ // ../../packages/ai-capabilities/src/adapters/prompt.ts
1714
+ function buildToolSafetyInstruction(capabilities) {
1715
+ const destructive = capabilities.filter((c) => c.destructive).map((c) => c.name);
1716
+ const withHints = capabilities.filter((c) => c.usageHint);
1717
+ const lines = ["## Tool use safety rules"];
1718
+ if (destructive.length > 0) {
1719
+ lines.push(`CRITICAL: Never call ${destructive.join(", ")} unless the user has EXPLICITLY and UNAMBIGUOUSLY requested it.`);
1720
+ lines.push(`- Only call destructive tools (${destructive.join(", ")}) when the user explicitly uses action words for a specific service.`);
1721
+ }
1722
+ if (withHints.length > 0) {
1723
+ lines.push("");
1724
+ lines.push("## Tool usage hints");
1725
+ for (const cap of withHints) {
1726
+ lines.push(`- ${cap.usageHint}`);
1470
1727
  }
1471
- return {
1472
- variables: mergedVariables,
1473
- sources,
1474
- parentEnv,
1475
- parentSecretKeys,
1476
- parentKeySources
1477
- };
1478
1728
  }
1479
- };
1480
- var environmentResolver = new EnvironmentResolver();
1729
+ return lines.join("\n");
1730
+ }
1731
+
1732
+ // ../../packages/ai-capabilities/src/trpc-caller.ts
1733
+ async function callTrpc(baseUrl, route, method, input, authToken) {
1734
+ const headers = {
1735
+ "Content-Type": "application/json",
1736
+ "Authorization": `Bearer ${authToken}`
1737
+ };
1738
+ const url = method === "GET" && input ? `${baseUrl}/api/trpc/${route}?input=${encodeURIComponent(JSON.stringify(input))}` : `${baseUrl}/api/trpc/${route}`;
1739
+ const res = await fetch(url, {
1740
+ method,
1741
+ headers,
1742
+ ...method === "POST" ? { body: JSON.stringify(input ?? {}) } : {},
1743
+ signal: AbortSignal.timeout(15e3)
1744
+ });
1745
+ const json = await res.json();
1746
+ if (json["error"]) throw new Error(JSON.stringify(json["error"]));
1747
+ const result = json["result"];
1748
+ return result?.["data"] ?? result ?? json;
1749
+ }
1481
1750
 
1482
1751
  // ../server/src/services/llms-txt-generator.ts
1483
- function generateAdminLlmsTxt(services, jwt) {
1484
- const baseUrl = `http://localhost:${env.PORT}`;
1485
- const trpcBase = `${baseUrl}/api/trpc`;
1752
+ function generateAdminLlmsTxt(services, jwt, project) {
1486
1753
  const lines = [];
1487
- lines.push("# Runeya \u2014 Service Management API");
1754
+ lines.push("# Runeya \u2014 Service Management");
1488
1755
  lines.push("");
1489
1756
  lines.push("> You are operating as an authenticated admin with full access to all services.");
1490
- lines.push(`> Base URL: ${trpcBase}`);
1491
- if (jwt) {
1492
- lines.push("> Authentication: pass `Authorization: Bearer $RUNEYA_API_TOKEN` on all tRPC requests.");
1493
- }
1757
+ lines.push("> Everything below is driven through the Runeya MCP tools.");
1494
1758
  lines.push("");
1759
+ if (project) {
1760
+ lines.push(`## Current project`);
1761
+ lines.push("");
1762
+ lines.push(`You are working on **${project.name}** (projectId: \`${project.id}\`${project.orgId ? `, orgId: \`${project.orgId}\`` : ""}).`);
1763
+ lines.push(`The services listed below are its own. Name this project \u2014 \`projectId=${project.id}\` \u2014 on any tool that takes one, and you will stay on what the user actually sees.`);
1764
+ lines.push("A call that names no project may answer for every project of the machine, which is far more than this screen shows: if a result mentions services you do not recognize, that is why.");
1765
+ lines.push("");
1766
+ }
1495
1767
  if (services.length === 0) {
1496
1768
  lines.push("No services configured.");
1497
1769
  return lines.join("\n");
@@ -1509,47 +1781,24 @@ function generateAdminLlmsTxt(services, jwt) {
1509
1781
  }
1510
1782
  lines.push("## MCP Tools");
1511
1783
  lines.push("");
1512
- lines.push("You have access to Runeya MCP tools to manage services. **Always prefer MCP tools** over raw HTTP calls.");
1513
- lines.push("Available tools: `list_services`, `get_service_status`, `start_service`, `stop_service`, `restart_service`, `get_logs`.");
1784
+ lines.push("Runeya is driven exclusively through the MCP tools below. There is no HTTP API to fall back on.");
1514
1785
  lines.push("");
1786
+ lines.push(RUNEYA_CAPABILITIES.map((c) => `\`${c.name}\``).join(", ") + ".");
1787
+ lines.push("");
1788
+ const hints = RUNEYA_CAPABILITIES.filter((c) => c.usageHint);
1789
+ if (hints.length > 0) {
1790
+ lines.push("### Usage hints");
1791
+ lines.push("");
1792
+ for (const cap of hints) lines.push(`- ${cap.usageHint}`);
1793
+ lines.push("");
1794
+ }
1515
1795
  if (jwt) {
1516
1796
  lines.push("**Important**: Pass the `authToken` parameter with value `$RUNEYA_API_TOKEN` (from environment) on every MCP tool call for authentication.");
1517
1797
  lines.push("");
1518
1798
  }
1519
1799
  lines.push("Use the service IDs and agent IDs listed above when calling these tools.");
1520
1800
  lines.push("");
1521
- lines.push("## API Reference (fallback)");
1522
- lines.push("");
1523
- lines.push("Only use raw HTTP calls if MCP tools are unavailable.");
1524
- lines.push("All endpoints use tRPC v11 over HTTP (`Content-Type: application/json`).");
1525
- lines.push("");
1526
- lines.push("**tRPC v11 request format:**");
1527
- lines.push('- **GET queries**: `?input={"id":"abc"}`');
1528
- lines.push('- **POST mutations**: JSON body `{"agentId":"<agentId>","processId":"<serviceId>"}`');
1529
- lines.push("");
1530
- lines.push(`### List services
1531
- \`GET ${trpcBase}/service.list\``);
1532
- lines.push("");
1533
- lines.push(`### Get service
1534
- \`GET ${trpcBase}/service.get?input={"agentId":"<agentId>","id":"<serviceId>"}\``);
1535
- lines.push("");
1536
- lines.push(`### Read logs
1537
- \`GET ${trpcBase}/process.logs?input={"agentId":"<agentId>","processId":"<serviceId>"}\``);
1538
- lines.push("");
1539
- lines.push(`### Start service
1540
- \`POST ${trpcBase}/process.start\`
1541
- Body: \`{"agentId":"<agentId>","processId":"<serviceId>"}\``);
1542
- lines.push("");
1543
- lines.push(`### Stop service
1544
- \`POST ${trpcBase}/process.stop\`
1545
- Body: \`{"agentId":"<agentId>","processId":"<serviceId>"}\``);
1546
- lines.push("");
1547
- lines.push(`### Restart service
1548
- \`POST ${trpcBase}/process.restart\`
1549
- Body: \`{"agentId":"<agentId>","processId":"<serviceId>"}\``);
1550
- lines.push("");
1551
- lines.push(`### Get service status
1552
- \`GET ${trpcBase}/process.status?input={"agentId":"<agentId>","processId":"<serviceId>"}\``);
1801
+ lines.push("If a tool you need does not exist, say so instead of improvising another route.");
1553
1802
  lines.push("");
1554
1803
  return lines.join("\n");
1555
1804
  }
@@ -2075,10 +2324,31 @@ async function resolveServiceVariables(service) {
2075
2324
  }
2076
2325
  var DockerConfigInput = DockerConfigSchema;
2077
2326
  var serviceRouter = router({
2078
- list: protectedProcedure.meta({ openapi: { method: "GET", path: "/services", tags: ["services"], summary: "List all services", protect: true } }).output(z2.any()).query(async ({ ctx }) => {
2327
+ /**
2328
+ * Sans `projectId`, la réponse couvre TOUT le poste : `serviceStore.list()`
2329
+ * rend chaque coffre, donc chaque organisation et chaque projet de la
2330
+ * machine. L'interface le supporte — elle n'affiche que le projet ouvert —
2331
+ * mais un appelant sans écran reçoit la liste entière, d'où le filtre.
2332
+ *
2333
+ * Un projet introuvable rend une liste vide, jamais tout le poste : un repli
2334
+ * silencieux ferait croire au filtrage tout en rendant les services des
2335
+ * autres organisations.
2336
+ */
2337
+ list: protectedProcedure.meta({ openapi: { method: "GET", path: "/services", tags: ["services"], summary: "List services (every project of the machine unless narrowed)", protect: true } }).input(z2.object({
2338
+ projectId: z2.string().max(128).optional(),
2339
+ orgId: z2.string().max(128).nullable().optional()
2340
+ }).optional()).output(z2.any()).query(async ({ input, ctx }) => {
2079
2341
  const all = await serviceStore.list();
2080
2342
  const allowedIds = getAllowedServiceIds(ctx);
2081
- const filtered = allowedIds ? all.filter((s) => allowedIds.has(s.id)) : all;
2343
+ let filtered = allowedIds ? all.filter((s) => allowedIds.has(s.id)) : all;
2344
+ if (input?.projectId) {
2345
+ const project = await projectStore.get({
2346
+ id: input.projectId,
2347
+ ...input.orgId !== void 0 ? { orgId: input.orgId } : {}
2348
+ });
2349
+ const ids = new Set(project?.serviceIds ?? []);
2350
+ filtered = filtered.filter((s) => ids.has(s.id));
2351
+ }
2082
2352
  return Promise.all(filtered.map(async (s) => ({
2083
2353
  ...s,
2084
2354
  effectiveAgentId: await resolveEffectiveAgentId(s)
@@ -3256,7 +3526,7 @@ async function vaultOfProject(projectId) {
3256
3526
  // ../server/src/services/image-storage.service.ts
3257
3527
  import { randomUUID as randomUUID3 } from "crypto";
3258
3528
  import { mkdir as mkdir6, writeFile as writeFile4, readFile as readFile6, unlink as unlink2, readdir as readdir3 } from "fs/promises";
3259
- import { existsSync } from "fs";
3529
+ import { existsSync as existsSync2 } from "fs";
3260
3530
  import { join as join6, extname, resolve as resolve2, sep as sep2 } from "path";
3261
3531
  var ALLOWED_MIME_TYPES = /* @__PURE__ */ new Set([
3262
3532
  "image/png",
@@ -3322,7 +3592,7 @@ var ImageStorageService = class {
3322
3592
  if (!metaFile) return null;
3323
3593
  const raw = JSON.parse(await readFile6(join6(this.dir, metaFile), "utf-8"));
3324
3594
  if (expectedContextId !== void 0 && raw.contextId !== expectedContextId) return null;
3325
- if (!existsSync(raw.filePath)) return null;
3595
+ if (!existsSync2(raw.filePath)) return null;
3326
3596
  return { filePath: raw.filePath, mimeType: raw.mimeType, contextId: raw.contextId };
3327
3597
  } catch {
3328
3598
  return null;
@@ -4554,13 +4824,9 @@ async function getAgentManager() {
4554
4824
  return agentManager2;
4555
4825
  }
4556
4826
  function buildPtyArgs(params, sessionId, opts) {
4557
- const { isResume, systemContext, apiBaseUrl, apiToken, model, mcpConfig, skipTokenInstructions, prompt } = params;
4827
+ const { isResume, systemContext, model, mcpConfig, skipTokenInstructions, prompt } = params;
4558
4828
  const sessionArg = isResume ? ["--resume", sessionId] : ["--session-id", sessionId];
4559
- const apiDocs = buildApiDocs(apiBaseUrl, apiToken);
4560
- const fullSystemContext = apiDocs ? `${systemContext}
4561
-
4562
- ${apiDocs}` : systemContext;
4563
- const systemPrompt = skipTokenInstructions ? fullSystemContext : `${fullSystemContext}
4829
+ const systemPrompt = skipTokenInstructions ? systemContext : `${systemContext}
4564
4830
 
4565
4831
  ${TOKEN_INSTRUCTIONS}`;
4566
4832
  const mcpArgs = mcpConfig && !opts.excludeMcp ? ["--mcp-config", mcpConfig] : [];
@@ -4719,7 +4985,9 @@ async function runClaudeViaPty(params) {
4719
4985
  // toutes les tools répondent « No auth token available », et `$RUNEYA_API_TOKEN`
4720
4986
  // ne résout à rien dans le shell du CLI. Le jeton est déjà là — la file le
4721
4987
  // signe elle-même, faute de requête HTTP d'où le tirer.
4722
- mcpApiToken: params.apiToken || void 0
4988
+ mcpApiToken: params.apiToken || void 0,
4989
+ mcpProjectId: params.projectId || void 0,
4990
+ mcpOrgId: params.orgId || void 0
4723
4991
  }).then(({ spawnId: id }) => {
4724
4992
  spawnId = id;
4725
4993
  if (signal.aborted) {
@@ -4866,16 +5134,12 @@ var EFFORT_THINKING_BUDGET = {
4866
5134
  high: 1e4
4867
5135
  };
4868
5136
  function buildClaudeSpawnConfig(params, opts) {
4869
- const { sessionId, prompt, isResume, systemContext, apiBaseUrl, apiToken, model, effort, images, mcpConfig, skipTokenInstructions, injectedEnv } = params;
5137
+ const { sessionId, prompt, isResume, systemContext, apiToken, model, effort, images, mcpConfig, skipTokenInstructions, injectedEnv } = params;
4870
5138
  const hasImages = images && images.length > 0;
4871
5139
  const sessionArg = isResume ? ["--resume", sessionId] : sessionId ? ["--session-id", sessionId] : [];
4872
5140
  const thinkingBudget = EFFORT_THINKING_BUDGET[effort] ?? 0;
4873
5141
  const thinkingArgs = thinkingBudget > 0 ? ["--thinking", "enabled"] : [];
4874
- const apiDocs = buildApiDocs(apiBaseUrl, apiToken);
4875
- const fullSystemContext = apiDocs ? `${systemContext}
4876
-
4877
- ${apiDocs}` : systemContext;
4878
- const systemPrompt = skipTokenInstructions ? fullSystemContext : `${fullSystemContext}
5142
+ const systemPrompt = skipTokenInstructions ? systemContext : `${systemContext}
4879
5143
 
4880
5144
  ${TOKEN_INSTRUCTIONS}`;
4881
5145
  const inputArgs = hasImages ? ["--input-format", "stream-json"] : ["-p", prompt];
@@ -5053,56 +5317,6 @@ var ClaudeCodeRunner = class {
5053
5317
  import { spawn as spawn2 } from "child_process";
5054
5318
  import { createInterface } from "readline";
5055
5319
  import { EventEmitter } from "events";
5056
-
5057
- // ../../packages/mcp-server/src/launch.ts
5058
- import { fileURLToPath } from "url";
5059
- import { createRequire } from "module";
5060
- import { existsSync as existsSync2 } from "fs";
5061
- function resolveMcpServerPath() {
5062
- try {
5063
- const req = createRequire(import.meta.url);
5064
- return req.resolve("@runeya/packages-mcp-server");
5065
- } catch {
5066
- }
5067
- const candidates = [
5068
- // Build packagé du CLI : dist/agent/index.js et dist/index.js côtoient
5069
- // dist/mcp-server/, copié là par le post-build.
5070
- new URL("../mcp-server/index.js", import.meta.url),
5071
- new URL("./mcp-server/index.js", import.meta.url),
5072
- // Monorepo, depuis un dist d'app.
5073
- new URL("../../../packages/mcp-server/dist/index.js", import.meta.url),
5074
- new URL("../../../../packages/mcp-server/dist/index.js", import.meta.url)
5075
- ];
5076
- for (const c of candidates) {
5077
- const p = fileURLToPath(c);
5078
- if (existsSync2(p)) return p;
5079
- }
5080
- throw new Error("Could not locate @runeya/packages-mcp-server (built dist not found)");
5081
- }
5082
- function pickEnv(env2) {
5083
- return {
5084
- ...env2.RUNEYA_BASE_URL ? { RUNEYA_BASE_URL: env2.RUNEYA_BASE_URL } : {},
5085
- ...env2.RUNEYA_API_TOKEN ? { RUNEYA_API_TOKEN: env2.RUNEYA_API_TOKEN } : {}
5086
- };
5087
- }
5088
- function codexMcpArgs(env2) {
5089
- const fields = [
5090
- `command=${tomlString("node")}`,
5091
- `args=[${tomlString(resolveMcpServerPath())}]`
5092
- ];
5093
- const entries = Object.entries(pickEnv(env2));
5094
- if (entries.length > 0) {
5095
- const inline = entries.map(([k, v]) => `${k}=${tomlString(v)}`).join(",");
5096
- fields.push(`env={${inline}}`);
5097
- }
5098
- return ["-c", `mcp_servers.runeya={${fields.join(",")}}`];
5099
- }
5100
- function tomlString(value) {
5101
- const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/[\u0000-\u001f\u007f]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
5102
- return `"${escaped}"`;
5103
- }
5104
-
5105
- // ../server/src/services/ai-runners/codex-app-server-client.ts
5106
5320
  function resolveMcpArgs(env2) {
5107
5321
  if (!env2["RUNEYA_API_TOKEN"]) return [];
5108
5322
  try {
@@ -5399,8 +5613,7 @@ var CodexRunner = class {
5399
5613
  this.lastThreadId = threadId;
5400
5614
  params.onThreadId?.(threadId);
5401
5615
  }
5402
- const apiDocs = buildApiDocs(apiBaseUrl, apiToken);
5403
- const systemParts = [systemContext, ...skipTokenInstructions ? [] : [TOKEN_INSTRUCTIONS], apiDocs].filter(Boolean);
5616
+ const systemParts = [systemContext, ...skipTokenInstructions ? [] : [TOKEN_INSTRUCTIONS]].filter(Boolean);
5404
5617
  const fullSystemContext = systemParts.join("\n\n");
5405
5618
  const fullPrompt = isResume && this.lastThreadId ? prompt : `${fullSystemContext}
5406
5619
 
@@ -5592,8 +5805,7 @@ ${prompt}`;
5592
5805
  this.lastThreadId = threadId;
5593
5806
  params.onThreadId?.(threadId);
5594
5807
  }
5595
- const apiDocs = buildApiDocs(apiBaseUrl, apiToken);
5596
- const systemParts = [systemContext, ...skipTokenInstructions ? [] : [TOKEN_INSTRUCTIONS], apiDocs].filter(Boolean);
5808
+ const systemParts = [systemContext, ...skipTokenInstructions ? [] : [TOKEN_INSTRUCTIONS]].filter(Boolean);
5597
5809
  const fullSystemContext = systemParts.join("\n\n");
5598
5810
  const fullPrompt = isResume && this.lastThreadId ? prompt : `${fullSystemContext}
5599
5811
 
@@ -5980,20 +6192,21 @@ async function* drainSession(session, signal, isReconnect) {
5980
6192
  if (signal?.aborted) return;
5981
6193
  }
5982
6194
  }
6195
+ async function kanbanContextFor(conv) {
6196
+ if (!conv?.kanbanBoardId) return "";
6197
+ const kanbanBoard = await kanbanStore.get(conv.kanbanBoardId);
6198
+ if (!kanbanBoard) return "";
6199
+ return "\n\n" + (conv.kanbanCardId ? await buildKanbanCardPrompt(kanbanBoard, conv.kanbanCardId) : generateKanbanPopulatePrompt(kanbanBoard));
6200
+ }
5983
6201
  async function buildCliSystemContext(conv, jwt) {
5984
6202
  const allServices = await serviceStore.list();
5985
6203
  const ref = conv ? await conversationStore.projectRefOf(conv) : null;
5986
6204
  const project = ref ? await projectStore.get(ref) : null;
5987
6205
  const ownServices = project ? allServices.filter((svc) => project.serviceIds.includes(svc.id)) : allServices;
5988
6206
  const resolvedServices = await Promise.all(ownServices.map(resolveServiceVariables));
5989
- let systemContext = generateAdminLlmsTxt(resolvedServices, jwt);
6207
+ let systemContext = generateAdminLlmsTxt(resolvedServices, jwt, project);
5990
6208
  if (!conv?.isCompanion) systemContext += "\n\n" + companionSystemNote();
5991
- if (conv?.kanbanBoardId) {
5992
- const kanbanBoard = await kanbanStore.get(conv.kanbanBoardId);
5993
- if (kanbanBoard) {
5994
- systemContext += "\n\n" + (conv.kanbanCardId ? await buildKanbanCardPrompt(kanbanBoard, conv.kanbanCardId) : generateKanbanPopulatePrompt(kanbanBoard));
5995
- }
5996
- }
6209
+ systemContext += await kanbanContextFor(conv);
5997
6210
  return systemContext;
5998
6211
  }
5999
6212
  async function resolveInjectedEnv(environmentId) {
@@ -6020,15 +6233,12 @@ async function startClaudeCodeSession(convId, prompt, opts = {}) {
6020
6233
  conversationStore.update(conv.id, { messages: conv.messages }, { silent: true }).catch(() => {
6021
6234
  });
6022
6235
  const systemContext = await buildCliSystemContext(conv, opts.jwt);
6023
- const mcpServerPath = fileURLToPath2(new URL("../mcp-server/index.js", import.meta.url));
6024
- const mcpConfig = JSON.stringify({
6025
- mcpServers: {
6026
- runeya: {
6027
- command: "node",
6028
- args: [mcpServerPath],
6029
- env: { RUNEYA_BASE_URL: `http://localhost:${env.PORT}`, ...opts.jwt ? { RUNEYA_API_TOKEN: opts.jwt } : {} }
6030
- }
6031
- }
6236
+ const mcpRef = conv ? await conversationStore.projectRefOf(conv) : null;
6237
+ const mcpConfig = runeyaMcpConfig({
6238
+ RUNEYA_BASE_URL: `http://localhost:${env.PORT}`,
6239
+ ...opts.jwt ? { RUNEYA_API_TOKEN: opts.jwt } : {},
6240
+ ...mcpRef?.id ? { RUNEYA_PROJECT_ID: mcpRef.id } : {},
6241
+ ...mcpRef?.orgId ? { RUNEYA_ORG_ID: mcpRef.orgId } : {}
6032
6242
  });
6033
6243
  const ac = new AbortController();
6034
6244
  const session = activeSessionRegistry.registerProviderApiSession(convId, ac);
@@ -6048,6 +6258,8 @@ async function startClaudeCodeSession(convId, prompt, opts = {}) {
6048
6258
  systemContext,
6049
6259
  apiBaseUrl: `http://localhost:${env.PORT}`,
6050
6260
  apiToken: opts.jwt ?? "",
6261
+ ...mcpRef?.id ? { projectId: mcpRef.id } : {},
6262
+ ...mcpRef?.orgId ? { orgId: mcpRef.orgId } : {},
6051
6263
  model: opts.model ?? "claude-opus-4-6",
6052
6264
  effort: opts.effort ?? "normal",
6053
6265
  signal: ac.signal,
@@ -6549,25 +6761,14 @@ Return ONLY the improved text, no explanation, no preamble.`;
6549
6761
  const cliPrompt = input.contextNote ? `${input.contextNote}
6550
6762
 
6551
6763
  ${input.prompt}` : input.prompt;
6552
- const allServices = await serviceStore.list();
6553
- const resolvedServices = await Promise.all(allServices.map(resolveServiceVariables));
6554
6764
  const jwt = ctx.authorization?.startsWith("Bearer ") ? ctx.authorization.slice(7) : void 0;
6555
- let systemContext = generateAdminLlmsTxt(resolvedServices, jwt);
6556
- if (conv.kanbanBoardId) {
6557
- const kanbanBoard = await kanbanStore.get(conv.kanbanBoardId);
6558
- if (kanbanBoard) {
6559
- systemContext += "\n\n" + (conv.kanbanCardId ? await buildKanbanCardPrompt(kanbanBoard, conv.kanbanCardId) : generateKanbanPopulatePrompt(kanbanBoard));
6560
- }
6561
- }
6562
- const mcpServerPath = fileURLToPath2(new URL("../mcp-server/index.js", import.meta.url));
6563
- const mcpConfig = JSON.stringify({
6564
- mcpServers: {
6565
- runeya: {
6566
- command: "node",
6567
- args: [mcpServerPath],
6568
- env: { RUNEYA_BASE_URL: `http://localhost:${env.PORT}`, ...jwt ? { RUNEYA_API_TOKEN: jwt } : {} }
6569
- }
6570
- }
6765
+ const systemContext = await buildCliSystemContext(conv, jwt);
6766
+ const mcpRef = await conversationStore.projectRefOf(conv);
6767
+ const mcpConfig = runeyaMcpConfig({
6768
+ RUNEYA_BASE_URL: `http://localhost:${env.PORT}`,
6769
+ ...jwt ? { RUNEYA_API_TOKEN: jwt } : {},
6770
+ ...mcpRef?.id ? { RUNEYA_PROJECT_ID: mcpRef.id } : {},
6771
+ ...mcpRef?.orgId ? { RUNEYA_ORG_ID: mcpRef.orgId } : {}
6571
6772
  });
6572
6773
  const imagePaths = [];
6573
6774
  if (input.imageIds && input.imageIds.length > 0) {
@@ -6603,6 +6804,8 @@ ${imagePaths.map((p) => `Image: ${p}`).join("\n")}` : cliPrompt;
6603
6804
  systemContext,
6604
6805
  apiBaseUrl: `http://localhost:${env.PORT}`,
6605
6806
  apiToken: jwt ?? "",
6807
+ ...mcpRef?.id ? { projectId: mcpRef.id } : {},
6808
+ ...mcpRef?.orgId ? { orgId: mcpRef.orgId } : {},
6606
6809
  model: input.model ?? "claude-opus-4-6",
6607
6810
  effort: input.effort ?? "normal",
6608
6811
  signal: ac.signal,
@@ -6665,16 +6868,8 @@ ${imagePaths.map((p) => `Image: ${p}`).join("\n")}` : cliPrompt;
6665
6868
  const cliPrompt = input.contextNote ? `${input.contextNote}
6666
6869
 
6667
6870
  ${input.prompt}` : input.prompt;
6668
- const allServices = await serviceStore.list();
6669
- const resolvedServices = await Promise.all(allServices.map(resolveServiceVariables));
6670
6871
  const jwt = ctx.authorization?.startsWith("Bearer ") ? ctx.authorization.slice(7) : void 0;
6671
- let systemContext = generateAdminLlmsTxt(resolvedServices, jwt);
6672
- if (conv.kanbanBoardId) {
6673
- const kanbanBoard = await kanbanStore.get(conv.kanbanBoardId);
6674
- if (kanbanBoard) {
6675
- systemContext += "\n\n" + (conv.kanbanCardId ? await buildKanbanCardPrompt(kanbanBoard, conv.kanbanCardId) : generateKanbanPopulatePrompt(kanbanBoard));
6676
- }
6677
- }
6872
+ const systemContext = await buildCliSystemContext(conv, jwt);
6678
6873
  const resolvedImages = input.imageIds && input.imageIds.length > 0 ? await resolveImagesToBase64(input.imageIds.map((id) => ({ imageId: id, mimeType: "" })), input.conversationId) : [];
6679
6874
  const convId = input.conversationId;
6680
6875
  const ac = new AbortController();
@@ -6764,12 +6959,7 @@ ${input.prompt}` : input.prompt;
6764
6959
  const authToken = ctx.authorization?.replace(/^Bearer\s+/i, "") ?? "";
6765
6960
  let system = await buildSystemPrompt(apiKey);
6766
6961
  system += "\n\n" + TOOL_SAFETY_INSTRUCTION;
6767
- if (conv && conv.kanbanBoardId) {
6768
- const kanbanBoard = await kanbanStore.get(conv.kanbanBoardId);
6769
- if (kanbanBoard) {
6770
- system += "\n\n" + (conv.kanbanCardId ? await buildKanbanCardPrompt(kanbanBoard, conv.kanbanCardId) : generateKanbanPopulatePrompt(kanbanBoard));
6771
- }
6772
- }
6962
+ system += await kanbanContextFor(conv);
6773
6963
  const resolvedImages = input.imageIds && input.imageIds.length > 0 ? await resolveImagesToBase64(input.imageIds.map((id) => ({ imageId: id, mimeType: "" })), input.conversationId) : [];
6774
6964
  let session;
6775
6965
  try {
@@ -6917,20 +7107,14 @@ ${input.prompt}` : input.prompt;
6917
7107
  if (input.model) args.push("--model", input.model);
6918
7108
  args.push("--dangerously-skip-permissions");
6919
7109
  }
7110
+ const ptyConv = input.sessionId ? await conversationStore.get(input.sessionId).catch(() => null) : null;
7111
+ const ptyRef = (ptyConv ? await conversationStore.projectRefOf(ptyConv) : null) ?? (input.projectId ? { id: input.projectId, orgId: input.orgId ?? null } : null);
6920
7112
  const jwt = ctx.authorization?.startsWith("Bearer ") ? ctx.authorization.slice(7) : void 0;
6921
- if (!isCodex && input.sessionId) {
7113
+ if (!isCodex && ptyConv) {
6922
7114
  try {
6923
- const conv = await conversationStore.get(input.sessionId);
6924
- if (conv) {
6925
- const systemContext = await buildCliSystemContext(conv, jwt);
6926
- const apiBase = input.apiBaseUrl ?? `http://localhost:${env.PORT}`;
6927
- const apiDocs = buildApiDocs(apiBase, jwt ?? "");
6928
- const fullSystemPrompt = apiDocs ? `${systemContext}
6929
-
6930
- ${apiDocs}` : systemContext;
6931
- if (fullSystemPrompt.trim().length > 0) {
6932
- args.push("--append-system-prompt", fullSystemPrompt);
6933
- }
7115
+ const systemContext = await buildCliSystemContext(ptyConv, jwt);
7116
+ if (systemContext.trim().length > 0) {
7117
+ args.push("--append-system-prompt", systemContext);
6934
7118
  }
6935
7119
  } catch (err) {
6936
7120
  console.warn("[chat.pty.start] buildCliSystemContext failed:", err.message);
@@ -6962,7 +7146,9 @@ ${apiDocs}` : systemContext;
6962
7146
  sessionId: input.sessionId,
6963
7147
  enableMcp: input.enableMcp,
6964
7148
  mcpApiBaseUrl: input.apiBaseUrl ?? `http://localhost:${env.PORT}`,
6965
- mcpApiToken: jwt
7149
+ mcpApiToken: jwt,
7150
+ ...ptyRef?.id ? { mcpProjectId: ptyRef.id } : {},
7151
+ ...ptyRef?.orgId ? { mcpOrgId: ptyRef.orgId } : {}
6966
7152
  }
6967
7153
  );
6968
7154
  lap("agent ai.spawnPty");
@@ -7319,4 +7505,4 @@ export {
7319
7505
  startCliSession,
7320
7506
  chatRouter
7321
7507
  };
7322
- //# sourceMappingURL=chunk-ZVUSEO5P.js.map
7508
+ //# sourceMappingURL=chunk-57NU22TS.js.map