@sshirkit/dsh-orchestrator 0.8.5 → 0.8.8

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
@@ -4,10 +4,19 @@ import { defineTool } from '@deepseek-ai/dsh-tools'
4
4
  import { ORCHESTRATE_TOOL } from './api.js'
5
5
  import { createCatalogPublisher } from './catalog.js'
6
6
  import { createDelegateTool } from './delegate.js'
7
- import { effectiveAllowed, installGate, isDelegatedChild } from './gate.js'
7
+ import { createSupervisionTurnState, effectiveAllowed, installGate, isDelegatedChild } from './gate.js'
8
8
  import { createOrchestrateTool } from './orchestrate.js'
9
9
  import { RETRY_SOURCE_KIND, createRetry } from './retry.js'
10
- 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'
11
20
  import { SWITCH_SOURCE_KIND, createSwitchNotices } from './switch-notice.js'
12
21
  import { installToolSurface } from './tool-surface.js'
13
22
  import { isDispatchEnabled } from './worker.js'
@@ -115,6 +124,8 @@ export const Config = z.object({
115
124
  superviseUnlimited: z.boolean().default(false).volatile(),
116
125
  /** Also notify when a child produced no new events; off saves a model turn. */
117
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(),
118
129
  })
119
130
 
120
131
  /** Read one config field whether it is a schemastery ref or a plain value. */
@@ -222,6 +233,7 @@ export function createSwitchPreStep({
222
233
  switchNotices,
223
234
  loadLlm = () => import('@deepseek-ai/dsh-llm'),
224
235
  logger,
236
+ supervisionTurnState,
225
237
  }) {
226
238
  const loadCreator = createUserMessageLoader({
227
239
  loadLlm,
@@ -235,6 +247,7 @@ export function createSwitchPreStep({
235
247
  if (decision?.kind === 'reject' || payload?.signal?.aborted) return decision
236
248
  const agent = payload?.agent
237
249
  if (agent === undefined || agent === null || isDelegatedChild(agent)) return decision
250
+ if (supervisionTurnState?.isTurnActive(agent.id, payload?.turn)) return decision
238
251
  const messages = decision?.messages
239
252
  if (!Array.isArray(messages)) return decision
240
253
  // Mirror `installModelSelection`: a step 1 with no messages (or an emptied step)
@@ -277,6 +290,176 @@ export function createSwitchPreStep({
277
290
  }
278
291
  }
279
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
+
280
463
  /**
281
464
  * Build the host side of supervision: the four adapters `createSupervisor`
282
465
  * needs, bound to the live registries. Exported so tests can drive the
@@ -330,6 +513,10 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
330
513
  const parent = ctx?.agents?.get?.(parentId)
331
514
  if (parent === undefined || parent === null) return false
332
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
+ }
333
520
  const stateOf = ctx?.sessionProjections?.stateOf
334
521
  if (typeof stateOf !== 'function') throw new Error('sessionProjections.stateOf is unavailable')
335
522
  const state = stateOf.call(ctx.sessionProjections, parent.session, 'inbox')
@@ -338,7 +525,7 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
338
525
  const pending = state[bucket]
339
526
  if (!Array.isArray(pending)) continue
340
527
  for (const message of pending) {
341
- if (message?.source?.kind === SUPERVISE_SOURCE_KIND) return true
528
+ if (isSupervisionMessage(message)) return true
342
529
  }
343
530
  }
344
531
  return false
@@ -361,18 +548,180 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
361
548
  * kind, because `hasPendingNotice` looks for exactly that kind in the parent inbox;
362
549
  * the retry policy uses a second one, so neither ever reads the other's queue.
363
550
  */
364
- 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) => {
365
699
  const parent = ctx?.agents?.get?.(parentId)
366
700
  if (parent === undefined || parent === null) return 'parent-gone'
367
701
  // The dynamic import is not retried once it failed: the supervisor reschedules
368
702
  // without spending the child's budget, and one warning is enough.
369
703
  const createMessage = await loadCreator()
370
704
  if (createMessage === undefined) return 'unavailable'
705
+ noticeCreator = createMessage
371
706
 
372
- const source = { kind, form: 'notice' }
373
- if (Array.isArray(childIds) && typeof childIds[0] === 'string') source.senderSessionId = childIds[0]
374
- 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
+ }
375
722
  parent.followup(message)
723
+ if (noticeMeta !== undefined && message.id !== undefined) pendingNoticeMeta.set(message.id, noticeMeta)
724
+ pruneNoticeMeta()
376
725
  try {
377
726
  const flushed = await ctx?.sessions?.flush?.(parent.session)
378
727
  if (flushed === false) warn('orchestrator: supervision: the notice was queued but session flush did not acknowledge it')
@@ -382,7 +731,7 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
382
731
  return 'queued'
383
732
  }
384
733
 
385
- 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)
386
735
 
387
736
  /** The retry notice: same delivery, its own `source.kind`. */
388
737
  const deliverRetry = (parentId, text, childIds) => deliverAs(RETRY_SOURCE_KIND, parentId, text, childIds)
@@ -435,7 +784,11 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
435
784
  return head
436
785
  }
437
786
 
438
- 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
+ }
439
792
  }
