@sshirkit/dsh-orchestrator 0.8.4 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,15 +1,22 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import z from '@deepseek-ai/schemastery'
3
3
  import { defineTool } from '@deepseek-ai/dsh-tools'
4
- import { z as zod } from 'zod'
5
4
  import { ORCHESTRATE_TOOL } from './api.js'
6
5
  import { createCatalogPublisher } from './catalog.js'
7
6
  import { createDelegateTool } from './delegate.js'
8
- import { effectiveAllowed, installGate, isDelegatedChild } from './gate.js'
7
+ import { createSupervisionTurnState, effectiveAllowed, installGate, isDelegatedChild } from './gate.js'
9
8
  import { createOrchestrateTool } from './orchestrate.js'
10
9
  import { RETRY_SOURCE_KIND, createRetry } from './retry.js'
11
- import { STAGES, initialState, reduceStage } from './stage.js'
12
- import { SUPERVISE_SOURCE_KIND, createSupervisor } from './supervise.js'
10
+ import {
11
+ SUPERVISE_SOURCE_KIND,
12
+ composeNotice,
13
+ createSupervisor,
14
+ getSupervisionChildIds,
15
+ hasNormalDeclarationText,
16
+ isPureSupervisionBatch,
17
+ isSupervisionMessage,
18
+ summarize,
19
+ } from './supervise.js'
13
20
  import { SWITCH_SOURCE_KIND, createSwitchNotices } from './switch-notice.js'
14
21
  import { installToolSurface } from './tool-surface.js'
15
22
  import { isDispatchEnabled } from './worker.js'
@@ -20,27 +27,11 @@ export { SUPERVISE_SOURCE_KIND, SWITCH_SOURCE_KIND }
20
27
  export const name = '@sshirkit/dsh-orchestrator'
21
28
 
22
29
  /**
23
- * Services used here: the projection registry, the tool registry, the subagent
30
+ * Services used here: inbox projection state, the tool registry, the subagent
24
31
  * service, and the live agent/session registries the supervision adapters read.
25
32
  */
26
33
  export const inject = ['sessionProjections', 'tools', 'subagents', 'agents', 'sessions']
27
34
 
28
- /**
29
- * Stage projection. The registry calls `.parse` on these schemas, so they must be
30
- * zod schemas (schemastery objects have no `.parse`), as the native plan projection does.
31
- */
32
- const stageProjection = {
33
- key: 'orchestrator',
34
- stateVersion: 1,
35
- stateSchema: zod.object({ stage: zod.enum(STAGES), plan: zod.boolean() }).strict(),
36
- init: (_header, inheritedEventCount) => initialState(inheritedEventCount),
37
- apply: reduceStage,
38
- wire: {
39
- viewSchema: zod.object({ stage: zod.enum(STAGES), plan: zod.boolean() }),
40
- view: (state) => ({ stage: state.stage, plan: state.plan }),
41
- },
42
- }
43
-
44
35
  /**
45
36
  * The tools a main agent keeps while orchestration mode is on — the shipped whitelist.
46
37
  *
@@ -133,6 +124,8 @@ export const Config = z.object({
133
124
  superviseUnlimited: z.boolean().default(false).volatile(),
134
125
  /** Also notify when a child produced no new events; off saves a model turn. */
135
126
  superviseNotifyOnNoProgress: z.boolean().default(false).volatile(),
127
+ /** Restore only todo/write UI events; never add model history or spend model tokens. */
128
+ restoreTodoOnSupervision: z.boolean().default(true).volatile(),
136
129
  })
137
130
 
138
131
  /** Read one config field whether it is a schemastery ref or a plain value. */
