integram-mcp 0.7.131 → 0.7.135

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.
Files changed (3) hide show
  1. package/README.md +4 -4
  2. package/index.js +46 -10
  3. package/package.json +1 -1
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.131
18
+ -- npx -y integram-mcp@0.7.135
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.131
52
+ -- npx -y integram-mcp@0.7.135
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.131"],
66
+ "args": ["-y", "integram-mcp@0.7.135"],
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.131"],
86
+ "args": ["-y", "integram-mcp@0.7.135"],
87
87
  "env": {
88
88
  "INTEGRAM_URL": "https://ai2o.online",
89
89
  "INTEGRAM_EMAIL": "you@example.com",
package/index.js CHANGED
@@ -241,6 +241,10 @@ export function withUpdateNotice(result) {
241
241
  extra.push(memoryBriefing);
242
242
  memoryBriefing = null; // one-shot: один брифинг на выбор воркспейса
243
243
  }
244
+ if (instanceNotice) {
245
+ extra.push(instanceNotice);
246
+ instanceNotice = null; // one-shot: блок платформы — один раз на процесс
247
+ }
244
248
  if (!extra.length) return result;
245
249
  return { ...result, content: [...result.content, { type: 'text', text: extra.join('\n') }] };
246
250
  }
@@ -275,9 +279,20 @@ export function buildUnreadNoticeText(data) {
275
279
 
276
280
  let memoryBriefing = null; // текст текущего воркспейса, one-shot
277
281
  let memoryBriefingWs = null; // для какого воркспейса собран
282
+ // Инстанс-правила («Правила платформы») — уровень ПРОЦЕССА: блок платформы
283
+ // доставляется один раз на жизнь процесса. При старте без воркспейса он едет
284
+ // в приписке первого ответа; пер-воркспейсный брифинг после этого просит
285
+ // только воркспейсный слой (?scope=workspace). Рестарт процесса возвращает
286
+ // блок — та же семантика, что у совета по версии; это названная цена.
287
+ let instanceNotice = null; // one-shot текст блока платформы
288
+ let instanceDelivered = false; // блок уже доставлен в этой жизни процесса
278
289
 
279
290
  export function setMemoryBriefing(text, ws) { memoryBriefing = text; memoryBriefingWs = ws; }
280
291
 
292
+ // Тестам и (будущему) ручному обновлению слоя; instanceDelivered не сбрасываем —
293
+ // дедуп в пределах жизни процесса не должен обходиться через сеттер.
294
+ export function setInstanceNotice(text) { instanceNotice = text; }
295
+
281
296
  export function buildMemoryBriefingText({ rules, items }) {
282
297
  const parts = [];
283
298
  if (rules) parts.push(String(rules).trim());
@@ -298,11 +313,28 @@ async function checkMemoryBriefing() {
298
313
  // Фиксируем воркспейс ДО await: две быстрые смены подряд не должны дать
299
314
  // позднему ответу пометить текст чужим слагом (гоночная заметка ревью).
300
315
  const ws = workspace;
301
- if (!ws || memoryBriefingWs === ws) return;
316
+ // Без воркспейса — единственный шанс доставить инстанс-слой ДО первого
317
+ // выбора (сессия стартует с (none)); блок платформы eдет один раз на процесс.
318
+ if (!ws) {
319
+ if (instanceDelivered) return;
320
+ try {
321
+ await ensureAuth();
322
+ const res = await apiFetch('/api/v2/instance/swarm-memory/rules', { signal: AbortSignal.timeout(3000) });
323
+ const rules = (res.data || res)?.rules || '';
324
+ if (rules) {
325
+ instanceNotice = ['\n📎 Правила платформы (общие для всех воркспейсов):', String(rules).trim()].join('\n');
326
+ log(instanceNotice);
327
+ }
328
+ instanceDelivered = true; // ставим и при пустом слое — второй фетч не нужен
329
+ } catch { /* нет сети — при следующем (none)-вызове повторим */ }
330
+ return;
331
+ }
332
+ if (memoryBriefingWs === ws) return;
302
333
  try {
303
334
  await ensureAuth();
335
+ const rulesScope = instanceDelivered ? '?scope=workspace' : ''; // дедуп: блок платформы уже в контексте
304
336
  const [rulesRes, recallRes] = await Promise.all([
305
- apiFetch(`/api/v2/${ws}/swarm-memory/rules`, { signal: AbortSignal.timeout(3000) }),
337
+ apiFetch(`/api/v2/${ws}/swarm-memory/rules${rulesScope}`, { signal: AbortSignal.timeout(3000) }),
306
338
  apiFetch(`/api/v2/${ws}/swarm-memory/recall`, { signal: AbortSignal.timeout(3000) }),
307
339
  ]);
308
340
  if (memoryBriefingWs === ws) return; // воркспейс сменился, пока летел запрос
@@ -311,6 +343,8 @@ async function checkMemoryBriefing() {
311
343
  const text = buildMemoryBriefingText({ rules, items });
312
344
  setMemoryBriefing(text, ws);
313
345
  if (text) log(text);
346
+ // Без ?scope прилетели ОБА блока — инстанс-слой уже в контексте, дальше дедуп
347
+ if (!rulesScope) instanceDelivered = true;
314
348
  } catch { /* нет сети — сессия работает без брифинга */ }
315
349
  }
316
350
 
@@ -804,14 +838,16 @@ create_automation({ name, trigger: { type, typeId }, active?, condition, actions
804
838
  on_member_joined: событие member.joined — новый участник воркспейса (пригласительная ссылка); в действиях доступны {{memberUserId}}, {{memberEmail}}, {{memberRole}}, {{workspaceSlug}}, {{meta}}
805
839
  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}}')
806
840
  on_issue_commented / on_issue_updated: событие PM-задачи (комментарий / правка полей), pm-переменные те же
807
- - Actions: send_notification, send_notification_to_group, update_field, create_object, delete_object, fire_webhook, run_ai_agent, run_script, run_server_function, run_video_job, 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 (работает и с internal-агентами реестра воркспейса), 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, link_issue
841
+ - Actions: send_notification, send_notification_to_group, update_field, create_object, delete_object, fire_webhook, run_ai_agent, run_script, run_server_function, run_video_job, telegram_send_message, telegram_send_card, telegram_send_draft, telegram_send_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 (работает и с internal-агентами реестра воркспейса), invoke_agent, telegram_send_invoice, telegram_forward, telegram_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, telegram_answer_shipping, telegram_business_reply, create_issue, update_issue, link_issue
842
+ telegram_send_card — render a workspace record as a rich message (Bot API 10.1+, markdown template + inline buttons with callback `a:<automationId>:<objId>`). Params: botId, typeId, objId?, template, buttons[], chatId|recipients.
843
+ telegram_send_draft — stream a message draft to a private chat (Bot API 10.1+; same draft_id animates text growth). Params: botId, chatId, text, draftId?, parseMode?.
808
844
  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 взаимно исключают друг друга — конфликт отвергается при сохранении. Роль без резолвимых участников → задача без исполнителя + уведомление роли (или триггера), прогон не падает.
809
845
  link_issue: { issue_id?, issue_number?, target_type?, target_id? } — привязывает задачу к цели через data-links (issue_id или issue_number; без них берётся {{_created_issue_id}} предыдущего create_issue); 409 (связь уже стоит) считается успехом.
810
846
  update_issue: { id, title?, description?, issue_type?, status?, priority?, assignee_id?, sprint_id?, parent_id?, estimate?, due_date?, labels? } — правит PM-задачу; id можно взять из {{pm_issue_id}}
811
847
  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)
812
848
  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}}.
