axmap-cli 1.5.0 → 1.7.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/.claude/commands/pipeline.md +9 -0
- package/README.ko.md +37 -0
- package/README.md +37 -0
- package/bin/axmap.mjs +6 -0
- package/mcp/README.md +9 -0
- package/mcp/pipeline.html +184 -0
- package/mcp/server.mjs +161 -20
- package/package.json +12 -3
- package/skills/pipeline/SKILL.md +14 -0
- package/src/agentcli.mjs +17 -14
- package/src/agentcli.mts +19 -0
- package/src/bridge.mjs +297 -219
- package/src/bridge.mts +282 -0
- package/src/codex-connection.mjs +151 -0
- package/src/codex-connection.mts +83 -0
- package/src/external-console.mjs +140 -97
- package/src/external-console.mts +128 -0
- package/src/managed-session.mjs +325 -169
- package/src/managed-session.mts +242 -0
- package/src/monitor-cli.mjs +89 -0
- package/src/monitor-cli.mts +66 -0
- package/src/monitor.mjs +245 -0
- package/src/monitor.mts +199 -0
- package/src/node-pty.d.ts +13 -0
- package/src/pipeline-graph.mjs +55 -0
- package/src/pipeline-graph.mts +51 -0
- package/src/pipeline-mcp.mjs +111 -0
- package/src/pipeline-mcp.mts +105 -0
- package/src/pipeline-statusline.mjs +135 -0
- package/src/pipeline-statusline.mts +106 -0
- package/src/pipeline-web.mjs +56 -0
- package/src/pipeline-web.mts +31 -0
- package/src/session-dialogue.mjs +168 -116
- package/src/session-dialogue.mts +136 -0
- package/src/session-mailbox.mjs +190 -0
- package/src/session-mailbox.mts +157 -0
- package/src/session-status.mjs +47 -41
- package/src/session-status.mts +50 -0
- package/src/session-types.mjs +7 -0
- package/src/session-types.mts +119 -0
- package/src/session-usage.mjs +33 -28
- package/src/session-usage.mts +39 -0
- package/src/terminal-bridge.mjs +293 -209
- package/src/terminal-bridge.mts +235 -0
- package/src/windows-console.mjs +42 -0
- package/src/windows-console.mts +29 -0
- package/tools/bench-console.mjs +70 -0
- package/tools/bridge.mjs +41 -6
- package/tools/build.mjs +39 -0
- package/tools/monitor.mjs +5 -0
- package/tools/pipeline.mjs +34 -0
- package/tools/run-tests.mjs +3 -2
- package/tools/windows-console.cs +116 -0
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/** Explicitly launched persistent CLI sessions. No transcript scraping, global
|
|
2
|
+
* hook edits, per-message process spawning, or inference while the queue is idle. */
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import net from 'node:net'
|
|
6
|
+
import { spawn } from 'node:child_process'
|
|
7
|
+
import { randomUUID, randomBytes, timingSafeEqual } from 'node:crypto'
|
|
8
|
+
import { bridgeHome, repoKey, writeJSON } from './bridge.mjs'
|
|
9
|
+
import { normalizeUsage, usageDelta } from './session-usage.mjs'
|
|
10
|
+
import { errorMessage } from './session-types.mjs'
|
|
11
|
+
import { connectCodexProxy } from './codex-connection.mjs'
|
|
12
|
+
import type { ProviderProcess } from './codex-connection.mjs'
|
|
13
|
+
import type { ChildProcessWithoutNullStreams } from 'node:child_process'
|
|
14
|
+
import type { Provider, SessionRecord, RequestState, LocalMessage, JobRecord } from './session-types.mjs'
|
|
15
|
+
import type { Usage } from './session-types.mjs'
|
|
16
|
+
|
|
17
|
+
interface ManagedSessionOptions {
|
|
18
|
+
provider: Provider; executable?: string; prefix?: string[]; args?: string[] | null; model?: string; role?: string
|
|
19
|
+
cwd?: string; maxTokens?: number; timeoutMs?: number; onEvent?: (event: Record<string, unknown>) => void
|
|
20
|
+
existingThreadId?: string; socketPath?: string
|
|
21
|
+
observeActive?: boolean
|
|
22
|
+
}
|
|
23
|
+
interface ProviderMessage {
|
|
24
|
+
id?: string | number; method?: string; event?: string; conversation_id?: string
|
|
25
|
+
error?: { message: string }; result?: unknown
|
|
26
|
+
params?: {
|
|
27
|
+
threadId?: string; tokenUsage?: { total: unknown }; item?: { type: string; text?: string }
|
|
28
|
+
turn?: { id: string; status: string; error?: { message: string } }
|
|
29
|
+
[key: string]: unknown
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
interface AgyResult { conversation_id: string; status: string; response?: unknown; error?: string; usage?: unknown }
|
|
33
|
+
|
|
34
|
+
const pipeFor = (id: string) => process.platform === 'win32' ? `\\\\.\\pipe\\axmap-${id}` : path.join(bridgeHome(), `${id}.sock`)
|
|
35
|
+
const uuid = (value: string | undefined) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value || '')
|
|
36
|
+
|
|
37
|
+
export async function startManagedSession({ provider, executable = provider, prefix = [], args = null, model, role = '', existingThreadId, socketPath, observeActive = false,
|
|
38
|
+
cwd = process.cwd(), maxTokens = 100000, timeoutMs = 120000, onEvent = () => {} }: ManagedSessionOptions) {
|
|
39
|
+
if (!['codex', 'agy'].includes(provider)) throw new Error('지원하는 세션은 codex 또는 agy입니다.')
|
|
40
|
+
if (!Number.isSafeInteger(maxTokens) || maxTokens < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1) throw new Error('양의 토큰/시간 한도가 필요합니다.')
|
|
41
|
+
if (typeof role !== 'string' || role.length > 1000) throw new Error('역할은 1000자 이하여야 합니다.')
|
|
42
|
+
if (existingThreadId && (provider !== 'codex' || !uuid(existingThreadId) || !socketPath || model || args)) throw new Error('기존 Codex thread와 로컬 socket이 필요하며 모델·실행 인수를 바꾸지 않습니다.')
|
|
43
|
+
const id = randomUUID(), token = randomBytes(32).toString('hex')
|
|
44
|
+
const sessionPath = path.join(bridgeHome(), 'sessions', `${id}.json`)
|
|
45
|
+
const s: SessionRecord = { id, token, provider, transport: 'stdio', role, model: model || null,
|
|
46
|
+
workspaces: [path.resolve(cwd)], repos: [repoKey(cwd)], state: 'starting', fullyIdle: false,
|
|
47
|
+
registeredAt: new Date().toISOString(), usage: null, usageKnown: true, maxTokens }
|
|
48
|
+
const jobs = new Map<string, JobRecord>()
|
|
49
|
+
let attachedUsageOrigin: Usage | null = null
|
|
50
|
+
let initialThreadState = 'idle'
|
|
51
|
+
const calls = new Map<string | number, { resolve: (result: unknown) => void; reject: (reason: Error) => void; timer: NodeJS.Timeout }>()
|
|
52
|
+
let child: ProviderProcess | undefined, sequence = 0, pending: JobRecord | null = null, closed = false, buffer = '', stderr = '', turnTimer: NodeJS.Timeout | undefined
|
|
53
|
+
const save = () => { s.registeredAt = new Date().toISOString(); writeJSON(sessionPath, s) }
|
|
54
|
+
const emit = (event: Record<string, unknown>) => onEvent({ session: id, ...event })
|
|
55
|
+
const write = (message: unknown) => {
|
|
56
|
+
if (closed || !child?.stdin.writable) throw new Error('세션 입력 연결이 종료됐습니다.')
|
|
57
|
+
child.stdin.write(JSON.stringify(message) + '\n')
|
|
58
|
+
}
|
|
59
|
+
const rpc = <T = unknown,>(method: string, params: unknown): Promise<T> => new Promise((resolve, reject) => {
|
|
60
|
+
const callId = ++sequence
|
|
61
|
+
const timer = setTimeout(() => { calls.delete(callId); reject(new Error(`${method}: 응답 시간 초과`)) }, 15000)
|
|
62
|
+
calls.set(callId, { resolve: value => resolve(value as T), reject, timer })
|
|
63
|
+
try { write({ id: callId, method, params }) } catch (e) { clearTimeout(timer); calls.delete(callId); reject(e) }
|
|
64
|
+
})
|
|
65
|
+
const finish = (state: RequestState, result?: unknown, error?: string, rawUsage?: unknown) => {
|
|
66
|
+
if (!pending) return
|
|
67
|
+
clearTimeout(turnTimer)
|
|
68
|
+
const usage = normalizeUsage(provider, rawUsage)
|
|
69
|
+
Object.assign(pending, { state, result, error, usage: pending.baselineKnown ? usageDelta(usage, pending.baseline) : null,
|
|
70
|
+
completedAt: new Date().toISOString(), conversationId: s.conversationId })
|
|
71
|
+
delete pending.baseline
|
|
72
|
+
delete pending.baselineKnown
|
|
73
|
+
if (usage) { s.usage = usage; if (existingThreadId && !attachedUsageOrigin) attachedUsageOrigin = usage }
|
|
74
|
+
s.usageKnown = usage !== null
|
|
75
|
+
emit({ event: 'result', request: { ...pending } })
|
|
76
|
+
pending = null; s.state = 'idle'; s.fullyIdle = true; delete s.pendingApproval; save()
|
|
77
|
+
}
|
|
78
|
+
const shutdown = (reason: string) => {
|
|
79
|
+
if (closed) return
|
|
80
|
+
finish('unknown', undefined, reason)
|
|
81
|
+
closed = true; clearTimeout(turnTimer)
|
|
82
|
+
for (const c of calls.values()) { clearTimeout(c.timer); c.reject(new Error(reason)) }
|
|
83
|
+
calls.clear()
|
|
84
|
+
s.state = 'closed'; s.fullyIdle = false; save()
|
|
85
|
+
child?.stdin.destroy(); child?.kill(); server.close()
|
|
86
|
+
}
|
|
87
|
+
let checkingSubmission = false
|
|
88
|
+
const handle = async (message: LocalMessage) => {
|
|
89
|
+
const offered = Buffer.from(typeof message.token === 'string' ? message.token : '')
|
|
90
|
+
const expected = Buffer.from(token)
|
|
91
|
+
if (offered.length !== expected.length || !timingSafeEqual(offered, expected)) throw new Error('로컬 세션 인증 실패')
|
|
92
|
+
if (message.action === 'notice') {
|
|
93
|
+
if (!existingThreadId || provider !== 'codex' || typeof message.text !== 'string' || !message.text.trim() || Buffer.byteLength(message.text) > 8192) throw new Error('기존 Codex 대화에 1~8192바이트 안내만 기록할 수 있습니다.')
|
|
94
|
+
const noticeId = randomUUID()
|
|
95
|
+
await rpc('thread/inject_items', { threadId: existingThreadId, items: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: `[axMap notice ${noticeId}; context only, no new model turn]\n${message.text}` }] }] })
|
|
96
|
+
writeJSON(path.join(bridgeHome(), 'notices', `${noticeId}.json`), { id: noticeId, to: id, conversationId: existingThreadId, repo: repoKey(cwd), text: message.text, createdAt: new Date().toISOString(), state: 'context_recorded', modelInvoked: false })
|
|
97
|
+
return { noticeId, conversationId: existingThreadId, state: 'context_recorded', modelInvoked: false }
|
|
98
|
+
}
|
|
99
|
+
if (message.action === 'status') return { id, state: s.state, usage: s.usage, pendingApproval: s.pendingApproval }
|
|
100
|
+
if (message.action === 'result') {
|
|
101
|
+
const result = jobs.get(message.id)
|
|
102
|
+
if (!result) throw new Error('이 세션에 해당 요청이 없습니다.')
|
|
103
|
+
const { baseline, baselineKnown, ...publicResult } = result
|
|
104
|
+
return publicResult
|
|
105
|
+
}
|
|
106
|
+
if (message.action === 'answer') {
|
|
107
|
+
const approval = s.pendingApproval
|
|
108
|
+
if (!approval || String(approval.id) !== String(message.id)) throw new Error('현재 대기 중인 승인 요청이 아닙니다.')
|
|
109
|
+
if (!['accept', 'decline', 'cancel'].includes(message.decision)) throw new Error('이번 실행의 accept, decline 또는 cancel만 지원합니다.')
|
|
110
|
+
write({ id: approval.id, result: { decision: message.decision } })
|
|
111
|
+
delete s.pendingApproval; s.state = 'running'; save(); return { answered: true }
|
|
112
|
+
}
|
|
113
|
+
if (message.action !== 'submit') throw new Error('지원하지 않는 로컬 세션 요청입니다.')
|
|
114
|
+
if (jobs.has(message.request?.id)) throw new Error('이미 접수한 요청 ID입니다. 다시 전송하지 않았습니다.')
|
|
115
|
+
if (closed || s.state !== 'idle' || pending) throw new Error('세션이 대기 중이 아닙니다. 요청을 전달하지 않았습니다.')
|
|
116
|
+
if (existingThreadId) {
|
|
117
|
+
if (checkingSubmission) throw new Error('다른 요청의 상태를 확인 중입니다.')
|
|
118
|
+
checkingSubmission = true
|
|
119
|
+
try {
|
|
120
|
+
const read = await rpc<{ thread: { id: string; status: { type: string } } }>('thread/read', { threadId: existingThreadId })
|
|
121
|
+
if (closed || pending || read.thread.id !== existingThreadId || read.thread.status.type !== 'idle') throw new Error('기존 대화가 다른 작업 중입니다. 새 요청을 전달하지 않았습니다.')
|
|
122
|
+
} finally { checkingSubmission = false }
|
|
123
|
+
}
|
|
124
|
+
if (!s.usageKnown) throw new Error('직전 요청의 사용량을 확인하지 못했습니다. 새 연결에서 예산을 확인하세요.')
|
|
125
|
+
if (s.usage && s.usage.totalTokens - (existingThreadId ? attachedUsageOrigin?.totalTokens ?? s.usage.totalTokens : 0) >= maxTokens) throw new Error('세션 토큰 한도에 도달했습니다.')
|
|
126
|
+
const request = message.request
|
|
127
|
+
if (!uuid(request?.id) || request.to !== id || typeof request.prompt !== 'string' || !request.prompt.trim() || Buffer.byteLength(request.prompt) > 32768) throw new Error('요청 형식이 올바르지 않습니다.')
|
|
128
|
+
pending = { id: request.id, to: id, state: 'submitted', baseline: s.usage, baselineKnown: s.usageKnown && (!existingThreadId || !!s.usage), result: '' }
|
|
129
|
+
jobs.set(request.id, pending); s.state = 'running'; s.fullyIdle = false; save()
|
|
130
|
+
const prompt = `[axMap request ${request.id}]\n요청자: ${request.from || 'axmap'}\n${role ? `역할: ${role}\n` : ''}${request.prompt}`
|
|
131
|
+
turnTimer = setTimeout(() => shutdown('실행 시간 한도 초과. 완료 여부가 불명확하므로 자동 재시도하지 않습니다.'), timeoutMs)
|
|
132
|
+
if (provider === 'agy') write({ event: 'user', message: { content: prompt } })
|
|
133
|
+
else rpc<{ turn: { id: string } }>('turn/start', { threadId: s.conversationId, input: [{ type: 'text', text: prompt }], ...(!existingThreadId ? { effort: 'low' } : {}) })
|
|
134
|
+
.then(r => { if (pending?.id === request.id) pending.turnId = r.turn.id })
|
|
135
|
+
.catch(e => shutdown(e.message))
|
|
136
|
+
return { accepted: true, session: id }
|
|
137
|
+
}
|
|
138
|
+
const server = net.createServer(socket => {
|
|
139
|
+
socket.setEncoding('utf8')
|
|
140
|
+
let input = '', handled = false
|
|
141
|
+
socket.setTimeout(15000, () => socket.destroy()); socket.on('error', () => {})
|
|
142
|
+
socket.on('data', chunk => {
|
|
143
|
+
if (handled) return
|
|
144
|
+
input += chunk
|
|
145
|
+
if (Buffer.byteLength(input) > 65536) return socket.destroy()
|
|
146
|
+
const end = input.indexOf('\n'); if (end < 0) return
|
|
147
|
+
handled = true
|
|
148
|
+
try { void handle(JSON.parse(input.slice(0, end))).then(result => socket.end(JSON.stringify({ result }) + '\n'), e => socket.end(JSON.stringify({ error: errorMessage(e) }) + '\n')) }
|
|
149
|
+
catch (e) { socket.end(JSON.stringify({ error: errorMessage(e) }) + '\n') }
|
|
150
|
+
})
|
|
151
|
+
})
|
|
152
|
+
fs.mkdirSync(bridgeHome(), { recursive: true, mode: 0o700 })
|
|
153
|
+
await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(pipeFor(id), resolve) })
|
|
154
|
+
if (process.platform !== 'win32') fs.chmodSync(pipeFor(id), 0o600)
|
|
155
|
+
save()
|
|
156
|
+
const cliArgs = args || (provider === 'codex' ? ['app-server', '--stdio']
|
|
157
|
+
: ['--input-format', 'stream-json', '--output-format', 'stream-json', '--disable-slash-commands', '--effort', 'low', ...(model ? ['--model', model] : [])])
|
|
158
|
+
child = existingThreadId ? connectCodexProxy({ executable, prefix, socketPath: socketPath!, cwd }) : spawn(executable, [...prefix, ...cliArgs], { cwd, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'],
|
|
159
|
+
env: { ...process.env, AXMAP_AGENT: `${provider}-${id.slice(0, 8)}`, AXMAP_SESSION: id } })
|
|
160
|
+
child.stdin.on('error', e => shutdown(e.message))
|
|
161
|
+
const exited = new Promise<{ code: number | null; signal?: NodeJS.Signals | null; error?: string }>(resolve => {
|
|
162
|
+
child.once('error', e => { shutdown(e.message); resolve({ code: 1, error: e.message }) })
|
|
163
|
+
child.once('exit', (code, signal) => { shutdown(`CLI가 종료됐습니다 (${code ?? signal}). ${stderr.slice(-1000)}`); resolve({ code, signal }) })
|
|
164
|
+
})
|
|
165
|
+
child.stderr.on('data', chunk => { stderr = (stderr + chunk.toString('utf8')).slice(-8192) })
|
|
166
|
+
child.stdout.setEncoding('utf8')
|
|
167
|
+
child.stdout.on('error', e => shutdown(e.message))
|
|
168
|
+
child.stdout.on('data', chunk => {
|
|
169
|
+
buffer += chunk
|
|
170
|
+
if (Buffer.byteLength(buffer) > 4 * 1024 * 1024) return shutdown('CLI 응답 크기 제한 초과')
|
|
171
|
+
while (buffer.includes('\n') && !closed) {
|
|
172
|
+
const end = buffer.indexOf('\n'), line = buffer.slice(0, end); buffer = buffer.slice(end + 1)
|
|
173
|
+
if (!line.trim()) continue
|
|
174
|
+
try {
|
|
175
|
+
const m = JSON.parse(line) as ProviderMessage
|
|
176
|
+
if (provider === 'agy') {
|
|
177
|
+
if (m.event === 'init') { s.conversationId = m.conversation_id; s.state = 'idle'; s.fullyIdle = true; save(); emit({ event: 'ready', conversationId: s.conversationId }) }
|
|
178
|
+
if (m.event === 'result' && pending) {
|
|
179
|
+
const r = m.result as AgyResult
|
|
180
|
+
if (r.conversation_id !== s.conversationId) throw new Error('agy 대화 ID가 바뀌었습니다.')
|
|
181
|
+
finish(r.status === 'SUCCESS' ? 'completed' : 'failed', r.response, r.error, r.usage)
|
|
182
|
+
}
|
|
183
|
+
continue
|
|
184
|
+
}
|
|
185
|
+
if (m.id !== undefined && !m.method) {
|
|
186
|
+
const call = calls.get(m.id)
|
|
187
|
+
if (call) { clearTimeout(call.timer); calls.delete(m.id); m.error ? call.reject(new Error(m.error.message)) : call.resolve(m.result) }
|
|
188
|
+
continue
|
|
189
|
+
}
|
|
190
|
+
if (m.id !== undefined && m.method) {
|
|
191
|
+
if (['item/commandExecution/requestApproval', 'item/fileChange/requestApproval'].includes(m.method)) {
|
|
192
|
+
s.pendingApproval = { id: m.id, method: m.method, ...m.params }; s.state = 'awaiting_user'; save()
|
|
193
|
+
emit({ event: 'awaiting_user', request: s.pendingApproval })
|
|
194
|
+
} else { write({ id: m.id, error: { code: -32601, message: '이 연결에서 지원하지 않는 사용자 입력입니다. 대화형 CLI에서 처리하세요.' } }) }
|
|
195
|
+
continue
|
|
196
|
+
}
|
|
197
|
+
if (m.params?.threadId !== s.conversationId) continue
|
|
198
|
+
if (m.method === 'thread/status/changed' && !pending) {
|
|
199
|
+
const status = m.params?.status as { type?: string } | undefined
|
|
200
|
+
s.state = status?.type === 'active' ? 'running' : status?.type === 'idle' ? 'idle' : 'unknown'
|
|
201
|
+
s.fullyIdle = s.state === 'idle'; save()
|
|
202
|
+
}
|
|
203
|
+
if (m.method === 'thread/tokenUsage/updated') {
|
|
204
|
+
if (pending) pending.rawUsage = m.params?.tokenUsage?.total
|
|
205
|
+
else { const usage = normalizeUsage(provider, m.params?.tokenUsage?.total); if (usage) { s.usage = usage; s.usageKnown = true; save() } }
|
|
206
|
+
}
|
|
207
|
+
if (m.method === 'item/completed' && pending && m.params?.item?.type === 'agentMessage') pending.result = m.params.item.text
|
|
208
|
+
if (m.method === 'turn/completed' && pending) {
|
|
209
|
+
const r = m.params?.turn
|
|
210
|
+
if (!r) throw new Error('Codex 실행 결과가 없습니다.')
|
|
211
|
+
if (pending.turnId && pending.turnId !== r.id) throw new Error('Codex 실행 ID가 다릅니다.')
|
|
212
|
+
finish(r.status === 'completed' ? 'completed' : 'failed', pending.result, r.error?.message, pending.rawUsage)
|
|
213
|
+
}
|
|
214
|
+
} catch (e) { shutdown(`CLI 프로토콜 오류: ${errorMessage(e)}`) }
|
|
215
|
+
}
|
|
216
|
+
})
|
|
217
|
+
try {
|
|
218
|
+
if (provider === 'codex') {
|
|
219
|
+
await rpc('initialize', { clientInfo: { name: 'axmap', version: '1' } })
|
|
220
|
+
write({ method: 'initialized' })
|
|
221
|
+
if (existingThreadId) {
|
|
222
|
+
const read = await rpc<{ thread: { id: string; cwd: string; status: { type: string } } }>('thread/read', { threadId: existingThreadId })
|
|
223
|
+
initialThreadState = read.thread.status.type
|
|
224
|
+
if (read.thread.id !== existingThreadId || (initialThreadState !== 'idle' && !(observeActive && initialThreadState === 'active'))) throw new Error('기존 thread가 idle 상태가 아닙니다. 전송하거나 새 대화를 만들지 않았습니다.')
|
|
225
|
+
// Parent workspace sessions can explicitly join a child Git repo. Never attach across unrelated roots.
|
|
226
|
+
const relative = path.relative(path.resolve(read.thread.cwd), path.resolve(cwd))
|
|
227
|
+
if (relative.startsWith('..') || path.isAbsolute(relative)) throw new Error('기존 thread와 요청 저장소 경로가 다릅니다.')
|
|
228
|
+
}
|
|
229
|
+
const r = await rpc<{ thread: { id: string }; model?: string }>(existingThreadId ? 'thread/resume' : 'thread/start', existingThreadId
|
|
230
|
+
? { threadId: existingThreadId, excludeTurns: true }
|
|
231
|
+
: { cwd: path.resolve(cwd), ...(model ? { model } : {}), sandbox: 'read-only', approvalPolicy: 'on-request' })
|
|
232
|
+
if (existingThreadId && r.thread.id !== existingThreadId) throw new Error('기존 thread ID가 바뀌었습니다.')
|
|
233
|
+
s.conversationId = r.thread.id; s.model = r.model || model || null; s.state = initialThreadState === 'active' ? 'running' : 'idle'; s.fullyIdle = s.state === 'idle'; save()
|
|
234
|
+
emit({ event: 'ready', conversationId: s.conversationId })
|
|
235
|
+
} else {
|
|
236
|
+
const deadline = Date.now() + 30000
|
|
237
|
+
while (s.state === 'starting' && !closed && Date.now() < deadline) await new Promise(r => setTimeout(r, 25))
|
|
238
|
+
if (s.state !== 'idle') throw new Error(`agy 시작 실패: ${stderr.slice(-1000) || s.state}`)
|
|
239
|
+
}
|
|
240
|
+
} catch (e) { shutdown(errorMessage(e)); throw e }
|
|
241
|
+
return { id, pid: child.pid, conversationId: s.conversationId, exited, close: () => shutdown('사용자가 관리형 연결을 종료했습니다.') }
|
|
242
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Generated from src/monitor-cli.mts. Edit the .mts source and run npm run build.
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createMonitor, renderMonitor } from './monitor.mjs';
|
|
4
|
+
import { errorMessage } from './session-types.mjs';
|
|
5
|
+
import { renderPipelineGraph } from './pipeline-graph.mjs';
|
|
6
|
+
export async function runMonitor(args) {
|
|
7
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
8
|
+
console.log('axmap monitor [--cwd <repo>] [--interval 1000] [--once | --json] [--no-color]\n세션·요청 파이프라인·자동 대화·선점·최근 이벤트를 실시간으로 표시합니다.\nTTY에서는 계속 갱신하며, 파이프/리디렉션에서는 한 번만 출력합니다. q / Esc / Ctrl+C 종료.');
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
const allowed = new Set(['--cwd', '--interval', '--once', '--json', '--no-color', '--graph']);
|
|
12
|
+
for (let i = 0; i < args.length; i++) {
|
|
13
|
+
if (!allowed.has(args[i]))
|
|
14
|
+
throw new Error(`알 수 없는 옵션: ${args[i]}`);
|
|
15
|
+
if (args[i] === '--cwd' || args[i] === '--interval') {
|
|
16
|
+
if (!args[i + 1] || args[i + 1].startsWith('--'))
|
|
17
|
+
throw new Error(`${args[i]} 값이 필요합니다.`);
|
|
18
|
+
i++;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const option = (name) => { const index = args.indexOf(name); return index < 0 ? undefined : args[index + 1]; };
|
|
22
|
+
const interval = Number(option('--interval') || 1000);
|
|
23
|
+
if (!Number.isInteger(interval) || interval < 250 || interval > 60000)
|
|
24
|
+
throw new Error('interval은 250~60000ms 정수여야 합니다.');
|
|
25
|
+
const collect = createMonitor(path.resolve(option('--cwd') || process.cwd()));
|
|
26
|
+
const render = args.includes('--graph') ? renderPipelineGraph : renderMonitor;
|
|
27
|
+
const live = !!process.stdout.isTTY && !!process.stdin.isTTY && process.env.TERM !== 'dumb' && !args.includes('--once') && !args.includes('--json');
|
|
28
|
+
const color = !!process.stdout.isTTY && !args.includes('--no-color') && process.env.NO_COLOR === undefined && process.env.TERM !== 'dumb';
|
|
29
|
+
if (!live) {
|
|
30
|
+
const snapshot = await collect();
|
|
31
|
+
console.log(args.includes('--json') ? JSON.stringify(snapshot, null, 2) : render(snapshot, { columns: process.stdout.columns || 100, rows: process.stdout.rows || 56, color }));
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
let stopped = false, frame = 0, timer, animation;
|
|
35
|
+
let latest = null;
|
|
36
|
+
const wasRaw = !!process.stdin.isRaw;
|
|
37
|
+
await new Promise(resolve => {
|
|
38
|
+
const restore = () => {
|
|
39
|
+
if (stopped)
|
|
40
|
+
return;
|
|
41
|
+
stopped = true;
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
clearInterval(animation);
|
|
44
|
+
process.stdin.off('data', input);
|
|
45
|
+
process.off('SIGINT', restore);
|
|
46
|
+
process.off('SIGTERM', restore);
|
|
47
|
+
process.off('exit', restore);
|
|
48
|
+
process.stdin.setRawMode(wasRaw);
|
|
49
|
+
process.stdin.pause();
|
|
50
|
+
process.stdout.write('\x1b[0m\x1b[?25h\x1b[?1049l');
|
|
51
|
+
resolve();
|
|
52
|
+
};
|
|
53
|
+
const input = (text) => { if (text === '\x1b' || text.includes('\x03') || /^[qQ]+$/.test(text))
|
|
54
|
+
restore(); };
|
|
55
|
+
const draw = () => {
|
|
56
|
+
if (stopped || !latest)
|
|
57
|
+
return;
|
|
58
|
+
const view = render(latest, { columns: process.stdout.columns || 100, rows: Math.max(1, (process.stdout.rows || 36) - 1), color, frame: frame++ });
|
|
59
|
+
process.stdout.write('\x1b[H' + view.replaceAll('\n', '\x1b[K\r\n') + '\x1b[K\x1b[J');
|
|
60
|
+
};
|
|
61
|
+
const update = async () => {
|
|
62
|
+
try {
|
|
63
|
+
const snapshot = await collect();
|
|
64
|
+
if (stopped)
|
|
65
|
+
return;
|
|
66
|
+
latest = snapshot;
|
|
67
|
+
draw();
|
|
68
|
+
}
|
|
69
|
+
catch (e) {
|
|
70
|
+
restore();
|
|
71
|
+
console.error(`axMap monitor: ${errorMessage(e)}`);
|
|
72
|
+
process.exitCode = 1;
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (!stopped)
|
|
76
|
+
timer = setTimeout(update, interval);
|
|
77
|
+
};
|
|
78
|
+
process.stdout.write('\x1b[?1049h\x1b[?25l\x1b[2J\x1b[H');
|
|
79
|
+
process.stdin.setEncoding('utf8');
|
|
80
|
+
process.stdin.setRawMode(true);
|
|
81
|
+
process.stdin.resume();
|
|
82
|
+
process.stdin.on('data', input);
|
|
83
|
+
process.once('SIGINT', restore);
|
|
84
|
+
process.once('SIGTERM', restore);
|
|
85
|
+
process.once('exit', restore);
|
|
86
|
+
animation = setInterval(draw, 180);
|
|
87
|
+
void update();
|
|
88
|
+
});
|
|
89
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { createMonitor, renderMonitor } from './monitor.mjs'
|
|
3
|
+
import type { MonitorSnapshot } from './monitor.mjs'
|
|
4
|
+
import { errorMessage } from './session-types.mjs'
|
|
5
|
+
import { renderPipelineGraph } from './pipeline-graph.mjs'
|
|
6
|
+
|
|
7
|
+
export async function runMonitor(args: string[]): Promise<void> {
|
|
8
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
9
|
+
console.log('axmap monitor [--cwd <repo>] [--interval 1000] [--once | --json] [--no-color]\n세션·요청 파이프라인·자동 대화·선점·최근 이벤트를 실시간으로 표시합니다.\nTTY에서는 계속 갱신하며, 파이프/리디렉션에서는 한 번만 출력합니다. q / Esc / Ctrl+C 종료.')
|
|
10
|
+
return
|
|
11
|
+
}
|
|
12
|
+
const allowed = new Set(['--cwd', '--interval', '--once', '--json', '--no-color', '--graph'])
|
|
13
|
+
for (let i = 0; i < args.length; i++) {
|
|
14
|
+
if (!allowed.has(args[i]!)) throw new Error(`알 수 없는 옵션: ${args[i]}`)
|
|
15
|
+
if (args[i] === '--cwd' || args[i] === '--interval') {
|
|
16
|
+
if (!args[i + 1] || args[i + 1]!.startsWith('--')) throw new Error(`${args[i]} 값이 필요합니다.`)
|
|
17
|
+
i++
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const option = (name: string) => { const index = args.indexOf(name); return index < 0 ? undefined : args[index + 1] }
|
|
21
|
+
const interval = Number(option('--interval') || 1000)
|
|
22
|
+
if (!Number.isInteger(interval) || interval < 250 || interval > 60000) throw new Error('interval은 250~60000ms 정수여야 합니다.')
|
|
23
|
+
const collect = createMonitor(path.resolve(option('--cwd') || process.cwd()))
|
|
24
|
+
const render = args.includes('--graph') ? renderPipelineGraph : renderMonitor
|
|
25
|
+
const live = !!process.stdout.isTTY && !!process.stdin.isTTY && process.env.TERM !== 'dumb' && !args.includes('--once') && !args.includes('--json')
|
|
26
|
+
const color = !!process.stdout.isTTY && !args.includes('--no-color') && process.env.NO_COLOR === undefined && process.env.TERM !== 'dumb'
|
|
27
|
+
if (!live) {
|
|
28
|
+
const snapshot = await collect()
|
|
29
|
+
console.log(args.includes('--json') ? JSON.stringify(snapshot, null, 2) : render(snapshot, { columns: process.stdout.columns || 100, rows: process.stdout.rows || 56, color }))
|
|
30
|
+
return
|
|
31
|
+
}
|
|
32
|
+
let stopped = false, frame = 0, timer: NodeJS.Timeout | undefined, animation: NodeJS.Timeout | undefined
|
|
33
|
+
let latest: MonitorSnapshot | null = null
|
|
34
|
+
const wasRaw = !!process.stdin.isRaw
|
|
35
|
+
await new Promise<void>(resolve => {
|
|
36
|
+
const restore = () => {
|
|
37
|
+
if (stopped) return
|
|
38
|
+
stopped = true; clearTimeout(timer); clearInterval(animation)
|
|
39
|
+
process.stdin.off('data', input); process.off('SIGINT', restore); process.off('SIGTERM', restore); process.off('exit', restore)
|
|
40
|
+
process.stdin.setRawMode(wasRaw); process.stdin.pause()
|
|
41
|
+
process.stdout.write('\x1b[0m\x1b[?25h\x1b[?1049l')
|
|
42
|
+
resolve()
|
|
43
|
+
}
|
|
44
|
+
const input = (text: string) => { if (text === '\x1b' || text.includes('\x03') || /^[qQ]+$/.test(text)) restore() }
|
|
45
|
+
const draw = () => {
|
|
46
|
+
if (stopped || !latest) return
|
|
47
|
+
const view = render(latest, { columns: process.stdout.columns || 100, rows: Math.max(1, (process.stdout.rows || 36) - 1), color, frame: frame++ })
|
|
48
|
+
process.stdout.write('\x1b[H' + view.replaceAll('\n', '\x1b[K\r\n') + '\x1b[K\x1b[J')
|
|
49
|
+
}
|
|
50
|
+
const update = async () => {
|
|
51
|
+
try {
|
|
52
|
+
const snapshot = await collect()
|
|
53
|
+
if (stopped) return
|
|
54
|
+
latest = snapshot; draw()
|
|
55
|
+
} catch (e) {
|
|
56
|
+
restore(); console.error(`axMap monitor: ${errorMessage(e)}`); process.exitCode = 1; return
|
|
57
|
+
}
|
|
58
|
+
if (!stopped) timer = setTimeout(update, interval)
|
|
59
|
+
}
|
|
60
|
+
process.stdout.write('\x1b[?1049h\x1b[?25l\x1b[2J\x1b[H')
|
|
61
|
+
process.stdin.setEncoding('utf8'); process.stdin.setRawMode(true); process.stdin.resume(); process.stdin.on('data', input)
|
|
62
|
+
process.once('SIGINT', restore); process.once('SIGTERM', restore); process.once('exit', restore)
|
|
63
|
+
animation = setInterval(draw, 180)
|
|
64
|
+
void update()
|
|
65
|
+
})
|
|
66
|
+
}
|