@devorch/cli-linux-x64 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,696 @@
1
+ import type { EngineInterface, Register, Timer } from 'claude-code'
2
+
3
+ import {
4
+ EventDispatcher, LineSplitter, SETTLE_MS, afterHealthyChild, cliSupports, clearsPendingWake, decideWake,
5
+ parseAnswerArgs, parseEnvelope, positionOf, wakeCommand, type LadderState, type PlatformEventEnvelope,
6
+ } from './core.ts'
7
+ import {
8
+ HEAL_MS, LOG_MAX_BYTES, WAKE_EXPIRY_MS, afterPoll, afterWakeClaimed, afterWakeExpired, afterWatchExit,
9
+ answerStdinArgv, canWatch, dedupe, handBackWake, health, isBaseUrl, logLine, parseUnwatchArgs, parseWatchArgs,
10
+ resolveBaseUrl, resolveExe, respawnDelayMs, restoreWatched, runStatus, statusLine, terminalAction, tokenOf,
11
+ updateHint, versionArgv, waitArgv, watchArgv, type WakeHealth, type WatchEntry,
12
+ } from './supervision.ts'
13
+
14
+ /**
15
+ * DevOrch companion mod: the thin host adapter over `$` (DEV-56, design-L0 "Adapter code paths").
16
+ *
17
+ * This file only performs host calls (process spawn/run, timers, `$.command.run`, the status line, tool and command
18
+ * registration, `$.state`); every decision comes from `core.ts` or `supervision.ts`, which are node-tested. A branch
19
+ * on data that is not a plain host call belongs in `supervision.ts` with a test.
20
+ *
21
+ * The host requires `$` to be spelled `$.noun.op(...)` at each call site (never stored or passed), so every function
22
+ * that calls the host is a closure inside the `session.start` hook and the other hooks reach them through `ops`.
23
+ * Long-lived loops (one per watched run) keep running after that hook returns, as the host's spawn example shows.
24
+ *
25
+ * Invariants (design-L0 Domain Integrity Constraints):
26
+ * - only `wakeCommand(runId)` reaches `$.command.run`, with a run id the mod validated (CC-4);
27
+ * - no blocker or question text in the status line, toasts, tool results, command replies or the log (CC-4, D19);
28
+ * - no wake inside a main-loop turn or within SETTLE_MS of its end (CC-5), none while the Stop-hook host is armed (CC-6);
29
+ * - one long-lived `devorch run watch` child per watched run on rungs 1-2, zero processes per event (AC-4);
30
+ * - the mod reaches the server only through the CLI's argv and stdout: no HTTP call, no token.
31
+ *
32
+ * Spike-conditional branches (design-L0): this file implements the DEFAULT branch of each row (no console flash on
33
+ * spawn/run, main-loop `turn.complete` with `agentId` undefined, `$.command.run` queues until idle and accepts the
34
+ * `devorch-step` skill, a `clock.after` scheduled in `turn.complete` runs outside the turn). The Windows spike
35
+ * (`spike-tq27.md`) confirms or changes them; a rejected wake already degrades to `healthy: false`.
36
+ */
37
+
38
+ const TOOL = 'mcp__devorch-companion__devorch_companion'
39
+ const STOP_HOOK_MARKER = '.claude/hooks/interactive-loop/state/armed.json'
40
+ /** How long tool `watch` waits for the first envelope or child exit before it answers (D16). */
41
+ const FIRST_SIGNAL_MS = 5_000
42
+ /** A rung-3 `run wait` parks 25 s on the server; the process gets 10 s more. */
43
+ const POLL_TIMEOUT_MS = 35_000
44
+
45
+ type Run = {
46
+ entry: WatchEntry
47
+ ladder: LadderState
48
+ latest: PlatformEventEnvelope | null
49
+ lastToken: string | null
50
+ pendingWake: boolean
51
+ expiry: Timer | null
52
+ retry: Timer | null
53
+ child: AsyncGenerator<unknown, unknown> | null
54
+ stopped: boolean
55
+ /** The tool told the skill `healthy: true` for this run (D16). */
56
+ reportedHealthy: boolean
57
+ handedBack: boolean
58
+ firstSignal: (() => void)[]
59
+ sawFirst: boolean
60
+ retryWatch: boolean
61
+ }
62
+
63
+ type Cli = { ok: boolean; reason: string; exe: string | null; version: string | null }
64
+
65
+ /** The host-calling operations the session.start hook builds; the other hooks call these. */
66
+ type Ops = {
67
+ watch: (runId: string, baseUrl: unknown, lastToken?: string | null) => Promise<Run>
68
+ unwatch: (runId: string) => Promise<void>
69
+ firstSignal: (run: Run) => Promise<void>
70
+ evaluateAll: () => void
71
+ answer: (slug: string, blockerRef: string, text: string) => Promise<string>
72
+ shutdown: () => Promise<void>
73
+ }
74
+
75
+ export const register: Register = (on, options) => {
76
+ const runs = new Map<string, Run>()
77
+ const dispatcher = new EventDispatcher(() => {})
78
+ let ops: Ops | null = null
79
+ let cli: Cli = { ok: false, reason: 'not started', exe: null, version: null }
80
+ let stopHookArmed = false
81
+ let wakeHealth: WakeHealth = { misses: 0, wakeBroken: false }
82
+ let turnRunning = false
83
+ let lastTurnEnd: number | null = null
84
+ /** Diagnostics for the status action: the last wake decision and how far the last submit got. */
85
+ const diag: { decision?: { at: number; wake: boolean; reason?: string }; submit?: { at: number; stage: string } } = {}
86
+
87
+ const now = (): number => Date.now()
88
+ const idleForMs = (): number | null => (lastTurnEnd === null ? null : now() - lastTurnEnd)
89
+
90
+ // ---- pure views over the state (no host calls) ----------------------------------------------------------------
91
+
92
+ function healthOf(run: Run | null): { healthy: boolean; reason?: string } {
93
+ return health({ cliOk: cli.ok, cliReason: cli.reason, stopHookArmed, wakeBroken: wakeHealth.wakeBroken, rung: run ? run.ladder.rung : null })
94
+ }
95
+
96
+ function statusObject(runId?: string): Record<string, unknown> {
97
+ const asked = runId ? runs.get(runId) ?? null : null
98
+ return {
99
+ ...healthOf(asked),
100
+ cli: { ok: cli.ok, version: cli.version, path: cli.exe },
101
+ stopHookArmed,
102
+ wakeBroken: wakeHealth.wakeBroken,
103
+ turnRunning,
104
+ idleForMs: idleForMs(),
105
+ lastDecision: diag.decision ?? null,
106
+ lastSubmit: diag.submit ?? null,
107
+ runs: [...runs.values()]
108
+ .filter((r) => !runId || r.entry.runId === runId)
109
+ .map((r) => ({ ...runStatus({ runId: r.entry.runId, baseUrl: r.entry.baseUrl, pendingWake: r.pendingWake, latest: r.latest, ladder: r.ladder }), healthy: healthOf(r).healthy })),
110
+ }
111
+ }
112
+
113
+ function signalFirst(run: Run): void {
114
+ run.sawFirst = true
115
+ for (const resolve of run.firstSignal.splice(0)) resolve()
116
+ }
117
+
118
+ // ---- session lifecycle (R1: registration stays out of session.start's awaited path) ---------------------------
119
+
120
+ on('session.start', async ($, e, next) => {
121
+ const started = await next(e)
122
+ const cwd = e.cwd
123
+ const queue: string[] = []
124
+ let pluginRoot = ''
125
+ let dataDir = ''
126
+ let modVersion = '0.0.0-dev'
127
+ let wakeInFlight: string | null = null
128
+ let logLines: string[] = []
129
+ let logBytes = 0
130
+ let logFlush: Timer | null = null
131
+
132
+ // ---- logging (D19: ids and timings only) ------------------------------------------------------------------
133
+
134
+ function log(runId: string, event: string, extra: Parameters<typeof logLine>[3] = {}): void {
135
+ const line = logLine(now(), runId, event, extra)
136
+ logLines.push(line)
137
+ logBytes += line.length + 1
138
+ if (!dataDir) return
139
+ logFlush ??= $.clock.after(1_000, () => {
140
+ logFlush = null
141
+ void flushLog()
142
+ })
143
+ }
144
+
145
+ async function flushLog(): Promise<void> {
146
+ if (!dataDir) return
147
+ try {
148
+ if (logBytes > LOG_MAX_BYTES) {
149
+ await $.fs.write(`${dataDir}/companion.log.1`, logLines.join('\n') + '\n')
150
+ logLines = []
151
+ logBytes = 0
152
+ }
153
+ await $.fs.write(`${dataDir}/companion.log`, logLines.join('\n') + (logLines.length ? '\n' : ''))
154
+ } catch {
155
+ // the log is for measurement only; never fail a wake over it
156
+ }
157
+ }
158
+
159
+ // ---- status line and the hand-back wake (D6, D7, D16) ------------------------------------------------------
160
+
161
+ function redraw(): void {
162
+ const views = [...runs.values()].map((r) => ({ runId: r.entry.runId, latest: r.latest, ladder: r.ladder }))
163
+ const hint = cli.ok && cli.version ? updateHint(modVersion, cli.version) : null
164
+ $.ui.status(cli.ok ? statusLine(views, stopHookArmed, hint) : `DevOrch: offline (${cli.reason})`)
165
+ }
166
+
167
+ function checkHandBack(run: Run): void {
168
+ const nowHealthy = healthOf(run).healthy
169
+ if (nowHealthy) {
170
+ run.handedBack = false
171
+ return
172
+ }
173
+ if (handBackWake({ reportedHealthy: run.reportedHealthy, nowHealthy, stopHookArmed, handedBack: run.handedBack })) {
174
+ run.handedBack = true
175
+ run.reportedHealthy = false
176
+ $.clock.after(0, () => void submit(run.entry.runId, 'hand-back'))
177
+ }
178
+ }
179
+
180
+ // ---- the watched set in $.state (D10) ----------------------------------------------------------------------
181
+
182
+ async function persist(): Promise<void> {
183
+ const value = { runs: [...runs.values()].map((r) => ({ ...r.entry, ...(r.lastToken ? { lastToken: r.lastToken } : {}) })) }
184
+ try {
185
+ await $.state.set({ plugin: 'devorch-companion', key: 'watched' }, value)
186
+ } catch {
187
+ // session state is a convenience for hot reload; the server's position stays authoritative
188
+ }
189
+ }
190
+
191
+ // ---- wakes (D2, D3, CC-5, CC-6) ----------------------------------------------------------------------------
192
+
193
+ function evaluateAll(): void {
194
+ for (const run of runs.values()) evaluate(run)
195
+ }
196
+
197
+ function evaluate(run: Run): void {
198
+ if (run.stopped) return
199
+ const decision = decideWake({
200
+ watchedRunId: run.entry.runId,
201
+ turnRunning,
202
+ idleForMs: idleForMs(),
203
+ stopHookArmed,
204
+ wakePending: run.pendingWake,
205
+ latest: run.latest,
206
+ })
207
+ diag.decision = { at: now(), wake: decision.wake, ...(decision.wake ? {} : { reason: decision.reason }) }
208
+ if (decision.wake) {
209
+ if (wakeInFlight && wakeInFlight !== run.entry.runId) {
210
+ if (!queue.includes(run.entry.runId)) queue.push(run.entry.runId)
211
+ return
212
+ }
213
+ $.clock.after(0, () => void submit(run.entry.runId, 'wake'))
214
+ } else if (decision.retryInMs !== undefined) {
215
+ $.clock.after(decision.retryInMs, () => evaluate(run))
216
+ }
217
+ }
218
+
219
+ async function submit(runId: string, why: 'wake' | 'hand-back'): Promise<void> {
220
+ const run = runs.get(runId)
221
+ if (!run) return
222
+ diag.submit = { at: now(), stage: 'entered' }
223
+ stopHookArmed = await $.fs.exists(`${cwd}/${STOP_HOOK_MARKER}`).catch(() => false)
224
+ diag.submit = { at: now(), stage: 'marker-checked' }
225
+ if (stopHookArmed) {
226
+ redraw()
227
+ return
228
+ }
229
+ if (why === 'wake') {
230
+ if (run.pendingWake || turnRunning) {
231
+ diag.submit = { at: now(), stage: run.pendingWake ? 'skipped: pending' : 'skipped: turn running' }
232
+ return
233
+ }
234
+ run.pendingWake = true
235
+ run.expiry?.cancel()
236
+ run.expiry = $.clock.after(WAKE_EXPIRY_MS, () => onWakeExpired(run))
237
+ }
238
+ wakeInFlight = runId
239
+ log(runId, why === 'wake' ? 'wake-submitted' : 'hand-back-submitted', { token: run.lastToken })
240
+ try {
241
+ diag.submit = { at: now(), stage: 'command.run called' }
242
+ await $.command.run(wakeCommand(runId))
243
+ diag.submit = { at: now(), stage: 'command.run resolved' }
244
+ } catch (err) {
245
+ diag.submit = { at: now(), stage: `command.run rejected: ${String(err).slice(0, 200)}` }
246
+ // Rejected (unknown name, busy, past a Stop): the wake mechanism is broken for this build, so the skill's
247
+ // own ScheduleWakeup must own the wake (D6). Spike rows TQ-3/TQ-12 decide whether a different path exists.
248
+ run.pendingWake = false
249
+ run.expiry?.cancel()
250
+ wakeHealth = { ...wakeHealth, wakeBroken: true }
251
+ $.ui.toast('DevOrch: could not wake the session; /devorch-step keeps its own wakeup')
252
+ log(runId, 'wake-rejected')
253
+ redraw()
254
+ for (const r of runs.values()) checkHandBack(r)
255
+ } finally {
256
+ if (wakeInFlight === runId) wakeInFlight = null
257
+ const nextRunId = queue.shift()
258
+ const queued = nextRunId ? runs.get(nextRunId) : undefined
259
+ if (queued) evaluate(queued)
260
+ }
261
+ }
262
+
263
+ function onWakeExpired(run: Run): void {
264
+ if (!run.pendingWake || run.stopped) return
265
+ run.pendingWake = false
266
+ run.expiry = null
267
+ const r = afterWakeExpired(wakeHealth)
268
+ wakeHealth = { misses: r.misses, wakeBroken: r.wakeBroken }
269
+ $.ui.toast(r.toast)
270
+ log(run.entry.runId, 'wake-expired')
271
+ redraw()
272
+ if (r.reevaluate) evaluate(run)
273
+ checkHandBack(run)
274
+ }
275
+
276
+ // ---- one line from the CLI ---------------------------------------------------------------------------------
277
+
278
+ async function onLine(run: Run, line: string): Promise<void> {
279
+ const envelope = parseEnvelope(line)
280
+ if (!envelope || run.stopped) return
281
+ const d = dedupe(run.lastToken, envelope)
282
+ if (!d.dispatch) return
283
+ if (d.lastToken !== run.lastToken) {
284
+ run.lastToken = d.lastToken
285
+ void persist()
286
+ }
287
+ log(run.entry.runId, 'line', { token: tokenOf(envelope), rung: run.ladder.rung })
288
+ signalFirst(run)
289
+
290
+ let terminal: 'none' | 'seen' | 'wake' = 'none'
291
+ if (positionOf(envelope)) {
292
+ run.latest = envelope
293
+ if (run.pendingWake && clearsPendingWake(envelope)) {
294
+ run.pendingWake = false
295
+ run.expiry?.cancel()
296
+ run.expiry = null
297
+ wakeHealth = afterWakeClaimed(wakeHealth)
298
+ log(run.entry.runId, 'wake-claimed', { token: run.lastToken })
299
+ }
300
+ terminal = terminalAction(envelope, turnRunning, idleForMs())
301
+ }
302
+ redraw()
303
+ await dispatcher.dispatch(envelope)
304
+ if (terminal === 'seen') {
305
+ $.ui.toast(`DevOrch: run ${run.entry.runId.slice(0, 8)} finished`)
306
+ await unwatch(run.entry.runId)
307
+ return
308
+ }
309
+ evaluate(run)
310
+ }
311
+
312
+ // ---- the source ladder (D4, D5) ----------------------------------------------------------------------------
313
+
314
+ function setLadder(run: Run, ladder: LadderState): void {
315
+ const before = run.ladder.rung
316
+ run.ladder = ladder
317
+ if (ladder.rung !== before) {
318
+ log(run.entry.runId, 'rung', { rung: ladder.rung })
319
+ if (ladder.rung >= 3) $.ui.toast(`DevOrch: run ${run.entry.runId.slice(0, 8)} ${ladder.reason}`)
320
+ }
321
+ redraw()
322
+ checkHandBack(run)
323
+ }
324
+
325
+ async function superviseWatch(run: Run): Promise<void> {
326
+ const exe = cli.exe
327
+ if (!exe) return offline(run)
328
+ while (!run.stopped && (run.ladder.rung === 1 || run.ladder.rung === 2)) {
329
+ const heal = $.clock.after(HEAL_MS, () => setLadder(run, afterHealthyChild(run.ladder)))
330
+ let code: number | null = null
331
+ try {
332
+ const child = $.process.spawn({ argv: watchArgv(exe, run.entry.runId, run.entry.baseUrl, run.lastToken) })
333
+ run.child = child
334
+ log(run.entry.runId, 'spawn', { rung: run.ladder.rung })
335
+ const splitter = new LineSplitter()
336
+ for (;;) {
337
+ const piece = await child.next()
338
+ if (piece.done) {
339
+ code = piece.value.code
340
+ break
341
+ }
342
+ if (piece.value.stream !== 'stdout') continue
343
+ for (const line of splitter.push(piece.value.text)) await onLine(run, line)
344
+ }
345
+ for (const line of splitter.flush()) await onLine(run, line)
346
+ } catch {
347
+ code = null // could not start, or killed
348
+ } finally {
349
+ heal.cancel()
350
+ run.child = null
351
+ }
352
+ if (run.stopped) return
353
+ log(run.entry.runId, 'exit', { exitCode: code, rung: run.ladder.rung })
354
+ signalFirst(run)
355
+ if (code === 0) {
356
+ $.ui.toast(`DevOrch: run ${run.entry.runId.slice(0, 8)} finished`)
357
+ await unwatch(run.entry.runId)
358
+ return
359
+ }
360
+ setLadder(run, afterWatchExit(run.ladder, code))
361
+ if (run.ladder.rung === 2) await $.clock.sleep(respawnDelayMs(run.ladder.restarts)).catch(() => {})
362
+ }
363
+ if (run.stopped) return
364
+ if (run.ladder.rung === 3) return pollLoop(run)
365
+ return offline(run)
366
+ }
367
+
368
+ /** Rung 3: sequential one-shot long-polls; retries the watch child every 10 minutes (D4, D5). */
369
+ async function pollLoop(run: Run): Promise<void> {
370
+ const exe = cli.exe
371
+ if (!exe) return offline(run)
372
+ run.retryWatch = false
373
+ run.retry?.cancel()
374
+ run.retry = $.clock.after(HEAL_MS, () => {
375
+ run.retryWatch = true
376
+ })
377
+ let failures = 0
378
+ while (!run.stopped && run.ladder.rung === 3) {
379
+ let exitCode = 75
380
+ let stdout = ''
381
+ try {
382
+ const r = await $.process.run(waitArgv(exe, run.entry.runId, run.entry.baseUrl, run.lastToken), { timeoutMs: POLL_TIMEOUT_MS })
383
+ exitCode = r.exitCode
384
+ stdout = r.stdout
385
+ } catch {
386
+ exitCode = 75 // could not start or timed out: treat as transport
387
+ }
388
+ if (run.stopped) return
389
+ signalFirst(run)
390
+ const outcome = afterPoll(exitCode, failures)
391
+ if (outcome.kind === 'line') {
392
+ failures = 0
393
+ for (const line of new LineSplitter().push(stdout + '\n')) await onLine(run, line)
394
+ } else if (outcome.kind === 'retry') {
395
+ failures = outcome.failures
396
+ await $.clock.sleep(outcome.delayMs).catch(() => {})
397
+ } else if (outcome.kind === 'offline') {
398
+ setLadder(run, { rung: 4, restarts: run.ladder.restarts, reason: outcome.reason })
399
+ return offline(run)
400
+ }
401
+ if (run.retryWatch) {
402
+ run.retry?.cancel()
403
+ run.retry = null
404
+ setLadder(run, { rung: 1, restarts: 0, reason: 'retrying the watch child' })
405
+ return superviseWatch(run)
406
+ }
407
+ }
408
+ }
409
+
410
+ /** Rung 4: no source; `healthy: false` hands the wake to the skill. Retries the handshake every 10 minutes. */
411
+ function offline(run: Run): void {
412
+ if (run.stopped) return
413
+ if (run.ladder.rung !== 4) setLadder(run, { rung: 4, restarts: run.ladder.restarts, reason: cli.reason })
414
+ run.retry?.cancel()
415
+ run.retry = $.clock.after(HEAL_MS, () => void retryOffline(run))
416
+ }
417
+
418
+ async function retryOffline(run: Run): Promise<void> {
419
+ if (run.stopped) return
420
+ await handshake()
421
+ if (!cli.ok) return offline(run)
422
+ setLadder(run, { rung: 1, restarts: 0, reason: 'watching' })
423
+ void superviseWatch(run)
424
+ }
425
+
426
+ // ---- watch / unwatch ---------------------------------------------------------------------------------------
427
+
428
+ async function defaultBaseUrl(explicit?: unknown): Promise<string> {
429
+ return resolveBaseUrl(explicit, options?.apiBase, (await $.env.get('DEVORCH_API_BASE')) ?? undefined)
430
+ }
431
+
432
+ async function watch(rawRunId: string, baseUrl: unknown, lastToken: string | null = null): Promise<Run> {
433
+ const runId = rawRunId.toLowerCase()
434
+ const existing = runs.get(runId)
435
+ if (existing) {
436
+ if (existing.ladder.rung === 4) void retryOffline(existing)
437
+ return existing
438
+ }
439
+ const run: Run = {
440
+ entry: { runId, baseUrl: await defaultBaseUrl(baseUrl), addedAt: now() },
441
+ ladder: { rung: 1, restarts: 0, reason: 'watching' },
442
+ latest: null, lastToken, pendingWake: false, expiry: null, retry: null, child: null, stopped: false,
443
+ reportedHealthy: false, handedBack: false, firstSignal: [], sawFirst: false, retryWatch: false,
444
+ }
445
+ runs.set(runId, run)
446
+ await persist()
447
+ log(runId, 'watch')
448
+ redraw()
449
+ if (!cli.ok) await handshake()
450
+ if (cli.ok) void superviseWatch(run)
451
+ else offline(run)
452
+ return run
453
+ }
454
+
455
+ async function stop(run: Run): Promise<void> {
456
+ run.stopped = true
457
+ run.expiry?.cancel()
458
+ run.retry?.cancel()
459
+ signalFirst(run)
460
+ try {
461
+ await run.child?.return(undefined) // ends the loop, which kills the child
462
+ } catch {
463
+ // already gone
464
+ }
465
+ }
466
+
467
+ async function unwatch(rawRunId: string): Promise<void> {
468
+ const runId = rawRunId.toLowerCase()
469
+ const run = runs.get(runId)
470
+ if (!run) return
471
+ await stop(run)
472
+ runs.delete(runId)
473
+ log(runId, 'unwatch')
474
+ await persist()
475
+ redraw()
476
+ }
477
+
478
+ /** Waits for the first envelope or child exit, at most FIRST_SIGNAL_MS (D16). */
479
+ async function firstSignal(run: Run): Promise<void> {
480
+ if (run.sawFirst) return
481
+ await Promise.race([
482
+ new Promise<void>((resolve) => run.firstSignal.push(resolve)),
483
+ $.clock.sleep(FIRST_SIGNAL_MS).catch(() => {}),
484
+ ])
485
+ }
486
+
487
+ // ---- the CLI handshake (D8, D13) ---------------------------------------------------------------------------
488
+
489
+ async function readText(path: string): Promise<string | null> {
490
+ try {
491
+ const text = await $.fs.read(path)
492
+ return typeof text === 'string' ? text : null
493
+ } catch {
494
+ return null
495
+ }
496
+ }
497
+
498
+ async function handshake(): Promise<void> {
499
+ const cliJson = pluginRoot ? await readText(`${pluginRoot}/cli.json`) : null
500
+ const resolved = resolveExe({ env: (await $.env.get('DEVORCH_EXE')) ?? undefined, userConfig: options?.devorchExe, cliJson })
501
+ if (resolved.exe === null) {
502
+ cli = { ok: false, reason: resolved.reason, exe: null, version: null }
503
+ redraw()
504
+ return
505
+ }
506
+ let stdout: string | null = null
507
+ try {
508
+ const r = await $.process.run(versionArgv(resolved.exe), { timeoutMs: 15_000 })
509
+ stdout = r.exitCode === 0 ? r.stdout : null
510
+ } catch {
511
+ stdout = null
512
+ }
513
+ const supports = cliSupports(stdout)
514
+ let version: string | null = null
515
+ try {
516
+ version = stdout ? ((JSON.parse(stdout) as { version?: string }).version ?? null) : null
517
+ } catch {
518
+ version = null
519
+ }
520
+ cli = { ok: supports.ok, reason: supports.ok ? supports.reason : `${supports.reason} (${resolved.source})`, exe: resolved.exe, version }
521
+ redraw()
522
+ }
523
+
524
+ // ---- /devorch-answer: the answer goes on stdin, never in argv, and is never echoed (CC-4) ------------------
525
+
526
+ async function answer(slug: string, blockerRef: string, text: string): Promise<string> {
527
+ if (!cli.exe) await handshake()
528
+ const exe = cli.exe
529
+ if (!exe) return `devorch CLI unavailable: ${cli.reason}`
530
+ // One watched base URL when every watched run shares it; otherwise the configured default.
531
+ const bases = new Set([...runs.values()].map((r) => r.entry.baseUrl))
532
+ const baseUrl = bases.size === 1 ? ([...bases][0] as string) : await defaultBaseUrl()
533
+ let argv: string[]
534
+ try {
535
+ argv = answerStdinArgv(exe, slug, blockerRef, baseUrl)
536
+ } catch (error) {
537
+ return `Not sent: ${error instanceof Error ? error.message : 'invalid arguments'}`
538
+ }
539
+ try {
540
+ const r = await $.process.run(argv, { stdin: text, timeoutMs: 30_000 })
541
+ return r.exitCode === 0 ? `answered ${blockerRef}` : `devorch blocker answer failed (exit ${r.exitCode})`
542
+ } catch {
543
+ return 'devorch blocker answer could not run'
544
+ }
545
+ }
546
+
547
+ async function shutdown(): Promise<void> {
548
+ for (const run of [...runs.values()]) await stop(run)
549
+ await flushLog()
550
+ }
551
+
552
+ ops = { watch, unwatch, firstSignal, evaluateAll, answer, shutdown }
553
+
554
+ void (async () => {
555
+ try {
556
+ const env = await $.process.hookEnv()
557
+ pluginRoot = env.CLAUDE_PLUGIN_ROOT ?? ''
558
+ dataDir = env.CLAUDE_PLUGIN_DATA ?? ''
559
+ const manifest = pluginRoot ? await readText(`${pluginRoot}/.claude-plugin/plugin.json`) : null
560
+ modVersion = manifest ? ((JSON.parse(manifest) as { version?: string }).version ?? modVersion) : modVersion
561
+ } catch {
562
+ // no data folder: the log stays in memory
563
+ }
564
+ try {
565
+ await $.tool.register({
566
+ name: 'devorch_companion',
567
+ description:
568
+ 'The DevOrch companion mod. status {runId?}: whether this session wakes itself for the run (healthy) or the ' +
569
+ 'skill must keep its own ScheduleWakeup (healthy:false), plus each watched run\'s rung, control, lease and ' +
570
+ 'open blocker refs. watch {runId, baseUrl?}: arm the wake for a run this session drives in a loop (answers ' +
571
+ 'after the first event, at most 5 s). unwatch {runId}: stop.',
572
+ inputSchema: {
573
+ type: 'object',
574
+ properties: {
575
+ action: { type: 'string', enum: ['status', 'watch', 'unwatch'] },
576
+ runId: { type: 'string', description: 'SdlcRun external id (GUID).' },
577
+ baseUrl: { type: 'string', description: 'The DevOrch API base URL the run lives on, when not the default.' },
578
+ },
579
+ required: ['action'],
580
+ },
581
+ })
582
+ await $.command.register({ name: 'devorch-watch', description: 'Watch a DevOrch run (no argument: list watched runs).', argumentHint: '[runId] [baseUrl]', immediate: true })
583
+ await $.command.register({ name: 'devorch-unwatch', description: 'Stop watching a DevOrch run.', argumentHint: '<runId|all>', immediate: true })
584
+ await $.command.register({ name: 'devorch-answer', description: 'Answer an open DevOrch blocker.', argumentHint: '<slug> <ref> <answer...>', immediate: true })
585
+ } catch {
586
+ $.ui.toast('DevOrch: could not register the companion tool and commands')
587
+ }
588
+ stopHookArmed = await $.fs.exists(`${cwd}/${STOP_HOOK_MARKER}`).catch(() => false)
589
+ await handshake()
590
+ const held = await $.state.get({ plugin: 'devorch-companion', key: 'watched' }).catch(() => ({ value: undefined }))
591
+ // No --since on restore: the session lost `latest` with the reload, so it needs the current position now,
592
+ // not the next change (a parked run would otherwise leave the restored watch with nothing to wake on).
593
+ for (const entry of restoreWatched(held.value)) await watch(entry.runId, entry.baseUrl, null)
594
+ redraw()
595
+ })()
596
+ return started
597
+ })
598
+
599
+ on('session.end', async ($, e, next) => {
600
+ await ops?.shutdown()
601
+ return next(e)
602
+ })
603
+
604
+ // ---- turn tracking (CC-5; spike TQ-2 default branch: main loop = agentId undefined) ---------------------------
605
+
606
+ on('turn.start', ($, e, next) => {
607
+ if (e.agentId === undefined) turnRunning = true
608
+ return next(e)
609
+ })
610
+
611
+ on('turn.complete', ($, e, next) => {
612
+ if (e.agentId === undefined) {
613
+ turnRunning = false
614
+ lastTurnEnd = now()
615
+ // Re-evaluate once the settle window has passed, from a timer: never submit inside the hook (D2, TQ-13).
616
+ $.clock.after(SETTLE_MS, () => ops?.evaluateAll())
617
+ }
618
+ return next(e)
619
+ })
620
+
621
+ // ---- the generic event hook for other plugins (D9, AC-3): subscribe and read only ------------------------------
622
+
623
+ on('engine.create', async (_$, e, next) => {
624
+ const beneath: Omit<EngineInterface, 'devorch'> = await next(e)
625
+ return {
626
+ ...beneath,
627
+ devorch: {
628
+ on: (pattern: string, handler: (envelope: PlatformEventEnvelope) => void | Promise<void>) => dispatcher.on(pattern, handler),
629
+ latest: (runId: string) => runs.get(runId.toLowerCase())?.latest ?? null,
630
+ status: () => statusObject() as never,
631
+ },
632
+ }
633
+ })
634
+
635
+ // ---- the model tool (D6, D16) ---------------------------------------------------------------------------------
636
+
637
+ on('tool.run', { tool: TOOL }, async ($, e) => {
638
+ const raw = e as unknown as { action?: unknown; runId?: unknown; baseUrl?: unknown }
639
+ const input = { ...raw, runId: typeof raw.runId === 'string' ? raw.runId.toLowerCase() : raw.runId }
640
+ const reply = (value: unknown) => ({ result: JSON.stringify(value) }) as never
641
+ if (input.action === 'status') {
642
+ const runId = typeof input.runId === 'string' ? input.runId : undefined
643
+ const value = statusObject(runId)
644
+ if (value.healthy === true) for (const r of runs.values()) if (!runId || r.entry.runId === runId) r.reportedHealthy = true
645
+ return reply(value)
646
+ }
647
+ if (!ops) return reply({ watching: false, healthy: false, reason: 'companion not started' })
648
+ if (input.action === 'watch') {
649
+ const runId = String(input.runId ?? '')
650
+ const allowed = canWatch([...runs.keys()], runId)
651
+ if (!allowed.ok) return reply({ watching: false, healthy: false, reason: allowed.reason })
652
+ if (input.baseUrl !== undefined && !isBaseUrl(input.baseUrl)) return reply({ watching: false, healthy: false, reason: 'baseUrl must be an http(s) URL' })
653
+ const run = await ops.watch(runId, input.baseUrl)
654
+ await ops.firstSignal(run)
655
+ const h = healthOf(run)
656
+ run.reportedHealthy = h.healthy
657
+ return reply({ watching: runs.has(runId), ...h })
658
+ }
659
+ if (input.action === 'unwatch') {
660
+ await ops.unwatch(String(input.runId ?? ''))
661
+ return reply({ watching: false })
662
+ }
663
+ return reply({ error: 'action must be status, watch or unwatch' })
664
+ })
665
+
666
+ // ---- slash commands -------------------------------------------------------------------------------------------
667
+
668
+ on('command.run', { command: 'devorch-watch' }, async ($, e) => {
669
+ const parsed = parseWatchArgs(e.args)
670
+ if ('error' in parsed) return { text: parsed.error }
671
+ if (parsed.list) {
672
+ const rows = (statusObject().runs as Record<string, unknown>[]).map((r) => `${r.runId} ${r.baseUrl} rung ${r.rung} ${r.control ?? '-'} blockers ${(r.openBlockers as unknown[]).length}`)
673
+ return { text: rows.length ? rows.join('\n') : 'Not watching a run. /devorch-watch <runId> [baseUrl]' }
674
+ }
675
+ if (!ops) return { text: 'DevOrch companion not started' }
676
+ const allowed = canWatch([...runs.keys()], parsed.runId)
677
+ if (!allowed.ok) return { text: `Not watching: ${allowed.reason}` }
678
+ const run = await ops.watch(parsed.runId, parsed.baseUrl ?? undefined)
679
+ return { text: `Watching ${run.entry.runId} on ${run.entry.baseUrl}` }
680
+ })
681
+
682
+ on('command.run', { command: 'devorch-unwatch' }, async ($, e) => {
683
+ const parsed = parseUnwatchArgs(e.args)
684
+ if ('error' in parsed) return { text: parsed.error }
685
+ const ids = parsed.all ? [...runs.keys()] : [parsed.runId]
686
+ for (const id of ids) await ops?.unwatch(id)
687
+ return { text: `Stopped watching ${ids.length} run(s)` }
688
+ })
689
+
690
+ on('command.run', { command: 'devorch-answer' }, async ($, e) => {
691
+ const parsed = parseAnswerArgs(e.args)
692
+ if (!parsed) return { text: 'usage: /devorch-answer <slug> <ref> <answer...>' }
693
+ if (!ops) return { text: 'DevOrch companion not started' }
694
+ return { text: await ops.answer(parsed.slug, parsed.blockerRef, parsed.answer) }
695
+ })
696
+ }