440
793
 
441
794
  /**
@@ -444,10 +797,14 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
444
797
  * `send_message` cold resume recreates it. Exported for the same reason as
445
798
  * `createSupervision` — a plain recording object is enough to test it.
446
799
  */
447
- export function createSupervisionHooks(supervisor, { headSeq, retry } = {}) {
800
+ export function createSupervisionHooks(supervisor, { headSeq, retry, scheduleReconcileInbox } = {}) {
801
+ const activeParents = new Map()
448
802
  const forget = (childId) => {
449
803
  try {
450
804
  supervisor.forget(childId)
805
+ const parentId = activeParents.get(childId) ?? dispatched.get(childId)?.parentId
806
+ activeParents.delete(childId)
807
+ if (parentId !== undefined) scheduleReconcileInbox?.(parentId)
451
808
  } catch {
452
809
  // A registry failure here cannot affect the dispatch either.
453
810
  }
@@ -485,6 +842,7 @@ export function createSupervisionHooks(supervisor, { headSeq, retry } = {}) {
485
842
  const parentId = parent?.id
486
843
  if (typeof childId !== 'string' || typeof parentId !== 'string') return
487
844
  remember(childId, { parentId, label: args?.description })
845
+ activeParents.set(childId, parentId)
488
846
  // The retry policy keys on the same record: a child this plugin did not dispatch is
489
847
  // never retried, so the host's own `subagent` children stay untouched.
490
848
  try {
@@ -525,6 +883,7 @@ export function createSupervisionHooks(supervisor, { headSeq, retry } = {}) {
525
883
  // An unreadable registry means "no entry"; re-tracking is idempotent anyway.
526
884
  }
527
885
  try {
886
+ activeParents.set(childId, record.parentId)
528
887
  supervisor.track({
529
888
  childId,
530
889
  parentId: record.parentId,
@@ -553,7 +912,18 @@ export function apply(ctx, config) {
553
912
  wakeParent: supervision.deliverRetry,
554
913
  logger: ctx.logger,
555
914
  })
556
- 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
557
927
 
558
928
  // The dispatch switch is volatile config: the panel writes it and the loader announces the
559
929
  // change. A notice pushed at that moment would splice into a turn the user is still reading,
@@ -634,7 +1004,12 @@ export function apply(ctx, config) {
634
1004
 
635
1005
  const gates = new Map()
636
1006
 
637
- 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
+ })
638
1013
 
639
1014
  /**
640
1015
  * The Allowed Tools panel must offer every tool the host really has, including the ones
@@ -709,6 +1084,7 @@ export function apply(ctx, config) {
709
1084
  // Settlement is one of the two edges a live child stops at; a lease held past this
710
1085
  // point would refuse every later writer until its TTL.
711
1086
  releaseWriteLease(childId)
1087
+ hooks.forget(childId)
712
1088
  void Promise.resolve(retry.settle(childId, info, info?.runId)).catch((error) => {
713
1089
  try {
714
1090
  ctx.logger?.warn?.(`orchestrator: retry: cannot apply the settlement of ${childId}: ${messageOf(error)}`)
@@ -720,6 +1096,49 @@ export function apply(ctx, config) {
720
1096
  { global: true },
721
1097
  )
722
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
+
723
1142
  ctx.on('agent/created', (payload) => {
724
1143
  const agent = payload?.agent
725
1144
  // A new root agent is the only place a preset or scope-local tool becomes visible,
@@ -736,13 +1155,8 @@ export function apply(ctx, config) {
736
1155
  return
737
1156
  }
738
1157
 
739
- // Installed even while the switch is off: the guard follows the switch per call,
740
- // so turning dispatch mode on in an open conversation takes effect at once.
741
- const gate = installFor(agent)
742
- gates.set(agent.id, gate)
743
- // Baseline only: an agent created while the switch is off must not receive a
744
- // "switched to off" notice for a flip nobody made.
745
- switchNotices.observe(agent.id)
1158
+ // The same idempotent path handles startup enumeration and later creations.
1159
+ registerRootAgent(agent)
746
1160
  // A resumed agent with a parentSession that still read as a main agent means the
747
1161
  // depth test degraded: the cold-resume regression looked exactly like this.
748
1162
  if (payload?.source === 'resume' && agent.session?.header?.parentSession !== undefined) {
@@ -750,15 +1164,14 @@ export function apply(ctx, config) {
750
1164
  `orchestrator: agent ${agent.id} resumed with a parentSession but no delegation depth; gated it as a main agent`,
751
1165
  )
752
1166
  }
753
- if (!dispatchEnabled()) return
754
- ctx.logger.info(
755
- `orchestrator: main agent ${agent.id}: armed whitelist gate (${gate.allowed.length} allowed: [${gate.allowed.join(', ')}])`,
756
- )
757
- if (gate.guardError !== undefined) {
758
- ctx.logger.warn(`orchestrator: main agent ${agent.id}: guard not installed: ${gate.guardError}`)
759
- }
760
1167
  })
761
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
+
762
1175
  // A gated agent that goes away takes its guard with it: the entry is the only owner of
763
1176
  // the disposer, so dropping it here must not leave a predicate behind.
764
1177
  ctx.on('agent/disposed', (payload) => {
@@ -770,18 +1183,11 @@ export function apply(ctx, config) {
770
1183
  // A worker may be disposed without a settlement edge (host shutdown, killed process),
771
1184
  // so this is the second, independent release path for its write lease.
772
1185
  releaseWriteLease(id)
1186
+ unregisterRootAgent(agent)
1187
+ supervision.scheduleReconcileInbox(id)
773
1188
  // A disposed worker must not keep a supervision slot: until it is resumed its session
774
1189
  // is gone, and the tick would only read a dead log. A resume re-arms it above.
775
1190
  if (isDelegatedChild(agent)) hooks.forget(id)
776
- switchNotices.forget(id)
777
- const gate = gates.get(id)
778
- if (gate === undefined) return
779
- gates.delete(id)
780
- try {
781
- gate.dispose()
782
- } catch (error) {
783
- ctx.logger.warn(`orchestrator: main agent ${id}: cannot lift the gate: ${messageOf(error)}`)
784
- }
785
1191
  })
786
1192
 
787
1193
  /**
@@ -810,9 +1216,36 @@ export function apply(ctx, config) {
810
1216
  * reentrancy, rides inside the user's own turn with zero extra bubbles or turns, and leaves
811
1217
  * the pending flag untouched if an outer hook rejects or aborts the step.
812
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
+
813
1237
  ctx.on(
814
1238
  'agent/pre-step',
815
- 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
+ }),
816
1249
  { global: true },
817
1250
  )
818
1251
  }
package/lib/rules.js CHANGED
@@ -39,12 +39,15 @@ export function mainAgentRule(allowedTools, preferred = DELEGATE_TOOL) {
39
39
  '此时告知用户子代理模型可能不可用,只提供通知中的 A/B 选项(A 派生新子代理重做 / B 更换子代理模型后重试)并等待用户答复;' +
40
40
  '不要建议继续唤醒旧子代理,未经用户选择 A 不要另派子代理重复工作,也不要私自换模型重发。' +
41
41
  '严禁通过 run_code 触达宿主:禁用 import/require/process/fetch/eval,也禁用 ' +
42
- 'sandbox_permissions/justification;run_code 内只能调用 delegate 和 orchestrate。' +
42
+ 'sandbox_permissions/justification;run_code 仅作为 PTC 传输层,只可通过 tools 调用当前 allowedTools 中已授权的工具;' +
43
+ 'PTC 不扩大权限,巡检回合的 todo_write 禁令与「巡检:正常」声明后的工具锁继续生效。' +
43
44
  '仅当当前用户消息显式点名时才传 provider/model/reasoning_effort,否则三者全部省略(用调度面板路由);' +
44
45
  '点名的模型仅限本次派发,严禁复用历史轮次、历史派发或摘要中的模型,严禁假定未声明的默认模型,不确定先询问。' +
45
46
  (allowedNames === ''
46
47
  ? ' 当前主代理无可用工具(白名单为空)。'
47
48
  : ` 主代理可用工具(白名单驱动,其余全部禁用): ${allowedNames}。`) +
48
- ' '
49
+ '(【插件巡检】自动唤醒回合的巡检例外仅指不自动推进主任务与禁止调用 todo_write;' +
50
+ '巡检回合仍受当前工具白名单(allowedTools)制约,仅检查并按需干预在跑子代理,禁止修改 todo_write;' +
51
+ '确认无需干预时只回复一行「巡检:正常」并立即结束,禁止附加工具调用。) '
49
52
  )
50
53
  }