acpgram 0.0.0-stage → 1.12.0

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/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "acpgram",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.12.0",
4
+ "type": "module",
5
+ "description": "Telegram gateway to AI coding agents (Gemini CLI, Claude Code, Antigravity CLI, Codex) over the Agent Client Protocol",
6
+ "license": "MIT",
7
+ "author": "Alexey Seleznev",
8
+ "keywords": [
9
+ "telegram",
10
+ "telegram-bot",
11
+ "agent-client-protocol",
12
+ "acp",
13
+ "gemini-cli",
14
+ "claude-code",
15
+ "antigravity",
16
+ "codex",
17
+ "ai",
18
+ "llm",
19
+ "cli"
20
+ ],
21
+ "homepage": "https://github.com/selesnow/acpgram#readme",
22
+ "bugs": {
23
+ "url": "https://github.com/selesnow/acpgram/issues"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/selesnow/acpgram.git"
28
+ },
29
+ "bin": {
30
+ "acpgram": "./src/cli.mjs"
31
+ },
32
+ "files": [
33
+ "src",
34
+ "README*.md",
35
+ "LICENSE"
36
+ ],
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "engines": {
41
+ "node": ">=22.13.0"
42
+ },
43
+ "scripts": {
44
+ "start": "node --disable-warning=ExperimentalWarning src/main.mjs",
45
+ "setup": "node --disable-warning=ExperimentalWarning src/setup.mjs",
46
+ "service:install": "node src/service.mjs install",
47
+ "service:uninstall": "node src/service.mjs uninstall",
48
+ "service:status": "node src/service.mjs status",
49
+ "test": "node --test \"test/**/*.test.mjs\"",
50
+ "prepublishOnly": "npm test"
51
+ }
52
+ }
package/src/access.mjs ADDED
@@ -0,0 +1,238 @@
1
+ // Права сотрудников на движки и модели, каталоги моделей движков и выбор модели / уровня рассуждений пользователя.
2
+ //
3
+ // - Движки: сотруднику по умолчанию доступен только движок по умолчанию (DEFAULT_ENGINE), остальные выдаёт администратор.
4
+ // - Модели: по умолчанию все модели движка; администратор может оставить сотруднику только часть (отдельно по движкам).
5
+ // - Администратору доступно всё.
6
+ // - Каталог (список моделей и уровней рассуждений) присылает сам агент в ответе session/new; бот хранит его в settings.
7
+ import { tmpdir } from 'node:os';
8
+ import { ADMIN_ID, db, langOf, log } from './ctx.mjs';
9
+ import { DEFAULT_ENGINE, ENGINES, autoValue, createAgent, isAuthError, isAvailable, parseCatalog, selectionRequest, setNeedsLogin } from './engines.mjs';
10
+ import { t } from './i18n.mjs';
11
+
12
+ const parseJson = (s, fallback) => {
13
+ try {
14
+ return s ? JSON.parse(s) : fallback;
15
+ } catch {
16
+ return fallback;
17
+ }
18
+ };
19
+ const isEngineId = (id) => typeof id === 'string' && Object.hasOwn(ENGINES, id);
20
+
21
+ // ---------- каталоги ----------
22
+
23
+ /** @returns {{models: {id,name}[], efforts: {id,name}[], defaultModel: string|null, defaultEffort: string|null, at: string}|null} */
24
+ export const getCatalog = (engineId) => (isEngineId(engineId) ? parseJson(db.getSetting(`catalog:${engineId}`), null) : null);
25
+
26
+ /**
27
+ * Сохраняет каталог из ответа session/new чистой сессии (probeCatalog). Пустой список не затирает ранее полученный:
28
+ * агент мог ответить урезанно (сбой, другая модель с другим набором уровней рассуждений).
29
+ */
30
+ export function saveCatalog(engine, res) {
31
+ const c = parseCatalog(engine, res);
32
+ const old = getCatalog(engine.id);
33
+ if (!c.models.length && !c.efforts.length) return old;
34
+ const catalog = {
35
+ models: c.models.length ? c.models : old?.models ?? [],
36
+ efforts: c.efforts.length ? c.efforts : old?.efforts ?? [],
37
+ defaultModel: c.defaultModel ?? old?.defaultModel ?? null,
38
+ defaultEffort: c.defaultEffort ?? old?.defaultEffort ?? null,
39
+ at: new Date().toISOString(),
40
+ };
41
+ db.setSetting(`catalog:${engine.id}`, JSON.stringify(catalog));
42
+ return catalog;
43
+ }
44
+
45
+ const probes = new Map(); // движок → идущий запрос каталога (не запускаем агента повторно)
46
+ const probeAgents = new Set(); // запущенные для этого агенты — при остановке бота завершаются вместе с ним
47
+
48
+ /** Завершает агентов, запущенных за списком моделей (при остановке бота: зависший движок не должен держать службу). */
49
+ export function killProbes() {
50
+ for (const a of probeAgents) a.close();
51
+ probeAgents.clear();
52
+ }
53
+ const probeFailedAt = new Map(); // движок → время неудачи (пауза перед повтором)
54
+ const PROBE_RETRY_MS = 5 * 60_000;
55
+
56
+ /**
57
+ * Короткий запуск агента без запроса (в tmpdir, с настройками по умолчанию) — только чтобы узнать его модели и уровни
58
+ * рассуждений. Одновременно не больше одного запуска на движок; после неудачи — пауза PROBE_RETRY_MS.
59
+ */
60
+ export function probeCatalog(engine, timeoutMs = 120_000) {
61
+ if (probes.has(engine.id)) return probes.get(engine.id);
62
+ if (Date.now() - (probeFailedAt.get(engine.id) ?? 0) < PROBE_RETRY_MS) return Promise.reject(new Error('недавняя попытка не удалась, повтор позже'));
63
+ const run = (async () => {
64
+ const a = createAgent(engine, { cwd: tmpdir(), onPermission: async () => ({ outcome: 'cancelled' }) });
65
+ probeAgents.add(a);
66
+ let timer;
67
+ try {
68
+ const res = await Promise.race([a.init(null), new Promise((_, rej) => (timer = setTimeout(() => rej(new Error('нет ответа')), timeoutMs)))]);
69
+ probeFailedAt.delete(engine.id);
70
+ setNeedsLogin(engine.id, false);
71
+ return saveCatalog(engine, res);
72
+ } catch (e) {
73
+ probeFailedAt.set(engine.id, Date.now());
74
+ setNeedsLogin(engine.id, isAuthError(e)); // нужен вход или ключ API — движок виден, но с предупреждением в /engine
75
+ throw e;
76
+ } finally {
77
+ clearTimeout(timer);
78
+ a.close(); // завершает агента вместе с дочерними процессами — и при ответе, и при тайм-ауте
79
+ probeAgents.delete(a);
80
+ probes.delete(engine.id);
81
+ }
82
+ })();
83
+ probes.set(engine.id, run);
84
+ return run;
85
+ }
86
+
87
+ /** Обновляет каталоги всех доступных движков по очереди (в фоне при старте бота). */
88
+ export async function refreshCatalogs() {
89
+ for (const e of Object.values(ENGINES).filter((x) => isAvailable(x.id))) {
90
+ try {
91
+ const c = await probeCatalog(e);
92
+ log(`${e.label}: моделей ${c?.models.length ?? 0}, уровней рассуждений ${c?.efforts.length ?? 0}`);
93
+ } catch (err) {
94
+ log(`⚠️ ${e.label}: не удалось получить список моделей — ${err.message}`);
95
+ }
96
+ }
97
+ }
98
+
99
+ // ---------- права ----------
100
+
101
+ /** Движки, выданные сотруднику (всегда с движком по умолчанию); администратору — все. Без учёта доступности на сервере. */
102
+ export function grantedEngines(userId) {
103
+ if (userId === ADMIN_ID) return Object.keys(ENGINES);
104
+ const extra = parseJson(db.getUser(userId)?.engines, []);
105
+ return [DEFAULT_ENGINE, ...Object.keys(ENGINES).filter((id) => id !== DEFAULT_ENGINE && Array.isArray(extra) && extra.includes(id))];
106
+ }
107
+
108
+ /** Можно ли пользователю работать в движке сейчас: выдан и запускается на сервере. */
109
+ export const canUseEngine = (userId, id) => isEngineId(id) && isAvailable(id) && grantedEngines(userId).includes(id);
110
+
111
+ /** Движки, которые пользователь может выбрать в /engine. */
112
+ export const userEngines = (userId) => grantedEngines(userId).filter((id) => isAvailable(id)).map((id) => ENGINES[id]);
113
+
114
+ /** Выдаёт или забирает у сотрудника движок (кроме движка по умолчанию). Возвращает новый список выданных. */
115
+ export function setEngineGrant(userId, engineId, on) {
116
+ if (!isEngineId(engineId) || engineId === DEFAULT_ENGINE) return grantedEngines(userId);
117
+ const extra = new Set(grantedEngines(userId).filter((id) => id !== DEFAULT_ENGINE));
118
+ if (on) extra.add(engineId);
119
+ else extra.delete(engineId);
120
+ db.setUserEngines(userId, [...extra]);
121
+ return grantedEngines(userId);
122
+ }
123
+
124
+ /** Ограничение моделей сотрудника в движке: список разрешённых id или null (разрешены все). */
125
+ export function modelRestriction(userId, engineId) {
126
+ if (userId === ADMIN_ID) return null;
127
+ const list = parseJson(db.getUser(userId)?.models, {})?.[engineId];
128
+ return Array.isArray(list) ? list : null;
129
+ }
130
+
131
+ /** Сколько моделей каталога разрешено сотруднику (модели, исчезнувшие из каталога, не считаются); null — все. */
132
+ export const allowedCount = (userId, engineId) => (modelRestriction(userId, engineId) ? allowedModels(userId, engineId).length : null);
133
+
134
+ /** Модели движка, доступные пользователю (из каталога). */
135
+ export function allowedModels(userId, engineId) {
136
+ const models = getCatalog(engineId)?.models ?? [];
137
+ const r = modelRestriction(userId, engineId);
138
+ return r ? models.filter((m) => r.includes(m.id)) : models;
139
+ }
140
+
141
+ /**
142
+ * Включает или выключает модель в ограничении сотрудника. Если включены все — ограничение снимается.
143
+ * Последнюю разрешённую модель выключить нельзя. Возвращает {ok, restriction}.
144
+ */
145
+ export function toggleModel(userId, engineId, modelId) {
146
+ const all = (getCatalog(engineId)?.models ?? []).map((m) => m.id);
147
+ if (!all.includes(modelId)) return { ok: false, restriction: modelRestriction(userId, engineId) };
148
+ // считаем только модели из каталога: исчезнувшие id не должны мешать проверке «последней модели»
149
+ const set = new Set((modelRestriction(userId, engineId) ?? all).filter((id) => all.includes(id)));
150
+ if (set.has(modelId)) {
151
+ if (set.size === 1) return { ok: false, restriction: [...set] };
152
+ set.delete(modelId);
153
+ } else set.add(modelId);
154
+ const map = parseJson(db.getUser(userId)?.models, {}) || {};
155
+ const list = all.filter((id) => set.has(id));
156
+ if (list.length === all.length) delete map[engineId];
157
+ else map[engineId] = list;
158
+ db.setUserModels(userId, map);
159
+ return { ok: true, restriction: modelRestriction(userId, engineId) };
160
+ }
161
+
162
+ /** Снимает ограничение моделей сотрудника в движке. */
163
+ export function allowAllModels(userId, engineId) {
164
+ const map = parseJson(db.getUser(userId)?.models, {}) || {};
165
+ delete map[engineId];
166
+ db.setUserModels(userId, map);
167
+ }
168
+
169
+ // ---------- выбор пользователя ----------
170
+
171
+ const choiceKey = (userId, engineId, kind) => `${kind}:${userId}:${engineId}`;
172
+
173
+ /** Запоминает выбор модели или уровня рассуждений; null — «Авто» (как у агента по умолчанию). */
174
+ export const saveChoice = (userId, engineId, kind, value) => db.setSetting(choiceKey(userId, engineId, kind), value ?? null);
175
+
176
+ /**
177
+ * Модель и уровень рассуждений, с которыми пользователь должен работать в движке.
178
+ * null — настройка агента по умолчанию. Недоступный (запрещённый, исчезнувший из каталога) выбор не применяется;
179
+ * при ограничении моделей «Авто» недоступно — берётся первая разрешённая модель.
180
+ */
181
+ export function effectiveSelection(userId, engine) {
182
+ const catalog = getCatalog(engine.id);
183
+ const models = allowedModels(userId, engine.id);
184
+ let model = db.getSetting(choiceKey(userId, engine.id, 'model'));
185
+ if (model && !models.some((m) => m.id === model)) model = null;
186
+ if (!model && modelRestriction(userId, engine.id)) model = models[0]?.id ?? null;
187
+ let effort = db.getSetting(choiceKey(userId, engine.id, 'effort'));
188
+ if (effort && !(catalog?.efforts ?? []).some((e) => e.id === effort)) effort = null;
189
+ return { model, effort };
190
+ }
191
+
192
+ /** Название модели / уровня по каталогу. */
193
+ export function choiceName(engine, kind, value) {
194
+ const catalog = getCatalog(engine.id);
195
+ const list = kind === 'model' ? catalog?.models : catalog?.efforts;
196
+ return list?.find((x) => x.id === value)?.name ?? value;
197
+ }
198
+
199
+ /** Запрос нельзя выполнить в разрешённой модели — его не отправляем (ограничение моделей не должно «протекать»). */
200
+ export class ModelAccessError extends Error {
201
+ code = 'MODEL_ACCESS';
202
+ }
203
+
204
+ /**
205
+ * Приводит модель и уровень рассуждений живой сессии к выбору пользователя (перед каждым запросом).
206
+ * a.applied — что бот уже выставил в этой сессии (undefined — ничего, у агента его значение по умолчанию; '?' — неизвестно).
207
+ * При ограничении моделей сбой не прощается: бросает ModelAccessError, и запрос не отправляется.
208
+ */
209
+ export async function syncSelection(userId, a) {
210
+ const engine = a.engine;
211
+ const restricted = Boolean(modelRestriction(userId, engine.id));
212
+ const want = effectiveSelection(userId, engine);
213
+ if (restricted && !want.model) {
214
+ throw new ModelAccessError(t('access.noModels', langOf(userId), { engine: engine.label }));
215
+ }
216
+ a.applied ??= {};
217
+ for (const kind of ['model', 'effort']) {
218
+ if (kind === 'effort' && !engine.effortConfig) continue;
219
+ const target = want[kind];
220
+ const current = a.applied[kind];
221
+ if (target === (current ?? null)) continue;
222
+ // вернуться к «Авто» нужно, только если бот раньше выставлял своё значение
223
+ const value = target ?? (current != null ? autoValue(engine, getCatalog(engine.id), kind) : null);
224
+ if (value == null) continue;
225
+ try {
226
+ await a.request(...selectionRequest(engine, a.sessionId, kind, value));
227
+ a.applied[kind] = target;
228
+ // у новой модели может быть свой уровень рассуждений по умолчанию — выставляем его заново в этом же проходе
229
+ if (kind === 'model' && engine.effortConfig) a.applied.effort = '?';
230
+ } catch (e) {
231
+ log(`⚠️ ${engine.label}: не удалось выставить ${kind} = ${value}: ${e.message}`);
232
+ a.applied[kind] = '?'; // что сейчас в сессии — неизвестно, в следующий раз выставим снова
233
+ if (kind === 'model' && restricted) {
234
+ throw new ModelAccessError(t('access.switchFail', langOf(userId), { engine: engine.label, model: choiceName(engine, 'model', value) }));
235
+ }
236
+ }
237
+ }
238
+ }
package/src/acp.mjs ADDED
@@ -0,0 +1,225 @@
1
+ // Минимальный клиент Agent Client Protocol (JSON-RPC 2.0, построчный JSON по stdin/stdout)
2
+ // для запуска ACP-агента (Gemini CLI, Claude Code, Antigravity CLI) как подпроцесса. Движки — в engines.mjs.
3
+ import { spawn, spawnSync } from 'node:child_process';
4
+ import readline from 'node:readline';
5
+
6
+ const IS_WIN = process.platform === 'win32';
7
+
8
+ /** Запуск команды с учётом ОС. На Windows .cmd запускается только через оболочку. */
9
+ export function spawnCommand(command, args, opts = {}) {
10
+ if (IS_WIN) {
11
+ const q = (s) => (/\s/.test(s) ? `"${s}"` : s);
12
+ return spawn([command, ...args].map(q).join(' '), { ...opts, shell: true, windowsHide: true });
13
+ }
14
+ // своя группа процессов, чтобы при остановке завершить и всех потомков
15
+ return spawn(command, args, { ...opts, detached: true });
16
+ }
17
+
18
+ /** Завершает процесс вместе со всеми дочерними. */
19
+ export function killTree(proc, graceMs = 3000) {
20
+ if (!proc?.pid) return;
21
+ if (IS_WIN) {
22
+ spawnSync('taskkill', ['/pid', String(proc.pid), '/T', '/F'], { windowsHide: true });
23
+ return;
24
+ }
25
+ const signal = (sig) => {
26
+ try {
27
+ process.kill(-proc.pid, sig);
28
+ } catch {} // группа уже завершилась
29
+ };
30
+ signal('SIGTERM');
31
+ setTimeout(() => signal('SIGKILL'), graceMs).unref();
32
+ }
33
+
34
+ /**
35
+ * Проверяет, что команда агента запускается: `<команда> --version`.
36
+ * @returns {Promise<{ok: boolean, version?: string, error?: string, timeout?: boolean}>}
37
+ */
38
+ export function checkCommand(command, args = ['--version'], timeoutMs = 60_000) {
39
+ return new Promise((resolve) => {
40
+ let out = '';
41
+ let err = '';
42
+ let proc;
43
+ try {
44
+ proc = spawnCommand(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
45
+ } catch (e) {
46
+ return resolve({ ok: false, error: e.message });
47
+ }
48
+ const timer = setTimeout(() => {
49
+ killTree(proc, 0);
50
+ resolve({ ok: false, timeout: true, error: `нет ответа за ${timeoutMs / 1000} с` });
51
+ }, timeoutMs);
52
+ proc.stdout.on('data', (d) => (out += d));
53
+ proc.stderr.on('data', (d) => (err += d));
54
+ proc.on('error', (e) => {
55
+ clearTimeout(timer);
56
+ resolve({ ok: false, error: e.message });
57
+ });
58
+ // 'close', а не 'exit': к 'exit' вывод процесса может быть ещё не дочитан — версия оказалась бы пустой
59
+ // (и проверка минимальной версии движка пропустила бы старый), так изредка случалось на Linux
60
+ proc.on('close', (code) => {
61
+ clearTimeout(timer);
62
+ resolve(code === 0 ? { ok: true, version: out.trim() } : { ok: false, error: (err || out).trim().split(/\r?\n/).slice(-3).join(' | ') || `код ${code}` });
63
+ });
64
+ });
65
+ }
66
+
67
+ export class AcpAgent {
68
+ /**
69
+ * @param {object} o
70
+ * @param {string} o.cwd рабочая папка агента
71
+ * @param {string} o.command команда запуска агента
72
+ * @param {string[]} [o.args] аргументы режима ACP
73
+ * @param {string} [o.name] название агента для логов
74
+ * @param {(p:object)=>Promise<object>} [o.onPermission] обработчик session/request_permission, возвращает outcome
75
+ * @param {(u:object)=>void} [o.onUpdate] обработчик session/update
76
+ * @param {(code:number|null)=>void} [o.onExit]
77
+ */
78
+ constructor({ cwd, command, args = [], name = command, quietStderr = null, onPermission, onUpdate, onExit }) {
79
+ this.quietStderr = quietStderr; // RegExp служебных строк stderr, которые не пишем в лог бота
80
+ this.cwd = cwd;
81
+ this.name = name;
82
+ this.command = command;
83
+ this.args = args;
84
+ this.onPermission = onPermission;
85
+ this.onUpdate = onUpdate;
86
+ this.onExit = onExit;
87
+ this.nextId = 1;
88
+ this.pending = new Map();
89
+ this.sessionId = null;
90
+ this.proc = null;
91
+ this.closed = false;
92
+ }
93
+
94
+ start() {
95
+ this.proc = spawnCommand(this.command, this.args, { cwd: this.cwd, stdio: ['pipe', 'pipe', 'pipe'] });
96
+ readline.createInterface({ input: this.proc.stdout }).on('line', (l) => this.#onLine(l));
97
+ readline.createInterface({ input: this.proc.stderr }).on('line', (l) => {
98
+ if (!this.quietStderr?.test(l)) console.error(`[${this.name}:stderr]`, l);
99
+ });
100
+ // запись в уже завершившийся процесс (EPIPE) не должна ронять бота
101
+ this.proc.stdin.on('error', (e) => console.error('[acp] stdin:', e.message));
102
+ // команда не найдена и т.п.: без обработчика 'error' Node уронит весь бот, а 'exit' может не прийти
103
+ this.proc.on('error', (e) => this.#finish(null, `не удалось запустить ${this.command}: ${e.message}`));
104
+ this.proc.on('exit', (code) => this.#finish(code, `${this.name} завершился (код ${code})`));
105
+ }
106
+
107
+ #finished = false;
108
+ #finish(code, reason) {
109
+ if (this.#finished) return;
110
+ this.#finished = true;
111
+ this.closed = true;
112
+ for (const { reject } of this.pending.values()) reject(new Error(reason));
113
+ this.pending.clear();
114
+ this.onExit?.(code);
115
+ }
116
+
117
+ /**
118
+ * @param {string} [mode] режим сессии ACP (у каждого движка свои, см. engines.mjs); если не задан — режим агента по умолчанию
119
+ * @param {{resume?: string}} [opts] resume — id ранее созданной сессии ACP, которую нужно загрузить вместо новой
120
+ */
121
+ async init(mode, { resume } = {}) {
122
+ this.start();
123
+ await this.request('initialize', {
124
+ protocolVersion: 1,
125
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } },
126
+ });
127
+ // При загрузке агент «проигрывает» историю диалога уведомлениями session/update до ответа на запрос
128
+ const res = resume
129
+ ? await this.request('session/load', { sessionId: resume, cwd: this.cwd, mcpServers: [] })
130
+ : await this.request('session/new', { cwd: this.cwd, mcpServers: [] });
131
+ this.sessionId = resume || res.sessionId;
132
+ // Часть «проигрываемой» истории приходит уже после ответа на session/load — ждём затишья,
133
+ // иначе старый текст попадёт в начало первого нового ответа
134
+ if (resume) await this.#settle();
135
+ this.mode = res?.modes?.currentModeId ?? null;
136
+ if (mode && mode !== this.mode) {
137
+ await this.request('session/set_mode', { sessionId: this.sessionId, modeId: mode });
138
+ this.mode = mode;
139
+ }
140
+ return res;
141
+ }
142
+
143
+ prompt(text) {
144
+ return this.request('session/prompt', {
145
+ sessionId: this.sessionId,
146
+ prompt: [{ type: 'text', text }],
147
+ });
148
+ }
149
+
150
+ cancel() {
151
+ if (this.sessionId) this.#write({ jsonrpc: '2.0', method: 'session/cancel', params: { sessionId: this.sessionId } });
152
+ }
153
+
154
+ request(method, params) {
155
+ // процесс уже закрыт или завершился: ответа не будет, иначе промис повиснет навсегда
156
+ if (this.closed) return Promise.reject(new Error(`${this.name}: процесс агента уже завершён`));
157
+ const id = this.nextId++;
158
+ return new Promise((resolve, reject) => {
159
+ this.pending.set(id, { resolve, reject });
160
+ this.#write({ jsonrpc: '2.0', id, method, params });
161
+ });
162
+ }
163
+
164
+ close() {
165
+ if (this.closed || !this.proc) return;
166
+ this.closed = true;
167
+ // завершаем всё дерево процессов (оболочка -> node -> агент)
168
+ killTree(this.proc);
169
+ }
170
+
171
+ /** Ждёт, пока агент перестанет присылать session/update (не дольше maxMs). */
172
+ async #settle(quietMs = 1000, maxMs = 8000) {
173
+ const start = Date.now();
174
+ this.lastUpdateAt = Date.now();
175
+ while (!this.closed && Date.now() - this.lastUpdateAt < quietMs && Date.now() - start < maxMs) {
176
+ await new Promise((r) => setTimeout(r, 100));
177
+ }
178
+ }
179
+
180
+ #write(obj) {
181
+ this.proc.stdin.write(JSON.stringify(obj) + '\n');
182
+ }
183
+
184
+ async #onLine(line) {
185
+ let msg;
186
+ try {
187
+ msg = JSON.parse(line);
188
+ } catch {
189
+ return; // не JSON-RPC (например, служебный вывод) — игнорируем
190
+ }
191
+ // ответ на наш запрос
192
+ if (msg.id !== undefined && !msg.method) {
193
+ const p = this.pending.get(msg.id);
194
+ if (!p) return;
195
+ this.pending.delete(msg.id);
196
+ if (msg.error) p.reject(new Error(`ACP ${msg.error.code}: ${msg.error.message}`));
197
+ else p.resolve(msg.result);
198
+ return;
199
+ }
200
+ // запрос от агента
201
+ if (msg.id !== undefined && msg.method) {
202
+ if (msg.method === 'session/request_permission' && this.onPermission) {
203
+ let outcome;
204
+ try {
205
+ outcome = await this.onPermission(msg.params);
206
+ } catch {
207
+ outcome = { outcome: 'cancelled' };
208
+ }
209
+ this.#write({ jsonrpc: '2.0', id: msg.id, result: { outcome } });
210
+ } else {
211
+ this.#write({ jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'Method not supported' } });
212
+ }
213
+ return;
214
+ }
215
+ // уведомление
216
+ if (msg.method === 'session/update') {
217
+ this.lastUpdateAt = Date.now();
218
+ try {
219
+ this.onUpdate?.(msg.params.update);
220
+ } catch (e) {
221
+ console.error('[acp] ошибка в обработчике обновления:', e.message); // не роняем бота
222
+ }
223
+ }
224
+ }
225
+ }