axmap-cli 1.5.0 → 1.6.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.
Files changed (43) hide show
  1. package/README.ko.md +20 -0
  2. package/README.md +20 -0
  3. package/bin/axmap.mjs +6 -0
  4. package/mcp/README.md +6 -0
  5. package/mcp/pipeline.html +157 -0
  6. package/mcp/server.mjs +128 -18
  7. package/package.json +11 -3
  8. package/src/agentcli.mjs +17 -14
  9. package/src/agentcli.mts +19 -0
  10. package/src/bridge.mjs +296 -219
  11. package/src/bridge.mts +281 -0
  12. package/src/external-console.mjs +140 -97
  13. package/src/external-console.mts +128 -0
  14. package/src/managed-session.mjs +263 -169
  15. package/src/managed-session.mts +198 -0
  16. package/src/monitor-cli.mjs +87 -0
  17. package/src/monitor-cli.mts +64 -0
  18. package/src/monitor.mjs +240 -0
  19. package/src/monitor.mts +195 -0
  20. package/src/node-pty.d.ts +13 -0
  21. package/src/pipeline-mcp.mjs +109 -0
  22. package/src/pipeline-mcp.mts +103 -0
  23. package/src/pipeline-statusline.mjs +135 -0
  24. package/src/pipeline-statusline.mts +106 -0
  25. package/src/session-dialogue.mjs +168 -116
  26. package/src/session-dialogue.mts +136 -0
  27. package/src/session-status.mjs +47 -41
  28. package/src/session-status.mts +50 -0
  29. package/src/session-types.mjs +7 -0
  30. package/src/session-types.mts +118 -0
  31. package/src/session-usage.mjs +33 -28
  32. package/src/session-usage.mts +39 -0
  33. package/src/terminal-bridge.mjs +293 -209
  34. package/src/terminal-bridge.mts +235 -0
  35. package/src/windows-console.mjs +42 -0
  36. package/src/windows-console.mts +29 -0
  37. package/tools/bench-console.mjs +70 -0
  38. package/tools/bridge.mjs +9 -6
  39. package/tools/build.mjs +39 -0
  40. package/tools/monitor.mjs +5 -0
  41. package/tools/pipeline.mjs +26 -0
  42. package/tools/run-tests.mjs +3 -2
  43. package/tools/windows-console.cs +116 -0
