dsh-subscription-agents 0.0.0-stage → 1.2.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.
@@ -0,0 +1,227 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { StringDecoder } from 'node:string_decoder';
3
+
4
+ const MAX_PENDING = 2 * 1024 * 1024;
5
+ const MAX_LINE = 1024 * 1024;
6
+ const MAX_TEXT = 128 * 1024;
7
+ const TIMEOUT = 30 * 60_000;
8
+ const ID = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,159}$/;
9
+
10
+ /** Construct persistent CLI argv; execution cwd must match the supplied workspace. */
11
+ export function agentArgs(provider, { cwd, permissionMode, threadId, ephemeral = false } = {}) {
12
+ if (!['read-only', 'workspace-write', 'danger-full-access'].includes(permissionMode)) throw new Error('Unsupported agent permission mode');
13
+ if (typeof cwd !== 'string' || !cwd) throw new Error('Agent workspace is required');
14
+ if (threadId !== undefined && (typeof threadId !== 'string' || !ID.test(threadId))) throw new Error('Invalid CLI thread identifier');
15
+ if (ephemeral && threadId) throw new Error('An ephemeral CLI request cannot resume a thread');
16
+ if (provider === 'codex') {
17
+ const base = [
18
+ '-c', 'cli_auth_credentials_store="file"', '-a', 'never', '-s', permissionMode, '-C', cwd,
19
+ '--disable', 'multi_agent', '--disable', 'multi_agent_v2', 'exec',
20
+ ];
21
+ return [...base, ...(threadId ? ['resume'] : []), '--json', '--skip-git-repo-check', ...(ephemeral ? ['--ephemeral'] : []), ...(threadId ? [threadId] : []), '-'];
22
+ }
23
+ if (provider === 'claude') {
24
+ // acceptEdits grants edits, not an unconfined Bash bypass, even for a full-access parent.
25
+ return ['-p', '--output-format', 'stream-json', '--verbose', '--tools', 'default', '--permission-mode', permissionMode === 'read-only' ? 'plan' : 'acceptEdits', '--permission-prompts', 'none', ...(ephemeral ? ['--no-session-persistence'] : []), ...(threadId ? ['--resume', threadId] : [])];
26
+ }
27
+ throw new Error('Unsupported CLI provider');
28
+ }
29
+
30
+ const capped = value => typeof value === 'string' ? value.slice(0, MAX_TEXT) : '';
31
+ const printable = value => typeof value === 'string' ? capped(value) : capped(JSON.stringify(value ?? ''));
32
+
33
+ /** Run a persistent CLI turn; normalized events are awaited sequentially with bounded backpressure. */
34
+ export async function runAgent({ provider, exe, env, cwd, permissionMode, threadId, ephemeral, prompt, signal, onEvent }) {
35
+ const args = agentArgs(provider, { cwd, permissionMode, threadId, ephemeral });
36
+ if (typeof prompt !== 'string' || !prompt.trim() || Buffer.byteLength(prompt) > 512 * 1024) throw new Error('Invalid agent prompt');
37
+ if (signal?.aborted) throw new Error('Agent cancelled');
38
+ if (typeof onEvent !== 'function') throw new Error('Agent event callback is required');
39
+ const child = spawn(exe, args, { cwd, env, stdio: ['pipe', 'pipe', 'pipe'], detached: process.platform !== 'win32', windowsHide: true });
40
+ const decoder = new StringDecoder('utf8');
41
+ let pending = '', pendingBytes = 0, stderrBytes = 0, stdoutBytes = 0;
42
+ let vendorId = threadId, text = '', usage, terminal = false, terminalError, stopped;
43
+ let forceTimer, closed = false, processing = false, closeCode, closeSignal;
44
+ const tools = new Map(), messages = new Set();
45
+ let queue = [], queuedBytes = 0;
46
+ let resolveDone;
47
+ const done = new Promise(resolve => { resolveDone = resolve; });
48
+ const kill = sig => { try { if (child.pid && process.platform !== 'win32') process.kill(-child.pid, sig); else child.kill(sig); } catch { /* Already stopped. */ } };
49
+ const stop = error => {
50
+ if (stopped) return;
51
+ stopped = error instanceof Error ? error : new Error(error);
52
+ queue = []; queuedBytes = 0;
53
+ child.stdout.resume();
54
+ kill('SIGTERM');
55
+ forceTimer = setTimeout(() => kill('SIGKILL'), 750);
56
+ forceTimer.unref?.();
57
+ };
58
+ const abort = () => stop('Agent cancelled');
59
+ const timeout = setTimeout(() => stop('Agent execution timed out'), TIMEOUT);
60
+ timeout.unref?.();
61
+ signal?.addEventListener('abort', abort, { once: true });
62
+ async function emit(event) {
63
+ if (!stopped) await onEvent(event);
64
+ }
65
+ async function setThread(id) {
66
+ if (typeof id !== 'string' || !ID.test(id)) return;
67
+ if (vendorId && vendorId !== id) throw new Error('CLI changed the pinned thread identifier');
68
+ if (!vendorId) { vendorId = id; await emit({ type: 'thread', id }); }
69
+ }
70
+ async function completedText(value, key) {
71
+ if (!value || messages.has(key)) return;
72
+ messages.add(key);
73
+ const next = capped(value);
74
+ text = capped(text ? text + '\n\n' + next : next);
75
+ await emit({ type: 'text', text: next });
76
+ }
77
+ async function startTool(id, name, input) {
78
+ if (typeof id !== 'string' || !id || tools.has(id)) return;
79
+ if (tools.size >= 4096) throw new Error('Too many CLI tool calls');
80
+ const item = { id: capped(id), name: capped(name), args: input && typeof input === 'object' ? input : {} };
81
+ if (Buffer.byteLength(JSON.stringify(item.args)) > MAX_LINE) throw new Error('CLI tool input exceeds limit');
82
+ tools.set(id, item);
83
+ await emit({ type: 'tool-start', ...item });
84
+ }
85
+ async function endTool(id, name, input, value, isError) {
86
+ await startTool(id, name, input);
87
+ const item = tools.get(id);
88
+ if (!item || item.ended) return;
89
+ item.ended = true;
90
+ const { ended, ...fields } = item;
91
+ await emit({ type: 'tool-end', ...fields, text: printable(value), isError: Boolean(isError) });
92
+ }
93
+ async function codex(event) {
94
+ if (event.type === 'thread.started') await setThread(event.thread_id);
95
+ if (event.type === 'turn.completed') { terminal = true; usage = event.usage; }
96
+ if (event.type === 'turn.failed' || event.type === 'error') { terminal = true; terminalError = capped(event.error?.message || event.message || 'Codex turn failed'); }
97
+ if (!['item.started', 'item.updated', 'item.completed'].includes(event.type) || !event.item) return;
98
+ const item = event.item, complete = event.type === 'item.completed', id = item.id;
99
+ if (item.type === 'agent_message' && complete) return completedText(item.text, id);
100
+ if (item.type === 'command_execution') {
101
+ const input = { command: item.command };
102
+ await startTool(id, 'Bash', input);
103
+ if (complete) await endTool(id, 'Bash', input, `${item.aggregated_output || ''}${item.exit_code != null ? `\n[exit code: ${item.exit_code}]` : ''}`, item.status !== 'completed' || (item.exit_code != null && item.exit_code !== 0));
104
+ } else if (item.type === 'file_change') {
105
+ const input = { changes: item.changes };
106
+ await startTool(id, 'File changes', input);
107
+ if (complete) await endTool(id, 'File changes', input, item.changes, item.status === 'failed');
108
+ } else if (item.type === 'mcp_tool_call') {
109
+ const name = `${item.server}/${item.tool}`;
110
+ await startTool(id, name, item.arguments);
111
+ if (complete) await endTool(id, name, item.arguments, item.error?.message || item.result, item.status === 'failed');
112
+ } else if (item.type === 'collab_tool_call') {
113
+ const tool = typeof item.tool === 'string' ? item.tool : 'collaboration';
114
+ const receivers = Array.isArray(item.receiver_thread_ids) ? item.receiver_thread_ids.filter(id => typeof id === 'string' && ID.test(id)) : [];
115
+ const states = item.agents_states && typeof item.agents_states === 'object' && !Array.isArray(item.agents_states)
116
+ ? Object.entries(item.agents_states).filter(([agent]) => ID.test(agent)).slice(0, 32) : [];
117
+ const failed = item.status === 'failed';
118
+ if (tool === 'wait' && !receivers.length && !states.length && !failed && !tools.has(id)) return;
119
+ const labels = { wait:'Ожидание внутренних агентов Codex', spawn_agent:'Запуск внутреннего агента Codex', send_input:'Сообщение внутреннему агенту Codex', close_agent:'Завершение внутреннего агента Codex' };
120
+ const input = { action:tool, agents:receivers.length ? receivers : states.map(([agent]) => agent), ...(typeof item.prompt === 'string' && item.prompt ? {prompt:item.prompt} : {}) };
121
+ const name = `Codex ${tool}`;
122
+ input.description = labels[tool] || 'Внутренние агенты Codex';
123
+ await startTool(id, name, input);
124
+ if (complete) {
125
+ const summary = states.length ? states.map(([agent,state])=>`${agent}: ${printable(state)}`).join('\n')
126
+ : failed ? 'Внутренний вызов Codex завершился с ошибкой.'
127
+ : tool === 'wait' ? 'Вызов ожидания завершён. CLI не передал состояния внутренних агентов; это не означает завершение основной задачи.'
128
+ : 'Внутренний вызов Codex завершён.';
129
+ await endTool(id, name, input, summary, failed);
130
+ }
131
+ } else if (['web_search', 'todo_list'].includes(item.type)) {
132
+ await startTool(id, item.type, item);
133
+ if (complete) await endTool(id, item.type, item, item, item.status === 'failed');
134
+ }
135
+ }
136
+ async function claude(event) {
137
+ // Nested vendor subagents must not replace the main thread identity or replies.
138
+ if (event.parent_tool_use_id != null) return;
139
+ if (typeof event.session_id === 'string') await setThread(event.session_id);
140
+ if (event.type === 'rate_limit_event') {
141
+ const info = event.rate_limit_info;
142
+ const label = ({ five_hour: '5 часов', seven_day: '7 дней', seven_day_sonnet: 'Sonnet · 7 дней', seven_day_opus: 'Opus · 7 дней' })[info?.rateLimitType];
143
+ const used = info?.status === 'rejected' ? 1 : info?.utilization;
144
+ if (label && Number.isFinite(used) && used >= 0 && used <= 1) {
145
+ const window = { label, usedPercent: used * 100 };
146
+ if (Number.isFinite(info.resetsAt) && info.resetsAt > 0 && info.resetsAt <= 8.64e12) window.resetAt = info.resetsAt * 1000;
147
+ await emit({ type: 'quota', usage: { updatedAt: Date.now(), windows: [window] } });
148
+ }
149
+ }
150
+ if (event.type === 'assistant' && Array.isArray(event.message?.content)) {
151
+ for (const [index, block] of event.message.content.entries()) {
152
+ if (block.type === 'text') await completedText(block.text, `${event.uuid || event.message.id}:${index}`);
153
+ if (block.type === 'tool_use') await startTool(block.id, block.name, block.input);
154
+ }
155
+ }
156
+ if (event.type === 'user' && Array.isArray(event.message?.content)) {
157
+ for (const block of event.message.content) if (block.type === 'tool_result') await endTool(block.tool_use_id, 'Tool', {}, block.content, block.is_error);
158
+ }
159
+ if (event.type === 'result') {
160
+ terminal = true; usage = event.usage;
161
+ if (event.is_error || event.subtype !== 'success') terminalError = capped(event.result || event.errors?.join('\n') || 'Claude turn failed');
162
+ else if (!text && event.result) await completedText(event.result, 'final-result');
163
+ }
164
+ }
165
+ async function drain() {
166
+ if (processing) return;
167
+ processing = true;
168
+ try {
169
+ while (queue.length && !stopped) {
170
+ const { line, bytes } = queue.shift(); queuedBytes -= bytes;
171
+ let event;
172
+ try { event = JSON.parse(line); } catch { throw new Error('CLI returned malformed JSONL'); }
173
+ if (!event || typeof event !== 'object' || Array.isArray(event)) throw new Error('CLI returned invalid JSONL event');
174
+ await (provider === 'codex' ? codex(event) : claude(event));
175
+ if (queuedBytes < MAX_PENDING / 2 && !closed && !stopped) child.stdout.resume();
176
+ }
177
+ } catch (error) { stop(error); }
178
+ finally { processing = false; if (closed && !queue.length) resolveDone(); }
179
+ }
180
+ child.stdout.on('data', chunk => {
181
+ if (stopped) return;
182
+ stdoutBytes += chunk.length;
183
+ if (stdoutBytes > 64 * MAX_PENDING) return stop('CLI output exceeds turn limit');
184
+ pending += decoder.write(chunk); pendingBytes = Buffer.byteLength(pending);
185
+ if (pendingBytes > MAX_PENDING) return stop('CLI JSONL buffer exceeds limit');
186
+ let index;
187
+ while ((index = pending.indexOf('\n')) !== -1) {
188
+ const line = pending.slice(0, index).trim(); pending = pending.slice(index + 1);
189
+ if (!line) continue;
190
+ const bytes = Buffer.byteLength(line);
191
+ if (bytes > MAX_LINE) return stop('CLI event exceeds line limit');
192
+ queuedBytes += bytes; queue.push({ line, bytes });
193
+ }
194
+ if (queuedBytes > MAX_PENDING) return stop('CLI event queue exceeds limit');
195
+ if (queuedBytes >= MAX_PENDING / 2) child.stdout.pause();
196
+ void drain();
197
+ });
198
+ child.stderr.on('data', chunk => { stderrBytes += chunk.length; if (stderrBytes > MAX_PENDING * 4) stop('CLI diagnostics exceed limit'); });
199
+ for (const stream of [child.stdin, child.stdout, child.stderr]) stream.on('error', error => stop(new Error(`CLI stream failed: ${error.code || 'error'}`)));
200
+ child.once('error', error => stop(new Error(`CLI process failed: ${error.code || 'error'}`)));
201
+ child.once('close', (code, sig) => {
202
+ closed = true; closeCode = code; closeSignal = sig;
203
+ pending += decoder.end();
204
+ if (pending.trim() && !stopped) {
205
+ const bytes = Buffer.byteLength(pending);
206
+ if (bytes > MAX_LINE || queuedBytes + bytes > MAX_PENDING) stop('CLI trailing event exceeds limit');
207
+ else { queue.push({ line: pending.trim(), bytes }); queuedBytes += bytes; }
208
+ }
209
+ pending = '';
210
+ void drain();
211
+ if (!processing && !queue.length) resolveDone();
212
+ });
213
+ child.stdin.end(prompt);
214
+ if (signal?.aborted) abort();
215
+ try {
216
+ await done;
217
+ if (stopped) throw stopped;
218
+ if (closeCode !== 0 || closeSignal) throw new Error(`CLI exited unsuccessfully (${closeCode ?? closeSignal})`);
219
+ if (terminalError) throw new Error(terminalError);
220
+ if (!terminal) throw new Error('CLI ended without a terminal turn result');
221
+ if (!vendorId && !ephemeral) throw new Error('CLI did not identify its persistent thread');
222
+ return { ...(vendorId ? { threadId:vendorId } : {}), text, ...(usage ? { usage } : {}) };
223
+ } finally {
224
+ clearTimeout(timeout); clearTimeout(forceTimer);
225
+ signal?.removeEventListener('abort', abort);
226
+ }
227
+ }
package/cli.js ADDED
@@ -0,0 +1,103 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { access } from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { delimiter, join, isAbsolute } from 'node:path';
6
+
7
+ const path = [...new Set([join(homedir(), '.local/bin'), '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin', ...(process.env.PATH || '').split(delimiter).filter(isAbsolute)])].join(delimiter);
8
+ export const codexPrefix = ['-c', 'cli_auth_credentials_store="file"'];
9
+ export const callTimeout = 180_000;
10
+ export function cliEnv(provider, profile) {
11
+ return { HOME: homedir(), PATH: path, LANG: 'en_US.UTF-8', TERM: 'dumb', NO_COLOR: '1', ...(provider === 'codex' ? { CODEX_HOME: profile } : { CLAUDE_CONFIG_DIR: profile }) };
12
+ }
13
+ export async function executable(name) {
14
+ for (const dir of path.split(delimiter)) {
15
+ const file = join(dir, name);
16
+ try { await access(file, constants.X_OK); return file; } catch {}
17
+ }
18
+ }
19
+ export function run(exe, args, { env, cwd, signal, timeout = 15_000, input, onOutput } = {}) {
20
+ return new Promise((resolve, reject) => {
21
+ if (signal?.aborted) return reject(new Error('Операция отменена.'));
22
+ const child = spawn(exe, args, { cwd, env, stdio: ['pipe','pipe','pipe'], detached: process.platform !== 'win32', windowsHide: true });
23
+ let stdout = '', stderr = '', stopped, done = false, force;
24
+ const kill = kind => { try { if (child.pid && process.platform !== 'win32') process.kill(-child.pid, kind); else child.kill(kind); } catch {} };
25
+ const stop = reason => {
26
+ if (done || stopped) return;
27
+ stopped = reason;
28
+ kill('SIGTERM');
29
+ force = setTimeout(() => kill('SIGKILL'), 600);
30
+ force.unref?.();
31
+ };
32
+ const abort = () => stop('Операция отменена.');
33
+ const timer = setTimeout(() => stop('CLI не ответил вовремя.'), timeout);
34
+ timer.unref?.();
35
+ signal?.addEventListener('abort', abort, { once:true });
36
+ const finish = (err, value) => {
37
+ if (done) return; done = true;
38
+ clearTimeout(timer); clearTimeout(force);
39
+ signal?.removeEventListener('abort', abort);
40
+ if (err) reject(new Error(err)); else resolve(value);
41
+ };
42
+ child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8');
43
+ function consume(chunk, target) {
44
+ if (stopped || done) return;
45
+ if (target === 'out') stdout += chunk; else stderr += chunk;
46
+ if (stdout.length + stderr.length > 2_000_000) return stop('CLI вернул слишком большой ответ.');
47
+ onOutput?.(stdout, stderr);
48
+ }
49
+ child.stdout.on('data', chunk => consume(chunk, 'out'));
50
+ child.stderr.on('data', chunk => consume(chunk, 'err'));
51
+ child.stdin.on('error', () => {});
52
+ child.on('error', () => finish('Не удалось запустить CLI.'));
53
+ child.on('close', code => finish(stopped, { code, stdout, stderr }));
54
+ child.stdin.end(input);
55
+ });
56
+ }
57
+
58
+ export function command(provider, op) {
59
+ if (provider === 'codex') {
60
+ if (op === 'login') return [...codexPrefix, 'login'];
61
+ if (op === 'status') return [...codexPrefix, 'login', 'status'];
62
+ if (op === 'logout') return [...codexPrefix, 'logout'];
63
+ return [...codexPrefix, '-a', 'never', '-c', 'web_search="disabled"', ...['shell_tool','unified_exec','apps','plugins','hooks','memories','image_generation','browser_use','computer_use','multi_agent','multi_agent_v2'].flatMap(x => ['--disable',x]), 'exec','--sandbox','read-only','--skip-git-repo-check','--ephemeral','--ignore-user-config','--ignore-rules','--json','-'];
64
+ }
65
+ if (op === 'login') return ['auth','login','--claudeai'];
66
+ if (op === 'status') return ['auth','status','--json'];
67
+ if (op === 'logout') return ['auth','logout'];
68
+ return ['--safe-mode','-p','--output-format','stream-json','--verbose','--tools','','--strict-mcp-config','--no-chrome','--permission-prompts','none','--no-session-persistence'];
69
+ }
70
+ export function subscribed(provider, result) {
71
+ if (result.code !== 0) return false;
72
+ if (provider === 'codex') return /logged in using chatgpt/i.test(result.stdout + '\n' + result.stderr);
73
+ try {
74
+ const value = JSON.parse(result.stdout);
75
+ return value.loggedIn === true && value.authMethod === 'claude.ai';
76
+ } catch { return false; }
77
+ }
78
+ function readEvents(stdout) {
79
+ return stdout.split(/\r?\n/).flatMap(line => { try { return [JSON.parse(line)]; } catch { return []; } });
80
+ }
81
+ export function inference(provider, result) {
82
+ const events = readEvents(result.stdout);
83
+ const limits = events.filter(e => e?.type === 'rate_limit_event').map(e => e.rate_limit_info).filter(v => v && typeof v === 'object');
84
+ const windows = new Map();
85
+ for (const lim of limits) {
86
+ const label = ({ five_hour:'5 часов', seven_day:'7 дней', seven_day_sonnet:'Sonnet · 7 дней', seven_day_opus:'Opus · 7 дней' })[lim.rateLimitType];
87
+ const used = lim.status === 'rejected' ? 1 : lim.utilization;
88
+ if (!label || !Number.isFinite(used) || used < 0 || used > 1) continue;
89
+ windows.set(label, { label, usedPercent: used * 100, ...(Number.isFinite(lim.resetsAt) && lim.resetsAt > 0 ? { resetAt: lim.resetsAt * 1000 } : {}) });
90
+ }
91
+ const usage = windows.size ? { updatedAt: Date.now(), windows:[...windows.values()] } : undefined;
92
+ const rejected = limits.some(x => x.status === 'rejected');
93
+ const last = events.filter(e => e?.type === 'result').at(-1);
94
+ const errors = events.flatMap(e => ['error','turn.failed'].includes(e?.type) ? [e.message, e.error?.message] : []);
95
+ if (last?.is_error || result.code !== 0) errors.push(last?.result, result.stderr);
96
+ const joined = errors.filter(x => typeof x === 'string').join(' ');
97
+ const error = rejected || /rate.limit|usage limit|quota|hit your limit|too many requests|\b429\b/i.test(joined) ? 'quota' : /not logged|sign in|unauthorized|\b401\b|authentication/i.test(joined) ? 'auth' : 'other';
98
+ if (result.code !== 0 || last?.is_error || events.some(e => e?.type === 'turn.failed')) return { error, usage };
99
+ const text = provider === 'codex'
100
+ ? events.filter(e => e?.type === 'item.completed' && e.item?.type === 'agent_message').at(-1)?.item?.text
101
+ : last?.result;
102
+ return typeof text === 'string' && text.trim() ? { text: text.trim().slice(0, 32_000), usage } : { error, usage };
103
+ }