integram-mcp 0.7.62 → 0.7.67

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 CHANGED
@@ -15,7 +15,7 @@ claude mcp add integram \
15
15
  -e INTEGRAM_URL=https://ai2o.online \
16
16
  -e INTEGRAM_EMAIL=you@example.com \
17
17
  -e INTEGRAM_PASSWORD=secret \
18
- -- npx -y integram-mcp@0.7.62
18
+ -- npx -y integram-mcp@0.7.67
19
19
  ```
20
20
 
21
21
  Ставить ничего не нужно: `npx` скачает пакет сам.
@@ -43,7 +43,7 @@ claude mcp add integram \
43
43
  -e INTEGRAM_URL=http://localhost:8081 \
44
44
  -e INTEGRAM_EMAIL=you@example.com \
45
45
  -e INTEGRAM_PASSWORD=secret \
46
- -- npx -y integram-mcp@0.7.62
46
+ -- npx -y integram-mcp@0.7.67
47
47
  ```
48
48
 
49
49
  Удалить: `claude mcp remove integram`
@@ -57,7 +57,7 @@ claude mcp add integram \
57
57
  "mcpServers": {
58
58
  "integram": {
59
59
  "command": "npx",
60
- "args": ["-y", "integram-mcp@0.7.62"],
60
+ "args": ["-y", "integram-mcp@0.7.67"],
61
61
  "env": {
62
62
  "INTEGRAM_URL": "https://ai2o.online",
63
63
  "INTEGRAM_EMAIL": "you@example.com",
@@ -77,7 +77,7 @@ claude mcp add integram \
77
77
  "mcpServers": {
78
78
  "integram": {
79
79
  "command": "npx",
80
- "args": ["-y", "integram-mcp@0.7.62"],
80
+ "args": ["-y", "integram-mcp@0.7.67"],
81
81
  "env": {
82
82
  "INTEGRAM_URL": "https://ai2o.online",
83
83
  "INTEGRAM_EMAIL": "you@example.com",
package/index.js CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  import { createRequire } from 'module';
26
26
  import { rememberActivation as rememberActivationIn, applyActivation, forgetActivation } from './activation-memory.js';
27
27
  import { startOrphanWatchdog } from './orphan-watchdog.js';
28
+ import { enqueuePending, takePending } from './pending-hitl.js';
28
29
 
29
30
  // Own identity — read from package.json, never hardcoded: a hardcoded copy drifts
30
31
  // (it sat at 0.5.0 through the 0.6.0 and 0.7.0 releases).
@@ -244,10 +245,14 @@ const BUILT_IN_NAMES = new Set([
244
245
  'delete_workspace', 'clone_workspace', 'search_tools', 'confirm_action',
245
246
  ]);
246
247
 
247
- // Pending HITL state — stores the threadId for the last pending_confirmation
248
- const pendingHitlQueue = []; // [{ threadId, action, description, createdAt }, ...]
248
+ // Pending HITL state — each entry carries a short id so confirm_action names
249
+ // exactly which pending action it confirms (PM-241: a confirm used to execute
250
+ // the OLDEST queued action, not the approved one).
251
+ const pendingHitlQueue = []; // [{ id, threadId, action, description, createdAt, onApprove?, onReject? }, ...]
249
252
  const HITL_QUEUE_MAX_SIZE = 50;
250
253
  const HITL_QUEUE_TTL_MS = 10 * 60 * 1000; // 10 minutes
254
+ let _hitlSeq = 0;
255
+ const nextHitlId = () => `c${(++_hitlSeq).toString(36)}${Date.now().toString(36).slice(-4)}`;
251
256
 
252
257
  async function fetchTools() {
253
258
  const data = await apiFetch(`/api/v2/${workspace}/ai/tools`);
@@ -733,16 +738,18 @@ Block-based documents (like Notion). Activate via search_tools("документ
733
738
 
734
739
  Event-driven rules: when X happens → check condition → do Y. Activate via search_tools("automations").
735
740
 
736
- create_automation({ name, trigger: { type, typeId }, active?, condition, actions: [{ type, config }] })
741
+ create_automation({ name, trigger: { type, typeId }, active?, condition, actions: [{ type, …плоские ключи действия }] }) — действия хранятся с ПЛОСКИМИ ключами: { type: 'run_script', script: '…' }, вложенного config нет
737
742
  - active: false — создать выключенной (по умолчанию включена; выключенная не встаёт в расписание и не срабатывает)
738
743
  - Trigger types: on_create, on_update, on_delete, on_deadline, on_webhook, on_form_submit, schedule, manual, ai_analysis, on_metric_threshold, on_metric_silence, on_document, on_ncl_run_completed, on_ncl_requirement_created, on_ncl_evidence_stale, on_telegram_command, on_telegram_message, on_telegram_pre_checkout, on_telegram_shipping, on_telegram_payment, on_telegram_inline, on_telegram_join_request, on_telegram_business_connection, on_telegram_business_message, on_bot_chat_member, pm_deadline, on_issue_commented, on_issue_updated, on_issue_created, on_issue_status_changed, on_sprint_started, on_sprint_completed
739
744
  pm_deadline: { days: N (за сколько дней до due_date PM-задачи, default 1), hour: 0-23 (час UTC ежедневного скана, default 7) }; в действиях доступны {{pm_title}}, {{pm_number}}, {{pm_due_date}}, {{pm_assignee_email}} (send_notification адресуйте username: '{{pm_assignee_email}}')
740
745
  on_issue_commented / on_issue_updated: событие PM-задачи (комментарий / правка полей), pm-переменные те же
741
- - Actions: send_notification, send_notification_to_group, update_field, create_object, delete_object, fire_webhook, run_ai_agent, run_script, run_server_function, send_telegram, run_connector, send_email, update_related_records, set_requisite, update_related, http_request, if_else, switch, transform, wait_delay, request_approval, delegate_to_agent, invoke_agent, send_invoice, telegram_forward, answer_inline_query, telegram_ban, telegram_unban, telegram_restrict, telegram_promote, telegram_approve_join, telegram_decline_join, telegram_pin, telegram_unpin, telegram_get_chat, telegram_post_story, answer_shipping, telegram_business_reply, create_issue, update_issue
746
+ - Actions: send_notification, send_notification_to_group, update_field, create_object, delete_object, fire_webhook, run_ai_agent, run_script, run_server_function, send_telegram, send_telegram_media, create_document, run_connector, send_email, update_related_records, set_requisite, update_related, http_request, if_else, switch, transform, wait_delay, request_approval, delegate_to_agent, invoke_agent, send_invoice, telegram_forward, answer_inline_query, telegram_ban, telegram_unban, telegram_restrict, telegram_promote, telegram_approve_join, telegram_decline_join, telegram_pin, telegram_unpin, telegram_get_chat, telegram_post_story, answer_shipping, telegram_business_reply, create_issue, update_issue
742
747
  create_issue: { title, description?, issue_type?, priority?, assignee_id?, parent_id?, board_id?, sprint_id?, due_date?, estimate?, labels?, assigneeRole?, assigneeStrategy? } — создаёт PM-задачу; результат: {{_created_issue_id}}, {{_created_issue_number}}. assigneeRole — имя EAV-таблицы-роли воркспейса (строки = участники, у каждого логин в колонке «Логин»/«Username»/«Email», колонка ищется по имени или алиасу); assigneeStrategy: least_busy (умолчание) | first; assignee_id и assigneeRole взаимно исключают друг друга — конфликт отвергается при сохранении. Роль без резолвимых участников → задача без исполнителя + уведомление роли (или триггера), прогон не падает.
743
748
  update_issue: { id, title?, description?, issue_type?, status?, priority?, assignee_id?, sprint_id?, parent_id?, estimate?, due_date?, labels? } — правит PM-задачу; id можно взять из {{pm_issue_id}}
744
749
  update_related_records: { childTypeId, matchRefReqId, targetTypeId, targetMatchReqId, targetFieldReqId, sourceFieldReqId, operation: 'add'|'subtract'|'set' } — declarative cross-table update (e.g. inventory deduction: order items → match product ref → subtract from stock)
745
750
  run_server_function: { repo, fn, args?, resultVar?, idempotencyKey?, idempotencyMinutes? } — call a codespace server function (api/<fn>.js in a workspace git repo) from an automation; this is how repo code gets put on a schedule (trigger.type: 'schedule'), which previously was impossible since server functions were reachable only over HTTP from the portal. Same sandbox, capabilities and limits as the portal path (codespace/server-fn-executor.js); capabilities are declared by a "// capabilities:" comment inside the function file. Replay protection is ON by default: repo+fn+args+record runs once per idempotencyMinutes (default 1) — keep it BELOW the schedule interval or runs are silently skipped; 0 disables it. A failed call releases its claim so the next run retries. Sets {{_server_fn_error}} / {{_server_fn_skipped}}.
751
+ send_telegram_media: { kind: voice|video|document, botId?, chatId, text? (voice: TTS via Piper + ffmpeg→OGG, ffmpeg failure falls back to WAV document), videoJobId? (video-engine job id), fileUrl?, caption?, resultVar? } — send a voice note / video / file to a Telegram chat. chatId/text/caption accept {{variables}}. Sets {{_tg_media_message_id}} / {{_tg_media_error}}.
752
+ create_document: { title, markdown, resultVar? } — create a workspace document from markdown (a meeting protocol lands on the portal as a document). Owner: ctx.user id or the automation's created_by. Sets {{_document_id}} / {{_document_error}}.
746
753
  send_notification_to_group: { typeId, usernameReqId, title, body, filter?: { reqId, val } } — notifies all members of a table whose usernameReqId field is a valid Integram username; optional filter restricts to members where reqId==val (e.g. role filter)
747
754
  - list_automations, get_automation (single), update_automation, delete_automation, trigger_automation (manual run), get_automation_runs (execution log)
748
755
 
@@ -1285,6 +1292,7 @@ const CONFIRM_ACTION_DEF = {
1285
1292
  type: 'object',
1286
1293
  properties: {
1287
1294
  approved: { type: 'boolean', description: 'true = user confirmed, false = user rejected' },
1295
+ confirmId: { type: 'string', description: 'id of the pending action (printed in the REQUIRES CONFIRMATION response). Required when several actions are pending.' },
1288
1296
  },
1289
1297
  required: ['approved'],
1290
1298
  },
@@ -2268,7 +2276,7 @@ async function dispatchTool(request) {
2268
2276
  if (name === 'delete_workspace') return handleDeleteWorkspace(args?.slug || '');
2269
2277
  if (name === 'clone_workspace') return handleCloneWorkspace(args || {});
2270
2278
  if (name === 'search_tools') return handleSearchTools(args?.query || '');
2271
- if (name === 'confirm_action') return handleConfirmAction(args?.approved === true);
2279
+ if (name === 'confirm_action') return handleConfirmAction(args?.approved === true, args?.confirmId);
2272
2280
 
2273
2281
  // Check workspace is set
2274
2282
  if (!workspace) {
@@ -2277,7 +2285,10 @@ async function dispatchTool(request) {
2277
2285
 
2278
2286
  // Regular tool call → proxy to backend
2279
2287
  if (!activeTools.has(name)) {
2280
- return { content: [{ type: 'text', text: `Error: Tool "${name}" is not active. Use search_tools to discover and activate it first.` }], isError: true };
2288
+ // PM-164: называем похожие инструменты, чтобы модель не подменяла имя.
2289
+ const catalog = (allTools || []).map((t) => ({ name: t.name, group: t.group, description: t.description }));
2290
+ const text = buildNotActiveText(name, catalog, [...activeTools]);
2291
+ return { content: [{ type: 'text', text }], isError: true };
2281
2292
  }
2282
2293
 
2283
2294
  try {
@@ -2291,24 +2302,16 @@ async function dispatchTool(request) {
2291
2302
 
2292
2303
  // Check if this is a HITL confirmation request
2293
2304
  if (result?.status === 'pending_confirmation') {
2294
- // Evict expired entries
2295
2305
  const now = Date.now();
2296
- while (pendingHitlQueue.length && pendingHitlQueue[0].createdAt < now - HITL_QUEUE_TTL_MS) {
2297
- pendingHitlQueue.shift();
2298
- }
2299
- // Cap queue size
2300
- if (pendingHitlQueue.length >= HITL_QUEUE_MAX_SIZE) {
2301
- pendingHitlQueue.shift();
2302
- }
2303
- pendingHitlQueue.push({
2306
+ const entry = enqueuePending(pendingHitlQueue, {
2307
+ id: nextHitlId(),
2304
2308
  threadId: result.threadId,
2305
2309
  action: name,
2306
2310
  description: result.message || `Pending: ${name}`,
2307
2311
  createdAt: now,
2308
- });
2309
- const queueNote = pendingHitlQueue.length > 1 ? ` (${pendingHitlQueue.length} actions queued)` : '';
2312
+ }, { now, ttlMs: HITL_QUEUE_TTL_MS, maxSize: HITL_QUEUE_MAX_SIZE });
2310
2313
  return {
2311
- content: [{ type: 'text', text: `⚠️ REQUIRES CONFIRMATION: ${result.message}${queueNote}\n\nAsk the user to confirm or reject, then call confirm_action(approved=true/false).` }],
2314
+ content: [{ type: 'text', text: buildHitlConfirmationText({ tool: name, message: result.message, queued: pendingHitlQueue.length, confirmId: entry.id }) }],
2312
2315
  };
2313
2316
  }
2314
2317
 
@@ -2366,12 +2369,21 @@ async function dispatchTool(request) {
2366
2369
 
2367
2370
  // ─── confirm_action handler ──────────────────────────────────────────────────
2368
2371
 
2369
- async function handleConfirmAction(approved) {
2370
- if (pendingHitlQueue.length === 0) {
2372
+ async function handleConfirmAction(approved, confirmId) {
2373
+ // PM-241: подтверждение идёт ПО ИМЕНИ ожидания. Без имени берётся
2374
+ // единственное ожидание; при нескольких — отказ с перечнем, не угадывание.
2375
+ const taken = takePending(pendingHitlQueue, confirmId, { ttlMs: HITL_QUEUE_TTL_MS });
2376
+ if (taken.error === 'EMPTY') {
2371
2377
  return { content: [{ type: 'text', text: 'No pending action to confirm.' }], isError: true };
2372
2378
  }
2379
+ if (taken.error === 'AMBIGUOUS') {
2380
+ return { content: [{ type: 'text', text: `Multiple pending actions; pass confirmId of the one the user approved: ${taken.available.join(', ')}.` }], isError: true };
2381
+ }
2382
+ if (taken.error === 'UNKNOWN_CONFIRM_ID') {
2383
+ return { content: [{ type: 'text', text: `No pending action with confirmId "${confirmId}". Live ids: ${taken.available.join(', ') || 'none'}.` }], isError: true };
2384
+ }
2373
2385
 
2374
- const pending = pendingHitlQueue.shift();
2386
+ const pending = taken.entry;
2375
2387
  try {
2376
2388
  let msg;
2377
2389
  if (pending.onApprove) {
@@ -2393,7 +2405,7 @@ async function handleConfirmAction(approved) {
2393
2405
  }
2394
2406
 
2395
2407
  const remaining = pendingHitlQueue.length > 0 ? ` (${pendingHitlQueue.length} more pending — call confirm_action again)` : '';
2396
- return { content: [{ type: 'text', text: msg + remaining }] };
2408
+ return { content: [{ type: 'text', text: `[${pending.action}] ${msg}${remaining}` }] };
2397
2409
  } catch (err) {
2398
2410
  return { content: [{ type: 'text', text: `Error confirming action: ${err.message}` }], isError: true };
2399
2411
  }
@@ -2448,13 +2460,8 @@ async function handleDeleteWorkspace(slug) {
2448
2460
  if (_pendingDeleteSlug !== slug) {
2449
2461
  _pendingDeleteSlug = slug;
2450
2462
  const now = Date.now();
2451
- while (pendingHitlQueue.length && pendingHitlQueue[0].createdAt < now - HITL_QUEUE_TTL_MS) {
2452
- pendingHitlQueue.shift();
2453
- }
2454
- if (pendingHitlQueue.length >= HITL_QUEUE_MAX_SIZE) {
2455
- pendingHitlQueue.shift();
2456
- }
2457
- pendingHitlQueue.push({
2463
+ const entry = enqueuePending(pendingHitlQueue, {
2464
+ id: nextHitlId(),
2458
2465
  threadId: `delete-ws-${slug}`,
2459
2466
  action: 'delete_workspace',
2460
2467
  description: `Permanently delete workspace "${slug}" and ALL its data`,
@@ -2474,7 +2481,7 @@ async function handleDeleteWorkspace(slug) {
2474
2481
  return `Workspace "${slug}" and all its data have been permanently deleted.`;
2475
2482
  },
2476
2483
  onReject: () => { _pendingDeleteSlug = null; },
2477
- });
2484
+ }, { now, ttlMs: HITL_QUEUE_TTL_MS, maxSize: HITL_QUEUE_MAX_SIZE });
2478
2485
  return {
2479
2486
  content: [{ type: 'text', text: `⚠️ REQUIRES CONFIRMATION: Permanently delete workspace "${slug}" and ALL its data. This action is irreversible.\n\nAsk the user to confirm or reject, then call confirm_action(approved=true/false).` }],
2480
2487
  };
@@ -2830,19 +2837,97 @@ export function buildSearchToolsText(p) {
2830
2837
  if (p.builtinNames.length) {
2831
2838
  parts.push(`Already available (built-in): ${p.builtinNames.join(', ')}.`);
2832
2839
  }
2840
+ // «Nothing new» обязано выходить и КОГДА встроенные совпали: раньше строка
2841
+ // built-in возвращалась раньше ветки alreadyActiveNames, и повторный поиск
2842
+ // отвечал только «Already available (built-in)», скрывая, что группа УЖЕ
2843
+ // активна (инцидент PM-103, 14.09.2026 — модель так и не узнала, что
2844
+ // коннекторы активированы).
2845
+ if (!p.activatedNames.length && p.alreadyActiveNames.length) {
2846
+ parts.push(`Nothing new: all ${p.alreadyActiveNames.length} tools matching "${p.query}" are already active ` +
2847
+ `(${p.alreadyActiveNames.join(', ')}). Use them directly — no further search_tools call is needed.`);
2848
+ }
2833
2849
  if (parts.length) return parts.join(' ');
2834
2850
 
2835
- // Ничего не активировано. Разбираем, почему именно.
2836
- if (p.alreadyActiveNames.length) {
2837
- return `Nothing new: all ${p.alreadyActiveNames.length} tools matching "${p.query}" are already active ` +
2838
- `(${p.alreadyActiveNames.join(', ')}). Use them directly — no further search_tools call is needed.`;
2839
- }
2840
2851
  const groupsMsg = p.knownGroups.length
2841
2852
  ? p.knownGroups.slice().sort().join(', ')
2842
2853
  : '(no tools loaded — select a workspace first)';
2843
2854
  return `No tools found matching "${p.query}". Available groups: ${groupsMsg}`;
2844
2855
  }
2845
2856
 
2857
+ // ─── PM-164: similar-name guard ──────────────────────────────────────────────
2858
+
2859
+ /**
2860
+ * Детерминированный поиск похожих имён: общие токены (по '_') или подстрока.
2861
+ * Сам запрошенный тул не предлагается. Сортировка: больше общих токенов — выше.
2862
+ */
2863
+ export function findSimilarTools(name, catalog, limit = 3) {
2864
+ const tokens = (n) => n.split('_').filter(Boolean);
2865
+ const nameToks = new Set(tokens(name));
2866
+ const scored = [];
2867
+ for (const t of catalog) {
2868
+ if (t.name === name) continue;
2869
+ let shared = 0;
2870
+ for (const tok of tokens(t.name)) {
2871
+ if (nameToks.has(tok)) shared += 1;
2872
+ else if (t.name.includes(name) || name.includes(t.name)) shared += 1;
2873
+ }
2874
+ if (shared === 0) continue;
2875
+ scored.push({ tool: t, score: shared });
2876
+ }
2877
+ scored.sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name));
2878
+ return scored.slice(0, limit).map((s) => s.tool);
2879
+ }
2880
+
2881
+ /**
2882
+ * Текст ошибки «тул не активен» с подсказкой похожих: активный похожий тул —
2883
+ * с ПРЯМЫМ запретом подмены; неактивный — с подсказкой активировать группу.
2884
+ */
2885
+ export function buildNotActiveText(name, catalog, activeNames) {
2886
+ const similar = findSimilarTools(name, catalog);
2887
+ if (!similar.length) {
2888
+ return `Error: Tool "${name}" is not active. Use search_tools to discover and activate it first.`;
2889
+ }
2890
+ const activeSet = new Set(activeNames);
2891
+ const activeHits = similar.filter((t) => activeSet.has(t.name));
2892
+ const inactiveHits = similar.filter((t) => !activeSet.has(t.name));
2893
+ const lines = [`Error: Tool "${name}" is not active. Use search_tools to discover and activate it first.`];
2894
+ if (activeHits.length) {
2895
+ const listed = activeHits.map((t) => `"${t.name}" (group "${t.group}")`).join(', ');
2896
+ lines.push(
2897
+ `⚠️ Similar tool ${listed} IS ACTIVE but is a DIFFERENT tool. Do NOT call it instead of "${name}".`,
2898
+ );
2899
+ }
2900
+ if (inactiveHits.length) {
2901
+ const listed = inactiveHits.map((t) => `"${t.name}" (group "${t.group}")`).join(', ');
2902
+ const groups = [...new Set(inactiveHits.map((t) => t.group).filter(Boolean))];
2903
+ lines.push(
2904
+ `Similar inactive tool(s): ${listed}. If one of these is what you meant, activate its group first: ` +
2905
+ groups.map((g) => `search_tools("${g}")`).join(' or ') +
2906
+ ` — then call the tool by its exact name.`,
2907
+ );
2908
+ }
2909
+ return lines.join('\n');
2910
+ }
2911
+
2912
+ /**
2913
+ * Текст REQUIRES CONFIRMATION: первой строкой имя вызываемого тула
2914
+ * (PM-164: пять подтверждений промаха прошло, потому что имя не показывалось),
2915
+ * предупреждение о похожих именах и confirmId (PM-241).
2916
+ */
2917
+ export function buildHitlConfirmationText(p) {
2918
+ const message = p.message || `Pending: ${p.tool}`;
2919
+ const queueNote = p.queued > 1 ? ` (${p.queued} actions queued)` : '';
2920
+ const confirmLine = p.confirmId ? `\nconfirm id: ${p.confirmId}\nAsk the user to confirm or reject, then call confirm_action(approved=true/false, confirmId="${p.confirmId}").` : '\nAsk the user to confirm or reject, then call confirm_action(approved=true/false).';
2921
+ return (
2922
+ `⚠️ REQUIRES CONFIRMATION — tool: ${p.tool}${queueNote}\n` +
2923
+ `${message}\n\n` +
2924
+ `Before asking the user, verify the tool name above is what you intended — ` +
2925
+ `similar names are different tools (e.g. set_grant is access rights, ` +
2926
+ `set_portal_config is portal config).` +
2927
+ confirmLine
2928
+ );
2929
+ }
2930
+
2846
2931
  async function handleSearchTools(query) {
2847
2932
  try {
2848
2933
  const available = t => !activeTools.has(t.name) && !BUILT_IN_NAMES.has(t.name);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "integram-mcp",
3
- "version": "0.7.62",
3
+ "version": "0.7.67",
4
4
  "type": "module",
5
5
  "description": "MCP server for Integram — connect AI assistants to your workspace via Model Context Protocol",
6
6
  "mcpName": "io.github.judas-priest/integram",
@@ -26,6 +26,7 @@
26
26
  "files": [
27
27
  "index.js",
28
28
  "activation-memory.js",
29
+ "pending-hitl.js",
29
30
  "orphan-watchdog.js"
30
31
  ],
31
32
  "dependencies": {
@@ -0,0 +1,52 @@
1
+ // pending-hitl.js — очередь ожидающих подтверждения действий MCP-прокси.
2
+ //
3
+ // Инцидент 08.09.2026 (PM-241, воркспейс nevod-vision): в очереди висело два
4
+ // действия, confirm_action исполнял ПЕРВОЕ — старейшее, — хотя подтверждали
5
+ // последнее. Ответ «Удалено 5 объектов» уехал от чужого ожидания, запрошенные
6
+ // записи остались живы. Отсюда: каждое ожидание несёт короткий id,
7
+ // confirm_action подтверждает ПО ИМЕНИ, без имени берёт единственное
8
+ // ожидание, а при нескольких — отказывается гадать: исполнение необратимо.
9
+
10
+ /**
11
+ * Положить ожидание в очередь: сперва выкинуть протухшие, затем держать
12
+ * потолок (при переполнении падает старейший). Мутирует queue.
13
+ *
14
+ * @param {Array} queue — общий массив очереди
15
+ * @param {object} entry — { id, threadId, action, description, createdAt, onApprove?, onReject? }
16
+ * @param {object} opts — { now, ttlMs, maxSize }
17
+ * @returns {object} тот же entry
18
+ */
19
+ export function enqueuePending(queue, entry, { now, ttlMs, maxSize }) {
20
+ while (queue.length && queue[0].createdAt < now - ttlMs) queue.shift();
21
+ if (queue.length >= maxSize) queue.shift();
22
+ queue.push(entry);
23
+ return entry;
24
+ }
25
+
26
+ /**
27
+ * Взять ожидание к исполнению и УБРАТЬ из очереди — «взял» значит «исполнил»,
28
+ * повторное подтверждение того же id невозможно.
29
+ *
30
+ * confirmId назван → берётся ровно он; не найден — отказ с перечнем живых id.
31
+ * confirmId опущен → единственное ожидание берётся (старое поведение для
32
+ * случая «подтверждают сразу»); при нескольких — отказ: угадывать нельзя.
33
+ *
34
+ * @param {Array} queue — общий массив очереди (мутируется)
35
+ * @param {string|undefined} confirmId
36
+ * @param {object} [opts] — { now, ttlMs }
37
+ * @returns {{ entry: object, remaining: number } | { error: string, available: string[] }}
38
+ */
39
+ export function takePending(queue, confirmId, { now = Date.now(), ttlMs } = {}) {
40
+ if (ttlMs != null) {
41
+ while (queue.length && queue[0].createdAt < now - ttlMs) queue.shift();
42
+ }
43
+ const available = queue.map((e) => e.id);
44
+ if (!queue.length) return { error: 'EMPTY', available: [] };
45
+ if (confirmId == null) {
46
+ if (queue.length > 1) return { error: 'AMBIGUOUS', available };
47
+ return { entry: queue.shift(), remaining: queue.length };
48
+ }
49
+ const idx = queue.findIndex((e) => e.id === confirmId);
50
+ if (idx === -1) return { error: 'UNKNOWN_CONFIRM_ID', available };
51
+ return { entry: queue.splice(idx, 1)[0], remaining: queue.length };
52
+ }