integram-mcp 0.7.150 → 0.7.154

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.150
18
+ -- npx -y integram-mcp@0.7.154
19
19
  ```
20
20
 
21
21
  Ставить ничего не нужно: `npx` скачает пакет сам.
@@ -49,7 +49,7 @@ claude mcp add integram \
49
49
  -e INTEGRAM_URL=http://localhost:8081 \
50
50
  -e INTEGRAM_EMAIL=you@example.com \
51
51
  -e INTEGRAM_PASSWORD=secret \
52
- -- npx -y integram-mcp@0.7.150
52
+ -- npx -y integram-mcp@0.7.154
53
53
  ```
54
54
 
55
55
  Удалить: `claude mcp remove integram`
@@ -63,7 +63,7 @@ claude mcp add integram \
63
63
  "mcpServers": {
64
64
  "integram": {
65
65
  "command": "npx",
66
- "args": ["-y", "integram-mcp@0.7.150"],
66
+ "args": ["-y", "integram-mcp@0.7.154"],
67
67
  "env": {
68
68
  "INTEGRAM_URL": "https://ai2o.online",
69
69
  "INTEGRAM_EMAIL": "you@example.com",
@@ -83,7 +83,7 @@ claude mcp add integram \
83
83
  "mcpServers": {
84
84
  "integram": {
85
85
  "command": "npx",
86
- "args": ["-y", "integram-mcp@0.7.150"],
86
+ "args": ["-y", "integram-mcp@0.7.154"],
87
87
  "env": {
88
88
  "INTEGRAM_URL": "https://ai2o.online",
89
89
  "INTEGRAM_EMAIL": "you@example.com",
package/auth-token.js ADDED
@@ -0,0 +1,18 @@
1
+ // mcp-server/auth-token.js
2
+ // PM-1003: refresh-токен живёт в Set-Cookie (iam/router.js:20-27), тело ответа
3
+ // login его вырезает. refresh-маршрут принимает токен из ТЕЛА — поэтому клиент
4
+ // хранит куку сам и шлёт её значение в теле. Ротация: после каждого refresh
5
+ // перечитываем и тело, и куку (повтор старого токена > 30 c отзывает family).
6
+ export function pickAccessToken(data) {
7
+ return data?.accessToken || data?.data?.accessToken || data?.data?.token || null;
8
+ }
9
+
10
+ export function extractRefreshToken(body, setCookie) {
11
+ if (body?.refreshToken) return body.refreshToken;
12
+ const cookies = setCookie || [];
13
+ for (const line of cookies) {
14
+ const m = /(?:^|;\s*)refresh_token=([^;\s]+)/.exec(line);
15
+ if (m && m[1]) return decodeURIComponent(m[1]);
16
+ }
17
+ return null;
18
+ }
package/index.js CHANGED
@@ -26,6 +26,8 @@ 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
28
  import { enqueuePending, takePending } from './pending-hitl.js';
29
+ import { compactToolResult } from './output-cap.js';
30
+ import { extractRefreshToken, pickAccessToken } from './auth-token.js';
29
31
 
30
32
  // Own identity — read from package.json, never hardcoded: a hardcoded copy drifts
31
33
  // (it sat at 0.5.0 through the 0.6.0 and 0.7.0 releases).
@@ -85,15 +87,18 @@ export function toolErrorResult(err) {
85
87
 
86
88
  async function login() {
87
89
  if (!EMAIL || !PASSWORD) throw new Error('INTEGRAM_EMAIL and INTEGRAM_PASSWORD are required');
88
- const data = await apiFetch('/api/v2/iam/login', {
90
+ const res = await fetch(`${BASE_URL}/api/v2/iam/login`, {
89
91
  method: 'POST',
92
+ headers: { 'Content-Type': 'application/json' },
90
93
  body: JSON.stringify({ email: EMAIL, password: PASSWORD }),
91
94
  });
95
+ const data = await res.json().catch(() => ({}));
92
96
  if (!data.ok) throw new Error(`Login failed: ${JSON.stringify(data.error)}`);
93
- accessToken = data.accessToken || data.data?.accessToken || data.data?.token;
94
- refreshToken = data.refreshToken || data.data?.refreshToken;
97
+ accessToken = pickAccessToken(data);
98
+ // PM-1003: refresh-токен приезжает только Set-Cookie'ем — читаем его.
99
+ refreshToken = extractRefreshToken(data, res.headers.getSetCookie?.() ?? []);
95
100
  tokenExp = decodeExp(accessToken);
96
- log(`Logged in as ${EMAIL}, token expires ${new Date(tokenExp * 1000).toISOString()}`);
101
+ log(`Logged in as ${EMAIL}, token expires ${new Date(tokenExp * 1000).toISOString()}, refresh: ${refreshToken ? 'captured' : 'none'}`);
97
102
  }
98
103
 
99
104
  async function ensureAuth() {
@@ -105,13 +110,18 @@ async function ensureAuth() {
105
110
  _authPromise = (async () => {
106
111
  if (refreshToken) {
107
112
  try {
108
- const data = await apiFetch('/api/v2/iam/refresh', {
113
+ const rres = await fetch(`${BASE_URL}/api/v2/iam/refresh`, {
109
114
  method: 'POST',
115
+ headers: { 'Content-Type': 'application/json' },
110
116
  body: JSON.stringify({ refreshToken }),
111
117
  });
118
+ const data = await rres.json().catch(() => ({}));
112
119
  if (data.ok) {
113
- accessToken = data.accessToken || data.data?.accessToken || data.data?.token;
114
- refreshToken = data.refreshToken || data.data?.refreshToken || refreshToken;
120
+ const nextAccess = pickAccessToken(data);
121
+ const nextRefresh = extractRefreshToken(data, rres.headers.getSetCookie?.() ?? []);
122
+ accessToken = nextAccess;
123
+ // Ротация: берём НОВЫЙ токен; старый мёртв — fallback на старый замаскировал бы потерю.
124
+ refreshToken = nextRefresh;
115
125
  tokenExp = decodeExp(accessToken);
116
126
  log('Token refreshed');
117
127
  return;
@@ -426,7 +436,7 @@ list_workspaces → switch_workspace (required), or create_workspace.
426
436
 
427
437
  ## Tool discovery
428
438
  Only core tools are active from the start; search_tools(keyword) activates groups on demand and reports what it activated.
429
- docs_map(), docs_search(query), ask_advisor(question) read the platform docs corpus from the start — use them before guessing.
439
+ docs_map(), docs_search(query) read the platform docs corpus from the start; ask_advisor(question) reads it too but belongs to the advisor group — activate it first with search_tools("advisor"). Use them before guessing.
430
440
  Similar names are NOT interchangeable (set_grant vs set_portal_config): verify the exact name before a confirmation-gated call; never substitute a similar active tool.
431
441
 
432
442
  ## PM task policy
@@ -958,7 +968,7 @@ export const EN_DESCRIPTIONS = {
958
968
  report_bulk_update: 'Bulk-update records via SET expressions on report columns (requires confirmation). Works only if the report has SET columns. Returns: { count, preview } or a confirmation status.',
959
969
  set_report_visibility: 'Show or hide a report in the list.',
960
970
  // Grants / permissions
961
- list_members: 'Show all workspace users with their roles and access level. Use for "show users", "who has access", "permissions", "member list" (admin only). Returns: { items:[{id,userId,email,name,username,role,roleId,roleName,lastSeenAt}], total }, where id is the membership ID (needed for remove_member and update_member_role — it is NOT userId), lastSeenAt — last visit, null if never visited.',
971
+ list_members: 'Show all workspace users with their roles and access level. Use for "show users", "who has access", "permissions", "member list" (admin only). Returns: { items:[{membershipId,userId,email,name,username,role,roleId,roleName,lastSeenAt}], total }, where membershipId is the membership ID (needed for remove_member and update_member_role — it is NOT userId), lastSeenAt — last visit, null if never visited.',
962
972
  list_roles: 'Show all roles and their access rights to object types (READ/WRITE/ADMIN). Use for "what roles exist", "role permissions", "what can an editor do" (admin only). Returns: { items:[{id,name}], total }.',
963
973
  list_domain_roles: 'List domain (quartet) role assignments — the narrowing layer on top of the system role: effective access = min(system role, domain role), owner/admin unaffected. Returns: { items:[{id,username,email,role,roleId,roleName}] } (admin only).',
964
974
  set_domain_role: 'Assign a domain (quartet) role to a user — a custom workspace role that can ONLY narrow their grants (it can never expand access). roleId=null clears the assignment. The role must be a custom role of THIS workspace (see list_roles) and the user must be a member. Requires confirmation (admin only). NOT a replacement for set_grant: regular role grants — set_grant.',
@@ -1256,7 +1266,7 @@ export const EN_DESCRIPTIONS = {
1256
1266
  // Normalizer
1257
1267
  start_normalization: 'Start normalization of files from a folder. mode=auto — fully automatic; mode=assisted — with schema confirmation. Returns a jobId for tracking.',
1258
1268
  get_normalization_status: 'Get normalization job status by jobId.',
1259
- confirm_normalization_schema: 'Confirm the data schema designed by the normalizer (HITL step). Call when status.stage = "architecting".',
1269
+ confirm_normalization_schema: 'Confirm the data schema designed by the normalizer (HITL step). Call when status.stage = "architecting" AND status.schemaTables > 0 from get_normalization_status — the stage is set before the architect answers; at schemaTables = 0 the call returns "schema is still being built".',
1260
1270
  confirm_normalization_resolution: 'Confirm entity matching (deduplication). Call when pendingApprovals > 0.',
1261
1271
  cancel_normalization: 'Cancel a normalization job.',
1262
1272
  // Timeseries
@@ -1322,7 +1332,7 @@ export const EN_DESCRIPTIONS = {
1322
1332
  // Activity Intelligence
1323
1333
  get_team_activity: 'Team activity stats: messages, closed topics, tasks (including overdue), decisions, debates, reactions per member. Hot topics, blockers, recent decisions.',
1324
1334
  get_user_activity: 'Get activity for a specific user: messages, tasks (open/completed/overdue), decisions, blockers assigned to them.',
1325
- generate_team_digest: 'AI team digest: who completed what, blockers, overdue items, accepted decisions, participation balance.',
1335
+ generate_team_digest: 'AI team digest: who completed what, blockers, overdue items, accepted decisions, participation balance. Counts teamchat messages/topics, decisions and debates — PM tasks are NOT included — use pm_briefing for those.',
1326
1336
  // Orgs
1327
1337
  list_orgs: 'List organizations of the current user.',
1328
1338
  get_org: 'Get organization info by slug.',
@@ -1606,7 +1616,7 @@ async function dispatchTool(request) {
1606
1616
  return toolErrorResult(resumeErr);
1607
1617
  }
1608
1618
  return {
1609
- content: [{ type: 'text', text: typeof resumeData.data === 'string' ? resumeData.data : JSON.stringify(resumeData.data) }],
1619
+ content: [{ type: 'text', text: compactToolResult(name, resumeData.data) }],
1610
1620
  };
1611
1621
  } catch (e) {
1612
1622
  log(`Elicitation not supported by client or failed: ${e.message}`);
@@ -1628,7 +1638,7 @@ async function dispatchTool(request) {
1628
1638
  }
1629
1639
 
1630
1640
  return {
1631
- content: [{ type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result, null, 2) }],
1641
+ content: [{ type: 'text', text: compactToolResult(name, result) }],
1632
1642
  };
1633
1643
  } catch (err) {
1634
1644
  return toolErrorResult(err);
@@ -1644,11 +1654,17 @@ async function handleConfirmAction(approved, confirmId) {
1644
1654
  if (taken.error === 'EMPTY') {
1645
1655
  return { content: [{ type: 'text', text: 'No pending action to confirm.' }], isError: true };
1646
1656
  }
1657
+ // PM-1017: протухшее подтверждение (TTL 10 минут, очередь в памяти процесса) —
1658
+ // отдельный отказ: агент сразу повторяет операцию, а не ищет чужой confirmId.
1659
+ if (taken.error === 'EXPIRED') {
1660
+ return { content: [{ type: 'text', text: `Pending action expired (TTL ${Math.round(HITL_QUEUE_TTL_MS / 60000)} min). Repeat the operation to get a fresh confirmation.` }], isError: true };
1661
+ }
1647
1662
  if (taken.error === 'AMBIGUOUS') {
1648
1663
  return { content: [{ type: 'text', text: `Multiple pending actions; pass confirmId of the one the user approved: ${taken.available.join(', ')}.` }], isError: true };
1649
1664
  }
1650
1665
  if (taken.error === 'UNKNOWN_CONFIRM_ID') {
1651
- return { content: [{ type: 'text', text: `No pending action with confirmId "${confirmId}". Live ids: ${taken.available.join(', ') || 'none'}.` }], isError: true };
1666
+ const expiredNote = taken.expiredHint ? ' Older pending actions may have expired (TTL 10 min) — repeat the operation if this was one of them.' : '';
1667
+ return { content: [{ type: 'text', text: `No pending action with confirmId "${confirmId}". Live ids: ${taken.available.join(', ') || 'none'}.${expiredNote}` }], isError: true };
1652
1668
  }
1653
1669
 
1654
1670
  const pending = taken.entry;
package/output-cap.js ADDED
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Кэп размера ответа тула в MCP-прокси.
3
+ *
4
+ * Инцидент 19.10.2026: pm_list_issues(limit:100) вернул 242 КБ одним куском —
5
+ * клиент (Claude Code) выгрузил ответ в файл, модель его не видела. Прокси —
6
+ * единственное место, через которое проходят ВСЕ 779 тулов, и единственное,
7
+ * где кэпа не было: встроенный агент режет своё (runner.js
8
+ * _compactToolResultRaw, 16000 символов). Логика здесь — копия runner-версии
9
+ * с двумя отличиями:
10
+ * 1) бюджет 60000 символов (лимит клиента ~100 КБ — оставлен запас);
11
+ * 2) списки режутся ТОЛЬКО при переборе бюджета, а не по счёту (runner режет
12
+ * items>20 безусловно — для MCP это ломало бы легальные списки вроде
13
+ * get_lookup с 80 опциями).
14
+ *
15
+ * Контракт усечённого ответа (валидный JSON):
16
+ * _truncated: true — это часть, не полный ответ;
17
+ * _compacted — человекочитаемо: «Показано K из N», «X КБ из Y КБ»;
18
+ * _howToContinue — как дочитать, с настоящими именами аргументов;
19
+ * _tool, _originalSize — кто и сколько отдавал;
20
+ * total/offset/has_more/nextOffset/nextCursor — вынесены наверх ДО усечения,
21
+ * иначе тонут в обрезанном хвосте JSON.
22
+ * Синхронизировать с backend/src/api/v2/modules/ai/agent/runner.js при смене
23
+ * контракта (_truncated/_compacted) — там тот же конверт для встроенного агента.
24
+ */
25
+ const OUTPUT_MAX_CHARS = 60000;
26
+
27
+ // Размер ответа pivot/aggregate/group растёт от кардинальности: offset не
28
+ // помогает, лечится только сужением фильтра.
29
+ const CARDINALITY_RE = /^(pivot|aggregate|group)_/;
30
+
31
+ // Поля пагинации, которые обязаны пережить усечение.
32
+ const PROMOTED_FIELDS = ['total', 'offset', 'limit', 'has_more', 'nextOffset', 'nextCursor'];
33
+
34
+ const fmtKb = (n) => `${Math.max(1, Math.round(n / 1024))} КБ`;
35
+
36
+ // Частичный кусок режется ПОСЛЕ эскейпинга, а не фиксированной арифметикой:
37
+ // 58 000 кавычек при JSON.stringify превращаются в ~116 000 символов
38
+ // (\" \\), фиксированный slice(0, N) бюджет пробивает. Итеративно сжимаем,
39
+ // пока сериализованный кусок не влезет.
40
+ function fitPartial(raw, budget) {
41
+ let s = raw.slice(0, budget);
42
+ while (s.length > 500 && JSON.stringify(s).length > budget) {
43
+ s = s.slice(0, Math.max(500, Math.floor(s.length * budget / JSON.stringify(s).length) - 64));
44
+ }
45
+ return s;
46
+ }
47
+
48
+ function envelope(toolName, fields, originalSize) {
49
+ return {
50
+ ...fields,
51
+ // Контрактные ключи — ПОСЛЕ спреда данных: результат тула не может
52
+ // подделать пометку «это часть» собственным _truncated/_tool/_compacted.
53
+ _truncated: true,
54
+ _tool: String(toolName ?? '').slice(0, 120),
55
+ _compacted: fields._compacted
56
+ ?? `Показана часть: ${fmtKb(fields.partial?.length ?? 0)} из ${fmtKb(originalSize)}. Это НЕ полный ответ.`,
57
+ _originalSize: originalSize,
58
+ };
59
+ }
60
+
61
+ function howToContinue(toolName, result, keptCount = null) {
62
+ if (CARDINALITY_RE.test(toolName)) {
63
+ return 'Число групп/значений превышает лимит вывода. Сузь запрос фильтром — повторение с offset или большим limit не поможет.';
64
+ }
65
+ if (keptCount === 0) {
66
+ // Ни один item не влез целиком — offset вести в пустоту, честный совет — сузить.
67
+ return 'Записи слишком велики для лимита вывода. Сузь выборку фильтром или запроси меньше полей.';
68
+ }
69
+ if (typeof result?.nextOffset === 'number') {
70
+ return `Текст обрезан. Вызови ${toolName} снова с offset=${result.nextOffset} — продолжение с этого места.`;
71
+ }
72
+ if (result?.truncated === true && typeof result?.path === 'string') {
73
+ // read_blob: continuation-подсказка по его собственному протоколу
74
+ // (baseCommit при частичном чтении приходит null — про правку не упоминаем)
75
+ return `Файл обрезан. Вызови read_blob снова с offset=(прежний offset||0)+длина полученного content, чтобы дочитать.`;
76
+ }
77
+ if (Array.isArray(result?.items) && result.items.length > 0) {
78
+ // keptCount — сколько реально влезло; result.items.length — сколько было.
79
+ const next = (Number(result.offset) || 0) + (keptCount ?? result.items.length);
80
+ return `Повтори ${toolName} с offset=${next} — следующая страница. Вместо большого limit сужай выборку фильтрами/поиском: много адресных запросов лучше одного широкого.`;
81
+ }
82
+ return `Ответ обрезан по размеру. Повтори ${toolName} с более узким фильтром или поиском: много адресных запросов лучше одного широкого.`;
83
+ }
84
+
85
+ export function compactToolResult(toolName, result) {
86
+ // toolName приходит невалидированным из JSON-RPC — зажимаем до любого
87
+ // использования (входит в _tool и в тексты _howToContinue).
88
+ toolName = String(toolName ?? '').slice(0, 120);
89
+ // Строковые ответы: маленькие — как есть, большие — partial-конверт.
90
+ if (typeof result === 'string') {
91
+ if (result.length <= OUTPUT_MAX_CHARS) return result;
92
+ return JSON.stringify(envelope(toolName, { partial: fitPartial(result, OUTPUT_MAX_CHARS - 2000) }, result.length));
93
+ }
94
+ if (result == null || typeof result !== 'object') {
95
+ return JSON.stringify(result ?? null);
96
+ }
97
+
98
+ const raw = JSON.stringify(result, null, 2);
99
+ if (raw.length <= OUTPUT_MAX_CHARS) return raw;
100
+
101
+ const promoted = {};
102
+ for (const f of PROMOTED_FIELDS) {
103
+ const v = result[f];
104
+ if (v === undefined) continue;
105
+ // Строковые токены (nextCursor) зажимаем: гигантский курсор от сбойного
106
+ // тула не должен пробивать бюджет ни в одной ветке.
107
+ promoted[f] = typeof v === 'string' && v.length > 1000 ? v.slice(0, 1000) : v;
108
+ }
109
+
110
+ let fields = null;
111
+
112
+ // Текстовые тела (read_file/download_file — как в runner.js): метаданные
113
+ // сохраняем целиком, режем только тело. Сжатие ПОСЛЕ сериализации:
114
+ // newlines/кавычки текста удваиваются в JSON, арифметика по сырым символам
115
+ // бюджет пробивает.
116
+ const textKey = result.extractedText != null ? 'extractedText' : result.base64 != null ? 'base64' : null;
117
+ if (textKey) {
118
+ const meta = { ...result };
119
+ delete meta[textKey];
120
+ delete meta._compacted; // данные тула не перебивают честную пометку конверта
121
+ const fullText = String(result[textKey]);
122
+ const metaJson = JSON.stringify(meta, null, 2);
123
+ const textBudget = Math.max(OUTPUT_MAX_CHARS - metaJson.length - textKey.length - 200, 500);
124
+ if (fullText.length > textBudget) {
125
+ let shown = fullText.slice(0, textBudget);
126
+ const build = (s) => JSON.stringify(envelope(toolName, {
127
+ _compacted: `Текст обрезан: показано ${fmtKb(s.length)} из ${fmtKb(fullText.length)}.`,
128
+ ...meta,
129
+ [textKey]: s,
130
+ _howToContinue: textKey === 'extractedText'
131
+ ? `Текст обрезан. Вызови ${toolName} снова с offset=${(Number(result.offset) || 0) + s.length} — продолжение с этого места.`
132
+ : `Содержимое обрезано (${fmtKb(s.length)} из ${fmtKb(fullText.length)}). Загружай файл по частям меньшего размера.`,
133
+ }, raw.length));
134
+ let out = build(shown);
135
+ while (out.length > OUTPUT_MAX_CHARS && shown.length > 500) {
136
+ shown = shown.slice(0, Math.max(500, Math.floor(shown.length * OUTPUT_MAX_CHARS / out.length) - 64));
137
+ out = build(shown);
138
+ }
139
+ fields = JSON.parse(out); // конверт уже собран — идёт в общий страж ниже
140
+ }
141
+ }
142
+
143
+ // Списки: держим префикс items, влезающий в бюджет вместе с прочими полями
144
+ // и конвертом. Режем только при переборе бюджета, не по счёту.
145
+ if (!fields && Array.isArray(result.items) && result.items.length > 0) {
146
+ const kept = [];
147
+ let size = JSON.stringify({ ...result, items: kept, ...promoted }, null, 2).length + 800;
148
+ for (const item of result.items) {
149
+ kept.push(item);
150
+ size += JSON.stringify(item, null, 2).length + 2;
151
+ if (size > OUTPUT_MAX_CHARS) { kept.pop(); break; }
152
+ }
153
+ // result-owned _compacted не перебивает наш (спред результата — после него,
154
+ // поэтому выкидываем ключ из копии до спреда)
155
+ const { _compacted: drop, ...rest } = result;
156
+ fields = {
157
+ _compacted: `Показано ${kept.length} из ${result.items.length} записей (полный ответ ${fmtKb(raw.length)}). Это НЕ полный ответ.`,
158
+ ...promoted,
159
+ ...rest,
160
+ items: kept,
161
+ _howToContinue: howToContinue(toolName, result, kept.length),
162
+ };
163
+ }
164
+
165
+ if (!fields) {
166
+ fields = {
167
+ _compacted: `Показана часть: ${fmtKb(OUTPUT_MAX_CHARS - 2000)} из ${fmtKb(raw.length)}. Это НЕ полный ответ.`,
168
+ ...promoted,
169
+ partial: fitPartial(raw, OUTPUT_MAX_CHARS - 2000),
170
+ _howToContinue: howToContinue(toolName, result),
171
+ };
172
+ }
173
+
174
+ let out = JSON.stringify(envelope(toolName, fields, raw.length));
175
+ // Единственный честный выход при переборе: конверт с куском сырого JSON;
176
+ // бюджет partial урезается на размер promoted, чтобы и здесь влезть.
177
+ if (out.length > OUTPUT_MAX_CHARS) {
178
+ const promotedJson = JSON.stringify(promoted);
179
+ out = JSON.stringify(envelope(toolName, {
180
+ _compacted: `Показана часть: ${fmtKb(OUTPUT_MAX_CHARS - 2000)} из ${fmtKb(raw.length)}. Это НЕ полный ответ.`,
181
+ ...promoted,
182
+ partial: fitPartial(raw, Math.max(OUTPUT_MAX_CHARS - 2000 - promotedJson.length, 500)),
183
+ _howToContinue: howToContinue(toolName, result),
184
+ }, raw.length));
185
+ }
186
+ return out;
187
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "integram-mcp",
3
- "version": "0.7.150",
3
+ "version": "0.7.154",
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,8 +26,10 @@
26
26
  "files": [
27
27
  "index.js",
28
28
  "activation-memory.js",
29
+ "output-cap.js",
29
30
  "pending-hitl.js",
30
- "orphan-watchdog.js"
31
+ "orphan-watchdog.js",
32
+ "auth-token.js"
31
33
  ],
32
34
  "dependencies": {
33
35
  "@modelcontextprotocol/sdk": "^1.12.1",
package/pending-hitl.js CHANGED
@@ -37,16 +37,27 @@ export function enqueuePending(queue, entry, { now, ttlMs, maxSize }) {
37
37
  * @returns {{ entry: object, remaining: number } | { error: string, available: string[] }}
38
38
  */
39
39
  export function takePending(queue, confirmId, { now = Date.now(), ttlMs } = {}) {
40
+ const prePurge = queue.length;
40
41
  if (ttlMs != null) {
41
42
  while (queue.length && queue[0].createdAt < now - ttlMs) queue.shift();
42
43
  }
44
+ const expiredCount = prePurge - queue.length;
43
45
  const available = queue.map((e) => e.id);
44
- if (!queue.length) return { error: 'EMPTY', available: [] };
46
+ if (!queue.length) {
47
+ // PM-1017: «протухло» и «не было» — разные отказы: агент по EXPIRED понимает,
48
+ // что операцию надо ПОВТОРИТЬ, а не искать чужой confirmId.
49
+ if (expiredCount > 0) return { error: 'EXPIRED', available: [], expiredCount };
50
+ return { error: 'EMPTY', available: [] };
51
+ }
45
52
  if (confirmId == null) {
46
53
  if (queue.length > 1) return { error: 'AMBIGUOUS', available };
47
54
  return { entry: queue.shift(), remaining: queue.length };
48
55
  }
49
56
  const idx = queue.findIndex((e) => e.id === confirmId);
50
- if (idx === -1) return { error: 'UNKNOWN_CONFIRM_ID', available };
57
+ if (idx === -1) {
58
+ // Именованный id мог протухнуть, пока очередь жива другими ожиданиями, —
59
+ // точного различения нет (историю id не храним), подсказываем обе причины.
60
+ return { error: 'UNKNOWN_CONFIRM_ID', available, expiredHint: expiredCount > 0 };
61
+ }
51
62
  return { entry: queue.splice(idx, 1)[0], remaining: queue.length };
52
63
  }