813
849
  run_video_job: { scenario, resultVar? } — queue a video-engine render job (scenario = steps[] + narration, the pipeline tts→record→assemble lives in the video-engine module). Does NOT wait for the render: jobId lands in {{_video_job_id}} and {{resultVar}}; status/result via /video-engine/jobs/:id. Sets {{_video_job_error}} on failure.
814
- 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}}.
850
+ telegram_send_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}}.
815
851
  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}}.
816
852
  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)
817
853
  - list_automations, get_automation (single), update_automation, delete_automation, trigger_automation (manual run), get_automation_runs (execution log)
@@ -949,7 +985,7 @@ Activate via search_tools("memory").
949
985
  - share_insight(key, value) — share with other agents in shared namespace
950
986
  - find_procedure(query) — find step-by-step recipes from memory
951
987
  - list_contradictions / resolve_contradiction — manage conflicting facts
952
- - Правила и топ-факты воркспейса сервер сам приписывает к первому ответу (recall для этого не зови); общие для ВСЕХ агентов правила пиши через add_rule — их подхватывает каждый внутренний агент.
988
+ - Правила и топ-факты воркспейса сервер сам приписывает к первому ответу (recall для этого не зови); правила воркспейса пиши через add_rule (без scope) — их подхватывает каждый внутренний агент. scope=instance — только admin, факты/указатели для всех воркспейсов инстанса.
953
989
 