@@ -240,6 +233,7 @@ export function createSwitchPreStep({
240
233
  switchNotices,
241
234
  loadLlm = () => import('@deepseek-ai/dsh-llm'),
242
235
  logger,
236
+ supervisionTurnState,
243
237
  }) {
244
238
  const loadCreator = createUserMessageLoader({
245
239
  loadLlm,
@@ -253,6 +247,7 @@ export function createSwitchPreStep({
253
247
  if (decision?.kind === 'reject' || payload?.signal?.aborted) return decision
254
248
  const agent = payload?.agent
255
249
  if (agent === undefined || agent === null || isDelegatedChild(agent)) return decision
250
+ if (supervisionTurnState?.isTurnActive(agent.id, payload?.turn)) return decision
256
251
  const messages = decision?.messages
257
252
  if (!Array.isArray(messages)) return decision
258
253
  // Mirror `installModelSelection`: a step 1 with no messages (or an emptied step)
@@ -295,6 +290,176 @@ export function createSwitchPreStep({
295
290
  }
296
291
  }
297
292
 
293
+ /** Deep copies keep both the projection and a later append out of the cached snapshot. */
294
+ function cloneTodos(todos) {
295
+ return structuredClone(todos)
296
+ }
297
+
298
+ /** Remember only non-empty root task lists that still belong to the current topic. */
299
+ export function createTodoSnapshotTracker(ctx, { isRegistered = () => true } = {}) {
300
+ const snapshots = new Map()
301
+ const restorationTokens = new WeakMap()
302
+ const restorationKind = 'orchestrator-todo-restoration'
303
+ const record = (session, todos, source) => {
304
+ // Append snapshots the payload; only a token owned by this exact session is ours.
305
+ if (source?.kind === restorationKind && restorationTokens.get(session)?.has(source.token)) return
306
+ if (session === undefined || !Array.isArray(todos)) return
307
+ snapshots.set(session, { todos: cloneTodos(todos), eligible: todos.length > 0 })
308
+ }
309
+ const canRestore = (session) => {
310
+ const record = snapshots.get(session)
311
+ return record?.eligible === true && record.todos.length > 0
312
+ }
313
+ return {
314
+ bind(agent) {
315
+ const session = agent?.session
316
+ if (session === undefined || snapshots.has(session)) return
317
+ try {
318
+ record(session, ctx?.sessionProjections?.snapshot?.(session, ['todos'])?.values?.todos)
319
+ } catch {
320
+ // A missing projection must not prevent a root agent from being installed.
321
+ }
322
+ },
323
+ record,
324
+ canRestore,
325
+ invalidate(session) {
326
+ const record = snapshots.get(session)
327
+ if (record !== undefined) record.eligible = false
328
+ else if (session !== undefined) snapshots.set(session, { todos: [], eligible: false })
329
+ },
330
+ forget: (session) => snapshots.delete(session),
331
+ async restore(agent, payload, config) {
332
+ const session = agent?.session
333
+ if (!canRestore(session) || configValue(config, 'restoreTodoOnSupervision', true) !== true) return
334
+ if (payload?.signal?.aborted || typeof session?.append !== 'function') return
335
+ let token
336
+ let tokens
337
+ try {
338
+ if (typeof ctx?.agents?.turnBoundaryOf === 'function' &&
339
+ ctx.agents.turnBoundaryOf(session)?.lastTurn !== payload?.turn) return
340
+ const todos = ctx?.sessionProjections?.snapshot?.(session, ['todos'])?.values?.todos
341
+ if (todos !== null || !isRegistered(agent)) return
342
+ if (typeof ctx?.agents?.get === 'function' && ctx.agents.get(agent.id) !== agent) return
343
+ const restoredTodos = cloneTodos(snapshots.get(session).todos)
344
+ token = randomUUID()
345
+ tokens = restorationTokens.get(session)
346
+ if (tokens === undefined) restorationTokens.set(session, tokens = new Set())
347
+ tokens.add(token)
348
+ // todo/write is log-only; its projection reads todos and ignores this origin.
349
+ await session.append('todo/write', {
350
+ todos: restoredTodos,
351
+ source: { kind: restorationKind, token },
352
+ })
353
+ } catch {
354
+ // UI restoration is best-effort and must never interrupt a real model step.
355
+ } finally {
356
+ tokens?.delete(token)
357
+ if (tokens?.size === 0) restorationTokens.delete(session)
358
+ }
359
+ },
360
+ }
361
+ }
362
+
363
+ /** Auxiliary host context alone must never fabricate a supervision model request. */
364
+ function isRuntimeContext(message) {
365
+ return ['time-context', 'runtime-context'].includes(message?.source?.kind)
366
+ }
367
+
368
+ /** Reconcile claimed notices synchronously on both sides of downstream awaits. */
369
+ function filterSupervisionMessages(messages, { isLive, rebuildNotice, agent, staleIds }) {
370
+ return messages.flatMap((message) => {
371
+ if (staleIds.has(message?.id)) return []
372
+ if (!isSupervisionMessage(message)) return [message]
373
+ const originalIds = getSupervisionChildIds(message)
374
+ const liveIds = originalIds.filter(isLive)
375
+ if (liveIds.length === 0) {
376
+ staleIds.add(message.id)
377
+ return []
378
+ }
379
+ if (liveIds.length === originalIds.length) return [message]
380
+ const rebuilt = rebuildNotice?.(message, liveIds, agent.id)
381
+ if (rebuilt !== undefined) return [rebuilt]
382
+ // Safe fallback for old hosts: never retain a stale child's original body.
383
+ return [{
384
+ ...message,
385
+ content: [{ type: 'text', text: composeNotice(liveIds.map((childId) => ({ childId }))) }],
386
+ source: { ...message.source, senderSessionId: liveIds[0], childIds: liveIds },
387
+ }]
388
+ })
389
+ }
390
+
391
+ /** Filter claimed inbox messages before any downstream handler can add model context. */
392
+ export function createSupervisionPreStep({
393
+ ctx, config, supervisor, supervisionTurnState, todoTracker, nextStep, rebuildNotice, retainNotices,
394
+ }) {
395
+ const isLive = (id) => supervisor.has(id) && ctx?.agents?.get?.(id) !== undefined
396
+ const run = async (payload, next) => {
397
+ const agent = payload?.agent
398
+ if (agent === undefined || agent === null || isDelegatedChild(agent)) return nextStep(payload, next)
399
+ const messages = Array.isArray(payload.messages) ? payload.messages : []
400
+ const firstStep = payload?.step === 1
401
+ if (firstStep) supervisionTurnState.clearAgent(agent.id)
402
+ const staleIds = new Set()
403
+ let wasSupervision = false
404
+ let restored = false
405
+ const reconcile = (batch) => {
406
+ wasSupervision ||= batch.some(isSupervisionMessage)
407
+ const remaining = filterSupervisionMessages(batch, { isLive, rebuildNotice, agent, staleIds })
408
+ const substantive = remaining.filter((message) => !isRuntimeContext(message))
409
+ const hasSubstantive = substantive.length > 0
410
+ const hasOrdinary = substantive.some((message) => !isSupervisionMessage(message))
411
+ if (remaining.some((message) => message?.source?.kind === 'user')) todoTracker.invalidate(agent.session)
412
+ if (hasOrdinary) supervisionTurnState.clearAgent(agent.id)
413
+ else if (wasSupervision && !hasSubstantive) supervisionTurnState.clearTurn(agent.id, payload.turn)
414
+ return { remaining, hasSubstantive, hasOrdinary, pure: isPureSupervisionBatch(substantive) }
415
+ }
416
+ const restoreOnce = () => {
417
+ // Spend the shared budget before awaiting; reconcile at the caller after its final await.
418
+ if (restored) return
419
+ restored = true
420
+ return todoTracker.restore(agent, payload, config)
421
+ }
422
+ let current = reconcile(messages)
423
+ if (wasSupervision && !current.hasSubstantive) {
424
+ await restoreOnce()
425
+ current = reconcile(messages)
426
+ if (!current.hasSubstantive) return { kind: 'reject' }
427
+ }
428
+ const pure = current.pure
429
+ if (firstStep && pure && !payload?.signal?.aborted) {
430
+ todoTracker.bind(agent)
431
+ supervisionTurnState.bindTurn(agent.id, payload.turn)
432
+ }
433
+ let decision
434
+ try {
435
+ decision = await nextStep({ ...payload, messages: current.remaining }, next)
436
+ } catch (error) {
437
+ supervisionTurnState.clearTurn(agent.id, payload.turn)
438
+ throw error
439
+ }
440
+ if (decision?.kind !== 'enter' || payload?.signal?.aborted) {
441
+ supervisionTurnState.clearTurn(agent.id, payload.turn)
442
+ return decision
443
+ }
444
+ if (!Array.isArray(decision.messages)) return decision
445
+ current = reconcile(decision.messages)
446
+ if ((wasSupervision && !current.hasSubstantive) || (pure && !current.hasOrdinary)) {
447
+ await restoreOnce()
448
+ current = reconcile(decision.messages)
449
+ }
450
+ if (wasSupervision && !current.hasSubstantive) return { kind: 'reject' }
451
+ return { ...decision, messages: current.remaining }
452
+ }
453
+ return async (payload, next) => {
454
+ const release = retainNotices?.(payload)
455
+ try {
456
+ return await run(payload, next)
457
+ } finally {
458
+ release?.()
459
+ }
460
+ }
461
+ }
462
+
298
463
  /**
299
464
  * Build the host side of supervision: the four adapters `createSupervisor`
300
465
  * needs, bound to the live registries. Exported so tests can drive the
@@ -348,6 +513,10 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
348
513
  const parent = ctx?.agents?.get?.(parentId)
349
514
  if (parent === undefined || parent === null) return false
350
515
  try {
516
+ if (parent.inbox !== null && typeof parent.inbox === 'object') {
517
+ return [parent.inbox.nextTurn, parent.inbox.nextStep].some((bucket) =>
518
+ Array.isArray(bucket) && bucket.some(isSupervisionMessage))
519
+ }
351
520
  const stateOf = ctx?.sessionProjections?.stateOf
352
521
  if (typeof stateOf !== 'function') throw new Error('sessionProjections.stateOf is unavailable')
353
522
  const state = stateOf.call(ctx.sessionProjections, parent.session, 'inbox')
@@ -356,7 +525,7 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
356
525
  const pending = state[bucket]
357
526
  if (!Array.isArray(pending)) continue
358
527
  for (const message of pending) {
359
- if (message?.source?.kind === SUPERVISE_SOURCE_KIND) return true
528
+ if (isSupervisionMessage(message)) return true
360
529
  }
361
530
  }
362
531
  return false
@@ -379,18 +548,180 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
379
548
  * kind, because `hasPendingNotice` looks for exactly that kind in the parent inbox;
380
549
  * the retry policy uses a second one, so neither ever reads the other's queue.
381
550
  */
382
- const deliverAs = async (kind, parentId, text, childIds) => {
551
+ const pendingNoticeMeta = new Map()
552
+ const noticeOwners = new Map()
553
+ const claimedNotices = new Map()
554
+ const reconcileScheduled = new Set()
555
+ let noticeCreator
556
+ const liveChildIds = (ids) => ids.filter((id) => supervisor.has(id) && isChildAlive(id))
557
+ const inboxMessages = (parent) => [parent?.inbox?.nextTurn, parent?.inbox?.nextStep]
558
+ .flatMap((bucket) => Array.isArray(bucket) ? bucket : [])
559
+
560
+ /** Claimed and in-flight notices stay owned across every downstream await. */
561
+ const pruneNoticeMeta = () => {
562
+ for (const [id, meta] of pendingNoticeMeta) {
563
+ if (noticeOwners.has(id)) continue
564
+ const parent = ctx?.agents?.get?.(meta.parentId)
565
+ if (parent === undefined || (parent.inbox && !inboxMessages(parent).some((message) => message.id === id))) {
566
+ pendingNoticeMeta.delete(id)
567
+ }
568
+ }
569
+ // Bound only unowned old-host metadata; active owners must never lose their rows.
570
+ for (const id of pendingNoticeMeta.keys()) {
571
+ if (pendingNoticeMeta.size <= 256) break
572
+ if (!noticeOwners.has(id)) pendingNoticeMeta.delete(id)
573
+ }
574
+ }
575
+
576
+ const ownNotice = (id) => noticeOwners.set(id, (noticeOwners.get(id) ?? 0) + 1)
577
+ const releaseNotice = (id) => {
578
+ const remaining = (noticeOwners.get(id) ?? 0) - 1
579
+ if (remaining > 0) noticeOwners.set(id, remaining)
580
+ else noticeOwners.delete(id)
581
+ }
582
+
583
+ /** The synchronous public claimed event bridges claim -> pre-step without a timer. */
584
+ const claimNotice = ({ agent, message, turn } = {}) => {
585
+ if (!agent || isDelegatedChild(agent) || !isSupervisionMessage(message) || !pendingNoticeMeta.has(message.id)) return
586
+ let claims = claimedNotices.get(agent)
587
+ if (claims === undefined) claimedNotices.set(agent, claims = new Map())
588
+ if (claims.has(message.id)) return
589
+ claims.set(message.id, turn)
590
+ ownNotice(message.id)
591
+ }
592
+
593
+ /** Also release claims when another hook rejects before our pre-step ever runs. */
594
+ const releaseClaimedNotices = (agent, turn, ids) => {
595
+ const claims = claimedNotices.get(agent)
596
+ if (claims === undefined) return
597
+ for (const [id, ownerTurn] of claims) {
598
+ if ((turn !== undefined && ownerTurn !== turn) || (ids !== undefined && !ids.has(id))) continue
599
+ claims.delete(id)
600
+ releaseNotice(id)
601
+ }
602
+ if (claims.size === 0) claimedNotices.delete(agent)
603
+ pruneNoticeMeta()
604
+ }
605
+
606
+ /** Transfer pending claims to a counted pre-step owner, including concurrent re-entry. */
607
+ const retainNotices = (payload) => {
608
+ const agent = payload?.agent
609
+ if (!agent || isDelegatedChild(agent)) return
610
+ const ids = new Set((Array.isArray(payload.messages) ? payload.messages : [])
611
+ .filter(isSupervisionMessage).map((message) => message.id).filter((id) => pendingNoticeMeta.has(id)))
612
+ for (const id of ids) ownNotice(id)
613
+ // Transfer only this batch; another concurrent pre-step may own other claims in the same turn.
614
+ releaseClaimedNotices(agent, payload.turn, ids)
615
+ let released = false
616
+ return () => {
617
+ if (released) return
618
+ released = true
619
+ for (const id of ids) releaseNotice(id)
620
+ pruneNoticeMeta()
621
+ }
622
+ }
623
+
624
+ /** Rebuild from the original rows, so a partial settlement never leaves stale text. */
625
+ const buildNotice = (createMessage, parentId, ids, text, meta = {}) => {
626
+ const rowsByChildId = meta.rowsByChildId ?? new Map((meta.rows ?? []).map((row) => [row.childId, { ...row }]))
627
+ const composeMeta = { ...meta.composeMeta }
628
+ const rows = ids.map((childId) => rowsByChildId.get(childId) ?? { childId })
629
+ const body = text ?? composeNotice(rows, composeMeta)
630
+ const message = createMessage({
631
+ content: [{ type: 'text', text: body }],
632
+ source: { kind: SUPERVISE_SOURCE_KIND, form: 'notice', senderSessionId: ids[0], childIds: [...ids] },
633
+ })
634
+ return { message, meta: { parentId, rowsByChildId, composeMeta } }
635
+ }
636
+
637
+ /** Reuse the original rows and timestamp; old notices fall back to live log summaries. */
638
+ const noticeMetaFor = (message, ids, parentId) => {
639
+ const saved = pendingNoticeMeta.get(message.id)
640
+ if (saved !== undefined) return saved
641
+ const now = Date.now()
642
+ const rows = ids.map((childId) => {
643
+ try {
644
+ return { childId, ...summarize(readEvents(childId), { now }) }
645
+ } catch {
646
+ return { childId }
647
+ }
648
+ })
649
+ return { parentId, rows, composeMeta: { now } }
650
+ }
651
+
652
+ /** Claimed notices retain their id so downstream handlers cannot reintroduce old text. */
653
+ const rebuildNotice = (message, ids, parentId) => {
654
+ const createMessage = noticeCreator ?? ((input) => ({ ...message, ...input }))
655
+ const updated = buildNotice(createMessage, parentId, ids, undefined, noticeMetaFor(message, ids, parentId))
656
+ const rebuilt = { ...updated.message, id: message.id ?? updated.message.id }
657
+ if (pendingNoticeMeta.has(message.id)) pendingNoticeMeta.set(rebuilt.id, updated.meta)
658
+ return rebuilt
659
+ }
660
+
661
+ /** One pass reports races; only a bounded microtask chain may retry a failed mutation. */
662
+ const reconcileInbox = (parentId) => {
663
+ const parent = ctx?.agents?.get?.(parentId)
664
+ let retry = false
665
+ for (const message of inboxMessages(parent).filter(isSupervisionMessage)) {
666
+ const originalIds = getSupervisionChildIds(message)
667
+ const ids = liveChildIds(originalIds)
668
+ if (ids.length === originalIds.length && ids.length > 0) continue
669
+ if (ids.length > 0 && typeof parent.inbox.replace !== 'function') continue
670
+ const updated = ids.length > 0 ? rebuildNotice(message, ids, parentId) : undefined
671
+ const result = updated === undefined
672
+ ? parent.inbox.remove?.(message.id)
673
+ : parent.inbox.replace(message.id, updated)
674
+ if (result === false) {
675
+ retry = true
676
+ continue
677
+ }
678
+ if (updated === undefined && !noticeOwners.has(message.id)) pendingNoticeMeta.delete(message.id)
679
+ }
680
+ pruneNoticeMeta()
681
+ return retry
682
+ }
683
+
684
+ /** Inbox mutation must run outside the synchronous session/event publish stack. */
685
+ const scheduleReconcileInbox = (parentId, attempt = 0) => {
686
+ if (typeof parentId !== 'string' || reconcileScheduled.has(parentId)) return
687
+ reconcileScheduled.add(parentId)
688
+ queueMicrotask(() => {
689
+ reconcileScheduled.delete(parentId)
690
+ try {
691
+ if (reconcileInbox(parentId) && attempt < 2) scheduleReconcileInbox(parentId, attempt + 1)
692
+ } catch (error) {
693
+ warn(`orchestrator: supervision: cannot reconcile the parent inbox: ${messageOf(error)}`)
694
+ }
695
+ })
696
+ }
697
+
698
+ const deliverAs = async (kind, parentId, text, childIds, meta) => {
383
699
  const parent = ctx?.agents?.get?.(parentId)
384
700
  if (parent === undefined || parent === null) return 'parent-gone'
385
701
  // The dynamic import is not retried once it failed: the supervisor reschedules
386
702
  // without spending the child's budget, and one warning is enough.
387
703
  const createMessage = await loadCreator()
388
704
  if (createMessage === undefined) return 'unavailable'
705
+ noticeCreator = createMessage
389
706
 
390
- const source = { kind, form: 'notice' }
391
- if (Array.isArray(childIds) && typeof childIds[0] === 'string') source.senderSessionId = childIds[0]
392
- const message = createMessage({ content: [{ type: 'text', text }], source })
707
+ if (ctx?.agents?.get?.(parentId) !== parent) return 'parent-gone'
708
+ let message
709
+ let noticeMeta
710
+ if (kind === SUPERVISE_SOURCE_KIND) {
711
+ const originalIds = getSupervisionChildIds({ source: { childIds } })
712
+ const ids = liveChildIds(originalIds)
713
+ if (ids.length === 0) return 'stale'
714
+ const notice = buildNotice(createMessage, parentId, ids, ids.length === originalIds.length ? text : undefined, meta)
715
+ message = notice.message
716
+ noticeMeta = notice.meta
717
+ } else {
718
+ const source = { kind, form: 'notice' }
719
+ if (Array.isArray(childIds) && typeof childIds[0] === 'string') source.senderSessionId = childIds[0]
720
+ message = createMessage({ content: [{ type: 'text', text }], source })
721
+ }
393
722
  parent.followup(message)
723
+ if (noticeMeta !== undefined && message.id !== undefined) pendingNoticeMeta.set(message.id, noticeMeta)
724
+ pruneNoticeMeta()
394
725
  try {
395
726
  const flushed = await ctx?.sessions?.flush?.(parent.session)
396
727
  if (flushed === false) warn('orchestrator: supervision: the notice was queued but session flush did not acknowledge it')
@@ -400,7 +731,7 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
400
731
  return 'queued'
401
732
  }
402
733
 
403
- const deliver = (parentId, text, childIds) => deliverAs(SUPERVISE_SOURCE_KIND, parentId, text, childIds)
734
+ const deliver = (parentId, text, childIds, meta) => deliverAs(SUPERVISE_SOURCE_KIND, parentId, text, childIds, meta)
404
735
 
405
736
  /** The retry notice: same delivery, its own `source.kind`. */
406
737
  const deliverRetry = (parentId, text, childIds) => deliverAs(RETRY_SOURCE_KIND, parentId, text, childIds)
@@ -453,7 +784,11 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
453
784
  return head
454
785
  }
455
786
 
456
- return { supervisor, isParentAlive, isChildAlive, readEvents, headSeq, hasPendingNotice, deliver, deliverRetry }
787
+ return {
788
+ supervisor, isParentAlive, isChildAlive, readEvents, headSeq, hasPendingNotice,
789
+ deliver, deliverRetry, rebuildNotice, scheduleReconcileInbox, pendingNoticeMeta,
790
+ claimNotice, releaseClaimedNotices, retainNotices,
791
+ }
457
792
  }
458
793
 
459
794
  /**
@@ -462,10 +797,14 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
462
797
  * `send_message` cold resume recreates it. Exported for the same reason as
463
798
  * `createSupervision` — a plain recording object is enough to test it.
464
799
  */
465
- export function createSupervisionHooks(supervisor, { headSeq, retry } = {}) {
800
+ export function createSupervisionHooks(supervisor, { headSeq, retry, scheduleReconcileInbox } = {}) {
801
+ const activeParents = new Map()
466
802
  const forget = (childId) => {
467
803
  try {
468
804
  supervisor.forget(childId)
805
+ const parentId = activeParents.get(childId) ?? dispatched.get(childId)?.parentId
806
+ activeParents.delete(childId)
807
+ if (parentId !== undefined) scheduleReconcileInbox?.(parentId)
469
808
  } catch {
470
809
  // A registry failure here cannot affect the dispatch either.
471
810
  }
@@ -503,6 +842,7 @@ export function createSupervisionHooks(supervisor, { headSeq, retry } = {}) {
503
842
  const parentId = parent?.id
504
843
  if (typeof childId !== 'string' || typeof parentId !== 'string') return
505
844
  remember(childId, { parentId, label: args?.description })
845
+ activeParents.set(childId, parentId)
506
846
  // The retry policy keys on the same record: a child this plugin did not dispatch is
507
847
  // never retried, so the host's own `subagent` children stay untouched.
508
848
  try {
@@ -543,6 +883,7 @@ export function createSupervisionHooks(supervisor, { headSeq, retry } = {}) {
543
883
  // An unreadable registry means "no entry"; re-tracking is idempotent anyway.
544
884
  }
545
885
  try {
886
+ activeParents.set(childId, record.parentId)
546
887
  supervisor.track({
547
888
  childId,
548
889
  parentId: record.parentId,
@@ -561,8 +902,6 @@ export function createSupervisionHooks(supervisor, { headSeq, retry } = {}) {
561
902
  }
562
903
 
563
904
  export function apply(ctx, config) {
564
- ctx.sessionProjections.register(stageProjection)
565
-
566
905
  const supervision = createSupervision({ ctx, config })
567
906
 
568
907
  // A child that dies without a closing message is woken again on the same durable session,
@@ -573,7 +912,18 @@ export function apply(ctx, config) {
573
912
  wakeParent: supervision.deliverRetry,
574
913
  logger: ctx.logger,
575
914
  })
576
- const hooks = createSupervisionHooks(supervision.supervisor, { headSeq: supervision.headSeq, retry })
915
+ const hooks = createSupervisionHooks(supervision.supervisor, {
916
+ headSeq: supervision.headSeq,
917
+ retry,
918
+ scheduleReconcileInbox: supervision.scheduleReconcileInbox,
919
+ })
920
+ const supervisionTurnState = createSupervisionTurnState()
921
+ const rootAgents = new Map()
922
+ const sessionToRootAgent = new Map()
923
+ const todoTracker = createTodoSnapshotTracker(ctx, {
924
+ isRegistered: (agent) => rootAgents.get(agent.id) === agent,
925
+ })
926
+ const currentTurnOf = (agent) => ctx.agents?.turnBoundaryOf?.(agent.session)?.lastTurn
577
927
 
578
928
  // The dispatch switch is volatile config: the panel writes it and the loader announces the
579
929
  // change. A notice pushed at that moment would splice into a turn the user is still reading,
@@ -654,7 +1004,12 @@ export function apply(ctx, config) {
654
1004
 
655
1005
  const gates = new Map()
656
1006
 
657
- const installFor = (agent) => installGate({ agent, allowed: allowedTools, enabled: dispatchEnabled })
1007
+ const installFor = (agent) => installGate({
1008
+ agent,
1009
+ allowed: allowedTools,
1010
+ enabled: dispatchEnabled,
1011
+ checkSupervision: (current, tool, options) => supervisionTurnState.checkTool(current.id, currentTurnOf(current), tool, options),
1012
+ })
658
1013
 
659
1014
  /**
660
1015
  * The Allowed Tools panel must offer every tool the host really has, including the ones
@@ -729,6 +1084,7 @@ export function apply(ctx, config) {
729
1084
  // Settlement is one of the two edges a live child stops at; a lease held past this
730
1085
  // point would refuse every later writer until its TTL.
731
1086
  releaseWriteLease(childId)
1087
+ hooks.forget(childId)
732
1088
  void Promise.resolve(retry.settle(childId, info, info?.runId)).catch((error) => {
733
1089
  try {
734
1090
  ctx.logger?.warn?.(`orchestrator: retry: cannot apply the settlement of ${childId}: ${messageOf(error)}`)
@@ -740,6 +1096,49 @@ export function apply(ctx, config) {
740
1096
  { global: true },
741
1097
  )
742
1098
 
1099
+ /** Registration also covers roots that were already alive when the plugin mounted. */
1100
+ const registerRootAgent = (agent) => {
1101
+ if (agent === undefined || agent === null || isDelegatedChild(agent)) return
1102
+ if (rootAgents.get(agent.id) === agent) return
1103
+ const previous = rootAgents.get(agent.id)
1104
+ if (previous !== undefined) unregisterRootAgent(previous)
1105
+ const gate = installFor(agent)
1106
+ gates.set(agent.id, gate)
1107
+ rootAgents.set(agent.id, agent)
1108
+ sessionToRootAgent.set(agent.session, agent)
1109
+ todoTracker.bind(agent)
1110
+ switchNotices.observe(agent.id)
1111
+ if (!dispatchEnabled()) return
1112
+ ctx.logger.info(
1113
+ `orchestrator: main agent ${agent.id}: armed whitelist gate (${gate.allowed.length} allowed: [${gate.allowed.join(', ')}])`,
1114
+ )
1115
+ if (gate.guardError !== undefined) {
1116
+ ctx.logger.warn(`orchestrator: main agent ${agent.id}: guard not installed: ${gate.guardError}`)
1117
+ }
1118
+ }
1119
+
1120
+ const unregisterRootAgent = (agent) => {
1121
+ if (rootAgents.get(agent.id) !== agent) return
1122
+ rootAgents.delete(agent.id)
1123
+ supervision.releaseClaimedNotices(agent)
1124
+ if (sessionToRootAgent.get(agent.session) === agent) sessionToRootAgent.delete(agent.session)
1125
+ supervisionTurnState.clearAgent(agent.id)
1126
+ todoTracker.forget(agent.session)
1127
+ switchNotices.forget(agent.id)
1128
+ const gate = gates.get(agent.id)
1129
+ gates.delete(agent.id)
1130
+ try {
1131
+ gate?.dispose()
1132
+ } catch (error) {
1133
+ ctx.logger.warn(`orchestrator: main agent ${agent.id}: cannot lift the gate: ${messageOf(error)}`)
1134
+ }
1135
+ }
1136
+
1137
+ ctx.effect(() => () => {
1138
+ for (const agent of rootAgents.values()) unregisterRootAgent(agent)
1139
+ sessionToRootAgent.clear()
1140
+ }, 'orchestrator: root agents')
1141
+
743
1142
  ctx.on('agent/created', (payload) => {
744
1143
  const agent = payload?.agent
745
1144
  // A new root agent is the only place a preset or scope-local tool becomes visible,
@@ -756,13 +1155,8 @@ export function apply(ctx, config) {
756
1155
  return
757
1156
  }
758
1157
 
759
- // Installed even while the switch is off: the guard follows the switch per call,
760
- // so turning dispatch mode on in an open conversation takes effect at once.
761
- const gate = installFor(agent)
762
- gates.set(agent.id, gate)
763
- // Baseline only: an agent created while the switch is off must not receive a
764
- // "switched to off" notice for a flip nobody made.
765
- switchNotices.observe(agent.id)
1158
+ // The same idempotent path handles startup enumeration and later creations.
1159
+ registerRootAgent(agent)
766
1160
  // A resumed agent with a parentSession that still read as a main agent means the
767
1161
  // depth test degraded: the cold-resume regression looked exactly like this.
768
1162
  if (payload?.source === 'resume' && agent.session?.header?.parentSession !== undefined) {
@@ -770,15 +1164,14 @@ export function apply(ctx, config) {
770
1164
  `orchestrator: agent ${agent.id} resumed with a parentSession but no delegation depth; gated it as a main agent`,
771
1165
  )
772
1166
  }
773
- if (!dispatchEnabled()) return
774
- ctx.logger.info(
775
- `orchestrator: main agent ${agent.id}: armed whitelist gate (${gate.allowed.length} allowed: [${gate.allowed.join(', ')}])`,
776
- )
777
- if (gate.guardError !== undefined) {
778
- ctx.logger.warn(`orchestrator: main agent ${agent.id}: guard not installed: ${gate.guardError}`)
779
- }
780
1167
  })
781
1168
 
1169
+ try {
1170
+ for (const agent of ctx.agents?.list?.() ?? []) registerRootAgent(agent)
1171
+ } catch (error) {
1172
+ ctx.logger.warn(`orchestrator: cannot register existing root agents: ${messageOf(error)}`)
1173
+ }
1174
+
782
1175
  // A gated agent that goes away takes its guard with it: the entry is the only owner of
783
1176
  // the disposer, so dropping it here must not leave a predicate behind.
784
1177
  ctx.on('agent/disposed', (payload) => {
@@ -790,18 +1183,11 @@ export function apply(ctx, config) {
790
1183
  // A worker may be disposed without a settlement edge (host shutdown, killed process),
791
1184
  // so this is the second, independent release path for its write lease.
792
1185
  releaseWriteLease(id)
1186
+ unregisterRootAgent(agent)
1187
+ supervision.scheduleReconcileInbox(id)
793
1188
  // A disposed worker must not keep a supervision slot: until it is resumed its session
794
1189
  // is gone, and the tick would only read a dead log. A resume re-arms it above.
795
1190
  if (isDelegatedChild(agent)) hooks.forget(id)
796
- switchNotices.forget(id)
797
- const gate = gates.get(id)
798
- if (gate === undefined) return
799
- gates.delete(id)
800
- try {
801
- gate.dispose()
802
- } catch (error) {
803
- ctx.logger.warn(`orchestrator: main agent ${id}: cannot lift the gate: ${messageOf(error)}`)
804
- }
805
1191
  })
806
1192
 
807
1193
  /**
@@ -830,9 +1216,36 @@ export function apply(ctx, config) {
830
1216
  * reentrancy, rides inside the user's own turn with zero extra bubbles or turns, and leaves
831
1217
  * the pending flag untouched if an outer hook rejects or aborts the step.
832
1218
  */
1219
+ ctx.on('agent/inbox/claimed', supervision.claimNotice, { global: true })
1220
+
1221
+ ctx.on('session/event', (session, event) => {
1222
+ const agent = sessionToRootAgent.get(session)
1223
+ if (agent === undefined || isDelegatedChild(agent)) return
1224
+ if (event?.type === 'todo/write') {
1225
+ todoTracker.record(agent.session, event.data?.todos, event.data?.source)
1226
+ } else if (event?.type === 'assistant/message') {
1227
+ const turn = event.data?.turn
1228
+ if (supervisionTurnState.isTurnActive(agent.id, turn) && hasNormalDeclarationText(event.data?.message)) {
1229
+ supervisionTurnState.markNormalDeclared(agent.id, turn)
1230
+ }
1231
+ } else if (event?.type === 'turn/end') {
1232
+ supervision.releaseClaimedNotices(agent, event.data?.turn)
1233
+ supervisionTurnState.clearTurn(agent.id, event.data?.turn)
1234
+ }
1235
+ }, { global: true })
1236
+
833
1237
  ctx.on(
834
1238
  'agent/pre-step',
835
- createSwitchPreStep({ switchNotices, logger: ctx.logger }),
1239
+ createSupervisionPreStep({
1240
+ ctx,
1241
+ config,
1242
+ supervisor: supervision.supervisor,
1243
+ rebuildNotice: supervision.rebuildNotice,
1244
+ retainNotices: supervision.retainNotices,
1245
+ supervisionTurnState,
1246
+ todoTracker,
1247
+ nextStep: createSwitchPreStep({ switchNotices, logger: ctx.logger, supervisionTurnState }),
1248
+ }),
836
1249
  { global: true },
837
1250
  )
838
1251
  }