Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/**
* Пауза и отмена между узлами графа. Отмена бывает общей (вся задача)
* и поимённой: одна залипшая подзадача не должна требовать стопа всего запуска.
*/
class
Gate
{
constructor
(
)
{
this
.
paused
=
false
;
this
.
isAborted
=
false
;
this
.
abortedNodes
=
new
Set
(
)
;
}
pause
(
)
{
this
.
paused
=
true
;
}
resume
(
)
{
this
.
paused
=
false
;
}
abort
(
)
{
this
.
isAborted
=
true
;
this
.
paused
=
false
;
}
abortNode
(
nodeId
)
{
if
(
)
{
this
.
abortedNodes
.
add
(
String
(
)
)
;
}
}
nodeAborted
(
nodeId
)
{
return
this
.
abortedNodes
.
has
(
String
(
)
)
;
}
aborted
(
)
{
return
this
.
isAborted
;
}
throwIfAborted
(
)
{
if
(
this
.
isAborted
)
{
throw
new
Error
(
'cancelled'
)
;
}
}
waitIfPaused
(
)
{
return
new
Promise
(
resolve
=>
{
const
tick
=
(
)
=>
{
if
(
!
this
.
paused
||
this
.
isAborted
)
{
resolve
(
)
;
}
else
{
setTimeout
(
,
300
)
;
}
}
;
tick
(
)
;
}
)
;
}
}
/**
* Сессия оркестратора: запуск/пауза/стоп графа, события наружу, чекпоинты
* (память потока в MemorySaver — interrupt, time-travel, ручная правка стейта),
* снапшот после каждого шага в расширение (переживает рестарт IDE).
*
* Каждый запуск получает свой thread_id: история чекпоинтов не подмешивается
* к следующей задаче (каналы-merge-редьюсеры иначе склеили бы результаты).
*/
class
Orchestrator
{
constructor
(
rpc, options
)
{
this
.
rpc
=
;
this
.
mock
=
!
!
(
&&
.
mock
)
;
this
.
gate
=
new
Gate
(
)
;
this
.
runPromise
=
null
;
this
.
lastSnapshot
=
null
;
/** Граф и поток живут с первого start до конца сессии сайдкара. */
this
.
graphRef
=
null
;
this
.
threadId
=
null
;
/** Корень workspace: нужен git-инструментам и очистке worktree. */
this
.
workspaceRoot
=
''
;
/** Трейсер текущего запуска (Этап 5.2). */
this
.
tracer
=
null
;
}
get
running
(
)
{
return
!
!
this
.
runPromise
;
}
get
threadConfig
(
)
{
return
{
configurable
:
{
thread_id
:
this
.
threadId
}
}
;
}
async
handleCommand
(
method, params
)
{
switch
(
)
{
case
'start'
:
return
this
.
start
(
||
{
}
)
;
case
'pause'
:
this
.
gate
.
pause
(
)
;
return
{
paused
:
true
}
;
case
'resume'
:
this
.
gate
.
resume
(
)
;
return
{
resumed
:
true
}
;
case
'cancel'
:
return
this
.
cancel
(
)
;
case
'cancelNode'
:
{
const
=
String
(
(
&&
.
nodeId
)
||
''
)
;
if
(
!
)
{
throw
new
Error
(
'nodeId is empty'
)
;
}
this
.
gate
.
abortNode
(
)
;
return
{
cancelled
:
true
,
}
;
}
case
'status'
:
return
{
running
:
this
.
running
,
paused
:
this
.
gate
.
paused
}
;
case
'interrupt.resolve'
:
return
this
.
resolveInterrupt
(
||
{
}
)
;
case
'history'
:
return
this
.
history
(
||
{
}
)
;
case
'rewind'
:
return
this
.
rewind
(
||
{
}
)
;
case
'patchState'
:
return
this
.
patchState
(
||
{
}
)
;
case
'restartNode'
:
return
this
.
restartNode
(
||
{
}
)
;
case
'cleanup'
:
return
this
.
cleanupWorktrees
(
)
;
case
'trace.spans'
:
return
this
.
traceSnapshot
(
)
;
default
:
throw
new
Error
(
`unknown command: ${method}`
)
;
}
}
async
start
(
params
)
{
if
(
this
.
runPromise
)
{
throw
new
Error
(
'already running'
)
;
}
const
=
String
(
.
task
||
''
)
.
trim
(
)
;
if
(
!
)
{
throw
new
Error
(
'task is empty'
)
;
}
const
=
new
LlmClient
(
this
.
rpc
,
{
mock
:
this
.
mock
,
escalationThreshold
:
.
escalationThreshold
}
)
;
const
=
Array
.
isArray
(
.
tools
)
?
.
tools
:
[
]
;
const
emit
=
(
event
)
=>
this
.
rpc
.
notify
(
'graph.event'
,
)
;
this
.
gate
=
new
Gate
(
)
;
this
.
workspaceRoot
=
String
(
.
workspaceRoot
||
''
)
;
// Стабильный thread_id: resume той же задачи продолжает историю чекпоинтов,
// а не заводит новый поток — иначе rewind после рестарта сайдкара пуст.
const
=
.
resumeState
&&
.
resumeState
.
task
===
?
.
resumeState
:
null
;
this
.
threadId
=
.
threadId
||
(
&&
.
threadId
)
||
`run-${Date.now()}`
;
// Трейсер заводится на поток запуска: спаны уходят в host живым потоком,
// опционально пишутся в файл и на OTLP-endpoint (Этап 5.2).
const
=
.
trace
&&
typeof
.
trace
===
'object'
?
.
trace
:
{
}
;
this
.
tracer
=
new
Tracer
(
{
enabled
:
.
enabled
!==
false
,
file
:
typeof
.
file
===
'string'
?
.
file
:
''
,
otlpEndpoint
:
typeof
.
otlpEndpoint
===
'string'
?
.
otlpEndpoint
:
''
,
maxSpans
:
.
maxSpans
,
traceId
:
this
.
threadId
,
onSpan
:
span
=>
this
.
rpc
.
notify
(
'trace.span'
,
)
,
}
)
;
// Чекпоинтер обязателен: без него interrupt() не работает, а history/rewind пусты.
// FileSaver персистит историю в файл (машина времени переживает рестарт сайдкара);
// MemorySaver — фолбэк, когда путь не передан (mock-режим, тесты).
const
=
.
checkpointFile
?
new
FileSaver
(
String
(
.
checkpointFile
)
)
:
new
MemorySaver
(
)
;
const
=
buildOrchestratorGraph
(
{
,
,
invokeTool
:
(
name, input, nodeId
)
=>
this
.
rpc
.
request
(
'tool.invoke'
,
{
,
,
}
)
,
,
gate
:
this
.
gate
,
maxParallelWorkers
:
.
maxParallelWorkers
,
maxVerifyRetries
:
.
maxVerifyRetries
,
verifyCommand
:
.
verifyCommand
,
// reducer обогащает результаты ссылкой на дифф/коммит; git может быть
// недоступен — тогда просто остаются пустые строки.
// Бюджет (Этап 5.1): лимиты узла/запуска. Цены остаются в host.
budget
:
.
budget
,
// Трейсинг (Этап 5.2): спаны нод и вызовов модели.
tracer
:
this
.
tracer
,
language
:
.
language
===
'en'
?
'en'
:
'ru'
,
}
,
{
}
)
;
this
.
graphRef
=
;
const
=
;
const
=
?
{
,
round
:
.
round
||
0
,
results
:
.
results
||
{
}
,
summary
:
''
}
:
{
,
round
:
0
,
results
:
{
}
,
summary
:
''
}
;
if
(
)
{
emit
(
{
type
:
'log'
,
message
:
`resume из чекпоинта: раунд ${resumed.round}, результатов ${Object.keys(resumed.results||{}).length}`
}
)
;
}
emit
(
{
type
:
'graph.started'
,
message
:
`задача запущена: ${task}`
,
run
:
{
maxRounds
:
MAX_SUPERVISOR_ROUNDS
}
}
)
;
// Лимит рекурсии — на весь план целиком: пачка за пачкой, ретраи verify
// и раунды супервизора живут в одном лимите (шаг на пачку + шаг verify).
this
.
runPromise
=
this
.
drive
(
,
)
.
then
(
result
=>
{
this
.
emitFinish
(
)
;
return
{
ok
:
true
,
summary
:
.
summary
||
''
}
;
}
)
.
catch
(
err
=>
{
const
=
instanceof
Error
?
.
message
:
String
(
)
;
if
(
/cancelled|aborted/i
.
test
(
)
)
{
emit
(
{
type
:
'graph.cancelled'
,
message
:
.
language
===
'en'
?
'task cancelled'
:
'задача отменена'
}
)
;
return
{
ok
:
false
,
cancelled
:
true
}
;
}
emit
(
{
type
:
'graph.error'
,
message
:
`ошибка графа: ${message}`
}
)
;
return
{
ok
:
false
,
error
:
}
;
}
)
.
finally
(
(
)
=>
{
this
.
runPromise
=
null
;
}
)
;
return
{
started
:
true
,
resumed
:
!
!
}
;
}
/**
* Единый драйвер прогресса графа: свежий запуск (input = стейт), продолжение
* после interrupt (input = Command({resume})), replay после rewind (input = null
* + checkpoint_id в конфиге). Снапшоты и события — в одном месте.
*/
async
drive
(
graph, input, configOverrides
)
{
const
=
||
{
}
;
const
=
{
recursionLimit
:
200
,
streamMode
:
'values'
,
...
this
.
threadConfig
,
...
,
configurable
:
{
...
this
.
threadConfig
.
configurable
,
...
(
.
configurable
||
{
}
)
}
,
}
;
const
=
await
.
stream
(
,
)
;
let
=
''
;
for
await
(
const
of
)
{
=
.
summary
||
''
;
this
.
lastSnapshot
=
{
task
:
.
task
||
''
,
round
:
.
round
||
0
,
results
:
.
results
||
{
}
,
summary
:
.
summary
||
''
,
plan
:
Array
.
isArray
(
.
plan
)
?
.
plan
:
[
]
,
itemState
:
.
itemState
||
{
}
,
attempts
:
.
attempts
||
{
}
,
isolations
:
.
isolations
||
{
}
,
budget
:
.
budget
||
{
tokens
:
0
,
cost
:
0
}
,
errors
:
Array
.
isArray
(
.
errors
)
?
.
errors
:
[
]
,
// Для resume после рестарта сайдкара: продолжаем тот же поток чекпоинтов.
threadId
:
this
.
threadId
||
''
,
savedAt
:
Date
.
now
(
)
,
}
;
this
.
rpc
.
notify
(
'checkpoint'
,
this
.
lastSnapshot
)
;
}
return
{
}
;
}
/**
* git-инфо для reducer'а: дифф-статистика и короткий коммит одним заходом.
* Зонд ограничен коротким дедлайном: без extension host (дымовой тест,
* сайдкар вне IDE) ответа не будет, и ждать 10 минут нельзя. Недоступный git
* или закрытый allowlist — просто пустые ссылки, запуск не падает.
*/
async
collectDiff
(
)
{
try
{
const
=
await
this
.
rpc
.
request
(
'tool.invoke'
,
{
name
:
'terminal.run'
,
input
:
{
command
:
'git diff --stat'
}
,
nodeId
:
'reducer'
}
,
undefined
,
GIT_PROBE_TIMEOUT_MS
)
;
const
=
await
this
.
rpc
.
request
(
'tool.invoke'
,
{
name
:
'terminal.run'
,
input
:
{
command
:
'git rev-parse --short HEAD'
}
,
nodeId
:
'reducer'
}
,
undefined
,
GIT_PROBE_TIMEOUT_MS
)
;
return
{
diff_stat
:
stripExit
(
String
(
(
&&
.
output
)
||
''
)
)
.
slice
(
0
,
400
)
,
commit
:
shortCommit
(
(
&&
.
output
)
||
''
)
,
}
;
}
catch
{
return
{
}
;
}
}
/** Снапшот трейса для панели: спаны + агрегаты (топ по времени/деньгам). */
traceSnapshot
(
)
{
if
(
!
this
.
tracer
)
{
return
{
spans
:
[
]
,
summary
:
{
byTime
:
[
]
,
byCost
:
[
]
,
totalSpans
:
0
}
}
;
}
return
{
spans
:
this
.
tracer
.
list
(
)
,
summary
:
this
.
tracer
.
summary
(
)
}
;
}
emitFinish
(
result
)
{
this
.
rpc
.
notify
(
'graph.event'
,
{
type
:
'graph.finished'
,
message
:
`готово: ${result.summary||'см. результаты узлов'}`
,
run
:
{
round
:
(
this
.
lastSnapshot
&&
this
.
lastSnapshot
.
round
)
||
0
,
summary
:
.
summary
||
''
,
}
,
}
)
;
}
/**
* Решение по interrupt (подтверждение рискованной подзадачи): граф
* продолжается с того же места ноды командой Command({resume}).
*/
async
resolveInterrupt
(
params
)
{
if
(
!
this
.
graphRef
)
{
throw
new
Error
(
'no graph instance: start the task first'
)
;
}
if
(
this
.
runPromise
)
{
throw
new
Error
(
'already running'
)
;
}
const
=
.
approved
===
true
;
const
=
.
note
!==
undefined
&&
.
note
!==
null
?
String
(
.
note
)
:
undefined
;
this
.
runPromise
=
this
.
drive
(
this
.
graphRef
,
new
Command
(
{
resume
:
{
,
}
}
)
)
.
then
(
result
=>
{
this
.
emitFinish
(
)
;
return
{
ok
:
true
,
summary
:
.
summary
||
''
}
;
}
)
.
catch
(
err
=>
(
{
ok
:
false
,
error
:
instanceof
Error
?
.
message
:
String
(
)
}
)
)
.
finally
(
(
)
=>
{
this
.
runPromise
=
null
;
}
)
;
return
{
resuming
:
true
,
}
;
}
/** История чекпоинтов (time-travel): от свежего к старому, без тяжёлых полей. */
async
history
(
params
)
{
if
(
!
this
.
graphRef
)
{
return
{
entries
:
[
]
}
;
}
const
=
Math
.
max
(
1
,
Math
.
min
(
50
,
Number
(
.
limit
)
||
20
)
)
;
const
=
[
]
;
for
await
(
const
of
this
.
graphRef
.
getStateHistory
(
this
.
threadConfig
,
{
}
)
)
{
.
push
(
{
checkpointId
:
.
config
?.
?.
,
next
:
.
next
||
[
]
,
step
:
.
metadata
?.
,
round
:
.
values
?.
,
summary
:
.
values
?.
||
''
,
resultsCount
:
.
values
?.
?
Object
.
keys
(
.
values
.
results
)
.
filter
(
k
=>
(
.
values
.
results
[
]
||
''
)
!==
''
)
.
length
:
0
,
}
)
;
}
return
{
}
;
}
/** Машина времени: откат к чекпоинту и продолжение с него. */
async
rewind
(
params
)
{
if
(
!
this
.
graphRef
)
{
throw
new
Error
(
'no graph instance: start the task first'
)
;
}
if
(
this
.
runPromise
)
{
throw
new
Error
(
'rewind is only possible on a paused or finished graph'
)
;
}
const
=
String
(
.
checkpointId
||
''
)
;
if
(
!
)
{
throw
new
Error
(
'checkpointId is required'
)
;
}
const
=
{
configurable
:
{
thread_id
:
this
.
threadId
,
checkpoint_id
:
}
,
}
;
const
=
await
this
.
graphRef
.
getState
(
)
;
if
(
!
||
!
.
values
)
{
throw
new
Error
(
`checkpoint not found: ${checkpointId}`
)
;
}
this
.
runPromise
=
this
.
drive
(
this
.
graphRef
,
null
,
)
.
then
(
result
=>
{
this
.
emitFinish
(
)
;
return
{
ok
:
true
,
summary
:
.
summary
||
''
}
;
}
)
.
catch
(
err
=>
(
{
ok
:
false
,
error
:
instanceof
Error
?
.
message
:
String
(
)
}
)
)
.
finally
(
(
)
=>
{
this
.
runPromise
=
null
;
}
)
;
return
{
rewound
:
true
,
}
;
}
/**
* Ручная правка состояния на чекпоинте (JSON-патч из панели). Нужен
* checkpointId из history: патч пишется в ответ ноды next[0], поэтому
* на «хвосте» без next патчить просто нечего.
*/
async
patchState
(
params
)
{
if
(
!
this
.
graphRef
)
{
throw
new
Error
(
'no graph instance: start the task first'
)
;
}
if
(
this
.
runPromise
)
{
throw
new
Error
(
'patch is only possible on a paused or finished graph'
)
;
}
const
=
.
patch
&&
typeof
.
patch
===
'object'
?
.
patch
:
null
;
if
(
!
||
Object
.
keys
(
)
.
length
===
0
)
{
throw
new
Error
(
'patch is empty'
)
;
}
const
=
String
(
.
checkpointId
||
''
)
;
if
(
!
)
{
throw
new
Error
(
'checkpointId is required (pick one from history)'
)
;
}
const
=
{
configurable
:
{
thread_id
:
this
.
threadId
,
checkpoint_id
:
}
,
}
;
const
=
await
this
.
graphRef
.
getState
(
)
;
if
(
!
||
!
.
values
)
{
throw
new
Error
(
`checkpoint not found: ${checkpointId}`
)
;
}
// Чекпоинт посреди графа ждёт next[0] — патч пишем от его имени. На «хвосте»
// (next пуст, граф завершён) asNode неизвестен: SDK сам выводит автора
// последнего апдейта, поэтому просто не передаём третий аргумент.
/**
* Перезапуск одной ноды: возвращаем подзадачу в очередь, стираем её результат
* и продолжаем граф с router'а. Работает на остановленном графе (как rewind),
* иначе пачка уже идёт и подменить вход нельзя.
*/
async
restartNode
(
params
)
{
if
(
!
this
.
graphRef
)
{
throw
new
Error
(
'no graph instance: start the task first'
)
;
}
if
(
this
.
runPromise
)
{
throw
new
Error
(
'restart is only possible on a stopped graph'
)
;
}
const
=
String
(
.
nodeId
||
''
)
;
if
(
!
)
{
throw
new
Error
(
'nodeId is required'
)
;
}
const
=
await
this
.
graphRef
.
getState
(
this
.
threadConfig
)
;
const
=
(
&&
.
values
)
||
{
}
;
const
=
Array
.
isArray
(
.
plan
)
?
.
plan
:
[
]
;
const
=
.
find
(
entry
=>
&&
.
id
===
)
;
if
(
!
)
{
throw
new
Error
(
`node not found in the current plan: ${nodeId}`
)
;
}
const
=
(
.
itemState
||
{
}
)
[
]
;
if
(
===
'dispatched'
||
===
'running'
)
{
throw
new
Error
(
`node is still running: ${nodeId}`
)
;
}
const
=
Array
.
isArray
(
.
queue
)
?
.
queue
.
slice
(
)
:
[
]
;
if
(
!
.
some
(
entry
=>
&&
.
id
===
)
)
{
.
unshift
(
)
;
}
// null в results-редьюсере удаляет прошлый результат (см. graph.js).
await
this
.
graphRef
.
updateState
(
this
.
threadConfig
,
{
,
results
:
{
[
]
:
null
}
,
itemState
:
{
[
]
:
'queued'
}
,
attempts
:
{
[
]
:
0
}
,
}
,
'router'
)
;
this
.
rpc
.
notify
(
'graph.event'
,
{
type
:
'log'
,
message
:
`нода ${nodeId} перезапущена вручную`
}
)
;
this
.
runPromise
=
this
.
drive
(
this
.
graphRef
,
null
)
.
then
(
result
=>
{
this
.
emitFinish
(
)
;
return
{
ok
:
true
,
summary
:
.
summary
||
''
}
;
}
)
.
catch
(
err
=>
(
{
ok
:
false
,
error
:
instanceof
Error
?
.
message
:
String
(
)
}
)
)
.
finally
(
(
)
=>
{
this
.
runPromise
=
null
;
}
)
;
return
{
restarted
:
true
,
}
;
}
async
cancel
(
)
{
this
.
gate
.
abort
(
)
;
if
(
this
.
runPromise
)
{
await
this
.
runPromise
.
catch
(
(
)
=>
undefined
)
;
}
// Отменённый запуск не оставляет рабочих деревьев (Этап 4.1/4.5).
await
this
.
cleanupWorktrees
(
)
;
return
{
cancelled
:
true
}
;
}
/**
* Убрать рабочие деревья запуска: их пути лежат в последнем снапшоте.
* Best-effort: чистка не должна ронять отмену или отклонение патча.
*/
async
cleanupWorktrees
(
)
{
const
=
(
this
.
lastSnapshot
&&
this
.
lastSnapshot
.
isolations
)
||
{
}
;
const
=
Object
.
keys
(
)
;
const
=
.
map
(
id
=>
(
{
,
worktree
:
(
[
]
||
{
}
)
.
worktree
,
branch
:
(
[
]
||
{
}
)
.
branch
,
}
)
)
;
// Run-дерево/ветку тоже убираем: отказ не должен оставлять следов.
if
(
this
.
workspaceRoot
&&
this
.
threadId
)
{
.
push
(
{
id
:
'run'
,
worktree
:
runWorktreePath
(
this
.
workspaceRoot
,
this
.
threadId
)
,
branch
:
runBranch
(
this
.
threadId
)
,
}
)
;
}
if
(
.
length
===
0
)
{
return
{
cleaned
:
0
}
;
}
for
(
const
of
)
{
try
{
await
this
.
rpc
.
request
(
'tool.invoke'
,
{
name
:
'git.worktreeRemove'
,
input
:
{
worktree
:
.
worktree
,
branch
:
.
branch
,
workspaceRoot
:
this
.
workspaceRoot
}
,
nodeId
:
.
id
,
}
)
;
}
catch
(
)
{
this
.
rpc
.
notify
(
'graph.event'
,
{
type
:
'log'
,
message
:
`чистка worktree ${target.id} не удалась: ${err instanceofError? err.message:String(err)}`
}
)
;
}
}
this
.
rpc
.
notify
(
'graph.event'
,
{
type
:
'log'
,
message
:
`изоляция очищена: ${targets.length} worktree`
}
)
;
this
.
lastSnapshot
=
this
.
lastSnapshot
?
{
...
this
.
lastSnapshot
,
isolations
:
{
}
,
runWorktree
:
''
}
:
null
;
return
{
cleaned
:
.
length
}
;
}
}
/** git может не ответить за разумное время — зонд не должен вешать граф. */
const
GIT_PROBE_TIMEOUT_MS
=
2500
;
/** Короткий коммит принимаем только в hex-виде: иначе это текст отказа, а не ссылка. */
function
shortCommit
(
text
)
{
const
=
firstLine
(
stripExit
(
String
(
||
''
)
)
)
;
return
/^[0-9a-f]{4,40}$/i
.
test
(
)
?
:
''
;
}
/** Терминал расширения добавляет к выводу «(exit code N)» — в ссылке это лишнее. */