-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathcliRunner.cjs
More file actions
501 lines (454 loc) · 16.8 KB
/
Copy pathcliRunner.cjs
File metadata and controls
501 lines (454 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
const { spawn, spawnSync } = require('node:child_process')
const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')
const { createRuntimeSupervisor } = require('./runtimeSupervisor.cjs')
const { compactEvent, extractRunResult } = require('./cliEventParser.cjs')
const longRunningToolMonitor = require('./longRunningToolMonitor.cjs')
const DEFAULT_IDLE_TIMEOUT_MS = 300000
const DEFAULT_LONG_TOOL_IDLE_TIMEOUT_MS = 1800000
const MAX_TOOL_IDLE_TIMEOUT_MS = 7200000
const IDLE_CHECK_INTERVAL_MS = 5000
const DEFAULT_LOCAL_CWD = process.env.OPC_DEFAULT_CWD || ''
const MAX_STDOUT_CHARS = 1024 * 1024
const MAX_STDERR_CHARS = 256 * 1024
const BUNDLED_PLUGIN_NAMES = ['gstack-workflows']
function isSandboxCwd(value) {
return typeof value === 'string' && (value.startsWith('/vercel/') || value.includes('/sandbox/'))
}
function stripPathShellQuotes(value) {
let text = String(value || '').replace(/\u0000/g, '').trim()
while (/^["'`]/.test(text) || /["'`]$/.test(text)) {
const next = text.replace(/^["'`]+|["'`]+$/g, '').trim()
if (next === text) break
text = next
}
return text
}
function expandHome(value) {
const text = stripPathShellQuotes(value)
if (text === '~') return os.homedir()
if (text.startsWith('~/')) return path.join(os.homedir(), text.slice(2))
return text
}
function resolveCwd(requested, fallback) {
const candidate = expandHome(requested)
if (candidate && !isSandboxCwd(candidate) && fs.existsSync(candidate)) {
const stat = fs.statSync(candidate)
if (stat.isDirectory()) return candidate
if (stat.isFile()) return path.dirname(candidate)
}
if (DEFAULT_LOCAL_CWD && fs.existsSync(DEFAULT_LOCAL_CWD)) return DEFAULT_LOCAL_CWD
return fallback()
}
function bundledPluginDirs(root) {
return BUNDLED_PLUGIN_NAMES
.map(name => path.join(root, 'plugins', name))
.filter(pluginDir => fs.existsSync(path.join(pluginDir, '.claude-plugin', 'plugin.json')))
}
function profileMatchesSelection(profile, selected) {
return Boolean(!selected || profile?.model === selected || profile?.id === selected)
}
function runIdleTimeoutMs(env = process.env) {
const value = Number(env.OPC_DESKTOP_IDLE_TIMEOUT_MS)
if (Number.isFinite(value) && value > 0) return Math.min(Math.max(value, 30000), 900000)
return DEFAULT_IDLE_TIMEOUT_MS
}
function longToolIdleTimeoutMs(env = process.env) {
const value = Number(env.OPC_DESKTOP_LONG_TOOL_IDLE_TIMEOUT_MS)
if (Number.isFinite(value) && value > 0) return Math.min(Math.max(value, DEFAULT_IDLE_TIMEOUT_MS), MAX_TOOL_IDLE_TIMEOUT_MS)
return DEFAULT_LONG_TOOL_IDLE_TIMEOUT_MS
}
function commandLooksLongRunning(command = '') {
return longRunningToolMonitor.commandLooksLongRunning(command)
}
function classifyLongRunningTool(tool = {}, { baseMs = runIdleTimeoutMs(), env = process.env } = {}) {
return longRunningToolMonitor.classifyLongRunningTool(tool, {
baseMs,
longMs: longToolIdleTimeoutMs(env),
maxMs: MAX_TOOL_IDLE_TIMEOUT_MS,
})
}
function toolIdleTimeoutMs(tool = {}, { baseMs = runIdleTimeoutMs(), env = process.env } = {}) {
return classifyLongRunningTool(tool, { baseMs, env }).idleTimeoutMs
}
function findNode() {
const candidates = [
process.env.OPC_NODE,
process.env.NODE_BINARY,
'/usr/local/bin/node',
'/opt/homebrew/bin/node',
'/usr/bin/node',
'node',
].filter(Boolean)
for (const candidate of candidates) {
const probe = spawnSync(candidate, ['--version'], {
encoding: 'utf8',
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
})
if (probe.status === 0) return candidate
}
return 'node'
}
function cleanEnv(extra = {}) {
const env = { ...process.env, ...extra }
delete env.ELECTRON_RUN_AS_NODE
delete env.ELECTRON_NO_ATTACH_CONSOLE
return env
}
function appendBoundedText(current, next, maxChars) {
const text = `${current || ''}${next || ''}`
if (text.length <= maxChars) return text
return text.slice(-maxChars)
}
function tailText(value, maxChars = 4000) {
const text = String(value || '').trim()
if (text.length <= maxChars) return text
return `...${text.slice(-(maxChars - 3))}`
}
function sanitizeArgs(args) {
const sanitized = []
for (let index = 0; index < args.length; index += 1) {
sanitized.push(args[index])
if ((args[index] === '-p' || args[index] === '--print') && index + 1 < args.length) {
sanitized.push('[OPC_PROMPT]')
index += 1
} else if (args[index] === '--append-system-prompt' && index + 1 < args.length) {
sanitized.push('[OPC_MEMORY]')
index += 1
}
}
return sanitized
}
function createCliRunner({ projectRoot, cliPath, providerBridge, providerConfig, memoryStore, log, send }) {
let activeRun = null
const supervisor = createRuntimeSupervisor({ log })
function sendRuntime(run, phase, patch = {}) {
const snapshot = supervisor.snapshot(run)
send('opc:runtime', {
...snapshot,
phase: phase || snapshot.phase,
...patch,
})
}
function sendRuntimeActivity(run, change = {}) {
if (!run || run.finished) return
const snapshot = supervisor.snapshot(run)
const now = Date.now()
const phaseChanged = snapshot.phase && snapshot.phase !== run.lastRuntimePhase
const stale = now - (run.lastRuntimeEmitAt || 0) >= 1000
if (!change.force && !change.emit && !phaseChanged && !stale) return
run.lastRuntimePhase = snapshot.phase
run.lastRuntimeEmitAt = now
sendRuntime(run, snapshot.phase)
}
function finishRun(run, code, reason) {
if (!run || run.finished) return null
run.finished = true
if (run.idleTimer) clearInterval(run.idleTimer)
if (activeRun === run) activeRun = null
const durationMs = Date.now() - run.startedAt
const result = extractRunResult(run.stdout)
const stdout = tailText(run.stdout)
const stderr = tailText(run.stderr)
memoryStore.recordRun(run, code, durationMs, result)
supervisor.finish(run, reason)
sendRuntime(run, 'finished', { code, durationMs, reason })
send('opc:run-end', { code, durationMs, reason, taskId: run.taskId, result, stdout, stderr })
log(`OPC CLI finished reason=${reason} code=${code} durationMs=${durationMs}`)
return { code, durationMs, reason }
}
function markActivity(run = activeRun) {
if (run && !run.finished) run.lastActivityAt = Date.now()
}
function startIdleWatchdog(run) {
const baseTimeoutMs = runIdleTimeoutMs()
run.idleTimeoutMs = baseTimeoutMs
run.lastActivityAt = Date.now()
run.idleTimer = setInterval(() => {
if (!run || run.finished) return
const timeoutMs = Number(run.idleTimeoutMs || baseTimeoutMs)
const idleMs = Date.now() - run.lastActivityAt
const classification = run.longRunningTool
if (
classification?.longRunning &&
idleMs >= Number(classification.heartbeatMs || 0) &&
Date.now() - Number(run.lastHeartbeatAt || 0) >= Number(classification.heartbeatMs || 0)
) {
run.lastHeartbeatAt = Date.now()
const event = longRunningToolMonitor.heartbeatEventForTool(classification, { idleMs, taskId: run.taskId })
send('opc:event', event)
sendRuntime(run, 'tool', {
status: 'running',
statusText: event.message,
idleMs,
longRunningTool: classification,
})
}
if (idleMs < timeoutMs) return
send('opc:event', {
type: 'error',
message: `Aucune activité CLI depuis ${Math.round(idleMs / 1000)}s. Tâche arrêtée pour libérer OPC Desktop.`,
taskId: run.taskId,
})
supervisor.stop(run, 'idle-timeout')
finishRun(run, 124, 'idle-timeout')
stopLingeringRun(run)
}, IDLE_CHECK_INTERVAL_MS)
}
function extendIdleWatchdogForTool(run, tool = {}) {
if (!run || run.finished || !tool) return
const classification = classifyLongRunningTool(tool, { baseMs: runIdleTimeoutMs() })
run.longRunningTool = classification.longRunning ? classification : null
const nextTimeoutMs = classification.idleTimeoutMs
if (nextTimeoutMs <= Number(run.idleTimeoutMs || 0)) return
run.idleTimeoutMs = nextTimeoutMs
log(`OPC idle watchdog extended to ${Math.round(nextTimeoutMs / 1000)}s for ${tool.name || 'tool'} ${tool.target || ''}`.trim())
}
function stopLingeringRun(run) {
setTimeout(() => {
if (run?.child?.exitCode === null && run?.child?.signalCode === null) supervisor.stop(run, 'linger-term', { softKillTimeoutMs: 1200 })
}, 1000)
setTimeout(() => {
if (run?.child?.exitCode === null && run?.child?.signalCode === null) supervisor.stop(run, 'linger-kill', { softKillTimeoutMs: 50 })
}, 2500)
}
function handleCliEvent(event) {
const run = activeRun
markActivity(run)
const compact = compactEvent(event)
if (run?.taskId && compact && typeof compact === 'object') compact.taskId = run.taskId
if (run) {
const change = supervisor.recordEvent(run, compact || event)
extendIdleWatchdogForTool(run, supervisor.snapshot(run).currentTool)
sendRuntimeActivity(run, change)
}
send('opc:event', compact)
if (event?.type === 'result' && run) {
supervisor.markFinishing(run, 'result')
supervisor.stop(run, 'result')
finishRun(run, event.is_error ? 1 : 0, 'result')
stopLingeringRun(run)
}
}
function version() {
const node = findNode()
const cli = cliPath()
const result = spawnSync(node, [cli, '--version'], {
cwd: projectRoot(),
encoding: 'utf8',
env: cleanEnv(),
timeout: 5000,
})
return {
ok: result.status === 0,
node,
cli,
status: result.status,
version: (result.stdout || result.stderr || '').trim(),
error: result.error?.message || '',
}
}
function run(payload) {
if (activeRun) throw new Error('Une tâche est déjà en cours.')
const prompt = String(payload.prompt || '').trim()
if (!prompt) throw new Error('Prompt vide.')
const root = projectRoot()
const cwd = resolveCwd(payload.cwd, () => root)
const profile = providerConfig.profileForModel(payload.model)
if (!profileMatchesSelection(profile, payload.model)) {
throw new Error(`Le modèle ${payload.model || 'sélectionné'} est introuvable dans la configuration provider OPC.`)
}
if (profile && providerConfig.capabilities?.(profile)?.agent === false) {
throw new Error(`${profile.label || profile.model} est un provider de suggestions de code, pas un modèle agent OPC. Choisis un modèle agent pour lancer une session.`)
}
const model = profile?.model || payload.model || ''
const memoryEnabled = payload.memoryEnabled !== false
const memoryPrompt = memoryEnabled ? memoryStore.buildPrompt(cwd, model) : ''
const args = [
cliPath(),
'-p',
prompt,
'--verbose',
'--output-format',
'stream-json',
'--include-partial-messages',
]
for (const pluginDir of bundledPluginDirs(root)) args.push('--plugin-dir', pluginDir)
if (memoryPrompt) args.push('--append-system-prompt', memoryPrompt)
if (payload.bare !== false) args.push('--bare')
if (payload.effort) args.push('--effort', String(payload.effort))
if (payload.skipPermissions) {
args.push('--dangerously-skip-permissions')
} else if (payload.permissionMode) {
args.push('--permission-mode', String(payload.permissionMode))
}
if (payload.sessionId) args.push('--resume', String(payload.sessionId))
if (payload.maxTurns) args.push('--max-turns', String(payload.maxTurns))
if (payload.settingsPath) args.push('--settings', String(payload.settingsPath))
if (Array.isArray(payload.allowedTools) && payload.allowedTools.length) {
args.push('--allowedTools', payload.allowedTools.join(','))
}
const node = findNode()
const bridge = providerBridge.current()
if (!bridge) throw new Error('Provider bridge unavailable.')
const config = providerConfig.load()
const providerEnv = profile
? {
ANTHROPIC_BASE_URL: `http://127.0.0.1:${bridge.port}`,
ANTHROPIC_AUTH_TOKEN: bridge.authToken || 'opc-desktop-local',
ANTHROPIC_MODEL: profile.model,
ANTHROPIC_DEFAULT_SONNET_MODEL: config.defaultModel,
ANTHROPIC_DEFAULT_OPUS_MODEL: config.defaultModel,
ANTHROPIC_DEFAULT_HAIKU_MODEL: profile.model,
}
: {}
const logArgs = sanitizeArgs(args)
log(`Starting OPC CLI: ${node} ${logArgs.join(' ')} cwd=${cwd}`)
const child = spawn(node, args, {
cwd,
env: cleanEnv({ FORCE_COLOR: '0', NO_COLOR: '1', CLAUDE_CODE_MAX_RETRIES: '0', ...providerEnv }),
stdio: ['ignore', 'pipe', 'pipe'],
detached: process.platform !== 'win32',
})
activeRun = {
child,
stdout: '',
stderr: '',
startedAt: Date.now(),
lastActivityAt: Date.now(),
idleTimer: null,
taskId: String(payload.taskId || ''),
assistantId: String(payload.assistantId || ''),
chatId: String(payload.chatId || ''),
prompt: String(payload.displayPrompt || prompt),
cwd,
model,
memoryEnabled,
commandIntent: payload.commandIntent || null,
projectRuntimeContext: payload.projectRuntimeContext || null,
processGroup: process.platform !== 'win32',
}
supervisor.track(activeRun)
startIdleWatchdog(activeRun)
sendRuntime(activeRun, 'starting')
send('opc:run-start', {
pid: child.pid,
cwd,
command: [node, ...logArgs],
model,
taskId: activeRun.taskId,
memoryEnabled,
skipPermissions: Boolean(payload.skipPermissions),
permissionMode: payload.permissionMode,
commandIntent: activeRun.commandIntent,
projectRuntimeContext: activeRun.projectRuntimeContext,
})
if (memoryPrompt) {
send('opc:event', {
type: 'memory',
message: 'Mémoire durable OPC active',
path: memoryStore.memoryPath(),
})
}
let stdoutBuffer = ''
child.stdout.on('data', chunk => {
markActivity()
const text = String(chunk)
if (activeRun) activeRun.stdout = appendBoundedText(activeRun.stdout, text, MAX_STDOUT_CHARS)
stdoutBuffer += text
const lines = stdoutBuffer.split(/\r?\n/)
stdoutBuffer = lines.pop() || ''
for (const line of lines) {
if (!line.trim()) continue
try {
handleCliEvent(JSON.parse(line))
} catch {
send('opc:event', { type: 'stdout', text: line })
}
}
})
child.stderr.on('data', chunk => {
markActivity()
const text = String(chunk)
if (activeRun) activeRun.stderr = appendBoundedText(activeRun.stderr, text, MAX_STDERR_CHARS)
for (const line of text.split(/\r?\n/)) {
if (!line.trim()) continue
const event = { type: 'stderr', text: line, taskId: activeRun?.taskId || '' }
if (activeRun) sendRuntimeActivity(activeRun, supervisor.recordEvent(activeRun, event))
send('opc:event', event)
}
})
child.on('error', error => {
const event = { type: 'error', message: error.message, taskId: activeRun?.taskId || '' }
if (activeRun) sendRuntimeActivity(activeRun, supervisor.recordEvent(activeRun, event))
send('opc:event', event)
})
child.on('close', code => {
if (stdoutBuffer.trim()) {
try {
handleCliEvent(JSON.parse(stdoutBuffer))
} catch {
send('opc:event', { type: 'stdout', text: stdoutBuffer })
}
}
const finishedRun = activeRun
const finished = finishRun(finishedRun, code, 'close')
log(`OPC CLI exited code=${code} durationMs=${finished?.durationMs || 0}`)
})
}
function stop() {
if (!activeRun) return false
const run = activeRun
send('opc:event', { type: 'stopped', message: 'Tâche arrêtée par l’utilisateur.', taskId: run.taskId })
supervisor.stop(run, 'stopped')
finishRun(run, 130, 'stopped')
stopLingeringRun(run)
return true
}
function hasActiveRun() {
return Boolean(activeRun)
}
function activeChild() {
return activeRun?.child || null
}
function activeTaskId() {
return activeRun?.taskId || ''
}
function runtimeStatus() {
return supervisor.status()
}
function recordExternalEvent(event) {
const run = activeRun
markActivity(run)
if (!run || run.finished) return null
const payload = { ...event, taskId: run.taskId }
const change = supervisor.recordEvent(run, payload)
sendRuntimeActivity(run, change)
return supervisor.snapshot(run)
}
function cleanupRuntime() {
return supervisor.cleanup({ force: true, reason: 'manual-cleanup' })
}
return {
cleanupRuntime,
run,
stop,
touchActiveRun: () => markActivity(),
recordExternalEvent,
hasActiveRun,
activeChild,
activeTaskId,
runtimeStatus,
version,
}
}
module.exports = {
bundledPluginDirs,
classifyLongRunningTool,
commandLooksLongRunning,
createCliRunner,
resolveCwd,
stripPathShellQuotes,
toolIdleTimeoutMs,
}