@@ -0,0 +1,235 @@
1
+ /** The user launches an interactive CLI. axMap owns its PTY and a local,
2
+ * authenticated pipe; remote requests never launch/resume another model. */
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import net from 'node:net'
7
+ import { randomUUID, randomBytes, timingSafeEqual } from 'node:crypto'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { createRequire } from 'node:module'
10
+ import { bridgeHome, repoKey, readJSON, writeJSON } from './bridge.mjs'
11
+ import { errorCode, errorMessage } from './session-types.mjs'
12
+ import type { IPty } from 'node-pty'
13
+ import type { Provider, SessionRecord, LocalMessage, JobRecord, RequestState, TranscriptEntry } from './session-types.mjs'
14
+
15
+ interface TerminalOptions {
16
+ executable: string; args?: string[]; provider: Provider; cwd?: string; onData?: (data: string) => void; cols?: number; rows?: number
17
+ }
18
+ interface CommandHook { type: string; command: string; timeout: number; statusMessage?: string }
19
+ interface HookGroup { hooks?: Array<{ statusMessage?: string; [key: string]: unknown }>; [key: string]: unknown }
20
+ interface HookConfig { hooks?: Record<string, HookGroup[]>; [key: string]: unknown }
21
+
22
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
23
+ const validID = (id: string | undefined) => /^[0-9a-f-]{36}$/i.test(id || '')
24
+ const sessionFile = (id: string) => {
25
+ if (!validID(id)) throw new Error('잘못된 터미널 세션 ID입니다.')
26
+ return path.join(bridgeHome(), 'sessions', `${id}.json`)
27
+ }
28
+ const pipeFor = (id: string) => process.platform === 'win32'
29
+ ? `\\\\.\\pipe\\axmap-${id}` : path.join(bridgeHome(), `${id}.sock`)
30
+
31
+ export function sendTerminal(id: string, message: LocalMessage, token: string | null = null, { timeoutMs = 10000 } = {}): Promise<unknown> {
32
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) throw new Error('양의 응답 시간 한도가 필요합니다.')
33
+ const s = readJSON<SessionRecord>(sessionFile(id))
34
+ if (!['pty', 'stdio'].includes(s.transport || '')) throw new Error('로컬 관리형 세션이 아닙니다.')
35
+ return new Promise((resolve, reject) => {
36
+ const socket = net.createConnection(pipeFor(id))
37
+ socket.setEncoding('utf8')
38
+ let buffer = ''
39
+ const fail = (e: Error) => { socket.destroy(); reject(e) }
40
+ socket.setTimeout(timeoutMs, () => fail(new Error('로컬 세션 응답 시간 초과. 자동 재전송하지 마세요.')))
41
+ socket.on('error', fail)
42
+ socket.on('connect', () => socket.write(JSON.stringify({ ...message, token: token || s.token }) + '\n'))
43
+ socket.on('data', chunk => {
44
+ buffer += chunk
45
+ if (Buffer.byteLength(buffer) > 1024 * 1024) return fail(new Error('로컬 응답 크기 제한 초과'))
46
+ const end = buffer.indexOf('\n')
47
+ if (end < 0) return
48
+ socket.end()
49
+ try {
50
+ const response = JSON.parse(buffer.slice(0, end)) as { error?: string; result?: unknown }
51
+ if (response.error) reject(new Error(response.error)); else resolve(response.result)
52
+ } catch (e) { reject(e) }
53
+ })
54
+ socket.on('end', () => { if (!buffer.includes('\n')) reject(new Error('세션 연결이 응답 없이 종료됐습니다.')) })
55
+ })
56
+ }
57
+
58
+ export async function startTerminal({ executable, args = [], provider, cwd = process.cwd(), onData = () => {}, cols = 100, rows = 30 }: TerminalOptions) {
59
+ const { spawn } = await import('node-pty')
60
+ const id = randomUUID(), token = randomBytes(32).toString('hex')
61
+ const s: SessionRecord = { id, provider, transport: 'pty', token, workspaces: [cwd], repos: [repoKey(cwd)],
62
+ state: 'starting', fullyIdle: false, registeredAt: new Date().toISOString(), event: 'launch' }
63
+ const jobs = new Map<string, JobRecord>()
64
+ let pending: JobRecord | null = null, draft = false, term: IPty, closed = false, stopTimer: NodeJS.Timeout | undefined
65
+ const save = () => { s.registeredAt = new Date().toISOString(); writeJSON(sessionFile(id), s) }
66
+ const finish = (state: RequestState, result?: unknown, error?: string) => {
67
+ if (!pending) return
68
+ Object.assign(pending, { state, result, error, completedAt: new Date().toISOString() })
69
+ jobs.set(pending.id, { ...pending }); pending = null
70
+ }
71
+ const handle = (message: LocalMessage) => {
72
+ const offered = Buffer.from(typeof message.token === 'string' ? message.token : '')
73
+ const expected = Buffer.from(token)
74
+ if (offered.length !== expected.length || !timingSafeEqual(offered, expected)) throw new Error('로컬 세션 인증 실패')
75
+ if (message.action === 'status') return { state: s.state, id, provider }
76
+ if (message.action === 'result') {
77
+ const job = jobs.get(message.id)
78
+ if (!job) throw new Error('이 터미널에 해당 요청이 없습니다.')
79
+ return job
80
+ }
81
+ if (message.action === 'hook') {
82
+ clearTimeout(stopTimer)
83
+ const { input, event } = message
84
+ s.event = event; s.model = input.modelName || input.model || s.model
85
+ s.conversationId = input.conversationId || input.session_id || s.conversationId
86
+ if (event !== 'Stop') {
87
+ s.state = 'running'; s.fullyIdle = false
88
+ if (pending && event === 'UserPromptSubmit' && typeof input.prompt === 'string') {
89
+ pending.observed = input.prompt.includes(`[axMap request ${pending.id}]`)
90
+ }
91
+ save(); return {}
92
+ }
93
+ if (provider === 'agy' && input.fullyIdle !== true) { save(); return {} }
94
+ let answer = input.last_assistant_message
95
+ if (provider === 'agy') {
96
+ const log = path.join(process.env.AXMAP_AGY_HOME || path.join(os.homedir(), '.gemini', 'antigravity-cli'),
97
+ 'brain', s.conversationId || '', '.system_generated', 'logs', 'transcript.jsonl')
98
+ if (path.resolve(input.transcriptPath || '') !== log) throw new Error('종료 훅의 대화 기록 경로가 다릅니다.')
99
+ const lines = fs.readFileSync(log, 'utf8').trimEnd().split('\n').filter(Boolean).map(line => JSON.parse(line) as TranscriptEntry)
100
+ const lastUser = lines.findLast(e => e.type === 'USER_INPUT')
101
+ if (pending) pending.observed = String(lastUser?.content).includes(`[axMap request ${pending.id}]`)
102
+ answer = lines.findLast(e => e.type === 'PLANNER_RESPONSE' && e.source === 'MODEL' && e.status === 'DONE')?.content
103
+ }
104
+ if (pending) finish(pending.observed && !pending.interrupted && typeof answer === 'string' ? 'completed' : 'superseded',
105
+ pending.observed && !pending.interrupted ? answer : undefined,
106
+ pending.observed && !pending.interrupted ? undefined : '다른 입력이 섞였거나 이 요청의 응답을 확인하지 못했습니다.')
107
+ // Stop runs before the provider restores its input UI. Allow that handoff
108
+ // to finish before accepting another injected prompt.
109
+ s.state = 'settling'; s.fullyIdle = false; save()
110
+ stopTimer = setTimeout(() => { if (!closed && s.state === 'settling') { s.state = 'idle'; s.fullyIdle = true; draft = false; save() } }, 500)
111
+ return {}
112
+ }
113
+ if (message.action === 'submit') {
114
+ const request = message.request
115
+ if (closed || s.state !== 'idle' || draft || pending) throw new Error('상대가 대기 중이 아니거나 입력 중입니다. 작업을 전달하지 않았습니다.')
116
+ if (!validID(request?.id) || request.to !== id || typeof request.prompt !== 'string' || !request.prompt.trim() || Buffer.byteLength(request.prompt) > 32768) throw new Error('요청 형식이 올바르지 않습니다.')
117
+ const prompt = `[axMap request ${request.id}]\n요청자: ${String(request.from || 'axmap')}\n${request.prompt}`
118
+ if (/[\x00-\x08\x0b-\x1f\x7f]/.test(prompt)) throw new Error('터미널 제어 문자가 포함된 요청은 보낼 수 없습니다.')
119
+ pending = { id: request.id, to: id, state: 'submitted' }; jobs.set(request.id, pending)
120
+ s.state = 'running'; s.fullyIdle = false; save()
121
+ term.write(`\x1b[200~${prompt}\x1b[201~`)
122
+ setTimeout(() => { if (!closed) term.write('\r') }, 100)
123
+ return { accepted: true, session: id }
124
+ }
125
+ throw new Error('지원하지 않는 로컬 세션 요청입니다.')
126
+ }
127
+ fs.mkdirSync(bridgeHome(), { recursive: true, mode: 0o700 })
128
+ const server = net.createServer(socket => {
129
+ socket.setEncoding('utf8')
130
+ let buffer = '', handled = false
131
+ socket.setTimeout(15000, () => socket.destroy())
132
+ socket.on('error', () => {})
133
+ socket.on('data', chunk => {
134
+ if (handled) return
135
+ buffer += chunk
136
+ if (Buffer.byteLength(buffer) > 65536) return socket.destroy()
137
+ const end = buffer.indexOf('\n'); if (end < 0) return
138
+ handled = true
139
+ try { socket.end(JSON.stringify({ result: handle(JSON.parse(buffer.slice(0, end))) }) + '\n') }
140
+ catch (e) { socket.end(JSON.stringify({ error: errorMessage(e) }) + '\n') }
141
+ })
142
+ })
143
+ await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(pipeFor(id), resolve) })
144
+ if (process.platform !== 'win32') fs.chmodSync(pipeFor(id), 0o600)
145
+ save()
146
+ try {
147
+ term = spawn(executable, args, { name: 'xterm-256color', cols, rows, cwd, env: { ...process.env,
148
+ AXMAP_TERMINAL_SESSION: id, AXMAP_TERMINAL_TOKEN: token,
149
+ AXMAP_AGENT: `${provider}-${id.slice(0, 8)}`, AXMAP_SESSION: id,
150
+ }, useConpty: true, useConptyDll: process.platform === 'win32' })
151
+ } catch (e) { server.close(); s.state = 'closed'; save(); throw e }
152
+ term.onData(onData)
153
+ const exited = new Promise<{ exitCode: number; signal?: number }>(resolve => term.onExit(ev => {
154
+ if (closed) return
155
+ closed = true; clearTimeout(stopTimer)
156
+ // ConPTY may keep its input handle alive after a normal child exit.
157
+ if (process.platform === 'win32') { try { term.kill() } catch { /* already closed */ } }
158
+ finish('unknown', undefined, '요청의 완료를 확인하기 전에 세션이 종료됐습니다.')
159
+ s.state = 'closed'; s.fullyIdle = false; save(); server.close(); resolve(ev)
160
+ }))
161
+ return { id, pid: term.pid, exited,
162
+ input(data: string) {
163
+ const terminalReply = /^\x1b\[(?:\d+;\d+R|\?[^a-zA-Z]*[a-zA-Z])$/.test(String(data))
164
+ if (terminalReply) { term.write(data); return }
165
+ if (pending) pending.interrupted = true
166
+ draft = !String(data).includes('\r')
167
+ if (!draft) { s.state = 'running'; s.fullyIdle = false; save() }
168
+ term.write(data)
169
+ },
170
+ resize: (c: number, r: number) => term.resize(c, r),
171
+ close: () => term.kill(),
172
+ }
173
+ }
174
+
175
+ /** Copy only production dependencies from the npm package, not a developer's
176
+ * entire node_modules. This also keeps the setup copy independent of npm cache. */
177
+ export function installTerminalRuntime(sourceRoot: string, destRoot = ROOT) {
178
+ const source = path.resolve(sourceRoot), dest = path.resolve(destRoot)
179
+ const require = createRequire(path.join(source, 'package.json'))
180
+ const copied = new Set<string>()
181
+ function copy(name: string): void {
182
+ if (copied.has(name)) return
183
+ const descriptor = require.resolve(`${name}/package.json`)
184
+ const pkg = readJSON<{ dependencies?: Record<string, string>; optionalDependencies?: Record<string, string> }>(descriptor)
185
+ const target = path.join(dest, 'node_modules', ...name.split('/'))
186
+ if (path.resolve(path.dirname(descriptor)) !== path.resolve(target)) {
187
+ fs.mkdirSync(path.dirname(target), { recursive: true })
188
+ fs.cpSync(path.dirname(descriptor), target, { recursive: true, force: true })
189
+ }
190
+ copied.add(name)
191
+ for (const dependency of Object.keys(pkg.dependencies || {})) copy(dependency)
192
+ for (const dependency of Object.keys(pkg.optionalDependencies || {})) {
193
+ try { require.resolve(`${dependency}/package.json`) }
194
+ catch (e) { if (errorCode(e) === 'MODULE_NOT_FOUND') continue; throw e }
195
+ copy(dependency)
196
+ }
197
+ }
198
+ copy('node-pty')
199
+ const installed = createRequire(path.join(dest, 'package.json'))('node-pty')
200
+ if (typeof installed.spawn !== 'function') throw new Error('설치된 터미널 라이브러리를 불러오지 못했습니다.')
201
+ return { packages: [...copied], destination: dest }
202
+ }
203
+
204
+ export function installTerminalHooks(home = os.homedir(), provider = 'agy') {
205
+ if (!['agy', 'codex'].includes(provider)) throw new Error('지원하지 않는 CLI 훅입니다.')
206
+ const target = provider === 'agy' ? path.join(home, '.gemini', 'config', 'hooks.json')
207
+ : path.join(home, '.codex', 'hooks.json')
208
+ const config = fs.existsSync(target) ? readJSON<HookConfig>(target) : {}
209
+ if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error('기존 hooks.json을 읽지 못했습니다.')
210
+ if (provider === 'codex' && config.hooks !== undefined && (!config.hooks || typeof config.hooks !== 'object' || Array.isArray(config.hooks))) throw new Error('기존 Codex hooks 설정이 객체가 아닙니다.')
211
+ const definition: Record<string, CommandHook[]> = {}
212
+ const script = path.join(ROOT, 'tools', 'run.mjs')
213
+ if ([process.execPath, script].some(p => /["\r\n%&|<>^]/.test(p))) throw new Error('훅 경로에 지원하지 않는 셸 문자가 있습니다.')
214
+ for (const event of provider === 'agy' ? ['SessionStart', 'PreInvocation', 'Stop'] : ['SessionStart', 'UserPromptSubmit', 'Stop']) {
215
+ let command = `"${process.execPath}" "${script}" hook ${event}`
216
+ if (process.platform === 'win32') {
217
+ const wrapper = path.join(home, '.axmap', 'bridge', `terminal-${provider}-${event}.cmd`)
218
+ if (/[\s"%&|<>^]/.test(wrapper)) throw new Error('이 Windows 훅 경로에는 공백/셸 문자를 사용할 수 없습니다.')
219
+ fs.mkdirSync(path.dirname(wrapper), { recursive: true })
220
+ fs.writeFileSync(wrapper, `@echo off\r\n${command}\r\n`)
221
+ command = wrapper
222
+ }
223
+ if (provider === 'agy') definition[event] = [{ type: 'command', command, timeout: 10 }]
224
+ else {
225
+ config.hooks ||= {}
226
+ const existing = config.hooks[event] || []
227
+ if (!Array.isArray(existing)) throw new Error(`기존 Codex ${event} 설정이 배열이 아닙니다.`)
228
+ config.hooks[event] = existing.filter(group => !(Array.isArray(group.hooks) && group.hooks.some(h => h.statusMessage === 'axMap terminal bridge')))
229
+ config.hooks[event].push({ hooks: [{ type: 'command', command, timeout: 10, statusMessage: 'axMap terminal bridge' }] })
230
+ }
231
+ }
232
+ if (provider === 'agy') config['axmap-terminal'] = definition
233
+ writeJSON(target, config)
234
+ return target
235
+ }
@@ -0,0 +1,42 @@
1
+ // Generated from src/windows-console.mts. Edit the .mts source and run npm run build.
2
+ /** Cache a framework-only native helper; machines without csc keep the PS path. */
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+ import { spawnSync } from 'node:child_process';
8
+ import { fileURLToPath } from 'node:url';
9
+ const source = fileURLToPath(new URL('../tools/windows-console.cs', import.meta.url));
10
+ export function nativeConsoleHelper() {
11
+ if (process.platform !== 'win32' || process.env.AXMAP_CONSOLE_HELPER === 'powershell')
12
+ return null;
13
+ const framework = path.join(process.env.WINDIR || 'C:\\Windows', 'Microsoft.NET');
14
+ const compiler = ['Framework64', 'Framework'].map(p => path.join(framework, p, 'v4.0.30319', 'csc.exe')).find(p => fs.existsSync(p));
15
+ if (!compiler || !fs.existsSync(source))
16
+ return null;
17
+ const hash = createHash('sha256').update(fs.readFileSync(source)).digest('hex').slice(0, 24);
18
+ const dir = path.join(process.env.AXMAP_STATE_DIR || path.join(os.homedir(), '.axmap'), 'bridge', 'native');
19
+ const executable = path.join(dir, `console-${hash}.exe`);
20
+ if (fs.existsSync(executable))
21
+ return executable;
22
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
23
+ const temporary = path.join(dir, `${hash}-${randomUUID()}.exe`);
24
+ try {
25
+ const r = spawnSync(compiler, ['/nologo', '/optimize+', '/target:exe', '/reference:System.Web.Extensions.dll',
26
+ '/reference:System.Management.dll', `/out:${temporary}`, source], { encoding: 'utf8', windowsHide: true, timeout: 15000 });
27
+ if (r.error || r.status !== 0)
28
+ return null;
29
+ try {
30
+ fs.renameSync(temporary, executable);
31
+ }
32
+ catch (e) {
33
+ if (!fs.existsSync(executable))
34
+ throw e;
35
+ }
36
+ return executable;
37
+ }
38
+ finally {
39
+ if (fs.existsSync(temporary))
40
+ fs.unlinkSync(temporary);
41
+ }
42
+ }
@@ -0,0 +1,29 @@
1
+ /** Cache a framework-only native helper; machines without csc keep the PS path. */
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { createHash, randomUUID } from 'node:crypto'
6
+ import { spawnSync } from 'node:child_process'
7
+ import { fileURLToPath } from 'node:url'
8
+
9
+ const source = fileURLToPath(new URL('../tools/windows-console.cs', import.meta.url))
10
+ export function nativeConsoleHelper() {
11
+ if (process.platform !== 'win32' || process.env.AXMAP_CONSOLE_HELPER === 'powershell') return null
12
+ const framework = path.join(process.env.WINDIR || 'C:\\Windows', 'Microsoft.NET')
13
+ const compiler = ['Framework64', 'Framework'].map(p => path.join(framework, p, 'v4.0.30319', 'csc.exe')).find(p => fs.existsSync(p))
14
+ if (!compiler || !fs.existsSync(source)) return null
15
+ const hash = createHash('sha256').update(fs.readFileSync(source)).digest('hex').slice(0, 24)
16
+ const dir = path.join(process.env.AXMAP_STATE_DIR || path.join(os.homedir(), '.axmap'), 'bridge', 'native')
17
+ const executable = path.join(dir, `console-${hash}.exe`)
18
+ if (fs.existsSync(executable)) return executable
19
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
20
+ const temporary = path.join(dir, `${hash}-${randomUUID()}.exe`)
21
+ try {
22
+ const r = spawnSync(compiler, ['/nologo', '/optimize+', '/target:exe', '/reference:System.Web.Extensions.dll',
23
+ '/reference:System.Management.dll', `/out:${temporary}`, source], { encoding: 'utf8', windowsHide: true, timeout: 15000 })
24
+ if (r.error || r.status !== 0) return null
25
+ try { fs.renameSync(temporary, executable) }
26
+ catch (e) { if (!fs.existsSync(executable)) throw e }
27
+ return executable
28
+ } finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary) }
29
+ }
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+ /** Explicitly invoked real-console benchmark. Sends only the listed test prompts. */
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { randomUUID } from 'node:crypto'
6
+ import { consoleCall, attachConsole } from '../src/external-console.mjs'
7
+ import { dispatchRequest, waitForRequest } from '../src/bridge.mjs'
8
+ import { nativeConsoleHelper } from '../src/windows-console.mjs'
9
+
10
+ const args = process.argv.slice(2)
11
+ const option = n => { const i = args.indexOf(`--${n}`); return i < 0 ? undefined : args[i + 1] }
12
+ const pid = Number(option('pid'))
13
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('Usage: node tools/bench-console.mjs --pid <agy PID> [--output file]')
14
+ if (!nativeConsoleHelper()) throw new Error('Native helper is unavailable; refusing to label fallback timings as native.')
15
+ const originalMode = process.env.AXMAP_CONSOLE_HELPER
16
+ const report = { measuredAt: new Date().toISOString(), platform: process.platform, node: process.version,
17
+ pid, cwd: process.cwd(), snapshots: {}, requests: [], safetyChecks: {} }
18
+ const median = values => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]
19
+ try {
20
+ for (const mode of ['powershell', 'native']) {
21
+ if (mode === 'powershell') process.env.AXMAP_CONSOLE_HELPER = mode
22
+ else delete process.env.AXMAP_CONSOLE_HELPER
23
+ const samples = []
24
+ for (let i = 0; i < 7; i++) {
25
+ const start = performance.now()
26
+ consoleCall(pid)
27
+ samples.push(Number((performance.now() - start).toFixed(2)))
28
+ }
29
+ report.snapshots[mode] = { samplesMs: samples, medianMs: median(samples) }
30
+ console.log(JSON.stringify({ event: 'snapshots', mode, ...report.snapshots[mode] }))
31
+ }
32
+ const live = consoleCall(pid)
33
+ report.startedAt = live.startedAt
34
+ for (const [name, payload] of Object.entries({ changedIdentity: { startedAt: 'invalid' }, changedScreen: { startedAt: live.startedAt, expectedScreen: 'invalid', text: 'MUST_NOT_BE_SENT' } })) {
35
+ try { consoleCall(pid, name === 'changedScreen' ? 'send' : 'snapshot', payload); throw new Error('Safety rejection missing') }
36
+ catch (e) {
37
+ const expected = name === 'changedScreen' ? /Console changed/ : /identity changed/
38
+ if (!expected.test(e.message)) throw e
39
+ report.safetyChecks[name] = e.message
40
+ }
41
+ }
42
+ const session = attachConsole({ pid, cwd: process.cwd() })
43
+ report.sessionId = session.id
44
+ const memory = randomUUID().slice(0, 8)
45
+ const prompts = [
46
+ { prompt: `Transport latency test 1. Remember the code ${memory} for the next message. Do not use tools, MCP, commands or files. Reply in this chat with exactly: AXMAP_LATENCY_READY`, expected: 'AXMAP_LATENCY_READY' },
47
+ { prompt: 'Transport latency test 2. Do not use tools, MCP, commands or files. Reply in this chat with only the code I asked you to remember in the previous message.', expected: memory },
48
+ { prompt: 'Transport latency test 3 (Unicode). Do not use tools, MCP, commands or files. Reply in this chat with exactly: 한글_왕복_OK', expected: '한글_왕복_OK' },
49
+ ]
50
+ for (const { prompt, expected } of prompts) {
51
+ const start = performance.now()
52
+ const request = dispatchRequest({ to: session.id, cwd: process.cwd(), from: 'codex-latency-benchmark', prompt })
53
+ const dispatchMs = performance.now() - start
54
+ const result = await waitForRequest(request.id, process.cwd(), 30000)
55
+ const entry = { id: request.id, dispatchMs: Number(dispatchMs.toFixed(2)), roundTripMs: Number((performance.now() - start).toFixed(2)),
56
+ state: result.state, expected, result: result.result, passed: result.state === 'completed' && String(result.result).includes(expected) }
57
+ report.requests.push(entry)
58
+ console.log(JSON.stringify({ event: 'reply', ...entry }))
59
+ if (!entry.passed) { process.exitCode = 1; break }
60
+ }
61
+ report.snapshotSpeedup = Number((report.snapshots.powershell.medianMs / report.snapshots.native.medianMs).toFixed(2))
62
+ if (option('output')) {
63
+ const output = path.resolve(option('output'))
64
+ fs.mkdirSync(path.dirname(output), { recursive: true })
65
+ fs.writeFileSync(output, JSON.stringify(report, null, 2) + '\n')
66
+ }
67
+ } finally {
68
+ if (originalMode === undefined) delete process.env.AXMAP_CONSOLE_HELPER
69
+ else process.env.AXMAP_CONSOLE_HELPER = originalMode
70
+ }
package/tools/bridge.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import fs from 'node:fs'
3
3
  import { resolveBin } from '../src/agentcli.mjs'
4
4
  import { codexInvocation } from './mcp-register.mjs'
5
- import { dispatchRequest, installHooks, registerHook, requestResult, sessions, uninstallHooks } from '../src/bridge.mjs'
5
+ import { dispatchRequest, installHooks, registerHook, waitForRequest, sessions, uninstallHooks } from '../src/bridge.mjs'
6
6
  import { startManagedSession } from '../src/managed-session.mjs'
7
7
  import { runDialogue, startBackgroundDialogue, dialogueResult, stopDialogue } from '../src/session-dialogue.mjs'
8
8
  import { sendTerminal } from '../src/terminal-bridge.mjs'
@@ -64,12 +64,15 @@ try {
64
64
  break
65
65
  }
66
66
  case 'send': {
67
+ const waitMs = Number(option('wait-ms') || 0)
68
+ if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > 30000) throw new Error('wait-ms는 0~30000 정수여야 합니다.')
67
69
  const r = dispatchRequest({ to: option('to'), prompt: fs.readFileSync(0, 'utf8'), cwd: process.cwd(), from: process.env.AXMAP_AGENT || 'axmap' })
68
- output(r)
69
- if (r.state === 'unknown') process.exitCode = 2
70
+ const result = waitMs && r.state === 'submitted' ? await waitForRequest(r.id, process.cwd(), waitMs) : r
71
+ output(result)
72
+ if (result.state === 'unknown') process.exitCode = 2
70
73
  break
71
74
  }
72
- case 'result': output(requestResult(args[1], process.cwd())); break
75
+ case 'result': output(await waitForRequest(args[1], process.cwd(), Number(option('wait-ms') || 0))); break
73
76
  case undefined:
74
77
  case '--help':
75
78
  console.log(`axMap 로컬 세션 연결 — 관리형 Codex/agy와 제한된 자동 대화
@@ -87,8 +90,8 @@ axmap bridge uninstall 추가한 연결 훅 해제
87
90
  axmap bridge sessions 이 repo에 연결된 세션
88
91
  axmap bridge attach --pid <PID> 이미 실행한 Windows agy 콘솔을 현재 repo에 연결
89
92
  axmap bridge status [--json] 로컬 연결·작업·승인 대기·종료 상태 조회 (모델 호출 없음)
90
- axmap bridge send --to <세션 UUID> 본문은 stdin. 기존 세션에 전달
91
- axmap bridge result <요청 UUID> 제출/완료/불명 상태와 결과
93
+ axmap bridge send --to <세션 UUID> [--wait-ms 30000] 본문은 stdin. 전달 후 지정 시간까지 로컬에서 회신 대기
94
+ axmap bridge result <요청 UUID> [--wait-ms 30000] 제출/완료/불명 상태와 결과. 대기 중 모델 호출 없음
92
95
  관리형 stdio: Codex App Server / agy stream-json. PTY와 agentapi는 별도 실험 경로입니다.`)
93
96
  break
94
97
  default: throw new Error(`알 수 없는 bridge 명령: ${command}`)
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ /** TS owns migrated modules; checked-in JS keeps Node 20 and vendored installs usable. */
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { spawnSync } from 'node:child_process'
7
+ import { createRequire } from 'node:module'
8
+
9
+ const root = fileURLToPath(new URL('../', import.meta.url))
10
+ const check = process.argv.includes('--check')
11
+ // The stable CLI also works with TS 7's native compiler, without an unstable API.
12
+ const compiler = path.join(path.dirname(createRequire(import.meta.url).resolve('typescript/package.json')), 'bin', 'tsc')
13
+ const compiled = spawnSync(process.execPath, [compiler, '--project', path.join(root, 'tsconfig.json'), '--pretty', 'false'], {
14
+ cwd: root, stdio: 'inherit', windowsHide: true,
15
+ })
16
+ if (compiled.error) throw compiled.error
17
+ if (compiled.status !== 0) process.exit(compiled.status ?? 1)
18
+ const outputs = []
19
+ function collect(directory) {
20
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
21
+ const source = path.join(directory, entry.name)
22
+ if (entry.isDirectory()) { collect(source); continue }
23
+ if (!entry.name.endsWith('.mts')) continue
24
+ const relative = path.relative(root, source).replaceAll(path.sep, '/')
25
+ const text = fs.readFileSync(path.join(root, '.axmap', 'tsbuild', relative.replace(/\.mts$/, '.mjs')), 'utf8')
26
+ outputs.push({ target: source.replace(/\.mts$/, '.mjs'),
27
+ content: `// Generated from ${relative}. Edit the .mts source and run npm run build.\n${text}` })
28
+ }
29
+ }
30
+ collect(path.join(root, 'src'))
31
+ if (!outputs.length) throw new Error('TypeScript emitted no migrated modules.')
32
+ let stale = false
33
+ for (const { target, content } of outputs) {
34
+ if (fs.existsSync(target) && fs.readFileSync(target, 'utf8').replaceAll('\r\n', '\n') === content.replaceAll('\r\n', '\n')) continue
35
+ if (check) { console.error(`Stale generated JavaScript: ${path.relative(root, target)} (run npm run build)`); stale = true }
36
+ else fs.writeFileSync(target, content)
37
+ }
38
+ if (stale) process.exit(1)
39
+ console.log(`${check ? 'Checked' : 'Built'} ${outputs.length} TypeScript modules.`)
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { runMonitor } from '../src/monitor-cli.mjs'
3
+ import { errorMessage } from '../src/session-types.mjs'
4
+ try { await runMonitor(process.argv.slice(2)) }
5
+ catch (e) { console.error(`axMap monitor: ${errorMessage(e)}`); process.exitCode = 1 }
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs'
3
+ import { runPipelineOperation } from '../src/pipeline-mcp.mjs'
4
+ import { errorMessage } from '../src/session-types.mjs'
5
+ import { installPipelineStatusline, pipelineStatusline } from '../src/pipeline-statusline.mjs'
6
+ const output = value => process.stdout.write(JSON.stringify(value) + '\n')
7
+ let cancelled = false
8
+ process.on('message', message => { if (message?.type === 'cancel-observation') cancelled = true })
9
+ try {
10
+ const action = process.argv[2]
11
+ const option = name => { const at = process.argv.indexOf(`--${name}`); return at < 0 ? undefined : process.argv[at + 1] }
12
+ if (!action || action === '--help' || action === '-h') {
13
+ console.log('axmap pipeline install-statusline --provider claude|agy\naxmap pipeline uninstall-statusline --provider claude|agy\n현재 CLI의 상태줄에 axMap 진행을 표시합니다. 기존 명령은 보존하며 새 창은 열지 않습니다.\n대화 안 패널은 MCP ax_pipeline, 진행 알림은 ax_pipeline_watch를 사용하세요.')
14
+ } else if (action === 'install-statusline' || action === 'uninstall-statusline') {
15
+ console.log(JSON.stringify(installPipelineStatusline(option('provider'), option('home'), action === 'uninstall-statusline'), null, 2))
16
+ } else if (action === 'statusline') {
17
+ process.stdout.write(await pipelineStatusline(option('provider'), fs.readFileSync(0, 'utf8'), option('home')))
18
+ } else {
19
+ const args = JSON.parse(fs.readFileSync(0, 'utf8'))
20
+ const result = await runPipelineOperation(action, args, message => output({ type: 'progress', message }), () => cancelled)
21
+ output({ type: 'result', result })
22
+ }
23
+ } catch (e) {
24
+ if (process.argv[2] === 'statusline') console.log('axMap · 상태 확인 필요')
25
+ else output({ type: 'result', result: { content: [{ type: 'text', text: errorMessage(e) }], isError: true } })
26
+ } finally { if (process.connected) process.disconnect() }
@@ -40,9 +40,10 @@ if (files.length === 0) {
40
40
  // Windows ConPTY owns native console workers. Exercise it after other test
41
41
  // processes have exited so temporary console teardown cannot race the suite's
42
42
  // many concurrent subprocess fixtures. Both batches remain mandatory.
43
- const native = process.platform === 'win32' ? files.filter(f => path.basename(f) === 'terminal-bridge.test.mjs') : []
43
+ const nativeNames = new Set(['terminal-bridge.test.mjs', 'monitor-cli.test.mjs'])
44
+ const native = process.platform === 'win32' ? files.filter(f => nativeNames.has(path.basename(f))) : []
44
45
  const ordinary = files.filter(f => !native.includes(f))
45
- for (const batch of [ordinary, native].filter(batch => batch.length)) {
46
+ for (const batch of [ordinary, ...native.map(f => [f])].filter(batch => batch.length)) {
46
47
  const r = spawnSync(process.execPath, ['--test', ...batch], { stdio: 'inherit', cwd: root })
47
48
  if (r.status !== 0) process.exit(r.status ?? 1)
48
49
  }
@@ -0,0 +1,116 @@
1
+ // Uses only the Windows .NET Framework; no SDK, NuGet or model process required.
2
+ using System;
3
+ using System.Text;
4
+ using System.Diagnostics;
5
+ using System.Runtime.InteropServices;
6
+ using System.ComponentModel;
7
+ using System.Management;
8
+ using System.Collections.Generic;
9
+ using System.Web.Script.Serialization;
10
+ using System.Text.RegularExpressions;
11
+
12
+ public static class AxConsole {
13
+ [StructLayout(LayoutKind.Sequential)] public struct Coord { public short X,Y; }
14
+ [StructLayout(LayoutKind.Sequential)] public struct Rect { public short Left,Top,Right,Bottom; }
15
+ [StructLayout(LayoutKind.Sequential)] public struct Info { public Coord Size,Cursor; public short Attr; public Rect Window; public Coord Max; }
16
+ [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode, Size=20)] public struct Record {
17
+ [FieldOffset(0)] public short Type;
18
+ [FieldOffset(4)] public int Down;
19
+ [FieldOffset(8)] public short Repeat;
20
+ [FieldOffset(10)] public short Key;
21
+ [FieldOffset(14)] public char Char;
22
+ }
23
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool AttachConsole(uint pid);
24
+ [DllImport("kernel32.dll")] static extern bool FreeConsole();
25
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr CreateFile(string name,uint access,uint share,IntPtr sec,uint mode,uint flags,IntPtr template);
26
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetConsoleScreenBufferInfo(IntPtr h,out Info info);
27
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool ReadConsoleOutputCharacter(IntPtr h,[Out] char[] text,uint count,Coord at,out uint read);
28
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool WriteConsoleInput(IntPtr h,Record[] input,uint count,out uint written);
29
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
30
+ static void Check(bool ok) { if(!ok) throw new Win32Exception(Marshal.GetLastWin32Error()); }
31
+ static IntPtr Open(string name) {
32
+ var h=CreateFile(name,0xC0000000,3,IntPtr.Zero,3,0,IntPtr.Zero);
33
+ if(h==new IntPtr(-1)) throw new Win32Exception(Marshal.GetLastWin32Error());
34
+ return h;
35
+ }
36
+ static string Snapshot() {
37
+ var h=Open("CONOUT$"); try {
38
+ Info info; Check(GetConsoleScreenBufferInfo(h,out info));
39
+ var text=new StringBuilder();
40
+ for(int y=info.Window.Top;y<=info.Window.Bottom;y++) {
41
+ uint read; var row=new char[info.Size.X];
42
+ Check(ReadConsoleOutputCharacter(h,row,(uint)row.Length,new Coord { X=0,Y=(short)y },out read));
43
+ text.AppendLine(new string(row,0,(int)read).TrimEnd());
44
+ }
45
+ return text.ToString();
46
+ } finally { CloseHandle(h); }
47
+ }
48
+ static void Send(string text) {
49
+ var h=Open("CONIN$"); try {
50
+ var records=new Record[text.Length*2];
51
+ for(int i=0;i<text.Length;i++) {
52
+ var r=new Record {Type=1,Down=1,Repeat=1,Char=text[i],Key=(short)(text[i]=='\r'?13:0)};
53
+ records[i*2]=r; r.Down=0; records[i*2+1]=r;
54
+ }
55
+ uint written; Check(WriteConsoleInput(h,records,(uint)records.Length,out written));
56
+ if(written!=records.Length) throw new Exception("Partial console delivery; do not retry automatically.");
57
+ } finally { CloseHandle(h); }
58
+ }
59
+ static string Get(Dictionary<string,object> payload, string key) {
60
+ object value; return payload.TryGetValue(key,out value) ? value as string : null;
61
+ }
62
+ static Dictionary<string,object> Identity(int pid) {
63
+ using(var proc=Process.GetProcessById(pid)) {
64
+ if(proc.ProcessName!="agy") throw new Exception("Target is not agy.exe");
65
+ return new Dictionary<string,object> { {"pid",pid}, {"startedAt",proc.StartTime.ToUniversalTime().ToString("o")} };
66
+ }
67
+ }
68
+ static bool Headless(string commandLine) {
69
+ return Regex.IsMatch(commandLine ?? "", @"--input-format|--print(?:\s|=|$)|(?:^|\s)-p(?:\s|$)");
70
+ }
71
+ public static int Main(string[] args) {
72
+ Console.InputEncoding=new UTF8Encoding(false); Console.OutputEncoding=new UTF8Encoding(false);
73
+ // AttachConsole replaces standard handles. Preserve the caller's pipe first.
74
+ var reply=Console.Out;
75
+ var json=new JavaScriptSerializer { MaxJsonLength=1024*1024 };
76
+ try {
77
+ int pid=int.Parse(args[0]); var action=args[1];
78
+ if(pid<=0) throw new Exception("A positive PID is required");
79
+ var payload=json.Deserialize<Dictionary<string,object>>(Console.In.ReadToEnd());
80
+ if(action!="snapshot" && action!="send" && action!="ancestor") throw new Exception("Unsupported console action");
81
+ if(action=="ancestor") {
82
+ for(int i=0;i<12 && pid>0;i++) {
83
+ using(var entry=new ManagementObject("Win32_Process.Handle='"+pid+"'")) {
84
+ entry.Get();
85
+ if((string)entry["Name"]=="agy.exe") {
86
+ var result=Headless((string)entry["CommandLine"]) ? new Dictionary<string,object> {{"ignored",true}} : Identity(pid);
87
+ reply.WriteLine(json.Serialize(result)); return 0;
88
+ }
89
+ pid=Convert.ToInt32(entry["ParentProcessId"]);
90
+ }
91
+ }
92
+ throw new Exception("No interactive agy ancestor found");
93
+ }
94
+ var identity=Identity(pid);
95
+ using(var entry=new ManagementObject("Win32_Process.Handle='"+pid+"'")) {
96
+ entry.Get();
97
+ if(Headless((string)entry["CommandLine"])) throw new Exception("Target is not an interactive agy console");
98
+ }
99
+ if(Get(payload,"startedAt")!=null && Get(payload,"startedAt")!=(string)identity["startedAt"]) throw new Exception("Process identity changed");
100
+ FreeConsole(); Check(AttachConsole((uint)pid));
101
+ var screen=Snapshot();
102
+ if(action=="send") {
103
+ if(Get(payload,"expectedScreen")!=screen) throw new Exception("Console changed before delivery; input was not sent");
104
+ var text=Get(payload,"text");
105
+ if(text==null || text.Length>65536) throw new Exception("Invalid console input");
106
+ // Recheck identity immediately before mutating the console input queue.
107
+ if((string)Identity(pid)["startedAt"]!=(string)identity["startedAt"]) throw new Exception("Process identity changed");
108
+ Send(text);
109
+ }
110
+ FreeConsole(); identity["screen"]=screen;
111
+ reply.WriteLine(json.Serialize(identity)); return 0;
112
+ } catch(Exception e) {
113
+ FreeConsole(); reply.WriteLine(json.Serialize(new Dictionary<string,object> {{"error",e.Message}})); return 1;
114
+ }
115
+ }
116
+ }