integram-mcp 0.7.62 → 0.7.66
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 +4 -4
- package/index.js +117 -34
- package/package.json +2 -1
- package/pending-hitl.js +52 -0
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.
|
|
18
|
+
-- npx -y integram-mcp@0.7.66
|
|
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.
|
|
46
|
+
-- npx -y integram-mcp@0.7.66
|
|
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.
|
|
60
|
+
"args": ["-y", "integram-mcp@0.7.66"],
|
|
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.
|
|
80
|
+
"args": ["-y", "integram-mcp@0.7.66"],
|
|
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 —
|
|
248
|
-
|
|
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,7 +738,7 @@ 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,
|
|
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}}')
|
|
@@ -1285,6 +1290,7 @@ const CONFIRM_ACTION_DEF = {
|
|
|
1285
1290
|
type: 'object',
|
|
1286
1291
|
properties: {
|
|
1287
1292
|
approved: { type: 'boolean', description: 'true = user confirmed, false = user rejected' },
|
|
1293
|
+
confirmId: { type: 'string', description: 'id of the pending action (printed in the REQUIRES CONFIRMATION response). Required when several actions are pending.' },
|
|
1288
1294
|
},
|
|
1289
1295
|
required: ['approved'],
|
|
1290
1296
|
},
|
|
@@ -2268,7 +2274,7 @@ async function dispatchTool(request) {
|
|
|
2268
2274
|
if (name === 'delete_workspace') return handleDeleteWorkspace(args?.slug || '');
|
|
2269
2275
|
if (name === 'clone_workspace') return handleCloneWorkspace(args || {});
|
|
2270
2276
|
if (name === 'search_tools') return handleSearchTools(args?.query || '');
|
|
2271
|
-
if (name === 'confirm_action') return handleConfirmAction(args?.approved === true);
|
|
2277
|
+
if (name === 'confirm_action') return handleConfirmAction(args?.approved === true, args?.confirmId);
|
|
2272
2278
|
|
|
2273
2279
|
// Check workspace is set
|
|
2274
2280
|
if (!workspace) {
|
|
@@ -2277,7 +2283,10 @@ async function dispatchTool(request) {
|
|
|
2277
2283
|
|
|
2278
2284
|
// Regular tool call → proxy to backend
|
|
2279
2285
|
if (!activeTools.has(name)) {
|
|
2280
|
-
|
|
2286
|
+
// PM-164: называем похожие инструменты, чтобы модель не подменяла имя.
|
|
2287
|
+
const catalog = (allTools || []).map((t) => ({ name: t.name, group: t.group, description: t.description }));
|
|
2288
|
+
const text = buildNotActiveText(name, catalog, [...activeTools]);
|
|
2289
|
+
return { content: [{ type: 'text', text }], isError: true };
|
|
2281
2290
|
}
|
|
2282
2291
|
|
|
2283
2292
|
try {
|
|
@@ -2291,24 +2300,16 @@ async function dispatchTool(request) {
|
|
|
2291
2300
|
|
|
2292
2301
|
// Check if this is a HITL confirmation request
|
|
2293
2302
|
if (result?.status === 'pending_confirmation') {
|
|
2294
|
-
// Evict expired entries
|
|
2295
2303
|
const now = Date.now();
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
}
|
|
2299
|
-
// Cap queue size
|
|
2300
|
-
if (pendingHitlQueue.length >= HITL_QUEUE_MAX_SIZE) {
|
|
2301
|
-
pendingHitlQueue.shift();
|
|
2302
|
-
}
|
|
2303
|
-
pendingHitlQueue.push({
|
|
2304
|
+
const entry = enqueuePending(pendingHitlQueue, {
|
|
2305
|
+
id: nextHitlId(),
|
|
2304
2306
|
threadId: result.threadId,
|
|
2305
2307
|
action: name,
|
|
2306
2308
|
description: result.message || `Pending: ${name}`,
|
|
2307
2309
|
createdAt: now,
|
|
2308
|
-
});
|
|
2309
|
-
const queueNote = pendingHitlQueue.length > 1 ? ` (${pendingHitlQueue.length} actions queued)` : '';
|
|
2310
|
+
}, { now, ttlMs: HITL_QUEUE_TTL_MS, maxSize: HITL_QUEUE_MAX_SIZE });
|
|
2310
2311
|
return {
|
|
2311
|
-
content: [{ type: 'text', text:
|
|
2312
|
+
content: [{ type: 'text', text: buildHitlConfirmationText({ tool: name, message: result.message, queued: pendingHitlQueue.length, confirmId: entry.id }) }],
|
|
2312
2313
|
};
|
|
2313
2314
|
}
|
|
2314
2315
|
|
|
@@ -2366,12 +2367,21 @@ async function dispatchTool(request) {
|
|
|
2366
2367
|
|
|
2367
2368
|
// ─── confirm_action handler ──────────────────────────────────────────────────
|
|
2368
2369
|
|
|
2369
|
-
async function handleConfirmAction(approved) {
|
|
2370
|
-
|
|
2370
|
+
async function handleConfirmAction(approved, confirmId) {
|
|
2371
|
+
// PM-241: подтверждение идёт ПО ИМЕНИ ожидания. Без имени берётся
|
|
2372
|
+
// единственное ожидание; при нескольких — отказ с перечнем, не угадывание.
|
|
2373
|
+
const taken = takePending(pendingHitlQueue, confirmId, { ttlMs: HITL_QUEUE_TTL_MS });
|
|
2374
|
+
if (taken.error === 'EMPTY') {
|
|
2371
2375
|
return { content: [{ type: 'text', text: 'No pending action to confirm.' }], isError: true };
|
|
2372
2376
|
}
|
|
2377
|
+
if (taken.error === 'AMBIGUOUS') {
|
|
2378
|
+
return { content: [{ type: 'text', text: `Multiple pending actions; pass confirmId of the one the user approved: ${taken.available.join(', ')}.` }], isError: true };
|
|
2379
|
+
}
|
|
2380
|
+
if (taken.error === 'UNKNOWN_CONFIRM_ID') {
|
|
2381
|
+
return { content: [{ type: 'text', text: `No pending action with confirmId "${confirmId}". Live ids: ${taken.available.join(', ') || 'none'}.` }], isError: true };
|
|
2382
|
+
}
|
|
2373
2383
|
|
|
2374
|
-
const pending =
|
|
2384
|
+
const pending = taken.entry;
|
|
2375
2385
|
try {
|
|
2376
2386
|
let msg;
|
|
2377
2387
|
if (pending.onApprove) {
|
|
@@ -2393,7 +2403,7 @@ async function handleConfirmAction(approved) {
|
|
|
2393
2403
|
}
|
|
2394
2404
|
|
|
2395
2405
|
const remaining = pendingHitlQueue.length > 0 ? ` (${pendingHitlQueue.length} more pending — call confirm_action again)` : '';
|
|
2396
|
-
return { content: [{ type: 'text', text: msg
|
|
2406
|
+
return { content: [{ type: 'text', text: `[${pending.action}] ${msg}${remaining}` }] };
|
|
2397
2407
|
} catch (err) {
|
|
2398
2408
|
return { content: [{ type: 'text', text: `Error confirming action: ${err.message}` }], isError: true };
|
|
2399
2409
|
}
|
|
@@ -2448,13 +2458,8 @@ async function handleDeleteWorkspace(slug) {
|
|
|
2448
2458
|
if (_pendingDeleteSlug !== slug) {
|
|
2449
2459
|
_pendingDeleteSlug = slug;
|
|
2450
2460
|
const now = Date.now();
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
}
|
|
2454
|
-
if (pendingHitlQueue.length >= HITL_QUEUE_MAX_SIZE) {
|
|
2455
|
-
pendingHitlQueue.shift();
|
|
2456
|
-
}
|
|
2457
|
-
pendingHitlQueue.push({
|
|
2461
|
+
const entry = enqueuePending(pendingHitlQueue, {
|
|
2462
|
+
id: nextHitlId(),
|
|
2458
2463
|
threadId: `delete-ws-${slug}`,
|
|
2459
2464
|
action: 'delete_workspace',
|
|
2460
2465
|
description: `Permanently delete workspace "${slug}" and ALL its data`,
|
|
@@ -2474,7 +2479,7 @@ async function handleDeleteWorkspace(slug) {
|
|
|
2474
2479
|
return `Workspace "${slug}" and all its data have been permanently deleted.`;
|
|
2475
2480
|
},
|
|
2476
2481
|
onReject: () => { _pendingDeleteSlug = null; },
|
|
2477
|
-
});
|
|
2482
|
+
}, { now, ttlMs: HITL_QUEUE_TTL_MS, maxSize: HITL_QUEUE_MAX_SIZE });
|
|
2478
2483
|
return {
|
|
2479
2484
|
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
2485
|
};
|
|
@@ -2830,19 +2835,97 @@ export function buildSearchToolsText(p) {
|
|
|
2830
2835
|
if (p.builtinNames.length) {
|
|
2831
2836
|
parts.push(`Already available (built-in): ${p.builtinNames.join(', ')}.`);
|
|
2832
2837
|
}
|
|
2838
|
+
// «Nothing new» обязано выходить и КОГДА встроенные совпали: раньше строка
|
|
2839
|
+
// built-in возвращалась раньше ветки alreadyActiveNames, и повторный поиск
|
|
2840
|
+
// отвечал только «Already available (built-in)», скрывая, что группа УЖЕ
|
|
2841
|
+
// активна (инцидент PM-103, 14.09.2026 — модель так и не узнала, что
|
|
2842
|
+
// коннекторы активированы).
|
|
2843
|
+
if (!p.activatedNames.length && p.alreadyActiveNames.length) {
|
|
2844
|
+
parts.push(`Nothing new: all ${p.alreadyActiveNames.length} tools matching "${p.query}" are already active ` +
|
|
2845
|
+
`(${p.alreadyActiveNames.join(', ')}). Use them directly — no further search_tools call is needed.`);
|
|
2846
|
+
}
|
|
2833
2847
|
if (parts.length) return parts.join(' ');
|
|
2834
2848
|
|
|
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
2849
|
const groupsMsg = p.knownGroups.length
|
|
2841
2850
|
? p.knownGroups.slice().sort().join(', ')
|
|
2842
2851
|
: '(no tools loaded — select a workspace first)';
|
|
2843
2852
|
return `No tools found matching "${p.query}". Available groups: ${groupsMsg}`;
|
|
2844
2853
|
}
|
|
2845
2854
|
|
|
2855
|
+
// ─── PM-164: similar-name guard ──────────────────────────────────────────────
|
|
2856
|
+
|
|
2857
|
+
/**
|
|
2858
|
+
* Детерминированный поиск похожих имён: общие токены (по '_') или подстрока.
|
|
2859
|
+
* Сам запрошенный тул не предлагается. Сортировка: больше общих токенов — выше.
|
|
2860
|
+
*/
|
|
2861
|
+
export function findSimilarTools(name, catalog, limit = 3) {
|
|
2862
|
+
const tokens = (n) => n.split('_').filter(Boolean);
|
|
2863
|
+
const nameToks = new Set(tokens(name));
|
|
2864
|
+
const scored = [];
|
|
2865
|
+
for (const t of catalog) {
|
|
2866
|
+
if (t.name === name) continue;
|
|
2867
|
+
let shared = 0;
|
|
2868
|
+
for (const tok of tokens(t.name)) {
|
|
2869
|
+
if (nameToks.has(tok)) shared += 1;
|
|
2870
|
+
else if (t.name.includes(name) || name.includes(t.name)) shared += 1;
|
|
2871
|
+
}
|
|
2872
|
+
if (shared === 0) continue;
|
|
2873
|
+
scored.push({ tool: t, score: shared });
|
|
2874
|
+
}
|
|
2875
|
+
scored.sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name));
|
|
2876
|
+
return scored.slice(0, limit).map((s) => s.tool);
|
|
2877
|
+
}
|
|
2878
|
+
|
|
2879
|
+
/**
|
|
2880
|
+
* Текст ошибки «тул не активен» с подсказкой похожих: активный похожий тул —
|
|
2881
|
+
* с ПРЯМЫМ запретом подмены; неактивный — с подсказкой активировать группу.
|
|
2882
|
+
*/
|
|
2883
|
+
export function buildNotActiveText(name, catalog, activeNames) {
|
|
2884
|
+
const similar = findSimilarTools(name, catalog);
|
|
2885
|
+
if (!similar.length) {
|
|
2886
|
+
return `Error: Tool "${name}" is not active. Use search_tools to discover and activate it first.`;
|
|
2887
|
+
}
|
|
2888
|
+
const activeSet = new Set(activeNames);
|
|
2889
|
+
const activeHits = similar.filter((t) => activeSet.has(t.name));
|
|
2890
|
+
const inactiveHits = similar.filter((t) => !activeSet.has(t.name));
|
|
2891
|
+
const lines = [`Error: Tool "${name}" is not active. Use search_tools to discover and activate it first.`];
|
|
2892
|
+
if (activeHits.length) {
|
|
2893
|
+
const listed = activeHits.map((t) => `"${t.name}" (group "${t.group}")`).join(', ');
|
|
2894
|
+
lines.push(
|
|
2895
|
+
`⚠️ Similar tool ${listed} IS ACTIVE but is a DIFFERENT tool. Do NOT call it instead of "${name}".`,
|
|
2896
|
+
);
|
|
2897
|
+
}
|
|
2898
|
+
if (inactiveHits.length) {
|
|
2899
|
+
const listed = inactiveHits.map((t) => `"${t.name}" (group "${t.group}")`).join(', ');
|
|
2900
|
+
const groups = [...new Set(inactiveHits.map((t) => t.group).filter(Boolean))];
|
|
2901
|
+
lines.push(
|
|
2902
|
+
`Similar inactive tool(s): ${listed}. If one of these is what you meant, activate its group first: ` +
|
|
2903
|
+
groups.map((g) => `search_tools("${g}")`).join(' or ') +
|
|
2904
|
+
` — then call the tool by its exact name.`,
|
|
2905
|
+
);
|
|
2906
|
+
}
|
|
2907
|
+
return lines.join('\n');
|
|
2908
|
+
}
|
|
2909
|
+
|
|
2910
|
+
/**
|
|
2911
|
+
* Текст REQUIRES CONFIRMATION: первой строкой имя вызываемого тула
|
|
2912
|
+
* (PM-164: пять подтверждений промаха прошло, потому что имя не показывалось),
|
|
2913
|
+
* предупреждение о похожих именах и confirmId (PM-241).
|
|
2914
|
+
*/
|
|
2915
|
+
export function buildHitlConfirmationText(p) {
|
|
2916
|
+
const message = p.message || `Pending: ${p.tool}`;
|
|
2917
|
+
const queueNote = p.queued > 1 ? ` (${p.queued} actions queued)` : '';
|
|
2918
|
+
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).';
|
|
2919
|
+
return (
|
|
2920
|
+
`⚠️ REQUIRES CONFIRMATION — tool: ${p.tool}${queueNote}\n` +
|
|
2921
|
+
`${message}\n\n` +
|
|
2922
|
+
`Before asking the user, verify the tool name above is what you intended — ` +
|
|
2923
|
+
`similar names are different tools (e.g. set_grant is access rights, ` +
|
|
2924
|
+
`set_portal_config is portal config).` +
|
|
2925
|
+
confirmLine
|
|
2926
|
+
);
|
|
2927
|
+
}
|
|
2928
|
+
|
|
2846
2929
|
async function handleSearchTools(query) {
|
|
2847
2930
|
try {
|
|
2848
2931
|
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.
|
|
3
|
+
"version": "0.7.66",
|
|
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": {
|
package/pending-hitl.js
ADDED
|
@@ -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
|
+
}
|