954
990
  ## Portal (admin)
955
991
 
@@ -1040,7 +1076,7 @@ Bot reactions (commands + keywords) are stored as **automations** with trigger.b
1040
1076
  - Join request: trigger: { type: "on_telegram_join_request", botId: N, chatId? } — auto-approve/decline
1041
1077
  - Business connection: trigger: { type: "on_telegram_business_connection", botId: N }
1042
1078
  - Business message: trigger: { type: "on_telegram_business_message", botId: N }
1043
- Actions use send_telegram with chatId: "{{_tgChatId}}" to reply to sender.
1079
+ Actions use telegram_send_message with chatId: "{{_tgChatId}}" to reply to sender.
1044
1080
  Template vars: {{_tgCommand}}, {{_tgArgs}}, {{_tgChatId}}, {{_tgFromUsername}}, {{_tgFromFirstName}}, {{_tgMessage}}.
1045
1081
  Payment vars: {{_tgPaymentCurrency}}, {{_tgPaymentAmount}}, {{_tgPaymentPayload}}, {{_tgPaymentChargeId}}.
1046
1082
  Inline vars: {{_tgInlineQuery}}, {{_tgInlineQueryId}}, {{_tgInlineOffset}}.
@@ -1048,7 +1084,7 @@ Join vars: {{_tgJoinUserId}}, {{_tgJoinUsername}}, {{_tgJoinFirstName}}, {{_tgJo
1048
1084
  Business vars: {{_tgBusinessConnectionId}}, {{_tgBusinessUserId}}, {{_tgBusinessChatId}}, {{_tgBusinessCanReply}}.
1049
1085
  Filter automations by bot: list_automations with filter by trigger.botId (GET /automations?botId=N).
1050
1086
 
1051
- **Multi-screen keyboards (screens):** send_telegram supports hierarchical navigation via \`screens\`:
1087
+ **Multi-screen keyboards (screens):** telegram_send_message supports hierarchical navigation via \`screens\`:
1052
1088
  \`\`\`
1053
1089
  { screens: {
1054
1090
  main: { text: "Menu", buttons: [{ text: "Orders", go: "orders" }] },
@@ -1765,9 +1801,9 @@ export const EN_DESCRIPTIONS = {
1765
1801
  list_contradictions: 'Show unresolved contradictions in memory. Use when you need to clarify with the user what is current.',
1766
1802
  resolve_contradiction: 'Resolve a contradiction between two memory facts after clarifying with the user.',
1767
1803
  find_procedure: 'Find a procedure (step-by-step recipe) in memory by topic. Use before complex operations.',
1768
- list_rules: 'Show all workspace rules — positive instructions all agents must follow.',
1769
- add_rule: 'Add a workspace rule — a positive instruction for all agents (max 500 chars, up to 50 rules).',
1770
- remove_rule: 'Remove a workspace rule by key. Get keys via list_rules.',
1804
+ list_rules: 'Show rules — workspace layer by default, or the instance layer (scope=instance: facts/pointers for ALL workspaces).',
1805
+ add_rule: 'Add a workspace rule — a positive instruction for all agents (max 500 chars, up to 50 rules). scope=instance: admin-only, max 300 chars, FACT or POINTER only, never a directive (lands in every workspace context; keep the layer under ~10 entries).',
1806
+ remove_rule: 'Remove a rule by key. Get keys via list_rules.',
1771
1807
  list_shared_memories: 'List shared memories available to all agents.',
1772
1808
  get_shared_state: 'Get a value from the shared state. Without a key — all entries.',
1773
1809
  set_shared_state: 'Set a value in the shared state to coordinate between agents.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "integram-mcp",
3
- "version": "0.7.131",
3
+ "version": "0.7.135",
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",