dsh-pause-session 0.0.0-stage → 0.2.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/DEVELOPMENT.md +78 -0
  3. package/LICENSE +21 -0
  4. package/README.md +140 -2
  5. package/README.zh.md +101 -0
  6. package/REHEARSAL.md +90 -0
  7. package/cordis.patch.yml +3 -0
  8. package/docs/images/pause-controls.webp +0 -0
  9. package/icon.svg +5 -0
  10. package/lib/client.js +2024 -0
  11. package/lib/client.js.map +1 -0
  12. package/lib/index.js +2996 -0
  13. package/lib/index.js.map +1 -0
  14. package/lib/typert.host.d.ts +3 -0
  15. package/lib/typert.host.js +339 -0
  16. package/lib/typert.remote-client.d.ts +38 -0
  17. package/lib/typert.remote-client.d.ts.map +1 -0
  18. package/lib/typert.remote-client.js +244 -0
  19. package/lib/types/client/control.d.ts +99 -0
  20. package/lib/types/client/global.d.ts +125 -0
  21. package/lib/types/client/icons.d.ts +24 -0
  22. package/lib/types/client/index.d.ts +78 -0
  23. package/lib/types/client/locales.d.ts +67 -0
  24. package/lib/types/client/pill.d.ts +49 -0
  25. package/lib/types/client/remote.d.ts +71 -0
  26. package/lib/types/client/view.d.ts +151 -0
  27. package/lib/types/coldlog.d.ts +111 -0
  28. package/lib/types/composition.d.ts +94 -0
  29. package/lib/types/control.d.ts +95 -0
  30. package/lib/types/gate.d.ts +110 -0
  31. package/lib/types/global.d.ts +103 -0
  32. package/lib/types/history.d.ts +47 -0
  33. package/lib/types/index.d.ts +64 -0
  34. package/lib/types/park-state.d.ts +51 -0
  35. package/lib/types/park.d.ts +50 -0
  36. package/lib/types/registry.d.ts +117 -0
  37. package/lib/types/release-order.d.ts +21 -0
  38. package/lib/types/remote-adapter.d.ts +22 -0
  39. package/lib/types/remote.d.ts +158 -0
  40. package/lib/types/resume-activation.d.ts +27 -0
  41. package/lib/types/resume-text.d.ts +67 -0
  42. package/lib/types/resume.d.ts +126 -0
  43. package/lib/types/shared.d.ts +221 -0
  44. package/lib/types/snapshot.d.ts +29 -0
  45. package/lib/types/tree.d.ts +71 -0
  46. package/lib/types/triage.d.ts +120 -0
  47. package/locale/en.json +6 -0
  48. package/locale/zh.json +6 -0
  49. package/package.json +166 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/history.ts","../src/shared.ts","../src/coldlog.ts","../src/tree.ts","../src/global.ts","../src/release-order.ts","../src/composition.ts","../src/resume-text.ts","../src/resume-activation.ts","../src/resume.ts","../src/triage.ts","../src/snapshot.ts","../src/park-state.ts","../src/control.ts","../src/gate.ts","../src/park.ts","../src/remote.ts","../src/remote-adapter.ts","../src/registry.ts","../src/index.ts"],"sourcesContent":["/**\n * The message history a session's log derives to, and the one rule that reads\n * whether it still owes the model an answer.\n *\n * That question is asked twice and must have one answer: the clean wake asks it\n * before it hands a session an input (an input nobody owes an answer to would\n * open a turn of its own), and the decision list publishes it as the row's\n * `wake` field. A published promise that the wake then declines to keep is the\n * report lying, so both read the same derivation and the same rule.\n *\n * The derivation is the harness's own: the surface fold the loop reads its\n * history through, with the same message projections this process has\n * registered, and an interrupted tail closed exactly as the harness closes it\n * on the next read. `resume.ts` reads the live form of it\n * (`Session.deriveMessages()`); {@link derivedHistory} is the cold form over a\n * stored log, which is all the decision list may claim — it opens a log to read\n * it and never activates a session.\n * @module dsh-pause-session/history\n */\n\nimport type { Message } from '@deepseek-ai/dsh-llm'\nimport {\n deriveEventMessage, foldSurface, foldRequestHeader, interruptedTurnClosers,\n} from '@deepseek-ai/dsh-session'\nimport type { SessionEvent, SessionMessageProjection } from '@deepseek-ai/dsh-session'\n\n/**\n * Whether one derived history ends owing the model an answer: the last thing\n * said on the model-visible surface is not an assistant message.\n * @param messages - a derived history, in model-visible order.\n * @returns whether a model still owes that history a reply.\n */\nexport function owesReply(messages: readonly Message[]): boolean {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]\n // System and developer entries are request framing, not conversation.\n if (message === undefined || message.role === 'system' || message.role === 'developer') continue\n return message.role !== 'assistant'\n }\n return false\n}\n\n/**\n * The messages one stored log derives to, as the harness would read them on the\n * session's next activation: the open tail turn is closed with the harness's\n * own synthetic results first, then the log is folded into its surface.\n * @param events - the stored events, exactly as they are stored and in sequence order.\n * @param projections - this process's registered message projections.\n * @returns the derived history, in model-visible order.\n * @throws when the log cannot be folded — an event this build has no interpreter\n * for, or surface metadata that does not apply to this history.\n */\nexport function derivedHistory(\n events: readonly SessionEvent[],\n projections: readonly SessionMessageProjection[],\n): Message[] {\n const stored = [...events, ...interruptedTurnClosers(events)]\n const fold = foldSurface(stored, projections)\n return fold.nodes.flatMap((seq) => {\n const event = stored[seq]\n if (event === undefined) return []\n const message = deriveEventMessage(event, fold.projectedMessages)\n return message === null ? [] : [message]\n })\n}\n\n/**\n * Whether one stored log names the route a wake would be addressed to. The wake\n * needs a provider and a model to build a request at all, and the request\n * header the session itself persisted is the only place that names them.\n * @param events - the stored events, in sequence order.\n * @returns whether the log's last request header carries both route fields.\n */\nexport function routeNamed(events: readonly SessionEvent[]): boolean {\n const config = foldRequestHeader(events)?.config\n return config !== undefined && config.provider.length > 0 && config.model.length > 0\n}\n","/**\n * The identities both halves of dsh-pause-session name, the phase vocabulary\n * they share, and the one spelling a host log line gives a caught value.\n *\n * The browser bundle may value-import only the shell's baseline module table,\n * so this module imports nothing. The native Remote payloads are the live\n * vocabulary; there is no command encoding or slash-command surface here.\n * @module dsh-pause-session/shared\n */\n\n/** Result copy for a press or a release the durable registry refused to record. */\nexport const UNRECORDED_TEXT = 'pause could not write the pause registry, so it did not change the pause state.'\n\n/**\n * One user-facing answer from an action. The controls render `text` verbatim;\n * `kind` only says whether the press succeeded.\n */\nexport interface PauseAnswer {\n readonly kind: 'success' | 'error'\n readonly text: string\n}\n\n/**\n * One log line's text for a caught value.\n * @param error - the caught value.\n * @returns the error's message, or the value's own spelling.\n */\nexport function describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * The four park outcomes, listed in the order a park walks them — and the one\n * vocabulary the live status, the durable registry, and the published words all\n * derive from, so they cannot drift apart:\n *\n * - `draining`: paused, and the session is still working — a tool is running, or\n * a turn is between steps.\n * - `parking`: standing still at the park point; the session-level flush has\n * not resolved yet.\n * - `safe`: parked and flushed, so it is safe to walk away. The only clean one.\n * - `flush-failed`: parked, but the flush failed — the durable promise is not\n * kept, and it must never be read as clean.\n */\nexport const PARK_PHASES = ['draining', 'parking', 'safe', 'flush-failed'] as const\n\n/** One park outcome. */\nexport type ParkPhase = (typeof PARK_PHASES)[number]\n\n/**\n * How far along a phase is, worst first. The direction is not the order a park\n * walks: it orders how much of the promise each outcome keeps, which is what a\n * fold over several sessions has to compare. `safe` keeps all of it, `draining`\n * and `parking` are on their way, `flush-failed` has stopped trying — a park\n * that failed its flush is further from clean than one that is still working at\n * it, so it must never be the outcome a report rounds down to.\n */\nconst PHASE_SEVERITY: Record<ParkPhase, number> = {\n safe: 0,\n draining: 1,\n parking: 2,\n 'flush-failed': 3,\n}\n\n/**\n * Fold several records into the one verdict that speaks for all of them: the\n * worst phase any of them reached, and whether every one of them is clean.\n *\n * This is how a session's control answers for its tree. \"Safe to close\" is a\n * promise about everything the press registered, so it may be said only when\n * every member reached the flushed park point; anything else is reported as the\n * least-clean state in the set, never rounded up to the session's own.\n * @param phases - the durable phases of the records being spoken for.\n * @returns the worst phase, and whether that verdict is the clean one.\n */\nexport function foldTreePhases(phases: Iterable<ParkPhase>): { phase: ParkPhase; safe: boolean } {\n let worst: ParkPhase = 'safe'\n for (const phase of phases) {\n if (PHASE_SEVERITY[phase] > PHASE_SEVERITY[worst]) worst = phase\n }\n return { phase: worst, safe: worst === 'safe' }\n}\n\n/** Everything the browser is told about one paused session. */\nexport interface ParkStatus {\n /**\n * The phase of everything that session's press registered — the session and\n * the subagent members under it, folded by {@link foldTreePhases}. A member\n * still draining or stalled holds this at its own phase, because the control\n * that owns the tree may not say \"safe to close\" while any member of it is\n * not.\n */\n readonly phase: ParkPhase\n /** Whether the host commits to \"you can close the lid now\". */\n readonly safe: boolean\n /** Tools in flight when the status was published; empty once parked. */\n readonly runningTools: readonly string[]\n /**\n * Whether the resume that takes this pause back may re-open the session's\n * goal — the durable record's own opt-out, which outlives this process. It is\n * absent when this host could not read the record that holds it; a browser\n * that is not told shows no switch rather than a state it would have to\n * guess, and a guess here would tell the user their money is safe when\n * nobody knows whether it is.\n */\n readonly rearmGoal?: boolean\n}\n\n/** One JSON snapshot: the whole-app verdict plus every live paused session. */\nexport interface PauseSnapshot {\n readonly global: GlobalStatus\n readonly sessions: Readonly<Record<string, ParkStatus>>\n}\n\n/** The whole-app answer to \"can I close the lid?\". */\nexport type GlobalVerdict = 'idle' | 'waiting' | 'safe'\n\n/** A surface the whole-app report could not read at all. */\nexport type GlobalBlindSpot = 'trees' | 'jobs'\n\n/**\n * Everything the whole-app control publishes about the park as a whole.\n *\n * The counts and the names are one answer, not two: a report that says\n * \"3 registered, 1 safe\" and then fails to say which two are missing is the\n * kind of silence this control exists to prevent. The verdict is the only\n * summary, and it is derived here so the host and the browser cannot disagree\n * about it.\n */\nexport interface GlobalStatus {\n /** `idle` with nothing registered, `safe` only when every registered session is. */\n readonly verdict: GlobalVerdict\n /** Sessions this park owns — the durable list plus anything pressed since. */\n readonly registered: number\n /** How many of them reached the flushed park point. */\n readonly safe: number\n /**\n * The session this park belongs to — the first registered one this host can\n * hold, whatever phase it reached, so a client can address its reads at the\n * park instead of at whatever session the user happens to be looking at. A\n * park whose every record is unreadable here names the first of those: the\n * name is a fact about the park, and an address that cannot answer is the\n * client's fallback to take.\n *\n * The buckets below name a session only while it has something left to do,\n * and the clean case — every registered session `safe`, which is the ordinary\n * one — leaves all of them empty: without this field a park that finished\n * cleanly names no session at all. `undefined` when the park holds nothing,\n * and absent from a reading written before this field existed; a client must\n * not treat either absence as an address.\n */\n readonly parkedAt?: string\n /**\n * Registered sessions still working: a tool is in flight or a turn is between\n * steps. Their park point is announced on the native stream the park\n * registers, so a reader has nothing to watch here.\n */\n readonly draining: readonly string[]\n /**\n * How many registered sessions stand at the park point with their flush still\n * pending — the host's `parking` phase. Nothing announces a flush resolving,\n * so this is the one state a reader can only learn by asking again. A count\n * rather than names: it says how long to keep watching, not which transcript\n * a row belongs in, which is what `draining` is for.\n */\n readonly parking: number\n /**\n * Registered sessions that will not reach the park point in this process: a\n * flush that failed, a pause adopted from an earlier process, a press whose\n * registry write failed, or a record whose session this host cannot read and\n * therefore did not hold. Named, never folded into the count and forgotten.\n */\n readonly stalled: readonly string[]\n /** Registered sessions whose tree contains a route a restart cannot resume. */\n readonly unresumable: readonly string[]\n /** Registered sessions whose subagent tree could not be read — unknown, not clean. */\n readonly unreadTrees: readonly string[]\n /** Live background jobs owned by the registered trees; nothing here can stop them. */\n readonly jobs: readonly string[]\n /** Whole surfaces the report could not read, so their emptiness is not a fact. */\n readonly blind: readonly GlobalBlindSpot[]\n}\n\n/** How one decision-list row was read out of the session's own stored log. */\nexport type TriageReading = 'read' | 'unreadable'\n\n/**\n * What one stored log says about a tool call whose outcome was never recorded.\n *\n * The call event itself is durable; the harness turns every such call into a\n * synthetic `TOOL_OUTCOME_UNKNOWN` error result when it next reads the log, and\n * this is that same derivation taken without writing anything back. The marker\n * itself is never in the stored log of a session still on the list: the resume\n * that appends it is also the resume that drops the record putting it here.\n */\nexport interface TriageTrace {\n /** The tool's own name, from the call event the model produced. */\n readonly tool: string\n /** The provider-issued id pairing the call with the result that never arrived. */\n readonly callId: string\n}\n\n/**\n * One session that did not stop cleanly, as the decision list presents it.\n *\n * Every field is read from the session's own log or from the durable park\n * record; nothing here is derived from the fact that the session is merely\n * listed. `reading` is the honesty field: a log this host could not read says\n * `unreadable` and carries no facts, rather than an empty row that would read\n * as \"no traces\".\n */\nexport interface TriageRow {\n /** The parked session. */\n readonly sessionId: string\n /** The durable park outcome; never `safe`, which is the clean path's business. */\n readonly phase: Exclude<ParkPhase, 'safe'>\n /** When that outcome was last written. */\n readonly updatedAt: number\n /** Whether the facts below came from the log. */\n readonly reading: TriageReading\n /** What the stored log's last event was, with the step it belongs to when it has one. */\n readonly lastEvent?: string\n /** The turn and step that last event belongs to. */\n readonly turn?: number\n readonly step?: number\n /** Tools whose call event is durable and whose result is not — the unknown outcomes. */\n readonly traces: readonly TriageTrace[]\n /** Whether the stored log ends owing the model an answer. */\n readonly owed: boolean\n /**\n * Whether resuming this session may re-open its goal. Re-arming is what makes\n * a resumed goal spend its owner's rounds, so it is a per-session choice the\n * row shows and the list can flip.\n */\n readonly rearmGoal: boolean\n /**\n * Whether the host could hand this session its owed request at all: a log it\n * could not read, or one whose last request recorded no route, cannot be\n * woken — which is a fact about the entry, not a refusal of the user's choice.\n */\n readonly wakeable: boolean\n}\n\n/** The decision list: what did not stop cleanly, and each row's facts. */\nexport interface TriageList {\n /** Every listed session, in registry order. */\n readonly rows: readonly TriageRow[]\n}\n\n/**\n * The decisions the list offers for one row. The first four carry the row out;\n * `goal` changes what the next resume may spend without touching the park\n * itself.\n */\nexport const TRIAGE_ACTIONS = ['continue', 'note', 'review', 'leave', 'goal'] as const\n\n/** One decision the list offers. */\nexport type TriageAction = (typeof TRIAGE_ACTIONS)[number]\n","/**\n * Reading one parked session's stored log through a bound, and the facts the\n * morning list may claim from what it read.\n *\n * The decision list reads the same log the wake reads, but for the opposite\n * reason: the wake has to reproduce the session, so it reads everything. The\n * list only has to name where the session stopped, which tool call the log\n * never heard back from, and whether an answer is still owed — all of them\n * facts about the log's END. Reading from seq 0 to the end for every row, on\n * every time the panel opens, would make a long\n * session's cost grow with a log nobody is asking about.\n *\n * WHAT THE BOUND BUYS. A stored log is append-only, so the tail is stable: the\n * read takes the last {@link TRIAGE_WINDOW_EVENTS} events, or the whole log when\n * it is shorter, and the answer is derived from that. The window is complete\n * whenever the log fits inside it, which is the common case; the fold the rest\n * of this plugin reads history through is then the harness's own, over exactly\n * the events the harness would fold.\n *\n * WHAT THE TAIL ALONE PROVES. A truncated window still answers the list's\n * questions, for one reason the harness guarantees: a dangling tool call exists\n * only inside the step that is still open, because a step's end is written\n * after its results. So an unanswered call is always inside the final open\n * span, and the tail that contains that span contains every one of them. What\n * the window cannot prove — a log a replacement event rewrote from further back\n * — is not guessed at: {@link logFacts} reports `undefined` and the row says\n * `unreadable`, because a list that invents a stop position is worse than a\n * list that says it could not read one.\n * @module dsh-pause-session/coldlog\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { deriveEventMessage, foldSurface } from '@deepseek-ai/dsh-session'\nimport type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'\n// Type-only: the optional `ctx.sessionPersistence` read seam and its handle.\nimport type {} from '@deepseek-ai/dsh-session-persistence'\nimport { derivedHistory, owesReply, routeNamed } from './history.js'\nimport { describeError } from './shared.js'\nimport type { TriageTrace } from './shared.js'\n\n/**\n * Events the read looks at before it gives up. Sized to hold a whole final\n * step — the model exchange, its tool calls, and their results — with room to\n * spare, at a cost that does not grow with the session.\n */\nexport const TRIAGE_WINDOW_EVENTS = 2000\n\n/**\n * The longest log the read will walk while locating where its tail starts.\n *\n * The window's start is found by probing for the log's length, so a log longer\n * than this cannot be located from its end at a cost worth paying for a panel\n * left open. Such a log — a million stored events — is reported unreadable\n * rather than read from the front, which is the read this module exists to\n * avoid.\n */\nexport const TRIAGE_LOG_MAX_EVENTS = 1_000_000\n\n/**\n * Events that are not the session's own story: the bookkeeping of the pause\n * legacy command records a previous surface wrote, and the pending-input\n * splices the inbox writes. They are real and durable, but \"it stopped right\n * after the action finished\"\n * is not what \"where did it stop\" means.\n */\nconst BOOKKEEPING_EVENTS: ReadonlySet<string> = new Set(['command/run', 'command/done', 'agent/inbox/spliced'])\n\n/** How one stored log was seen by the bounded read. */\nexport type ColdLog =\n /** The events the read returned, and whether they are the whole stored log. */\n | { readonly kind: 'read'; readonly events: readonly SessionEvent[]; readonly complete: boolean }\n /** The log could not be opened or read, or it is longer than this read will walk. */\n | { readonly kind: 'unreadable' }\n\n/** The facts the decision list claims, all of them read off the log's end. */\nexport interface ColdFacts {\n /** What the stored log's last event was, and the turn/step it belongs to. */\n readonly last: SessionEvent | undefined\n /** Tool calls the stored events record and no stored result answers. */\n readonly traces: readonly TriageTrace[]\n /** Whether the stored log ends owing the model an answer. */\n readonly owed: boolean\n /** Whether the log names the route a wake would be addressed to. */\n readonly wakeable: boolean\n}\n\n/**\n * The turn and step an event belongs to, when it carries them.\n * @param event - one stored event.\n * @returns the position fields the event has, and nothing for the fields it does not.\n */\nexport function positionOf(event: SessionEvent): { readonly turn?: number; readonly step?: number } {\n const data = event.data\n if (typeof data !== 'object' || data === null) return {}\n const turn = 'turn' in data && typeof data.turn === 'number' ? data.turn : undefined\n const step = 'step' in data && typeof data.step === 'number' ? data.step : undefined\n return { ...turn === undefined ? {} : { turn }, ...step === undefined ? {} : { step } }\n}\n\n/**\n * Every tool call the STORED events record and no stored result answers.\n *\n * Deliberately the stored prefix rather than the repaired view: what a row\n * reports is the state of the session's own log, and the harness's synthetic\n * unknown-outcome results are exactly what that log is missing. Taking the\n * repaired view here would subtract the very traces the row exists to show.\n *\n * A call is answered only by a result the SAME window holds, which is what the\n * harness's own repair rule reads too: an unanswered call lives in the step\n * that is still open, so it is inside this window or it is answered.\n * @param events - the stored events the read returned, in sequence order.\n * @returns one trace per call with no result, in call order.\n */\nfunction unansweredCalls(events: readonly SessionEvent[]): TriageTrace[] {\n const names = new Map<string, string>()\n const answered = new Set<string>()\n for (const event of events) {\n if (event.type === 'tool/call') {\n names.set(String(event.data.callId), event.data.name)\n continue\n }\n if (event.type !== 'tool/result') continue\n answered.add(String(event.data.message.toolCallId))\n }\n return [...names].flatMap(([callId, tool]) => answered.has(callId) ? [] : [{ tool, callId }])\n}\n\n/**\n * Whether a log ends owing the model an answer, read from the tail alone.\n *\n * This is the harness's own rule — the last thing on the model-visible surface\n * is not an assistant message — read the way the harness reads it: the surface\n * fold over the events at hand, then the message the last node derives to. The\n * fold is handed a window rather than the whole log, so it refuses rather than\n * guesses when it meets a replacement it cannot resolve; a log it cannot fold\n * falls back to the last event that produces a message at all, which is the\n * same answer by a narrower route.\n * @param events - the stored events the read returned, in sequence order.\n * @param traces - the unanswered calls, as the row reports them.\n * @returns whether the session still owes the model a reply.\n */\nfunction tailOwesReply(events: readonly SessionEvent[], traces: readonly TriageTrace[]): boolean {\n // A log whose last step is open closes with a synthetic tool result for\n // every unanswered call, and a tool result is a message.\n if (traces.length > 0) return true\n const bySequence = new Map(events.map(event => [event.seq as number, event]))\n const lastNode = (): SessionEvent | undefined => {\n for (const seq of [...foldSurface(events).nodes].reverse()) {\n const event = bySequence.get(seq as number)\n if (event !== undefined) return event\n }\n return undefined\n }\n let anchor: SessionEvent | undefined\n try {\n anchor = lastNode()\n } catch {\n // The window cannot be folded as a log — an event it holds was rewritten\n // by something it does not. The narrower route still reads the same fact\n // off the end: the last event that derives a message.\n for (let at = events.length - 1; at >= 0; at -= 1) {\n const event = events[at]\n if (event === undefined || deriveEventMessage(event) === null) continue\n anchor = event\n break\n }\n }\n if (anchor === undefined) return false\n const message = deriveEventMessage(anchor)\n if (message === null) return false\n // System and developer entries are request framing, not conversation.\n if (message.role === 'system' || message.role === 'developer') return false\n return message.role !== 'assistant'\n}\n\n/**\n * The facts one bounded read of a stored log supports.\n *\n * A complete read is folded by the harness's own derivation, so the list and\n * the wake answer the \"does it still owe a reply\" question through one rule.\n * A truncated read answers from the tail, and only where the tail is proof: a\n * replacement event that rewrote a surface range from outside the window is\n * not visible here, so a log whose tail a later event could have rewritten is\n * reported unreadable rather than guessed at.\n * @param events - the stored events the read returned, in sequence order.\n * @param complete - whether those events are the whole stored log.\n * @param projections - this process's registered message projections.\n * @returns the row's facts, or `undefined` when this read cannot support them.\n */\nexport function logFacts(\n events: readonly SessionEvent[],\n complete: boolean,\n projections: Context['sessions']['messageProjections'],\n): ColdFacts | undefined {\n let last: SessionEvent | undefined\n for (let at = events.length - 1; at >= 0; at -= 1) {\n const event = events[at]\n if (event === undefined || BOOKKEEPING_EVENTS.has(event.type)) continue\n last = event\n break\n }\n const traces = unansweredCalls(events)\n const wakeableRoute = routeNamed(events)\n if (!complete) {\n // A truncated window has to hold the stop position, or it does not hold\n // the answer this row exists to publish: the log continued before what the\n // window saw, so \"no event to name\" would claim a session that left no\n // trace. That window is reported unreadable, not summarized.\n if (last === undefined) return undefined\n const owed = tailOwesReply(events, traces)\n return { last, traces, owed, wakeable: owed && wakeableRoute }\n }\n let owed: boolean\n try {\n owed = owesReply(derivedHistory(events, projections))\n } catch {\n return undefined\n }\n return { last, traces, owed, wakeable: owed && wakeableRoute }\n}\n\n/**\n * The one seam the length probe needs from an open handle: `read` at an offset\n * with a one-event length. It is the handle's own signature, narrowed here so a\n * reader can see that the probe never asks for a prefix it does not use.\n */\ninterface OffsetReader {\n /**\n * @param offset - first logical event seq to include.\n * @param length - maximum number of events to return.\n * @param options - cancellation for this read.\n * @returns a slice of the log, empty at or past its end.\n */\n read(\n offset?: number,\n length?: number,\n options?: { readonly signal?: AbortSignal },\n ): Promise<{ readonly events: readonly SessionEvent[] }>\n}\n\n/**\n * Whether one handle holds at least `count` events, asked without materializing\n * more than one of them.\n * @param handle - an open read handle onto the log.\n * @param count - the event count to test for.\n * @param signal - cancellation for the probe.\n * @returns whether the log reaches that far.\n */\nasync function reaches(handle: OffsetReader, count: number, signal?: AbortSignal): Promise<boolean> {\n return (await handle.read(count, 1, { ...signal === undefined ? {} : { signal } })).events.length > 0\n}\n\n/**\n * The stored log's own length, found by probing rather than by reading it.\n *\n * The handle's read seam is the only way to ask a backend anything, and it\n * takes an offset — so the count has to be probed for. The probe doubles until\n * it passes the end and then bisects, so a log of any length costs a handful\n * of one-event reads, and none of them materializes the prefix it skips.\n * @param handle - an open read handle onto the log.\n * @param signal - cancellation for the probe.\n * @returns the event count, or `undefined` when the log is longer than this read will walk.\n */\nasync function eventCount(handle: OffsetReader, signal?: AbortSignal): Promise<number | undefined> {\n let high = 1\n while (await reaches(handle, high, signal)) {\n if (high >= TRIAGE_LOG_MAX_EVENTS) return undefined\n high = Math.min(high * 2, TRIAGE_LOG_MAX_EVENTS)\n }\n let low = 0\n while (high - low > 1) {\n const mid = low + Math.floor((high - low) / 2)\n if (await reaches(handle, mid, signal)) low = mid\n else high = mid\n }\n // `reaches(n)` answers whether the event at zero-based index n exists; the\n // event count is one past the last existing index.\n return await reaches(handle, 0, signal) ? low + 1 : 0\n}\n\n/**\n * Read one session's stored log, bounded to the events the list's facts need.\n *\n * The window is the last `windowEvents` events, found by probing for the log's\n * length and then reading exactly that slice. A short log is returned whole and\n * marked complete; a log longer than {@link TRIAGE_LOG_MAX_EVENTS} is reported\n * unreadable without being read at all.\n * @param ctx - host context carrying the optional persistence service.\n * @param sessionId - the stored session to read.\n * @param windowEvents - how many events of the log's end one row may fold.\n * @param signal - cancellation for the open, probe, and read.\n * @returns the bounded read, or `unreadable` when no read seam exists, it refused, or the log is too long to walk.\n * @throws the cancellation reason when `signal` aborts the read.\n */\nexport async function coldRead(\n ctx: Context,\n sessionId: SessionId,\n windowEvents: number = TRIAGE_WINDOW_EVENTS,\n signal?: AbortSignal,\n): Promise<ColdLog> {\n const persistence = ctx.get('sessionPersistence')\n if (persistence === undefined) return { kind: 'unreadable' }\n let handle\n try {\n handle = await persistence.open(sessionId, 'read', {\n ...signal === undefined ? {} : { signal },\n })\n } catch (error: unknown) {\n if (signal?.aborted === true) throw error\n ctx.logger.warn(`pause: could not open the stored log of \"${sessionId}\": ${describeError(error)}`)\n return { kind: 'unreadable' }\n }\n try {\n const window = Math.max(1, Math.floor(windowEvents))\n const count = await eventCount(handle, signal)\n if (count === undefined) {\n ctx.logger.warn(`pause: the stored log of \"${sessionId}\" is longer than this read will walk`)\n return { kind: 'unreadable' }\n }\n const start = Math.max(0, count - window)\n const stored = await handle.read(start, window, {\n ...signal === undefined ? {} : { signal },\n })\n return { kind: 'read', events: stored.events, complete: start === 0 }\n } catch (error: unknown) {\n if (signal?.aborted === true) throw error\n ctx.logger.warn(`pause: could not read the stored log of \"${sessionId}\": ${describeError(error)}`)\n return { kind: 'unreadable' }\n } finally {\n await handle.close()\n }\n}\n","/**\n * One session's subagent tree, read from the parent catalogs.\n *\n * \"This session's work\" includes the subagents it delegated to, nested ones\n * included, so the session-header press and the status the header shows both\n * need the same answer to \"which sessions hang under this one\".\n * `listDescendants` is the harness's own recursive walk of the parent-owned\n * catalogs, and it is the only source: the tree is read from the parents that\n * record it, never guessed from session ids.\n *\n * A walk is read, not remembered. The tree is a fact that grows — a delegation\n * in flight publishes its child after the parent's catalog was read — so a\n * press walks the tree at press time and a status read walks it at read time.\n * `@module dsh-pause-session/tree`\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { SessionId } from '@deepseek-ai/dsh-session'\n// Type-only: the optional `ctx.subagents` service and its descendant rows.\nimport type {} from '@deepseek-ai/dsh-subagent'\nimport { describeError } from './shared.js'\n\n/** One session a walk found under another, with the catalog's own mode for it. */\nexport interface TreeMember {\n readonly id: SessionId\n /**\n * The catalog's durable mode for this child. `external` is a child with no\n * local session to park, and `unsupported` is a mode this build cannot read;\n * the other two are the harness's own split between a route a restart can\n * resume (`continuable`) and one it cannot.\n */\n readonly mode: 'one-shot' | 'external' | 'continuable' | 'unsupported'\n}\n\n/** One branch a walk reached and could not read. */\nexport interface UnreadBranch {\n readonly id: SessionId\n /**\n * `corrupt` and `unavailable` mean the branch's own catalog was not read, so\n * the members under it are unknown. `unsupported` means the parent's catalog\n * records a mode this build cannot read; that branch was still traversed, and\n * what it holds is known — but no restart can resume through it.\n */\n readonly reason: 'corrupt' | 'unsupported' | 'unavailable'\n}\n\n/** What one session's tree walk found. */\nexport interface TreeWalk {\n /**\n * Catalog descendants in pre-order, direct children first and each child's\n * own children after it. A missing subagent service leaves this empty.\n */\n readonly members: readonly TreeMember[]\n /**\n * Branches the walk reached and could not fully read. A branch named here may\n * hold members nobody can see, so it is never read as \"no members\".\n */\n readonly unread: readonly UnreadBranch[]\n /**\n * Whether the walk itself failed, so even the branches are unknown. Named\n * separately from {@link unread}, which lists the branches of a walk that ran.\n */\n readonly unreadWhole: boolean\n}\n\n/**\n * Read the subagent tree under one session.\n *\n * A failure to read a branch is reported as unread rather than as an empty\n * tree: the difference is what keeps a press from claiming it registered a tree\n * it never saw, and keeps a status answer from calling itself safe behind an\n * unknown branch.\n * @param ctx - host context carrying the optional subagent service.\n * @param rootSessionId - the session whose descendants are requested.\n * @param signal - cancellation for the catalog walk.\n * @returns the descendants found and what of the walk could not be read.\n * @throws the cancellation reason when `signal` aborts the walk.\n */\nexport async function walkDescendants(\n ctx: Context,\n rootSessionId: SessionId,\n signal?: AbortSignal,\n): Promise<TreeWalk> {\n const subagents = ctx.get('subagents')\n if (subagents === undefined) return { members: [], unread: [], unreadWhole: false }\n try {\n const rows = await subagents.listDescendants(rootSessionId, signal)\n const members: TreeMember[] = []\n const unread: UnreadBranch[] = []\n for (const row of rows) {\n if (row.kind === 'child') {\n members.push({ id: row.id, mode: row.mode })\n continue\n }\n unread.push({ id: row.id, reason: row.reason })\n }\n return { members, unread, unreadWhole: false }\n } catch (error: unknown) {\n if (signal?.aborted === true) throw error\n ctx.logger.warn(`pause: could not read the subagent tree of \"${rootSessionId}\": ${describeError(error)}`)\n return { members: [], unread: [], unreadWhole: true }\n }\n}\n","/**\n * The whole-app park: one action that registers every running session tree,\n * and the aggregate answer to \"can I close the lid?\".\n *\n * The per-session control owns one session's park; this module owns the set.\n * It reads three real sources and never infers what they can say themselves:\n *\n * - `ctx.agents.list()` plus the park activity fold decide which sessions are\n * running. A session with no live agent is not running, and a session with\n * nothing unfinished — no tool in flight, no turn open, no delivery the loop\n * has not claimed — is left alone.\n * - The subagent runtime's descendant rows decide the tree and the one-shot\n * fact. A row's `mode` is the harness's own durable record of whether that\n * child can be resumed after a restart; a branch the walk could not read is\n * reported as unread rather than assumed clean.\n * - The job registry decides which background jobs belong to the registered\n * trees. Those run outside the agent loop: this plugin cannot stop them, so\n * it names them.\n *\n * The aggregate is derived in one place so the host's answer and the browser's\n * reading of it cannot disagree, and it is a promise about the durable\n * registry: a session is `safe` only when its recorded phase says so.\n * @module dsh-pause-session/global\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type { SessionId } from '@deepseek-ai/dsh-session'\n// Type-only: the optional `ctx.jobs` service and its read-only projection.\nimport type {} from '@deepseek-ai/dsh-jobs'\nimport type { ParkWatch } from './park.js'\nimport type { ParkRegistry } from './registry.js'\nimport type { GlobalBlindSpot, GlobalStatus, GlobalVerdict, ParkPhase } from './shared.js'\nimport { walkDescendants } from './tree.js'\nimport type { TreeWalk } from './tree.js'\nimport type { PauseAnswer } from './shared.js'\n\n/**\n * How many times one press walks the trees again. A tree can grow while the\n * walk runs — a delegation already in flight publishes its child after the\n * parent's catalog was read — so the walk repeats until it stops finding a\n * running session this action has not pressed yet.\n */\nconst PRESS_ROUNDS = 4\n\n/** One session's live park state, as the per-session control sees it. */\nexport interface LivePark {\n readonly phase: ParkPhase\n /** Whether this process can still walk the session to a flushed park. */\n readonly moving: boolean\n}\n\n/** What one press of the per-session control did. */\nexport type PressResult = 'registered' | 'unrecordable' | 'not-live' | 'not-resumable' | 'already-paused'\n\n/** What the whole-app control needs from the per-session control. */\nexport interface GlobalPauseDeps {\n /**\n * @param sessionId - session to inspect.\n * @returns whether a press already owns this session.\n */\n isPaused(sessionId: SessionId): boolean\n /**\n * Press one session's pause and make it durable.\n * @param sessionId - session to register.\n * @param signal - cancellation for the resumability and registry reads.\n * @returns what the press did; only `registered` created a new park.\n */\n press(sessionId: SessionId, signal?: AbortSignal): Promise<PressResult>\n /**\n * Look at one session's mark now that it is paused.\n * @param sessionId - the session that was just pressed.\n */\n look(sessionId: SessionId): void\n /**\n * @returns every session a live mark owns, with the phase it reports now.\n */\n live(): ReadonlyMap<SessionId, LivePark>\n /**\n * @returns every registered session this process could not hold again — a\n * record whose session cannot be read here, so nothing in this process can\n * park it, release it, or act on it.\n */\n unheld(): ReadonlySet<SessionId>\n}\n\n/** The whole-app park, as the plugin entry drives it. */\nexport interface GlobalPause {\n /**\n * Register and park every running session tree in one action. Sessions this\n * pause already owns are left where they are; an idle session is not touched.\n * @param signal - cancellation for the tree reads this action performs.\n * @returns the aggregate as of this action's end.\n */\n pressAll(signal?: AbortSignal): Promise<PauseAnswer>\n /**\n * The aggregate as structured data for the native Remote stream.\n * @param signal - cancellation for the tree reads this read performs.\n * @returns the aggregate as of this read.\n */\n readState(signal?: AbortSignal, walks?: ReadonlyMap<SessionId, TreeWalk>): Promise<GlobalStatus>\n /**\n * Report one session a press could not register, so the aggregate names it.\n * The whole-app action records that fact for its own targets; a press of a\n * session's tree reports the members the registry refused through here.\n * @param sessionId - the session a press tried and failed to register.\n * @param unrecorded - whether it is now known to be unparked for that reason.\n */\n markUnrecorded(sessionId: SessionId, unrecorded: boolean): void\n}\n\n/** One tree walk as this aggregate reads it: the members, and the two ways a walk can be doubted. */\ninterface TreeReading {\n /** Catalog descendants of the walked session, direct children and deeper. */\n readonly members: readonly SessionId[]\n /** Whether any branch holds a route a restart cannot resume. */\n readonly unresumable: boolean\n /** Whether any branch could not be read, so the tree is not vouched for. */\n readonly unread: boolean\n /** Whether an unresumable member is still doing work. */\n readonly running: boolean\n}\n\n/** Fold one shared tree walk into the two doubts this report publishes. */\nfunction readingOf(walk: TreeWalk, watch: ParkWatch): TreeReading {\n return {\n members: walk.members.map(member => member.id),\n // A route no restart can resume, either because the catalog says so or\n // because it holds a mode this build cannot read.\n unresumable: walk.members.some(member => member.mode !== 'continuable')\n || walk.unread.some(branch => branch.reason === 'unsupported'),\n // `unsupported` was traversed, so its members are known; the other reasons\n // mean that branch was not read at all.\n unread: walk.unreadWhole || walk.unread.some(branch => branch.reason !== 'unsupported'),\n running: walk.members.some(member => {\n if (member.mode === 'continuable') return false\n const activity = watch.activity(member.id)\n return activity.turnOpen || activity.runningTools.length > 0\n }),\n }\n}\n\n/**\n * Mount the whole-app park.\n * @param ctx - host context carrying the agent store and the optional subagent\n * and job services.\n * @param watch - the activity fold that says whether a session has unfinished work.\n * @param registry - the durable list this aggregate is a promise about.\n * @param deps - the per-session press and the live phase of every mark.\n * @returns the one-press action and the aggregate read.\n */\nexport function mountGlobalPause(\n ctx: Context,\n watch: ParkWatch,\n registry: ParkRegistry,\n deps: GlobalPauseDeps,\n): GlobalPause {\n /**\n * Sessions this action tried to press and could not record. They are NOT\n * parked and they keep running, so the aggregate counts them and names them\n * instead of quietly leaving them out of a park it then calls safe.\n */\n const unrecorded = new Set<SessionId>()\n // Routes a whole-app press found running but could not register; named in the\n // aggregate so the user sees what the press did not stop.\n const notResumable = new Set<SessionId>()\n /** Record or clear one session's \"pressed and the registry refused\" state. */\n const markUnrecorded = (sessionId: SessionId, flag: boolean): void => {\n if (flag) unrecorded.add(sessionId)\n else unrecorded.delete(sessionId)\n }\n /** Per-episode tree walks; an entry lives exactly as long as the park owns it. */\n const walks = new Map<SessionId, TreeReading>()\n\n /**\n * Whether a session has unfinished work right now. Three real answers, any\n * of which is enough: the loop says it is driving the session, the activity\n * fold sees a tool in flight or a turn open, or the inbox holds a delivery\n * the loop has not claimed yet.\n */\n const running = (agent: Agent): boolean => {\n if (agent.status === 'running') return true\n const activity = watch.activity(agent.id)\n if (activity.turnOpen || activity.runningTools.length > 0) return true\n return agent.inbox.nextTurn.length + agent.inbox.nextStep.length > 0\n }\n\n /**\n * Read one session's subagent tree through the shared walker and remember the\n * reading for this park episode. The tree is a fact about the episode, not\n * about the moment it was asked, and the aggregate reads several sessions per\n * answer; the cache keeps that read from repeating a catalog round-trip it\n * has already paid for.\n */\n const walkTree = async (\n sessionId: SessionId,\n signal?: AbortSignal,\n shared?: ReadonlyMap<SessionId, TreeWalk>,\n ): Promise<TreeReading> => {\n signal?.throwIfAborted()\n const provided = shared?.get(sessionId)\n if (provided !== undefined) return readingOf(provided, watch)\n const cached = walks.get(sessionId)\n if (cached !== undefined) return cached\n // No subagent service at all: the walk would answer \"no members\", which is\n // not the same claim as \"no children\", and this report may not make it.\n const reading = ctx.get('subagents') === undefined\n ? { members: [], unresumable: false, unread: true, running: false }\n : readingOf(await walkDescendants(ctx, sessionId, signal), watch)\n walks.set(sessionId, reading)\n return reading\n }\n\n /**\n * Every running session and every descendant of one, minus the sessions this\n * pause already owns. Descendants are walked whether or not they are live\n * right now: the tree is the unit the user asked to stop. A member this host\n * has no live session for has nothing to hold and nothing to flush, and the\n * press leaves it alone rather than record a park that could never finish\n * (see `./control.ts`).\n */\n const runningTargets = async (signal?: AbortSignal): Promise<readonly SessionId[]> => {\n const found = new Set<SessionId>()\n for (const agent of ctx.agents.list()) if (running(agent)) found.add(agent.id)\n // The roots are fixed before the walk: a descendant discovered here is a\n // member of a tree, not a second tree to walk from.\n for (const root of [...found]) {\n for (const member of (await walkTree(root, signal)).members) found.add(member)\n }\n return [...found].filter(sessionId => !deps.isPaused(sessionId))\n }\n\n /**\n * Live jobs of the registered trees, plus the unowned ones every caller sees.\n *\n * One registry walk per owner is the whole answer the jobs contract allows:\n * `list()` with no caller answers with unowned jobs only, and `list(owner)`\n * answers for exactly one owner, because the registry preflights ownership\n * instead of letting a reader enumerate another session's work.\n */\n const liveJobs = (owners: Iterable<SessionId>): readonly string[] => {\n const jobs = ctx.get('jobs')\n if (jobs === undefined) return []\n const seen = new Set<string>()\n const collect = (owner?: SessionId): void => {\n for (const view of owner === undefined ? jobs.list() : jobs.list(owner)) {\n if (view.status !== 'running' && view.status !== 'stopping') continue\n seen.add(String(view.id))\n }\n }\n collect()\n for (const owner of owners) collect(owner)\n return [...seen]\n }\n\n /**\n * The aggregate. Every registered session is accounted for: the ones on\n * their way, the ones that will not get there in this process, the trees\n * that hold work a restart cannot resume, and the jobs nothing here can stop.\n * The park also names the session it belongs to, so a client can address its\n * reads there rather than at whatever session it is showing.\n */\n const status = async (\n signal?: AbortSignal,\n sharedWalks?: ReadonlyMap<SessionId, TreeWalk>,\n ): Promise<GlobalStatus> => {\n const phases = new Map<SessionId, LivePark>()\n // The durable list is the promise; a live mark is the same episode's\n // fresher phase, and a press that could not be recorded is neither.\n for (const [sessionId, record] of registry.parked) phases.set(sessionId, { phase: record.phase, moving: false })\n // Read out of the accessor's own snapshot rather than through it per mark,\n // so this read asks the live state once however many sessions it holds.\n const live = deps.live()\n for (const [sessionId, park] of live) phases.set(sessionId, park)\n for (const sessionId of unrecorded) phases.set(sessionId, { phase: 'draining', moving: false })\n const unheld = deps.unheld()\n // Walks are per episode: a session the park no longer owns drops its entry,\n // so a later press reads the tree again instead of reporting a stale one.\n for (const sessionId of [...walks.keys()]) if (!phases.has(sessionId)) walks.delete(sessionId)\n\n let safe = 0\n let parking = 0\n const draining: string[] = []\n const stalled: string[] = []\n for (const [sessionId, park] of phases) {\n // A record this process could not hold is not a park here, whatever its\n // durable phase says: nothing is standing at the gate for it, so counting\n // it as safe would promise a hold that does not exist.\n if (unheld.has(sessionId)) {\n stalled.push(String(sessionId))\n continue\n }\n if (park.phase === 'safe') {\n safe += 1\n continue\n }\n const bucket = park.moving ? draining : stalled\n bucket.push(String(sessionId))\n // Standing at the park point with the flush still pending is counted\n // apart from the sessions still draining: both are unfinished, and the\n // pill's sentence is about how much of the wait is left rather than about\n // what is still running.\n if (park.moving && park.phase === 'parking') parking += 1\n }\n\n const unresumable: string[] = []\n const unreadTrees: string[] = []\n const owners = [...phases.keys()]\n // The session this park belongs to: the first registered session this\n // process holds, so a client can address its reads at the park rather than\n // at whatever session the user is looking at. The buckets above name a\n // session only while it has work left, so a park that reached `safe` — the\n // clean, ordinary case — would otherwise name no session at all. A record\n // this process cannot hold is named only when there is nothing else to\n // name: it is a true fact about the park, but it cannot answer a read.\n const parkedAt = owners.find(sessionId => !unheld.has(sessionId)) ?? owners[0]\n // One walk is one catalog read, and the walks do not depend on each other:\n // a read of N registered sessions must not take N catalog round-trips end\n // to end. `walkTree` answers from its per-episode cache when it has one.\n const trees = await Promise.all(owners.map(async sessionId => [sessionId, await walkTree(sessionId, signal, sharedWalks)] as const))\n for (const [sessionId, tree] of trees) {\n if (tree.unresumable) unresumable.push(String(sessionId))\n if (tree.unread) unreadTrees.push(String(sessionId))\n }\n\n const blind: GlobalBlindSpot[] = []\n if (ctx.get('subagents') === undefined) blind.push('trees')\n if (ctx.get('jobs') === undefined) blind.push('jobs')\n\n const registered = phases.size\n // A tree nobody could read might hold a running descendant this park never\n // registered, so an unread tree is not a clean bill even when the session\n // itself is flushed.\n const verdict: GlobalVerdict = registered === 0\n ? 'idle'\n : safe === registered && unreadTrees.length === 0 && !trees.some(([, tree]) => tree.running)\n ? 'safe'\n : 'waiting'\n\n return {\n verdict,\n registered,\n safe,\n ...parkedAt === undefined ? {} : { parkedAt: String(parkedAt) },\n draining: draining.sort(),\n parking,\n stalled: stalled.sort(),\n unresumable: [...new Set(unresumable)].sort(),\n unreadTrees: unreadTrees.sort(),\n jobs: liveJobs(owners),\n blind,\n }\n }\n\n return {\n pressAll: async (signal) => {\n for (let round = 0; round < PRESS_ROUNDS; round += 1) {\n const targets = await runningTargets(signal)\n if (targets.length === 0) break\n for (const sessionId of targets) {\n signal?.throwIfAborted()\n // The press is a durable promise per session: one that cannot be\n // recorded is rolled back there and named here. A session whose\n // route is not resumable, or has no live log, is left out of the\n // registry rather than promised a wake the morning path must refuse.\n const pressed = await deps.press(sessionId, signal)\n switch (pressed) {\n case 'registered':\n notResumable.delete(sessionId)\n markUnrecorded(sessionId, false)\n deps.look(sessionId)\n break\n case 'unrecordable':\n markUnrecorded(sessionId, true)\n break\n case 'not-resumable':\n notResumable.add(sessionId)\n break\n default:\n break\n }\n }\n }\n const aggregate = await status(signal)\n const answer = aggregate.verdict === 'safe'\n ? 'Every session is paused.'\n : aggregate.verdict === 'idle'\n ? 'Nothing is running.'\n : 'Pausing is in progress.'\n const blocked = notResumable.size\n return unrecorded.size === 0 && blocked === 0\n ? { kind: 'success', text: answer }\n : {\n kind: 'error',\n text: `${answer} ${String(blocked)} session${blocked === 1 ? '' : 's'} could not be paused because its route is not resumable.`,\n }\n },\n readState: async (signal, walks) => await status(signal, walks),\n markUnrecorded,\n }\n}\n","/**\n * The order a tree release walks: parent before child, shallowest first.\n * @module dsh-pause-session/release-order\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { SessionId } from '@deepseek-ai/dsh-session'\nimport { describeError } from './shared.js'\n\n/** How a batch release is sequenced. */\nexport interface ReleaseOrder {\n /** The tree edge each child was found under. */\n readonly parents: ReadonlyMap<SessionId, SessionId>\n /** One list per depth, shallowest first. */\n readonly levels: readonly (readonly SessionId[])[]\n}\n\n/**\n * Sequence a batch release parent before child.\n * @param ctx - host context carrying the optional subagent catalog.\n * @param sessionIds - every recorded session, in registry order.\n * @param signal - cancellation for each catalog read.\n * @returns the parent of each child, and one list per depth level.\n */\nexport async function releaseOrder(\n ctx: Context,\n sessionIds: readonly SessionId[],\n signal?: AbortSignal,\n): Promise<ReleaseOrder> {\n const owned = new Set(sessionIds)\n const parentOf = new Map<SessionId, SessionId>()\n const subagents = ctx.get('subagents')\n if (subagents !== undefined) {\n for (const sessionId of sessionIds) {\n signal?.throwIfAborted()\n try {\n for (const child of await subagents.listChildren(sessionId, signal)) {\n if (owned.has(child.id)) parentOf.set(child.id, sessionId)\n }\n } catch (error: unknown) {\n if (signal?.aborted === true) throw error\n ctx.logger.warn(`pause: could not read the children of \"${sessionId}\": ${describeError(error)}`)\n }\n }\n }\n const depthOf = (sessionId: SessionId): number => {\n let steps = 0\n const seen = new Set<SessionId>([sessionId])\n for (let at = parentOf.get(sessionId); at !== undefined; at = parentOf.get(at)) {\n if (seen.has(at)) break\n seen.add(at)\n steps += 1\n }\n return steps\n }\n const levels = new Map<number, SessionId[]>()\n for (const sessionId of sessionIds) {\n const level = depthOf(sessionId)\n const bucket = levels.get(level)\n if (bucket === undefined) levels.set(level, [sessionId])\n else bucket.push(sessionId)\n }\n return {\n parents: parentOf,\n levels: [...levels.keys()].sort((left, right) => left - right)\n .map(level => levels.get(level) ?? []),\n }\n}\n","/**\n * Rebuild the scoped Agent composition a parked Session ran under.\n *\n * Activation is not only a persisted Session: the Agent preset supplies the\n * scoped tools, prompt sections, skills, and — for a subagent child — the\n * delegation context, persona, and tool restriction that were in force before\n * the park. A resume that loads the log without that setup starts a different\n * Agent on the same history.\n *\n * The preset a Session runs is the `agentPreset` projection, never the\n * creation-time header alone: a blank Session may select another preset before\n * its first turn, and the projection records the selection that actually ran.\n * A child with no independent selection joins its live parent's preset\n * generation; one that selected independently mounts the projected preset.\n * The durable child descriptor supplies the persona, tool filter, and route\n * that are reapplied only on cold resume.\n *\n * Both services are optional. A profile without `agentPresets` has no scoped\n * preset composition to restore, and this module leaves the resume unchanged.\n * A profile that mounts one but cannot read the Session projection cannot\n * prove what composition the Session ran, so it fails the resume instead of\n * silently starting a different Agent.\n * @module dsh-pause-session/composition\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent, AgentOptions, AgentSetup } from '@deepseek-ai/dsh-agent'\nimport type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'\n// Type-only: pulls the optional session projection read and preset roster faces.\nimport type {} from '@deepseek-ai/dsh-session-query'\nimport type {} from '@deepseek-ai/dsh-agent-preset-registry'\nimport { applyChildComposition, foldSubagentDescriptor } from '@deepseek-ai/dsh-subagent'\nimport type { ChildComposition } from '@deepseek-ai/dsh-subagent'\n\n/** The setup and route options a resumed Agent receives from its stored composition. */\nexport interface RestoredComposition {\n /** The durable child route, when the descriptor recorded one. */\n readonly agentOptions?: AgentOptions\n /** The scoped Agent world to mount before the Agent is published. */\n readonly setup?: AgentSetup\n}\n\n/**\n * A stored subagent route that no resume may reactivate.\n *\n * A one-shot child is terminal by contract; activating it as a root Agent\n * would turn a finished delegation into an ordinary conversation that happens\n * to share its Session id.\n */\nexport class UnresumableSessionError extends Error {\n constructor(sessionId: SessionId) {\n super(`subagent session \"${String(sessionId)}\" has a one-shot route and cannot be resumed`)\n this.name = 'UnresumableSessionError'\n }\n}\n\n/**\n * Whether the child's own log selected a preset before its descriptor.\n *\n * The creation-time selection precedes the first `subagent/descriptor`; a\n * selection after the descriptor belongs to the child's own later history and\n * does not decide which composition cold resume joins. This mirrors the\n * subagent runtime's own cold-resume rule.\n * @param events - the child's own log suffix, without the fork-inherited prefix.\n * @returns whether the child carries an independent preset selection.\n */\nexport function hasIndependentPresetSelection(events: readonly SessionEvent[]): boolean {\n for (const event of events) {\n if (event.type === 'subagent/descriptor') return false\n if (event.type === 'agent-preset/selected') return true\n }\n return false\n}\n\n/**\n * Whether a local Session may be parked under a promise of a later resume.\n *\n * A normal root Session has no child descriptor and is resumable. A local\n * subagent child is resumable only when its own durable descriptor is\n * `continuable`; a historical `one-shot` child is terminal and must never be\n * registered as a park the morning path would later have to refuse. External\n * executions have no local Session, so callers never reach this check.\n *\n * A profile without the optional Session-query service cannot prove the\n * descriptor's mode; it keeps the previous permissive behavior rather than\n * dropping every subagent. The web profile mounts the query service.\n * @param ctx - host context carrying the optional Session-query service.\n * @param sessionId - the local Session to inspect.\n * @param signal - cancellation for the observation read.\n * @returns whether a park of this Session may be resumed.\n * @throws the cancellation reason when `signal` aborts the read.\n */\nexport async function isResumableSession(\n ctx: Context,\n sessionId: SessionId,\n signal?: AbortSignal,\n): Promise<boolean> {\n const query = ctx.get('sessionQuery')\n if (query === undefined) return true\n const observation = await query.observeSession(sessionId, {\n ...signal === undefined ? {} : { signal },\n })\n try {\n const ownEvents = observation.events.slice(observation.inheritedEventCount)\n return foldSubagentDescriptor(ownEvents)?.mode !== 'one-shot'\n } finally {\n observation[Symbol.dispose]()\n }\n}\n\n/**\n * Read one parked Session's stored composition and build the resume options.\n *\n * The returned `setup` belongs to the unpublished Agent scope, so all\n * registrations exist before `agent/created`. For a root Session the setup\n * mounts the Session's projected preset, or the profile's default when the\n * Session never selected one. For a child under a live parent it applies the\n * child composition: an independent preset mounts separately, while an\n * inherited composition joins the parent's current generation; the historical\n * descriptor's persona and tool filter are reapplied in both cases.\n * @param ctx - host context carrying the optional preset and Session-query services.\n * @param sessionId - the parked Session being resumed.\n * @param parent - the live direct parent, when a child is resumed under it.\n * @param signal - cancellation for the observation read.\n * @returns the Agent options and setup to pass to `agents.resume`.\n * @throws {UnresumableSessionError} when the stored child route is one-shot.\n * @throws when a mounted preset roster cannot read the Session projection, or\n * a recorded preset cannot be restored.\n */\nexport async function restoreComposition(\n ctx: Context,\n sessionId: SessionId,\n parent: Agent | undefined,\n signal?: AbortSignal,\n): Promise<RestoredComposition> {\n const presets = ctx.get('agentPresets')\n const query = ctx.get('sessionQuery')\n if (query === undefined) {\n if (presets !== undefined) {\n throw new Error('resuming a composed Agent requires the session-query service')\n }\n return {}\n }\n const observation = await query.observeSession(sessionId, {\n ...(signal === undefined ? {} : { signal }),\n })\n try {\n const projections = observation.projections\n const ownEvents = observation.events.slice(observation.inheritedEventCount)\n const descriptor = foldSubagentDescriptor(ownEvents)\n if (descriptor?.mode === 'one-shot') throw new UnresumableSessionError(sessionId)\n if (presets === undefined || projections === undefined) {\n if (presets !== undefined) {\n throw new Error('resuming a composed Agent requires projected Session state')\n }\n return {}\n }\n if (parent === undefined) {\n // A root names its own preset; a Session that never selected one follows\n // the roster's default, exactly as the official Session controller does.\n const resolved = await presets.resolve(projections.values.agentPreset ?? undefined)\n return {\n setup: async (agentCtx) => { await presets.mount(agentCtx, resolved.id) },\n }\n }\n const independentlySelected = hasIndependentPresetSelection(ownEvents)\n const presetId = independentlySelected ? projections.values.agentPreset : undefined\n if (independentlySelected && typeof presetId !== 'string') {\n throw new Error(`subagent \"${String(sessionId)}\" has no projected agent preset to restore`)\n }\n const composition: ChildComposition = {\n ...typeof presetId === 'string' ? { agentPreset: presetId } : {},\n ...descriptor?.mode === 'continuable' && descriptor.persona !== undefined\n ? { persona: descriptor.persona }\n : {},\n ...descriptor?.mode === 'continuable' && descriptor.toolFilter !== undefined\n ? { toolFilter: descriptor.toolFilter }\n : {},\n }\n const agentOptions: AgentOptions | undefined = descriptor?.mode === 'continuable'\n ? {\n ...descriptor.agentProvider === undefined ? {} : { provider: descriptor.agentProvider },\n ...descriptor.agentModel === undefined ? {} : { model: descriptor.agentModel },\n ...descriptor.agentReasoningEffort === undefined\n ? {}\n : { reasoningEffort: descriptor.agentReasoningEffort },\n }\n : undefined\n return {\n ...agentOptions === undefined ? {} : { agentOptions },\n setup: async (agentCtx) => { await applyChildComposition(agentCtx, parent, composition) },\n }\n } finally {\n observation[Symbol.dispose]()\n }\n}\n","/**\n * User-facing copy and result shapes for the clean resume and tree release.\n * @module dsh-pause-session/resume-text\n */\n\nimport type { SessionId } from '@deepseek-ai/dsh-session'\nimport type { PauseAnswer } from './shared.js'\n\n/** Route knowledge the clean resume path needs. */\nexport interface ResumeOptions {\n /** Provider routes whose request conversion drops an empty user message. */\n readonly silentWakeRoutes: readonly string[]\n}\n\n/**\n * The one wake content a route that keeps an empty user message is given.\n */\nexport const WAKE_MARKER = '[pause: resumed from a pause]'\n\n/** How one resume asks the loop for the request it owes the session. */\nexport type WakeRequest =\n | { readonly kind: 'silent' }\n | { readonly kind: 'message'; readonly text: string }\n | { readonly kind: 'none' }\n\n/** Result copy for a resumed session; the model never sees it. */\nexport const RESUMED_TEXT = 'This session resumed from where it paused.'\n\n/** Result copy for a registered session whose park did not finish cleanly. */\nexport const UNCLEAN_TEXT = 'pause did not resume this session: its pause did not finish cleanly,'\n + ' so it needs your decision.'\n\n/** Result copy when nothing is parked under that session. */\nexport const NOT_PARKED_TEXT = 'pause has no pause recorded for this session.'\n\n/** Result copy for a session that is parked but could not be loaded back. */\nexport const ACTIVATION_FAILED_TEXT = 'pause could not reopen this session, so it stayed paused.'\n\n/** Result copy for a one-shot subagent route. */\nexport const UNRESUMABLE_TEXT = 'pause did not resume this session: it is a one-shot subagent route and cannot be resumed.'\n\n/** Result copy for the review decision. */\nexport const REVIEW_TEXT = 'pause did not activate this session: it is still parked, and nothing was sent to a model.'\n + ' Open it from your session list when you want to read it.'\n\n/** Copy for one goal opt-out change. */\nexport const REARM_GOAL_ON_TEXT = 'pause will re-open this session\\'s goal when it resumes it.'\nexport const REARM_GOAL_OFF_TEXT = 'pause will leave this session\\'s goal closed when it resumes it.'\n\n/** Why one record did not produce a running session. */\nexport type ResumeRefusal = 'not-parked' | 'not-clean' | 'activation-failed' | 'unrecorded' | 'not-activated' | 'unresumable'\n\n/** What one resume attempt did. */\nexport interface ResumeOutcome {\n readonly sessionId: SessionId\n readonly resumed: boolean\n readonly refusal?: ResumeRefusal\n}\n\n/** One resume attempt plus the answer the caller receives. */\nexport interface ResumeAttempt extends ResumeOutcome {\n readonly answer: PauseAnswer\n}\n\n/** What releasing one session's registered tree did. */\nexport interface ReleaseTreeOutcome {\n readonly members: number\n readonly resumed: number\n readonly refusals: readonly { readonly sessionId: SessionId; readonly refusal: ResumeRefusal }[]\n readonly answer: PauseAnswer\n}\n\n/**\n * How one tree-wide release answers the person who pressed it.\n * @param released - the sessions this release covered, in release order.\n * @returns one sentence about what came back and what did not.\n */\nexport function summarizeTreeRelease(released: readonly ResumeAttempt[]): string {\n const resumed = released.filter(attempt => attempt.resumed).length\n const head = resumed === 0\n ? 'pause resumed nothing from this tree'\n : resumed === 1\n ? 'pause resumed 1 session from where it stopped'\n : `pause resumed ${resumed} sessions from where they stopped`\n const refused = released.filter(attempt => !attempt.resumed)\n if (refused.length === 0) return `${head}.`\n const named = refused\n .filter(attempt => attempt.refusal === 'not-clean')\n .map(attempt => `\"${String(attempt.sessionId)}\"`)\n const rest = named.length === 0\n ? `${String(refused.length)} could not be resumed`\n : refused.length === named.length\n ? `${named.join(', ')} did not pause completely`\n : `${named.join(', ')} did not pause completely, and ${String(refused.length - named.length)} more could not be resumed`\n return `${head}; ${rest}.`\n}\n","/**\n * Reactivate one parked session: restore its composition, give it the route its\n * log recorded, deliver the wake it owes, and only then drop the gate and record.\n * @module dsh-pause-session/resume-activation\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport { createUserMessage } from '@deepseek-ai/dsh-llm'\nimport type { ContentBlock, LlmCallConfig } from '@deepseek-ai/dsh-llm'\nimport type { Session, SessionId } from '@deepseek-ai/dsh-session'\nimport type {} from '@deepseek-ai/dsh-goal'\nimport type { PauseGate } from './gate.js'\nimport { UnresumableSessionError, restoreComposition } from './composition.js'\nimport { owesReply } from './history.js'\nimport type { ParkRegistry } from './registry.js'\nimport { describeError, UNRECORDED_TEXT } from './shared.js'\nimport {\n ACTIVATION_FAILED_TEXT, RESUMED_TEXT, UNRESUMABLE_TEXT, WAKE_MARKER,\n} from './resume-text.js'\nimport type { ResumeAttempt, ResumeOptions, WakeRequest } from './resume-text.js'\n\n/** The activation entry points the resume path composes. */\nexport interface Activator {\n activate(sessionId: SessionId, request: WakeRequest, rearm: boolean, parentId?: SessionId, signal?: AbortSignal): Promise<ResumeAttempt>\n ensureRoute(agent: Agent): void\n wake(agent: Agent, request: WakeRequest): void\n rearmGoal(agent: Agent): void\n}\n\n/**\n * Build the activation closure.\n * @param ctx - host context carrying the agent store and goal service.\n * @param gate - the pause gate released after activation.\n * @param registry - the durable list the release forgets from.\n * @param options - the route knowledge the wake content depends on.\n * @returns the activation methods the resume path uses.\n */\nexport function createActivator(\n ctx: Context,\n gate: PauseGate,\n registry: ParkRegistry,\n options: ResumeOptions,\n): Activator {\n const routeOf = (session: Session): LlmCallConfig | undefined => session.requestHeader()?.config\n\n const ensureRoute = (agent: Agent): void => {\n if (agent.model.current() !== undefined) return\n const config = routeOf(agent.session)\n if (config === undefined) return\n agent.model.select({\n provider: config.provider,\n model: config.model,\n ...config.reasoningEffort === undefined ? {} : { reasoningEffort: config.reasoningEffort },\n })\n }\n\n const wakeContent = (provider: string): ContentBlock[] =>\n options.silentWakeRoutes.includes(provider) ? [] : [{ type: 'text', text: WAKE_MARKER }]\n\n const wake = (agent: Agent, request: WakeRequest): void => {\n if (request.kind === 'none') return\n if (gate.isHeld(agent.id) || agent.status !== 'idle') return\n if (!owesReply(agent.session.deriveMessages())) return\n const provider = routeOf(agent.session)?.provider\n if (provider === undefined) return\n const content: ContentBlock[] = request.kind === 'message'\n ? [{ type: 'text', text: request.text }]\n : wakeContent(provider)\n agent.followup(createUserMessage({ content, source: { kind: 'pause' } }))\n }\n\n const rearmGoal = (agent: Agent): void => {\n const goals = ctx.get('goals')\n if (goals === undefined) return\n try {\n const goal = goals.get(agent)\n if (goal === undefined || goal.phase !== 'active' || goal.activation !== 'disarmed') return\n if (goal.roundsStarted >= goal.maxGoalRounds) return\n goals.resume(agent, { id: goal.id, revision: goal.revision })\n } catch (error: unknown) {\n ctx.logger.warn(`pause: could not re-open the goal of \"${agent.id}\": ${describeError(error)}`)\n }\n }\n\n const activate = async (\n sessionId: SessionId,\n request: WakeRequest,\n rearm: boolean,\n parentId?: SessionId,\n signal?: AbortSignal,\n ): Promise<ResumeAttempt> => {\n const parent = parentId === undefined ? undefined : ctx.agents.get(parentId)\n let agent: Agent\n try {\n const composition = await restoreComposition(ctx, sessionId, parent, signal)\n agent = (await ctx.root.agents.resume({\n resumeSessionId: sessionId,\n ...parent === undefined ? {} : { parentAgent: parent },\n ...composition,\n ...signal === undefined ? {} : { signal },\n })).agent\n } catch (error: unknown) {\n if (error instanceof UnresumableSessionError) {\n return {\n sessionId,\n resumed: false,\n refusal: 'unresumable',\n answer: { kind: 'error', text: UNRESUMABLE_TEXT },\n }\n }\n ctx.logger.warn(`pause: could not open \"${sessionId}\" from its stored log: ${describeError(error)}`)\n return {\n sessionId,\n resumed: false,\n refusal: 'activation-failed',\n answer: { kind: 'error', text: ACTIVATION_FAILED_TEXT },\n }\n }\n ensureRoute(agent)\n wake(agent, request)\n try {\n await registry.forget(sessionId)\n } catch (error: unknown) {\n ctx.logger.warn(`pause: could not drop \"${sessionId}\" from the pause registry: ${describeError(error)}`)\n return { sessionId, resumed: false, refusal: 'unrecorded', answer: { kind: 'error', text: UNRECORDED_TEXT } }\n }\n gate.resume(sessionId)\n if (rearm) rearmGoal(agent)\n return { sessionId, resumed: true, answer: { kind: 'success', text: RESUMED_TEXT } }\n }\n\n return { activate, ensureRoute, wake, rearmGoal }\n}\n","/**\n * The clean resume path: bring back a session a previous process parked, and\n * let it answer the input that was already pending when it stopped.\n *\n * A resume invents no turn. At the park point the loop had claimed the\n * session's pending input onto the surface and built the request the gate then\n * held; after a restart that input is still the last thing the session says and\n * the model still owes it an answer. What is missing is only a reason for the\n * loop to build a request again, and the documented way to ask for one is a\n * wake input — a user message the loop claims.\n *\n * The wake is invisible only on the routes the composition declares in\n * `silentWakeRoutes`, whose conversion drops an empty user message. On every\n * other route the loop's request carries one visible marker instead, and the\n * marker reaches the model; that is an accepted cost of resuming at all.\n * Whether an empty user message survives is a property of the route's\n * conversion rather than of the loop, so the route is resolved per session —\n * from the request header the session itself persisted.\n *\n * The wake message is attributed to this plugin, never to the user: it is text\n * this module synthesized on the session's behalf, in the session's own log and\n * in front of the model, and a downstream consumer has to be able to tell it\n * apart from something the human typed.\n *\n * Only a cleanly parked session takes this path. A record that never reached\n * the park point, or whose flush did not finish, describes work whose durable\n * state nobody knows; waking it would spend its owner's money on a guess, and\n * deciding those sessions is the morning list's job, not this path's. That\n * holds whether or not the recorded session happens to be live in this process:\n * liveness is not the park outcome, and a session can be live without ever\n * having stopped.\n * @module dsh-pause-session/resume\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport { createUserMessage } from '@deepseek-ai/dsh-llm'\nimport type { ContentBlock, LlmCallConfig } from '@deepseek-ai/dsh-llm'\nimport type { Session, SessionId } from '@deepseek-ai/dsh-session'\n// Type-only: brings `ctx.get('goals')` and the goal view this path reads.\nimport type {} from '@deepseek-ai/dsh-goal'\nimport type { PauseGate } from './gate.js'\nimport { UnresumableSessionError, restoreComposition } from './composition.js'\nimport { owesReply } from './history.js'\nimport type { ParkRegistry } from './registry.js'\nimport { describeError, UNRECORDED_TEXT } from './shared.js'\nimport { walkDescendants } from './tree.js'\nimport { releaseOrder } from './release-order.js'\nimport { createActivator } from './resume-activation.js'\nimport type { PauseAnswer } from './shared.js'\nexport * from './resume-text.js'\nimport {\n ACTIVATION_FAILED_TEXT, NOT_PARKED_TEXT, REARM_GOAL_OFF_TEXT, REARM_GOAL_ON_TEXT,\n RESUMED_TEXT, REVIEW_TEXT, summarizeTreeRelease, UNCLEAN_TEXT, UNRESUMABLE_TEXT, WAKE_MARKER,\n} from './resume-text.js'\nimport type { ReleaseTreeOutcome, ResumeAttempt, ResumeOptions, ResumeRefusal, WakeRequest } from './resume-text.js'\n\ndeclare module '@deepseek-ai/dsh-llm' {\n interface MessageSourceMap {\n /**\n * Text dsh-pause-session synthesized on the session's behalf: the wake this\n * path delivers and the unknown-outcome note a decision adds. Declared so\n * the log, and anything reading it, can tell plugin-authored input from the\n * user's own.\n */\n 'pause': { kind: 'pause' }\n }\n}\n\n/** How this path is wired into the session control that owns the pause state. */\nexport interface ResumeDeps {\n /**\n * Take a live session's pause back: the durable record goes first, then the\n * gate. Owned by the session control so there is one release order.\n */\n release(sessionId: SessionId, text: string): Promise<PauseAnswer>\n /**\n * Whether the pause this process holds was adopted from the registry rather\n * than pressed here. Only an adopted pause is a restart: a press this process\n * made and took back must never wake a model.\n */\n adopted(sessionId: SessionId): boolean\n}\n\n/** The clean resume path, as the session control drives it. */\nexport interface ResumePath {\n /**\n * Resume one session the registry remembers.\n * @param sessionId - the session to resume.\n * @param request - which wake this resume delivers; see {@link WakeRequest}.\n * @param parentId - the direct parent a batch release already brought back, when there is one.\n * @param signal - cancellation for the cold load and setup.\n * @returns what happened, and the copy for whoever asked.\n */\n resumeSession(\n sessionId: SessionId,\n request: WakeRequest,\n parentId?: SessionId,\n signal?: AbortSignal,\n ): Promise<ResumeAttempt>\n /**\n * Resume one session the decision list officially owns — a record that is\n * known NOT to be clean, which the clean path above must refuse and this entry\n * exists to carry out. Same release order, same wake vocabulary.\n * @param sessionId - the listed session to bring back.\n * @param request - which wake the decision delivers; see {@link WakeRequest}.\n * @param finalize - whether the decision continues the session (`'release'`)\n * or only answers it (`'review'`). A review activates nothing and writes\n * nothing: opening a session to read it is the user's own action, not this\n * plugin's.\n * @param parentId - the direct parent a batch release already brought back, when there is one.\n * @param signal - cancellation for the cold load and setup.\n * @returns what happened, and the copy for whoever asked.\n */\n decideUnclean(\n sessionId: SessionId,\n request: WakeRequest,\n finalize: 'release' | 'review',\n parentId?: SessionId,\n signal?: AbortSignal,\n ): Promise<ResumeAttempt>\n /**\n * Resume every session the registry remembers, clean ones only. One session's\n * failure never stops the others.\n * @param signal - cancellation checked between release levels and forwarded to each load.\n * @returns one attempt per recorded session, in registry order.\n */\n resumeParked(signal?: AbortSignal): Promise<readonly ResumeAttempt[]>\n /**\n * Record or clear one session's goal opt-out.\n * @param sessionId - the parked session to change.\n * @param rearmGoal - whether the clean resume path may re-arm its goal.\n * @returns the copy for whoever asked.\n */\n setRearmGoal(sessionId: SessionId, rearmGoal: boolean): Promise<PauseAnswer>\n /**\n * Release one parked session and the registered members of its tree: the\n * counterpart of a press that registered a whole tree.\n * @param sessionId - the session whose tree the user released.\n * @param signal - cancellation for the tree read and each member's load.\n * @returns what happened to the tree, and the copy for whoever asked.\n */\n releaseTree(sessionId: SessionId, signal?: AbortSignal): Promise<ReleaseTreeOutcome>\n}\n\n/**\n * Build the clean resume path.\n * @param ctx - host context carrying the agent store, the session store, and the goal service when one is mounted.\n * @param gate - the pause gate the resume releases.\n * @param registry - the durable list this path reads and forgets from.\n * @param options - the route knowledge the wake content depends on.\n * @param deps - the control-owned release order and the adopted-pause fact.\n * @returns the path the session control exposes.\n */\nexport function installResumePath(\n ctx: Context,\n gate: PauseGate,\n registry: ParkRegistry,\n options: ResumeOptions,\n deps: ResumeDeps,\n): ResumePath {\n /** The route the session's next request will use, as its own log recorded it. */\n const { activate, ensureRoute, wake, rearmGoal } = createActivator(ctx, gate, registry, options)\n\n /**\n * Load one unclean session back from its stored log.\n *\n * This is the morning list's own entry point, and it exists precisely because\n * the clean path must keep refusing these records: the refusal is the clean\n * path's guarantee, not a guard this entry can borrow. A user who has read the\n * row and chosen one of the decisions that resume it has made the decision the\n * clean path is not allowed to make for them. The release order is the same\n * one: the durable record goes first, then the gate — so a record that cannot\n * be dropped leaves the session parked.\n *\n * A record this process holds no gate for is still this list's to clear: the\n * session is live, so the decision's own wake is what asks for its request,\n * and dropping the record is what stops a later process from re-holding a\n * session the user has already decided.\n * @param sessionId - the listed session to bring back.\n * @param request - which wake the decision delivers; see {@link WakeRequest}.\n * @param finalize - whether the decision continues the session (`'release'`)\n * or only answers it (`'review'`); a review activates nothing and writes\n * nothing.\n * @param parentId - the direct parent a batch release already brought back, when there is one.\n * @param signal - cancellation for the cold load and setup.\n * @returns what happened, and the copy for whoever asked.\n */\n const decideUnclean = async (\n sessionId: SessionId,\n request: WakeRequest,\n finalize: 'release' | 'review',\n parentId?: SessionId,\n signal?: AbortSignal,\n ): Promise<ResumeAttempt> => {\n const record = registry.get(sessionId)\n if (record === undefined) {\n return { sessionId, resumed: false, refusal: 'not-parked', answer: { kind: 'success', text: NOT_PARKED_TEXT } }\n }\n // Opening a session to read it is the user's own action in their session\n // list; this decision only answers, so it never activates an agent and\n // never writes. That is what makes it the safe choice on a session whose\n // side effects may already have happened.\n if (finalize === 'review') {\n return { sessionId, resumed: false, refusal: 'not-activated', answer: { kind: 'success', text: REVIEW_TEXT } }\n }\n const live = ctx.agents.get(sessionId)\n if (live === undefined) return await activate(sessionId, request, record.rearmGoal, parentId, signal)\n if (!gate.isPaused(sessionId)) {\n // This process holds nothing for the session — its record was found\n // unreadable at mount, or something else already released it. The session\n // is live, so the decision's own wake is what asks for the request it is\n // owed, and the record goes on the release path's own order.\n ensureRoute(live)\n wake(live, request)\n try {\n await registry.forget(sessionId)\n } catch (error: unknown) {\n ctx.logger.warn(`pause: could not drop \"${sessionId}\" from the pause registry: ${describeError(error)}`)\n return { sessionId, resumed: false, refusal: 'unrecorded', answer: { kind: 'error', text: UNRECORDED_TEXT } }\n }\n if (record.rearmGoal) rearmGoal(live)\n return { sessionId, resumed: true, answer: { kind: 'success', text: RESUMED_TEXT } }\n }\n const adopted = deps.adopted(sessionId)\n // An adopted pause with nothing standing at the gate has no continuation to\n // release: the process that built that request is gone, so the decision's\n // own wake is what asks for one.\n if (adopted) {\n ensureRoute(live)\n wake(live, request)\n }\n const released = await deps.release(sessionId, RESUMED_TEXT)\n if (released.kind === 'error') {\n return { sessionId, resumed: false, refusal: 'unrecorded', answer: released }\n }\n if (adopted && record.rearmGoal) rearmGoal(live)\n return { sessionId, resumed: true, answer: released }\n }\n\n /**\n * Resume one recorded session: the clean path's only entry point.\n *\n * The clean-only rule holds on every branch, live or not: a record that is\n * not `safe` is not a park that finished, so this path neither wakes it nor\n * drops it — whoever holds it stays held, and the row reaches the morning\n * list. A pause this process pressed itself is not a record at all: taking it\n * back is the press's own undo, and it delivers no wake.\n * @param sessionId - the recorded session to resume.\n * @param request - which wake this resume delivers; see {@link WakeRequest}.\n * @param parentId - the direct parent a batch release already brought back, when there is one.\n * @param signal - cancellation for the cold load and setup.\n * @returns what happened, and the copy for whoever asked.\n */\n const resumeSession = async (\n sessionId: SessionId,\n request: WakeRequest,\n parentId?: SessionId,\n signal?: AbortSignal,\n ): Promise<ResumeAttempt> => {\n const record = registry.get(sessionId)\n const live = ctx.agents.get(sessionId)\n\n if (live !== undefined) {\n if (!gate.isPaused(sessionId)) {\n // This process holds nothing here. An unclean record belongs to the\n // morning list, and refusing it here is what keeps it there.\n if (record !== undefined && record.phase !== 'safe') {\n return { sessionId, resumed: false, refusal: 'not-clean', answer: { kind: 'error', text: UNCLEAN_TEXT } }\n }\n if (record === undefined) {\n return { sessionId, resumed: false, refusal: 'not-parked', answer: { kind: 'success', text: NOT_PARKED_TEXT } }\n }\n // A clean record nothing is holding any more: the session is already\n // back (it became readable after this mount could not hold it), so the\n // park is over. The record goes first — a park this process cannot drop\n // is not one it may continue — and then the session is handed the\n // request it stopped in front of, which is this path's own job.\n try {\n await registry.forget(sessionId)\n } catch (error: unknown) {\n ctx.logger.warn(`pause: could not drop \"${sessionId}\" from the pause registry: ${describeError(error)}`)\n return { sessionId, resumed: false, refusal: 'unrecorded', answer: { kind: 'error', text: UNRECORDED_TEXT } }\n }\n ensureRoute(live)\n wake(live, request)\n if (record.rearmGoal) rearmGoal(live)\n return { sessionId, resumed: true, answer: { kind: 'success', text: RESUMED_TEXT } }\n }\n // A pause this process did NOT press is another process's verdict: only a\n // finished park may be woken from it. A press of this process's own is\n // the pause the user is taking back, and it delivers no wake either way.\n const adopted = deps.adopted(sessionId)\n if (adopted && record !== undefined && record.phase !== 'safe') {\n return { sessionId, resumed: false, refusal: 'not-clean', answer: { kind: 'error', text: UNCLEAN_TEXT } }\n }\n // An adopted pause with nothing standing at the gate has no continuation\n // to release: the process that built that request is gone.\n if (adopted) {\n ensureRoute(live)\n wake(live, request)\n }\n const released = await deps.release(sessionId, RESUMED_TEXT)\n if (released.kind === 'error') {\n return { sessionId, resumed: false, refusal: 'unrecorded', answer: released }\n }\n // Re-arming spends money on the session's own, so the record's opt-out\n // decides it — and only an adopted pause can have lost the activation.\n if (adopted && (record?.rearmGoal ?? true)) rearmGoal(live)\n return { sessionId, resumed: true, answer: released }\n }\n\n if (record === undefined) {\n return { sessionId, resumed: false, refusal: 'not-parked', answer: { kind: 'success', text: NOT_PARKED_TEXT } }\n }\n // The one rule of this path: a record that is not `safe` is not a park that\n // finished, and waking it would act on a durable state nobody knows.\n if (record.phase !== 'safe') {\n return { sessionId, resumed: false, refusal: 'not-clean', answer: { kind: 'error', text: UNCLEAN_TEXT } }\n }\n return await activate(sessionId, request, record.rearmGoal, parentId, signal)\n }\n\n /**\n * Order the recorded sessions so a session is released after the parent it\n * hangs from: waking a child needs its direct parent to be live first. The\n * relation is read from the parent catalogs themselves (which children this\n * session actually has), never guessed from ids; a branch whose catalog\n * cannot be read simply has no known parent and is released with the roots.\n * @param sessionIds - every recorded session, in registry order.\n * @param signal - cancellation for each catalog read.\n * @returns the parent of each child, and one list per depth level, shallowest first.\n */\n return {\n resumeSession,\n decideUnclean,\n releaseTree: async (sessionId, signal) => {\n // The tree is read here, not taken from the press: the members that were\n // registered are exactly the members whose records exist, and a member\n // the walk cannot reach has no record to release either.\n const rooted = [sessionId, ...(await walkDescendants(ctx, sessionId, signal)).members.map(member => member.id)]\n const registered = rooted.filter(member => registry.get(member) !== undefined)\n if (registered.length === 0) {\n return { members: 0, resumed: 0, refusals: [], answer: { kind: 'success', text: NOT_PARKED_TEXT } }\n }\n // One control, two jobs. A tree with nothing clean in it is a press being\n // taken back: the user is undoing the pause they just asked for, and the\n // clean-only rule must not stand in the way of that — it would leave a\n // session the user cancelled still parked, which is the one thing the\n // press-again button must never do. A tree that holds anything clean is\n // the release, and there the rule holds per record: the members that did\n // not stop cleanly keep their pause and are never silently woken.\n const cancelling = registered.every(member => {\n const record = registry.get(member)\n return record !== undefined && record.phase !== 'safe' && !deps.adopted(member)\n })\n const released: ResumeAttempt[] = []\n if (cancelling) {\n for (const member of registered) {\n signal?.throwIfAborted()\n const answer = await deps.release(member, RESUMED_TEXT)\n released.push(answer.kind === 'error'\n ? { sessionId: member, resumed: false, refusal: 'unrecorded', answer }\n : { sessionId: member, resumed: true, answer })\n }\n } else {\n const release = await releaseOrder(ctx, registered, signal)\n for (const level of release.levels) {\n signal?.throwIfAborted()\n for (const member of level) {\n // The rule, applied here rather than left to the entry points\n // below: a pause this process pressed is normally the user's own\n // to take back, so the clean path releases it without asking its\n // phase. In a tree release it is not — a member that did not stop\n // cleanly keeps its pause, and the caller names it.\n const record = registry.get(member)\n if (record !== undefined && record.phase !== 'safe') {\n released.push({\n sessionId: member,\n resumed: false,\n refusal: 'not-clean',\n answer: { kind: 'error', text: UNCLEAN_TEXT },\n })\n continue\n }\n released.push(await resumeSession(member, { kind: 'silent' }, release.parents.get(member), signal))\n }\n }\n }\n const root = released.find(attempt => attempt.sessionId === sessionId)\n const refusals = released\n .filter((attempt): attempt is ResumeAttempt & { refusal: ResumeRefusal } => !attempt.resumed && attempt.refusal !== undefined)\n .map(attempt => ({ sessionId: attempt.sessionId, refusal: attempt.refusal }))\n return {\n members: released.length,\n resumed: released.filter(attempt => attempt.resumed).length,\n refusals,\n // The root's own answer is what the person who pressed sees: their\n // session either came back or it did not, and the tree's other members\n // are named in the count and in the refusals.\n answer: root === undefined\n ? { kind: 'success', text: NOT_PARKED_TEXT }\n : { kind: refusals.length === 0 && root.resumed ? 'success' : 'error', text: summarizeTreeRelease(released) },\n }\n },\n resumeParked: async (signal) => {\n const release = await releaseOrder(ctx, registry.list().map(entry => entry.sessionId), signal)\n const attempts: ResumeAttempt[] = []\n for (const level of release.levels) {\n signal?.throwIfAborted()\n // One release per level and no concurrency cap inside it: the levels\n // are the milliseconds a child's wake needs, not a queue.\n attempts.push(...await Promise.all(level.map(sessionId =>\n resumeSession(sessionId, { kind: 'silent' }, release.parents.get(sessionId), signal))))\n }\n return attempts\n },\n setRearmGoal: async (sessionId, rearmGoal) => {\n try {\n await registry.setRearmGoal(sessionId, rearmGoal)\n } catch (error: unknown) {\n ctx.logger.warn(`pause: could not record the goal opt-out of \"${sessionId}\": ${describeError(error)}`)\n return { kind: 'error', text: UNRECORDED_TEXT }\n }\n return { kind: 'success', text: rearmGoal ? REARM_GOAL_ON_TEXT : REARM_GOAL_OFF_TEXT }\n },\n }\n}\n","/**\n * The morning decision list: every session that did not stop cleanly, the facts\n * its own log carries about where it stopped, and the listed verbs the user can\n * take on it.\n *\n * A session gets here by NOT being on the clean path. A record whose phase is\n * `safe` is woken silently by `./resume.ts` and never appears here; the other\n * three phases describe work nobody can vouch for, and guessing on them would\n * spend the owner's money on a guess. This module is the other half of that\n * rule, not a second copy of it: the reading is taken from the session's own\n * stored log through a read handle that claims no ownership and writes nothing,\n * so asking what happened cannot itself change what happened.\n *\n * WHAT ONE READ COSTS. The list is read when the panel opens and when a native\n * action changes the park, and what it publishes is about the end of a log that\n * only grows, so `./coldlog.ts` bounds each row's read to that end. A row whose\n * facts the bound cannot hold reports itself unreadable rather than publishing\n * a fragment.\n *\n * WHAT A ROW REPORTS. \"Where it stopped\" is the last event of the stored log\n * with the turn and step it belongs to. \"Which tool was in flight\" is the\n * `tool/call` events that no durable `tool/result` answers — a call event is\n * only written once the loop reached the dispatch, so an unanswered one is\n * exactly a tool the real world ran and the log never heard back from. The\n * harness turns each of those into a synthetic `TOOL_OUTCOME_UNKNOWN` error\n * result when it next reads the log; this module derives the same answer from\n * the stored events instead of writing it back. Nothing here is inferred from\n * the fact that the session is listed.\n *\n * WHAT THE ROW PROMISES. `wake` says the host can hand this session the request\n * it owes, and the wake that keeps that promise is `./resume.ts`'s. Both read\n * one rule from `./history.ts` over the same derivation the loop reads, so a\n * promise this list publishes is a promise that wake keeps. When the log cannot\n * be folded into that derivation, the promise is withheld and the reading is\n * reported; a withheld promise costs a user nothing, a broken one spends their\n * money.\n *\n * WHO MAY DECIDE. A decision carries the calling session and its target as wire\n * input, so this list acts only on rows its most recent read published to the\n * calling session: the caller's own read is what makes a target actionable.\n * Anything else is refused, not looked up.\n *\n * TWO OF THE FIVE VERBS PUT THE SESSION BACK ON THE CLEAN PATH. Continue and\n * continue-with-the-note go through `ResumePath.decideUnclean`, which activates\n * the session, wakes it and drops the durable record before the gate opens.\n *\n * THE OTHER THREE TOUCH NOTHING. Leave writes nothing at all: the record stays,\n * the session stays held, and the row is still on tomorrow's list. Review\n * answers without activating anything or writing anything — opening a session\n * to read it is the user's own action in their session history, and starting an\n * agent on their behalf is precisely what they declined. Goal flips the row's\n * own re-arm opt-out: it is the user path for the one thing a resume can spend\n * without the user watching it, and it takes effect on whatever resume comes\n * next. All five carry the same binding — the row must be one this caller was\n * shown — because each changes, or declines to change, durable state of a\n * parked session.\n * @module dsh-pause-session/triage\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'\n// Type-only: the optional `ctx.sessionPersistence` read seam and its handle.\nimport type {} from '@deepseek-ai/dsh-session-persistence'\nimport { coldRead, logFacts, positionOf, TRIAGE_WINDOW_EVENTS } from './coldlog.js'\nimport type { ParkRegistry, ParkedSession } from './registry.js'\nimport type { ResumePath } from './resume.js'\nimport type { TriageAction, TriageList, TriageRow } from './shared.js'\nimport type { PauseAnswer } from './shared.js'\n\n/** The route a wake input has to be addressed to; see `./resume.ts`. */\ntype WakeOf = Parameters<ResumePath['resumeSession']>[1]\n\n/** Result copy for a decision the list itself could not carry out. */\n/** Result copy for leaving one listed session alone. */\nexport const TRIAGE_LEFT_TEXT = 'pause left this session paused; it is still on the list.'\n\n/** Result copy for a decision aimed at a session that is not on the list. */\nexport const TRIAGE_NOT_LISTED_TEXT = 'pause has no unfinished pause for this session.'\n\n/**\n * Result copy for a decision aimed at a row the calling session was not shown.\n * The list is the only thing that legitimizes a target, so a target nobody read\n * is refused rather than acted on.\n */\nexport const TRIAGE_UNSHOWN_TEXT = 'pause did not act: this Session has not been shown that row.'\n + ' Read the decision list first.'\n\n/**\n * Model-facing text that goes with a wake when the user chooses to continue\n * with a note.\n *\n * It is written the way the harness writes its own recovery text: the same two\n * facts the synthetic tool result states (the call's outcome was never recorded;\n * verify before retrying anything with side effects), in the same voice, with no\n * mention of the stop mechanism. The harness's own version lives in the tool\n * result for that call, which is why this one does not repeat the call's name —\n * it warns about the step as a whole, and the specific result sits directly\n * above it in the history.\n */\nexport const UNKNOWN_OUTCOME_NOTE = 'A tool call from this step was interrupted: its call was recorded but no '\n + 'result was durably recorded, so its outcome is unknown. If it had side effects, verify the external state '\n + 'before doing anything else, and do not retry it blindly. Then continue with what I asked for.'\n\n/**\n * One registry entry this list owns: every park outcome but `safe`, which is\n * the silent path's business and never appears here.\n */\ntype ListedPark = Omit<ParkedSession, 'phase'> & { readonly phase: TriageRow['phase'] }\n\n/**\n * One row's facts, as the session's own log reports them.\n * @param ctx - host context carrying the registered message projections.\n * @param entry - the durable park record this row is built from.\n * @param events - the events the bounded read returned, in sequence order.\n * @param complete - whether those events are the whole stored log.\n * @returns the row, ready to publish, or `undefined` when the read cannot support it.\n */\nfunction rowOf(\n ctx: Context,\n entry: ListedPark,\n events: readonly SessionEvent[],\n complete: boolean,\n): TriageRow | undefined {\n const { sessionId, phase, updatedAt, rearmGoal } = entry\n const facts = logFacts(events, complete, ctx.sessions.messageProjections)\n // A log this read cannot fold into those facts says nothing rather than\n // something: the row reports itself unreadable, which is what a list that\n // must not lie does when it does not know.\n if (facts === undefined) return undefined\n const { last, traces, owed, wakeable } = facts\n return {\n sessionId: String(sessionId),\n phase,\n updatedAt,\n reading: 'read',\n ...last === undefined ? {} : { lastEvent: last.type, ...positionOf(last) },\n traces,\n owed,\n rearmGoal,\n // Two facts have to hold before this host can hand the session its owed\n // request: the log must name the route the wake would be addressed to, and\n // there must be an answer still owed for the wake to ask for.\n wakeable,\n }\n}\n\n/** What mounting the decision list hands back. */\nexport interface TriageListService {\n /**\n * Read the list for one calling session, and record the rows it was shown.\n * @param caller - the session the read was addressed to.\n * @param signal - cancellation for the stored-log reads.\n * @returns every session that did not stop cleanly, with the facts its own log carries.\n */\n read(caller: SessionId, signal?: AbortSignal): Promise<TriageList>\n /**\n * Carry out one decision on one listed session, for the caller that read it.\n * @param caller - the session the decision was addressed to.\n * @param sessionId - the listed session to act on.\n * @param action - which of the listed decisions was taken.\n * @param signal - cancellation for the cold load and setup.\n * @returns the outcome for whoever asked.\n */\n decide(\n caller: SessionId,\n sessionId: SessionId,\n action: TriageAction,\n signal?: AbortSignal,\n ): Promise<PauseAnswer>\n}\n\n/**\n * Mount the decision list over the durable registry and the clean resume path.\n *\n * The list is the registry's own complement: it asks for every record whose\n * phase is not `safe`, so a session that cleaned up is off the list by the same\n * fact that puts it on the silent path, and nothing has to be reconciled.\n * @param ctx - host context carrying the optional persistence service.\n * @param registry - the durable list of park outcomes.\n * @param resumePath - the path all three resuming decisions go through.\n * @param windowEvents - how many events of each stored log one read may fold.\n * @returns the list read and the decision verbs.\n */\nexport function mountTriageList(\n ctx: Context,\n registry: ParkRegistry,\n resumePath: ResumePath,\n windowEvents: number = TRIAGE_WINDOW_EVENTS,\n): TriageListService {\n /**\n * The rows each calling session was last shown by its own read. A decision\n * names its target as wire input, and the channel carries no\n * origin of its own, so this is what ties a target to the list the user read:\n * only a row this caller has been shown is acted on.\n */\n const shown = new Map<SessionId, ReadonlySet<string>>()\n\n const unreadable = (entry: ListedPark): TriageRow => ({\n sessionId: String(entry.sessionId),\n phase: entry.phase,\n updatedAt: entry.updatedAt,\n reading: 'unreadable',\n traces: [],\n owed: false,\n wakeable: false,\n rearmGoal: entry.rearmGoal,\n })\n\n const readable = async (entry: ListedPark, signal?: AbortSignal): Promise<TriageRow> => {\n const read = await coldRead(ctx, entry.sessionId, windowEvents, signal)\n // A log this host could not read says so. An empty row would claim the\n // session left no traces, which is precisely the verdict nobody has.\n if (read.kind === 'unreadable') return unreadable(entry)\n // Facts this bounded read cannot support say the same thing: the row is\n // reported unreadable rather than filled with a guess.\n return rowOf(ctx, entry, read.events, read.complete) ?? unreadable(entry)\n }\n\n /**\n * One decision, as the resume path's own verbs plus the two local verbs that\n * change nothing but the record. Review is the list's own \"do not run it\"\n * answer: it activates nothing and writes nothing, so the park is exactly as\n * it was. The goal toggle is the user path for the one thing a resume can\n * spend unasked.\n */\n const decide = async (\n caller: SessionId,\n sessionId: SessionId,\n action: TriageAction,\n signal?: AbortSignal,\n ): Promise<PauseAnswer> => {\n if (!(shown.get(caller)?.has(String(sessionId)) ?? false)) return { kind: 'error', text: TRIAGE_UNSHOWN_TEXT }\n const record = registry.get(sessionId)\n // `safe` is not a decision this list owns: that session belongs to the\n // silent path, and acting here would be a second resume.\n if (record === undefined || record.phase === 'safe') {\n return { kind: 'error', text: TRIAGE_NOT_LISTED_TEXT }\n }\n if (action === 'leave') return { kind: 'success', text: TRIAGE_LEFT_TEXT }\n if (action === 'goal') return await resumePath.setRearmGoal(sessionId, !record.rearmGoal)\n // Review is its own kind of decision, not a wake-less resume: it leaves the\n // park exactly as it was, so the row is still there for tomorrow and\n // nothing has been continued — or even activated — on the user's behalf.\n if (action === 'review') {\n return (await resumePath.decideUnclean(sessionId, { kind: 'none' }, 'review', undefined, signal)).answer\n }\n const wake: WakeOf = action === 'continue' ? { kind: 'silent' } : { kind: 'message', text: UNKNOWN_OUTCOME_NOTE }\n return (await resumePath.decideUnclean(sessionId, wake, 'release', undefined, signal)).answer\n }\n\n return {\n read: async (caller, signal) => {\n signal?.throwIfAborted()\n const rows = await Promise.all([...registry.parked.values()]\n .flatMap(entry => entry.phase === 'safe' ? [] : [readable({ ...entry, phase: entry.phase }, signal)]))\n shown.set(caller, new Set(rows.map(row => row.sessionId)))\n return { rows }\n },\n decide,\n }\n}\n","/**\n * Pure projection of the durable park and each live tree into the native\n * snapshot. This module owns the phase fold and the goal opt-out; it does not\n * press, release, or decide anything.\n * @module dsh-pause-session/snapshot\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { SessionId } from '@deepseek-ai/dsh-session'\nimport type { ParkWatch } from './park.js'\nimport type { ParkRegistry } from './registry.js'\nimport { walkDescendants } from './tree.js'\nimport type { TreeWalk } from './tree.js'\nimport { foldTreePhases } from './shared.js'\nimport type { ParkMark } from './park-state.js'\nimport type { GlobalStatus, ParkPhase, ParkStatus, PauseSnapshot } from './shared.js'\n\n/** What the snapshot projection needs from the control. */\nexport interface SnapshotDeps {\n readonly ctx: Context\n readonly marks: ReadonlyMap<SessionId, ParkMark>\n readonly watch: ParkWatch\n readonly registry: ParkRegistry\n /** Read the whole-app aggregate, reusing the walks this projection already paid for. */\n readGlobal(signal?: AbortSignal, walks?: ReadonlyMap<SessionId, TreeWalk>): Promise<GlobalStatus>\n}\n\n/** The phase a durable record holds for one session, live or adopted. */\nfunction recordedPhase(deps: SnapshotDeps, sessionId: SessionId): ParkPhase | undefined {\n return deps.marks.get(sessionId)?.phase ?? deps.registry.get(sessionId)?.phase\n}\n\n/** Fold one session's mark and its registered descendants into the header reading. */\nasync function treeStatus(\n deps: SnapshotDeps,\n sessionId: SessionId,\n mark: ParkMark,\n signal?: AbortSignal,\n knownWalk?: TreeWalk,\n): Promise<ParkStatus> {\n const walk = knownWalk ?? await walkDescendants(deps.ctx, sessionId, signal)\n const phases: ParkPhase[] = [mark.phase]\n const extraRunning: string[] = []\n for (const member of walk.members) {\n const phase = recordedPhase(deps, member.id)\n if (phase !== undefined) {\n phases.push(phase)\n continue\n }\n // A member this press could not register (one-shot/external route) is\n // still part of the tree. If it is doing work, the tree is not safe.\n if (member.mode !== 'continuable') {\n const activity = deps.watch.activity(member.id)\n if (activity.turnOpen || activity.runningTools.length > 0) {\n phases.push('draining')\n extraRunning.push(...activity.runningTools)\n }\n }\n }\n // An unread branch is unknown: it is neither clean nor a settled phase.\n for (let at = 0; at < walk.unread.length + (walk.unreadWhole ? 1 : 0); at += 1) phases.push('parking')\n\n const folded = foldTreePhases(phases)\n const runningTools = [\n ...(mark.phase === 'draining' ? deps.watch.activity(sessionId).runningTools : []),\n ...walk.members.flatMap(member => recordedPhase(deps, member.id) === 'draining'\n ? deps.watch.activity(member.id).runningTools\n : []),\n ...extraRunning,\n ]\n const record = deps.registry.get(sessionId)\n return {\n phase: folded.phase,\n safe: folded.safe,\n runningTools,\n ...record === undefined ? {} : { rearmGoal: record.rearmGoal },\n }\n}\n\n/**\n * Read every live mark and the whole-app aggregate in one pass.\n * @param deps - the control-owned marks, watch, registry, and aggregate reader.\n * @param signal - cancellation for the tree walks and aggregate.\n * @returns the native snapshot.\n */\nexport async function readSnapshot(\n deps: SnapshotDeps,\n signal?: AbortSignal,\n): Promise<PauseSnapshot> {\n const sessions: Record<string, ParkStatus> = {}\n const walks = new Map<SessionId, TreeWalk>()\n await Promise.all([...deps.marks].map(async ([sessionId, mark]) => {\n const walk = await walkDescendants(deps.ctx, sessionId, signal)\n // The aggregate has its own blind-spot reading for a host with no subagent\n // service; sharing an empty walk would erase that fact.\n if (deps.ctx.get('subagents') !== undefined) walks.set(sessionId, walk)\n sessions[String(sessionId)] = await treeStatus(deps, sessionId, mark, signal, walk)\n }))\n return { global: await deps.readGlobal(signal, walks), sessions }\n}\n","/**\n * One session's park episode: the durable phase writes, the activity walk that\n * settles them, and the press/release lifecycle. The control composes this with\n * the aggregate, the resume path, and the decision list.\n * @module dsh-pause-session/park-state\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { SessionId } from '@deepseek-ai/dsh-session'\nimport type { PauseGate } from './gate.js'\nimport type { LivePark, PressResult } from './global.js'\nimport type { ParkWatch } from './park.js'\nimport type { ParkRegistry } from './registry.js'\nimport { isResumableSession } from './composition.js'\nimport { describeError, UNRECORDED_TEXT } from './shared.js'\nimport type { ParkPhase, PauseAnswer } from './shared.js'\n\n/** One session's park in progress. */\nexport interface ParkMark {\n /** The phase the durable registry confirms for this session. */\n phase: ParkPhase\n /** Generation of the attempt that owns this mark. */\n generation: number\n /** Whether this mark is a live press or a record adopted at mount. */\n origin: 'press' | 'registry'\n /** Whether a settle attempt is already walking this mark. */\n advancing: boolean\n}\n\n/** The park lifecycle the session control composes. */\nexport interface ParkState {\n readonly marks: Map<SessionId, ParkMark>\n readonly unrecorded: Set<SessionId>\n readonly unheld: Set<SessionId>\n subscribe(listener: () => void): () => void\n notify(): void\n press(sessionId: SessionId, signal?: AbortSignal, knownResumable?: boolean): Promise<PressResult>\n /** Adopt one durable record as a mark that never advances in this process. */\n adopt(sessionId: SessionId, phase: ParkPhase): void\n look(sessionId: SessionId): void\n drop(sessionId: SessionId): void\n sync(sessionId: SessionId): void\n release(sessionId: SessionId, text: string): Promise<PauseAnswer>\n markUnrecorded(sessionId: SessionId, unrecorded: boolean): void\n live(): Map<SessionId, LivePark>\n cleanup(): void\n}\n\n/**\n * Mount the park episode state machine over the gate, registry, and activity fold.\n * @param ctx - host context carrying the session store and logger.\n * @param gate - the pause gate this state drives.\n * @param registry - the durable pause list every phase write goes to.\n * @param watch - the activity fold the park predicate reads.\n * @returns the park lifecycle the control composes.\n */\nexport function installParkState(\n ctx: Context,\n gate: PauseGate,\n registry: ParkRegistry,\n watch: ParkWatch,\n): ParkState {\n const marks = new Map<SessionId, ParkMark>()\n const unrecorded = new Set<SessionId>()\n const unheld = new Set<SessionId>()\n const listeners = new Set<() => void>()\n let notification: ReturnType<typeof setTimeout> | undefined\n let generation = 0\n\n /** One snapshot per burst of host changes, not one per phase write. */\n const notify = (): void => {\n if (notification !== undefined) return\n notification = setTimeout(() => {\n notification = undefined\n for (const listener of [...listeners]) listener()\n }, 20)\n }\n\n const drop = (sessionId: SessionId): void => {\n marks.delete(sessionId)\n notify()\n }\n\n const commit = async (sessionId: SessionId, mark: ParkMark, phase: ParkPhase): Promise<boolean> => {\n try {\n await registry.record(sessionId, phase)\n } catch (error: unknown) {\n ctx.logger.warn(`pause: could not record the park state of \"${sessionId}\" as ${phase}: ${describeError(error)}`)\n return false\n }\n const changed = mark.phase !== phase\n mark.phase = phase\n if (changed) notify()\n return true\n }\n\n const parked = (sessionId: SessionId): boolean => {\n const activity = watch.activity(sessionId)\n if (activity.runningTools.length > 0) return false\n return gate.isHeld(sessionId) || !activity.turnOpen\n }\n\n const advance = (sessionId: SessionId): boolean => {\n const mark = marks.get(sessionId)\n if (mark === undefined || mark.phase !== 'draining' || mark.advancing) return false\n if (mark.origin === 'registry') return false\n if (!parked(sessionId)) return false\n mark.advancing = true\n return true\n }\n\n const settle = async (sessionId: SessionId, attempt: number): Promise<void> => {\n const mark = marks.get(sessionId)\n if (mark === undefined || mark.generation !== attempt) return\n const owned = (): boolean => marks.get(sessionId) === mark && mark.generation === attempt\n const session = ctx.sessions.get(sessionId)\n try {\n if (session === undefined) {\n await commit(sessionId, mark, 'parking')\n return\n }\n await commit(sessionId, mark, 'parking')\n if (!owned()) return\n try {\n const flushed = await ctx.sessions.flush(session)\n if (!flushed) {\n await commit(sessionId, mark, 'flush-failed')\n return\n }\n } catch (error: unknown) {\n if (!owned()) return\n ctx.logger.warn(`pause: flush failed for \"${sessionId}\": ${describeError(error)}`)\n await commit(sessionId, mark, 'flush-failed')\n return\n }\n if (!owned()) return\n await commit(sessionId, mark, 'safe')\n } finally {\n if (marks.get(sessionId) === mark && mark.phase === 'draining') mark.advancing = false\n }\n }\n\n const look = (sessionId: SessionId): void => {\n if (marks.has(sessionId)) notify()\n if (!advance(sessionId)) return\n const attempt = marks.get(sessionId)?.generation\n if (attempt !== undefined) void settle(sessionId, attempt)\n }\n\n const press = async (\n sessionId: SessionId,\n signal?: AbortSignal,\n knownResumable = false,\n ): Promise<PressResult> => {\n if (ctx.sessions.get(sessionId) === undefined) return 'not-live'\n if (!knownResumable && !await isResumableSession(ctx, sessionId, signal)) return 'not-resumable'\n if (!gate.pause(sessionId)) return 'already-paused'\n const mark: ParkMark = { phase: 'draining', generation: ++generation, origin: 'press', advancing: false }\n marks.set(sessionId, mark)\n if (await commit(sessionId, mark, 'draining')) {\n unheld.delete(sessionId)\n notify()\n return 'registered'\n }\n drop(sessionId)\n gate.resume(sessionId)\n return 'unrecordable'\n }\n\n const release = async (sessionId: SessionId, text: string): Promise<PauseAnswer> => {\n if (!gate.isPaused(sessionId)) return { kind: 'success', text }\n try {\n await registry.forget(sessionId)\n } catch (error: unknown) {\n ctx.logger.warn(`pause: could not drop \"${sessionId}\" from the pause registry: ${describeError(error)}`)\n return { kind: 'error', text: UNRECORDED_TEXT }\n }\n gate.resume(sessionId)\n notify()\n return { kind: 'success', text }\n }\n\n const sync = (sessionId: SessionId): void => {\n if (!gate.isPaused(sessionId)) {\n drop(sessionId)\n return\n }\n }\n\n return {\n marks,\n unrecorded,\n unheld,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n notify,\n press,\n adopt: (sessionId, phase) => {\n marks.set(sessionId, { phase, generation: ++generation, origin: 'registry', advancing: false })\n },\n look,\n drop,\n sync,\n release,\n markUnrecorded: (sessionId, blocked) => {\n if (blocked) unrecorded.add(sessionId)\n else unrecorded.delete(sessionId)\n },\n live: () => new Map<SessionId, LivePark>([...marks].map(([sessionId, mark]) => [sessionId, {\n phase: mark.phase,\n moving: mark.origin === 'press' && mark.phase !== 'flush-failed' && ctx.sessions.get(sessionId) !== undefined,\n }])),\n cleanup: () => {\n if (notification !== undefined) clearTimeout(notification)\n marks.clear()\n listeners.clear()\n },\n }\n}\n","/**\n * The session control the browser half drives: the pause verb, the park state\n * machine behind it, and the live state channel that accompanies both.\n *\n * The host exposes this control through the native Typert Remote namespace:\n * `observe` streams snapshots and `act` / `triage` / `decide` drive the UI. No\n * slash command is registered. Phase changes wake the Remote stream through a\n * local listener set; the durable registry remains the source of truth for what\n * the snapshot reports.\n * @module dsh-pause-session/control\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { SessionId } from '@deepseek-ai/dsh-session'\n// Type-only: the optional `ctx.sessionPersistence` observation seam.\nimport type {} from '@deepseek-ai/dsh-session-persistence'\nimport type { PauseGate } from './gate.js'\nimport { isResumableSession } from './composition.js'\nimport { mountGlobalPause } from './global.js'\nimport type { GlobalPause } from './global.js'\nimport type { ParkWatch } from './park.js'\nimport type { ParkRegistry } from './registry.js'\nimport { installResumePath, NOT_PARKED_TEXT } from './resume.js'\nimport type { ReleaseTreeOutcome, ResumeAttempt, ResumeOptions, ResumePath } from './resume.js'\nimport { mountTriageList } from './triage.js'\nimport type { TriageListService } from './triage.js'\nimport type { TriageAction } from './shared.js'\nimport { describeError, UNRECORDED_TEXT } from './shared.js'\nimport type { ParkPhase, PauseSnapshot, TriageList } from './shared.js'\nimport { readSnapshot as readSnapshotOf } from './snapshot.js'\nimport { installParkState } from './park-state.js'\nimport { walkDescendants } from './tree.js'\nimport type { PauseAnswer } from './shared.js'\n\n/**\n * Whether this host can read one recorded session at all — a live session, or a\n * stored log the persistence backend can observe.\n * @param ctx - host context carrying the session store and the optional persistence service.\n * @param sessionId - the recorded session to look for.\n * @returns whether the session can be acted on here.\n */\nasync function sessionReadable(ctx: Context, sessionId: SessionId): Promise<boolean> {\n if (ctx.sessions.get(sessionId) !== undefined) return true\n const persistence = ctx.get('sessionPersistence')\n if (persistence === undefined) return false\n try {\n return await persistence.stat(sessionId) !== undefined\n } catch (error: unknown) {\n ctx.logger.warn(`pause: could not look for the stored log of \"${sessionId}\": ${describeError(error)}`)\n return false\n }\n}\n\n/** What one tree-wide press registered, and what it could not. */\nexport interface PressTreeOutcome {\n /** How many sessions this press covered: the session plus its descendants. */\n readonly members: number\n /** How many of them now have a durable park record behind them. */\n readonly registered: number\n /** Whether the pressed session itself is one of them. */\n readonly rootRegistered: boolean\n /** The members whose record could not be written; they are not paused. */\n readonly unrecorded: readonly SessionId[]\n /** Whether any branch was unread, so the subagent tree was not fully covered. */\n readonly unread: boolean\n /** Tree members on a one-shot or unreadable route; they were not registered. */\n readonly unresumable: readonly SessionId[]\n /** Branch ids the tree walk could not read. */\n readonly unreadBranches: readonly SessionId[]\n}\n\n/** What mounting the session control hands back to the plugin entry. */\nexport interface SessionControl {\n /**\n * Hold every session the registry remembers and can read, and publish the\n * marker for the ones that already have a live agent. Called once, right\n * after mount.\n */\n adopt(): Promise<void>\n /**\n * Read the whole app and every live paused session as one JSON-safe snapshot.\n * The native snapshot serves this; it never enters a Session log.\n * @param signal - cancellation for the tree reads this snapshot performs.\n * @returns the whole-app verdict and the paused sessions this process holds.\n */\n readSnapshot(signal?: AbortSignal): Promise<PauseSnapshot>\n /** Wake a listener after any visible status change. */\n subscribe(listener: () => void): () => void\n /** Press one Session tree. */\n pressTree(sessionId: SessionId, signal?: AbortSignal): Promise<PressTreeOutcome>\n /** Release one Session's registered tree. */\n releaseTree(sessionId: SessionId, signal?: AbortSignal): Promise<ReleaseTreeOutcome>\n /** Press every running Session tree. */\n pauseAll(signal?: AbortSignal): Promise<PauseAnswer>\n /** Resume every cleanly paused Session. */\n resumeAll(signal?: AbortSignal): Promise<PauseAnswer>\n /** Release every registered tree, cancelling a press that is still draining. */\n cancelAll(signal?: AbortSignal): Promise<PauseAnswer>\n /** Flip one Session's goal re-arm opt-out. */\n toggleGoal(sessionId: SessionId, signal?: AbortSignal): Promise<PauseAnswer>\n /** Read the morning list for one calling Session. */\n readTriage(caller: SessionId, signal?: AbortSignal): Promise<TriageList>\n /** Take one listed decision for one calling Session. */\n decideTriage(\n caller: SessionId,\n target: SessionId,\n action: TriageAction,\n signal?: AbortSignal,\n ): Promise<PauseAnswer>\n}\n\n/** How resuming all parked sessions answers the caller. */\nexport function summarizeResume(attempts: readonly ResumeAttempt[]): string {\n const resumed = attempts.filter(attempt => attempt.resumed).length\n const refused = attempts.length - resumed\n const head = resumed === 0\n ? 'pause resumed no session'\n : resumed === 1\n ? 'pause resumed 1 session from where it stopped'\n : `pause resumed ${resumed} sessions from where they stopped`\n if (refused === 0) return `${head}.`\n const unclean = attempts.filter(attempt => attempt.refusal === 'not-clean').length\n const rest = unclean === refused\n ? `${refused} did not pause completely and need your decision`\n : `${refused} could not be resumed`\n return `${head}; ${rest}.`\n}\n\n/**\n * Everything the session control needs from the composition: the clean resume\n * path's route knowledge, plus the bound the decision list reads each parked\n * log under.\n */\nexport interface SessionControlOptions extends ResumeOptions {\n /** Events of each stored log the decision list may fold per row; see `./coldlog.ts`. */\n readonly maxListedLogEvents?: number\n}\n\n/**\n * Contribute the session control: the pause verb, the per-session status read,\n * the global resume verb, and — for every paused session that has a live agent\n * — the resume marker.\n * @param ctx - host context carrying the agent store, the\n * session store, and the projection registry.\n * @param gate - the pause gate this control drives and reflects.\n * @param watch - the per-session activity fold the park predicate reads.\n * @param registry - the durable pause list every phase change is written to.\n * @param options - route knowledge the clean resume path needs, and the decision list's read bound.\n * @returns the mount-time adoption step and the morning resume path.\n */\nexport function installSessionControl(\n ctx: Context,\n gate: PauseGate,\n watch: ParkWatch,\n registry: ParkRegistry,\n options: SessionControlOptions,\n): SessionControl {\n const park = installParkState(ctx, gate, registry, watch)\n\n /**\n * Press one session's pause and register its whole tree behind it.\n *\n * \"One session's work\" includes the subagents it delegated to, nested ones\n * included, and the user does not pause them one by one. So the press walks\n * the session's own catalog tree and gives every member the same durable\n * treatment the session gets: {@link press} registers what it can hold, and a\n * member whose record cannot be written is named here rather than counted as\n * paused.\n *\n * A tree the walk could not read is the one case where the press does less\n * than the tree: the session itself is still registered — the user pressed a\n * session, and its park is real — and the answer says the subagents were not\n * covered rather than counting a tree nobody read.\n * @param sessionId - the session whose tree the user pressed.\n * @returns which members are registered and which could not be.\n */\n const pressTree = async (sessionId: SessionId, signal?: AbortSignal): Promise<PressTreeOutcome> => {\n // Nothing live means nothing this press could hold; the check is also what\n // keeps a session disposed in the middle of a press on the path that\n // records the park point it reached.\n if (ctx.sessions.get(sessionId) === undefined) {\n return { members: 0, registered: 0, rootRegistered: false, unrecorded: [], unread: false, unresumable: [], unreadBranches: [] }\n }\n const walk = await walkDescendants(ctx, sessionId, signal)\n // A tree this press could not read is not a reason to drop the session\n // itself: the user pressed a session, and its own park is still real. What\n // is refused is the claim about the tree, which is why the count stays at\n // the one member this press actually covers.\n if (walk.unreadWhole) {\n const pressed = await park.press(sessionId, signal)\n // The look is unconditional on purpose only after a mark exists: a\n // session that left the store during this press has a mark and cannot be\n // flushed, which is the one way its park still reaches a durable \"not\n // clean\" instead of a phase that never settles.\n if (pressed === 'registered') park.look(sessionId)\n globalPause.markUnrecorded(sessionId, pressed === 'unrecordable')\n return {\n members: pressed === 'registered' ? 1 : 0,\n registered: pressed === 'registered' ? 1 : 0,\n rootRegistered: pressed === 'registered',\n unrecorded: pressed === 'unrecordable' ? [sessionId] : [],\n unread: true,\n unresumable: [],\n unreadBranches: [],\n }\n }\n const registered: SessionId[] = []\n const unrecorded: SessionId[] = []\n const unresumable = walk.members.filter(member => member.mode !== 'continuable').map(member => member.id)\n const unreadBranches = walk.unread.map(branch => branch.id)\n const members = walk.members.filter(member => member.mode === 'continuable')\n for (const id of [sessionId, ...members.map(member => member.id)]) {\n // The press is per member on purpose: one member that cannot be recorded\n // is named while the rest keep the pause they got. A member on a\n // one-shot or external route is never registered: there is no later\n // resume that could honestly satisfy that promise.\n const pressed = await park.press(id, signal, id !== sessionId)\n if (pressed === 'registered') {\n registered.push(id)\n // A member this host has nothing live for has no mark to walk; one that\n // does is looked at now, exactly as the session's own press looked at\n // itself.\n park.look(id)\n } else if (pressed === 'unrecordable') {\n unrecorded.push(id)\n }\n // The aggregate owns the same fact, so a member the registry refused is\n // named by the whole-app report too. A skipped member is not a failed\n // promise and is not named as one.\n globalPause.markUnrecorded(id, pressed === 'unrecordable')\n }\n return {\n members: registered.length + unrecorded.length,\n registered: registered.length,\n rootRegistered: registered.includes(sessionId),\n unrecorded,\n unread: unreadBranches.length > 0,\n unresumable,\n unreadBranches,\n }\n }\n\n // The resume verb, the global resume verb, and the goal opt-out ride one\n // path. It is mounted here because the release order and the marked origin\n // are this control's own facts.\n const resumePath: ResumePath = installResumePath(ctx, gate, registry, options, {\n release: park.release,\n adopted: sessionId => park.marks.get(sessionId)?.origin === 'registry',\n })\n\n // The decision list reads the same durable registry and acts through the same\n // resume path, so a session is on exactly one of the two morning paths: the\n // silent one when its record says `safe`, this one otherwise.\n const triage: TriageListService = mountTriageList(ctx, registry, resumePath, options.maxListedLogEvents)\n\n // The whole-app park reads the marks through this one accessor, so the\n // aggregate and the per-session control can never describe different states.\n const globalPause: GlobalPause = mountGlobalPause(ctx, watch, registry, {\n isPaused: sessionId => gate.isPaused(sessionId),\n press: park.press,\n look: park.look,\n live: park.live,\n unheld: () => park.unheld,\n })\n\n const readSnapshot = (signal?: AbortSignal): Promise<PauseSnapshot> =>\n readSnapshotOf({ ctx, marks: park.marks, watch, registry, readGlobal: globalPause.readState }, signal)\n\n // One effect owns the subscriptions and the mark cleanup. There is no\n // status is the Remote stream and actions are Remote methods.\n ctx.effect(function* () {\n yield gate.onChange(sessionId => { park.sync(sessionId) })\n yield gate.onHeld(sessionId => {\n queueMicrotask(() => { park.look(sessionId) })\n })\n yield watch.onChange(sessionId => { park.look(sessionId) })\n yield ctx.on('agent/created', ({ agent }) => {\n park.sync(agent.id)\n return undefined\n })\n yield async () => {\n park.cleanup()\n }\n }, 'pause: session events')\n\n return {\n readSnapshot,\n subscribe: park.subscribe,\n pressTree: async (sessionId, signal) => await pressTree(sessionId, signal),\n releaseTree: async (sessionId, signal) => await resumePath.releaseTree(sessionId, signal),\n pauseAll: async (signal) => {\n const answer = await globalPause.pressAll(signal)\n park.notify()\n return answer\n },\n cancelAll: async (signal) => {\n const outcomes = []\n // A tree can mix a clean member with a press that is still draining. The\n // clean release then resumes the clean member and keeps the draining one;\n // repeat so the remaining all-unclean tree can take the cancel path.\n for (let round = 0; round < 3; round += 1) {\n const before = registry.parked.size\n for (const sessionId of [...registry.parked.keys()]) {\n signal?.throwIfAborted()\n outcomes.push((await resumePath.releaseTree(sessionId, signal)).answer)\n }\n if (registry.parked.size === before) break\n }\n park.notify()\n const failed = outcomes.filter(answer => answer.kind === 'error')\n return failed.length === 0\n ? { kind: 'success', text: 'Every pause was released.' }\n : { kind: 'error', text: failed.map(answer => answer.text).join(' ') }\n },\n resumeAll: async (signal) => {\n const answer = { kind: 'success' as const, text: summarizeResume(await resumePath.resumeParked(signal)) }\n park.notify()\n return answer\n },\n toggleGoal: async (sessionId) => {\n const record = registry.get(sessionId)\n if (record === undefined) return { kind: 'error', text: NOT_PARKED_TEXT }\n const answer = await resumePath.setRearmGoal(sessionId, !record.rearmGoal)\n park.notify()\n return answer\n },\n readTriage: async (caller, signal) => await triage.read(caller, signal),\n decideTriage: async (caller, target, action, signal) => {\n const answer = await triage.decide(caller, target, action, signal)\n park.notify()\n return answer\n },\n adopt: async () => {\n for (const entry of registry.list()) {\n // Every registered session this host can read is held again, whether or\n // not anything is live: the request that wakes it is the one this gate\n // must catch, and the wake-up may come from a scheduled task or a\n // webhook long after this mount. A record whose session cannot be read\n // is not held — the id would be pinned with nothing behind it and no\n // verb could ever clear it — and is reported instead.\n if (!await sessionReadable(ctx, entry.sessionId)) {\n park.unheld.add(entry.sessionId)\n ctx.logger.warn(`pause: the pause recorded for \"${entry.sessionId}\" is not held:`\n + ' this host cannot read that session')\n continue\n }\n if (gate.pause(entry.sessionId)) park.adopt(entry.sessionId, entry.phase)\n }\n // A session that was already live when this instance mounted still owes\n // the browser the marker: the registry holds the list, and nothing else\n // re-publishes it for agents that predate this mount.\n for (const agent of ctx.agents.list()) park.sync(agent.id)\n },\n }\n}\n","/**\n * The pause gate: one session's hold at the model-request waterfall.\n *\n * The hold sits on the `llm/stream` waterfall, which is the only point that\n * satisfies all four conditions at once: the previous step's tool calls have\n * drained, the request is already built, the session's pending input is\n * committed, and — because nothing pulls the adapter — no timer is armed\n * anywhere. Machine sleep, network loss, and the adapter's stream-idle\n * watchdog therefore cannot touch a parked request.\n * @module dsh-pause-session/gate\n */\n\nimport type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'\nimport type { SessionId } from '@deepseek-ai/dsh-session'\n\n/** Message of the failure a held request ends with when its plugin unloads first. */\nexport const PLUGIN_UNLOADED = 'pause: plugin lifetime ended while a request was held'\n\n/** One latch a paused request waits on. */\ninterface Latch {\n readonly promise: Promise<void>\n readonly open: () => void\n}\n\n/** One paused session and the latch every request of that session waits on. */\ninterface Pause {\n readonly sessionId: SessionId\n readonly released: Promise<void>\n release(): void\n /**\n * Requests of this session waiting at the gate right now. Membership in\n * `paused` says the session is marked; this count says a request has\n * actually arrived and stopped, which is a different fact — the one the\n * park state is built from.\n */\n holding: number\n}\n\n/** The abort signal's own error, or a stable one when the abort carried no reason. */\nfunction abortError(signal: AbortSignal): Error {\n return signal.reason instanceof Error ? signal.reason : new Error('pause: request aborted while held')\n}\n\n/** A latch without `Promise.withResolvers`, which this project's ES2022 lib predates. */\nfunction latch(): Latch {\n let open: () => void = () => {}\n const promise = new Promise<void>((resolve) => { open = resolve })\n return { promise, open }\n}\n\n/**\n * Resolve once the session is released or any of `signals` aborts. No timer is\n * armed: the wait ends only by release or by an abort, so a parked request\n * cannot be woken by the clock. Listeners are removed once the wait settles.\n */\nfunction raceRelease(released: Promise<void>, signals: readonly AbortSignal[]): Promise<void> {\n const wake = latch()\n const onAbort = (): void => { wake.open() }\n const watching = signals.filter(signal => !signal.aborted)\n if (watching.length !== signals.length) wake.open()\n for (const signal of watching) signal.addEventListener('abort', onAbort, { once: true })\n return Promise.race([released, wake.promise]).finally(() => {\n for (const signal of watching) signal.removeEventListener('abort', onAbort)\n })\n}\n\n/** Options of {@link PauseGate}. */\nexport interface PauseGateOptions {\n /** Aborted when the owning plugin unloads; a held request must never delegate after that. */\n readonly lifetime: AbortSignal\n}\n\n/** Per-session pause state and the waterfall listener that enforces it. */\nexport class PauseGate {\n /** Paused sessions; membership IS the pause state. */\n private readonly paused = new Map<SessionId, Pause>()\n private readonly listeners = new Set<(sessionId: SessionId, paused: boolean) => void>()\n private readonly heldListeners = new Set<(sessionId: SessionId, held: boolean) => void>()\n\n /**\n * @param options - the plugin-lifetime signal every held request races.\n */\n constructor(private readonly options: PauseGateOptions) {}\n\n /**\n * Subscribe to pause-state changes.\n * @param listener - called with the session whose state changed and its new state.\n * @returns the unsubscribe function.\n */\n onChange(listener: (sessionId: SessionId, paused: boolean) => void): () => void {\n this.listeners.add(listener)\n return () => { this.listeners.delete(listener) }\n }\n\n /**\n * Subscribe to \"a request arrived at / left the gate\" for a paused session.\n *\n * This is the moment a session can become parked, so it is also the moment a\n * park observer has to look. Listeners run synchronously inside the request\n * path: they must only record that a look is owed.\n * @param listener - called with the session and whether it now holds a request.\n * @returns the unsubscribe function.\n */\n onHeld(listener: (sessionId: SessionId, held: boolean) => void): () => void {\n this.heldListeners.add(listener)\n return () => { this.heldListeners.delete(listener) }\n }\n\n /**\n * @param sessionId - session to inspect.\n * @returns whether the session is currently paused.\n */\n isPaused(sessionId: SessionId): boolean {\n return this.paused.has(sessionId)\n }\n\n /**\n * @param sessionId - session to inspect.\n * @returns whether a model request of that session is waiting at the gate\n * right now. False for a session that is paused but whose loop has not built\n * its next request yet — a running tool, for instance, is still draining.\n */\n isHeld(sessionId: SessionId): boolean {\n return (this.paused.get(sessionId)?.holding ?? 0) > 0\n }\n\n /**\n * Enter one request that is about to wait. The count rises synchronously with\n * {@link hold}, so an observer notified at that moment reads `isHeld` as true.\n * @param pause - the session's pause record.\n * @returns the exit that lowers the count again.\n */\n private enter(pause: Pause): () => void {\n pause.holding += 1\n this.notifyHeld(pause.sessionId, true)\n return () => {\n pause.holding -= 1\n if (pause.holding === 0) this.notifyHeld(pause.sessionId, false)\n }\n }\n\n /**\n * Pause one session: its next model request is held until {@link resume}. A\n * request already past the waterfall keeps running — pausing never\n * interrupts a model call or a tool call that has started.\n * @param sessionId - session to pause.\n * @returns whether this call changed the state.\n */\n pause(sessionId: SessionId): boolean {\n if (this.paused.has(sessionId)) return false\n const release = latch()\n this.paused.set(sessionId, { sessionId, released: release.promise, release: release.open, holding: 0 })\n this.notify(sessionId, true)\n return true\n }\n\n /**\n * Resume one session: release everything it holds and stop holding what\n * follows. The requests sent from then on are the ones built before the\n * hold, so a resumed session continues from the point it stopped.\n * @param sessionId - session to resume.\n * @returns whether this call changed the state.\n */\n resume(sessionId: SessionId): boolean {\n const pause = this.paused.get(sessionId)\n if (pause === undefined) return false\n this.paused.delete(sessionId)\n pause.release()\n this.notify(sessionId, false)\n return true\n }\n\n /**\n * The wait one model request must finish before it may delegate, and the exit\n * that reports the request as no longer waiting.\n * @param request - the request reaching the waterfall.\n * @returns the wait plus its release, or `undefined` when this gate does not\n * hold that request.\n */\n hold(request: GenerateOptions): { readonly wait: Promise<void>; readonly left: () => void } | undefined {\n // Context compaction and session titling are background model work inside\n // the same session and carry a purpose; a session pause must never freeze\n // them. Only a request the loop built for its own turn is gateable.\n if (request.purpose !== undefined) return undefined\n const sessionId = request.sessionId\n if (sessionId === undefined) return undefined\n const pause = this.paused.get(sessionId)\n if (pause === undefined) return undefined\n const left = this.enter(pause)\n const wait = raceRelease(\n pause.released,\n request.signal === undefined ? [this.options.lifetime] : [request.signal, this.options.lifetime],\n )\n return { wait, left }\n }\n\n /**\n * The `llm/stream` listener.\n *\n * `ctx.waterfall` composes listeners synchronously, so this returns an async\n * iterator synchronously — an `async` listener would hand the loop a promise\n * where it iterates a stream. One generator body reaches `next()` at most\n * once, which is what makes delegation single-shot per HELD request; a flag\n * shared across requests would also short-circuit everything issued after\n * the release.\n * @param request - the full request, already built and frozen by the loop.\n * @param next - the downstream waterfall chain.\n * @returns the stream, delayed until this request may delegate.\n */\n readonly stream = (request: GenerateOptions, next: () => AsyncIterable<StreamChunk>): AsyncIterable<StreamChunk> => {\n const gate = this\n return (async function* gated(): AsyncIterable<StreamChunk> {\n const held = gate.hold(request)\n try {\n if (held !== undefined) await held.wait\n // The race decides when to stop waiting; the signals decide whether\n // delegating is allowed at this exact moment. A request whose phase\n // aborted, or whose plugin unloaded, must never reach the adapter.\n if (request.signal?.aborted === true) throw abortError(request.signal)\n if (gate.options.lifetime.aborted) throw new Error(PLUGIN_UNLOADED)\n yield* next()\n } finally {\n // Leaving is what tells an observer the session stopped standing at\n // the park point — whether it delegated or aborted.\n held?.left()\n }\n })()\n }\n\n private notify(sessionId: SessionId, paused: boolean): void {\n for (const listener of [...this.listeners]) listener(sessionId, paused)\n }\n\n private notifyHeld(sessionId: SessionId, held: boolean): void {\n for (const listener of [...this.heldListeners]) listener(sessionId, held)\n }\n}\n","/**\n * What a session is doing between \"pause was asked for\" and \"its next model\n * request is standing still at the gate\".\n *\n * Two facts decide that, and each has its own owner:\n *\n * - Whether a turn is open is derived state the harness already maintains:\n * the agent registry owns the `turnBoundary` session projection, which folds\n * `turn/start`, `turn/end`, `step/start`, and `step/end` into\n * `openTurnStartSeq`. Reading it through `ctx.agents` is a synchronous\n * projection read, not a scan of the event log (synchronous history reads are\n * prohibited for new code).\n * - Which tool is in flight is a log-derived per-session fact, so it is a\n * session projection too. The projection folds each committed\n * `tool/call` → `tool/result` pairing and keeps the calls in order; the\n * framework owns replay, caching, and disposal. This module listens only to\n * committed events so it can wake the control, never to keep a second copy\n * of the state itself.\n * @module dsh-pause-session/park\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Session, SessionId } from '@deepseek-ai/dsh-session'\nimport type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'\nimport { z } from 'zod'\n// Type-only: pulls the agent registry's Context merge (ctx.agents).\nimport type {} from '@deepseek-ai/dsh-agent'\n\n/** One tool call the session has committed but not yet answered. */\nconst openCallSchema = z.object({\n /** The provider-issued id pairing the call with the result that has not arrived. */\n callId: z.string(),\n /** The tool's own name, as the model called it. */\n name: z.string(),\n})\n\n/** The host-only projection state: open calls in call order. */\ntype OpenToolCall = z.infer<typeof openCallSchema>\n\n/**\n * The host-only fold behind {@link ParkWatch}. It is registered on the\n * plugin's fiber; unload removes it with every other registration.\n */\nconst parkActivityProjection: ProjectionDefinition<'dsh-pause-session/activity', OpenToolCall[]> = {\n key: 'dsh-pause-session/activity',\n stateSchema: z.array(openCallSchema),\n init: () => [],\n apply: (state, event) => {\n if (event.type === 'tool/call') {\n return [...state, { callId: String(event.data.callId), name: event.data.name }]\n }\n if (event.type === 'tool/result') {\n const callId = String(event.data.message.toolCallId)\n const at = state.findIndex(call => call.callId === callId)\n if (at < 0) return state\n return [...state.slice(0, at), ...state.slice(at + 1)]\n }\n return state\n },\n stateVersion: 1,\n}\n\n/** One session's current activity, as the control reports it. */\nexport interface ParkActivity {\n /** Whether the session is inside a turn — including one waiting for this very park. */\n readonly turnOpen: boolean\n /** Names of the calls currently in flight, in call order; empty when no tool is running. */\n readonly runningTools: readonly string[]\n}\n\n/** Both halves of the activity question for one session. */\nexport interface ParkWatch {\n /**\n * @param sessionId - session to inspect.\n * @returns the session's current turn and tool activity.\n */\n activity(sessionId: SessionId): ParkActivity\n /**\n * Subscribe to activity changes.\n * @param listener - called with the session whose activity changed; it must\n * only record that a look is owed, never re-enter the session.\n * @returns the unsubscribe function.\n */\n onChange(listener: (sessionId: SessionId) => void): () => void\n}\n\n/** Whether the agent registry's `turnBoundary` fold reports an open turn. */\nfunction turnOpen(ctx: Context, session: Session): boolean {\n return ctx.agents.turnBoundaryOf(session).openTurnStartSeq !== null\n}\n\n/**\n * Mount the per-session activity projection and its notification edge.\n * @param ctx - host context carrying the session store and the projection registry.\n * @returns the watch the park state is derived from.\n */\nexport async function mountParkWatch(ctx: Context): Promise<ParkWatch> {\n const activity = await ctx.sessionProjections.register(parkActivityProjection)\n const listeners = new Set<(sessionId: SessionId) => void>()\n\n const notify = (sessionId: SessionId): void => {\n for (const listener of [...listeners]) listener(sessionId)\n }\n\n ctx.effect(() => ctx.on('session/event', (session, event) => {\n switch (event.type) {\n case 'tool/call':\n case 'tool/result':\n // The projection owns the open-call list; the committed event only\n // says the control owes a look at it.\n notify(session.id)\n return\n case 'turn/start':\n case 'turn/end':\n // Turn state itself is read from the projection, but a turn boundary is\n // the other half of \"is this session standing still\": a turn that ends\n // with no further request can never produce the hold a park would wait\n // for, so the park predicate has to look again here.\n notify(session.id)\n return\n default:\n return\n }\n }), 'pause: session activity changes')\n\n return {\n activity: (sessionId) => {\n const session = ctx.sessions.get(sessionId)\n if (session === undefined) {\n // A session with no live log cannot be mid-turn; the park predicate\n // owns what that means.\n return { turnOpen: false, runningTools: [] }\n }\n return {\n turnOpen: turnOpen(ctx, session),\n runningTools: activity.stateOf(session).map(call => call.name),\n }\n },\n onChange: (listener) => {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n }\n}\n","/**\n * Native Remote transport for the pause controls.\n *\n * This module is deliberately self-contained: it imports only Cordis and the\n * Typert decorators. The Typert generator analyzes this file alone so a\n * third-party package can emit its Host reflection and Client contribution\n * without pulling the plugin's DSH-typed modules into the generation face.\n *\n * The UI uses this namespace on Web and Desktop alike. No slash command is\n * registered; the stream is the live status channel and the methods below are\n * the button actions.\n * @module dsh-pause-session/remote\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { principalOf, Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'\nimport type { RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol'\n\ndeclare module '@deepseek-ai/dsh-typert-protocol' {\n interface RemoteErrorDetailsMap {\n /** The pause control is personal; only the owner may read or drive it. */\n 'pause/owner-only': {}\n }\n}\n\n/** The phase a Session reports to the controls. */\nexport type PausePhaseWire = 'active' | 'draining' | 'parking' | 'safe' | 'flush-failed'\n\n/** One Session's pause state. */\nexport interface SessionStatusWire {\n readonly phase: PausePhaseWire\n readonly runningTools: readonly string[]\n readonly rearmGoal?: boolean\n}\n\n/** The whole-app verdict. */\nexport interface GlobalStatusWire {\n readonly verdict: 'idle' | 'waiting' | 'safe'\n readonly registered: number\n readonly safe: number\n readonly parkedAt?: string\n readonly draining: readonly string[]\n readonly parking: number\n readonly stalled: readonly string[]\n readonly unresumable: readonly string[]\n readonly unreadTrees: readonly string[]\n readonly jobs: readonly string[]\n readonly blind: readonly string[]\n}\n\n/** One live status snapshot: the aggregate plus every held Session. */\nexport interface PauseSnapshotWire {\n readonly global: GlobalStatusWire\n readonly sessions: Readonly<Record<string, SessionStatusWire>>\n}\n\n/** One row in the morning decision list. */\nexport interface TriageRowWire {\n readonly sessionId: string\n readonly phase: 'draining' | 'parking' | 'flush-failed'\n readonly updatedAt: number\n readonly reading: 'read' | 'unreadable'\n readonly lastEvent?: string\n readonly turn?: number\n readonly step?: number\n readonly traces: readonly { readonly tool: string; readonly callId: string }[]\n readonly owed: boolean\n readonly wakeable: boolean\n readonly rearmGoal: boolean\n}\n\n/** One button action. */\nexport interface PauseActionRequest {\n readonly action: 'pause' | 'resume' | 'pause-all' | 'resume-all' | 'cancel-all' | 'goal'\n /** The Session the control is addressed through. */\n readonly sessionId: string\n}\n\n/** One action outcome. */\nexport interface PauseActionResultWire {\n readonly ok: boolean\n readonly message: string\n}\n\n/** One decision-list read. */\nexport interface PauseTriageRequest {\n readonly caller: string\n}\n\n/** One decision on a listed Session. */\nexport interface PauseDecisionRequest {\n readonly caller: string\n readonly target: string\n readonly decision: 'continue' | 'note' | 'review' | 'leave' | 'goal'\n}\n\n/** Host callbacks the Remote service delegates to. */\n/**\n * Refuse a Remote call made by a principal other than the owner. In-process\n * callers (tests, the Host itself) have no invocation and are trusted.\n * @param ctx - the service Context.\n */\nfunction ownerOnly(ctx: Context): void {\n const invocation = (ctx as Context & { readonly invocation?: RemoteInvocation }).invocation\n if (invocation === undefined) return\n if (invocation.peer.principal?.kind !== 'owner') {\n throw new RemoteError('pause/owner-only', 'pause controls are available only to the owner', {})\n }\n}\n\n/**\n * Record one state-changing Remote action in the host log. The principal is\n * the owning user for owner calls and trusted in-process invocations; no wire\n * field can forge it.\n * @param ctx - the service Context.\n * @param action - the action pressed.\n * @param sessionId - the addressed Session.\n */\nfunction logAction(ctx: Context, action: string, sessionId: string): void {\n const invocation = (ctx as Context & { readonly invocation?: RemoteInvocation }).invocation\n const principal = principalOf(invocation)\n ctx.logger.info(`pause: ${action} \"${sessionId}\"`, {\n action,\n sessionId,\n principal: principal?.kind ?? 'owner',\n })\n}\n\nexport interface PauseRemoteApi {\n snapshot(signal?: AbortSignal): Promise<PauseSnapshotWire>\n subscribe(listener: () => void): () => void\n act(request: PauseActionRequest, signal?: AbortSignal): Promise<PauseActionResultWire>\n triage(request: PauseTriageRequest, signal?: AbortSignal): Promise<readonly TriageRowWire[]>\n decide(request: PauseDecisionRequest, signal?: AbortSignal): Promise<PauseActionResultWire>\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n pauseSession: PauseRemote\n }\n}\n\n/** Host service exposed to the browser as the `pauseSession` Remote namespace. */\nexport class PauseRemote extends TypertRemoteService {\n /** One snapshot per host version, shared by every connected observer. */\n private snapshotCache: { readonly version: number; readonly value: Promise<PauseSnapshotWire> } | undefined\n /** Bumped by every host notification; each observer compares it to its own cursor. */\n private version = 0\n /** Observers waiting for the next version. */\n private readonly waiters = new Set<() => void>()\n private readonly unsubscribe: () => void\n\n /**\n * @param ctx - host context owning the service.\n * @param api - the pause engine behind the wire methods.\n */\n constructor(ctx: Context, private readonly api: PauseRemoteApi) {\n super(ctx, 'pauseSession', { namespace: 'pauseSession' })\n this.unsubscribe = this.api.subscribe(() => {\n this.version += 1\n this.snapshotCache = undefined\n for (const wake of [...this.waiters]) wake()\n this.waiters.clear()\n })\n ctx.effect(() => this.unsubscribe, 'pause: remote updates')\n }\n\n /**\n * One exact snapshot, used by tests and by a reconnect that cannot wait for\n * the first stream item.\n * @param signal - carrier cancellation.\n * @returns the current aggregate and session states.\n */\n @Remote('snapshot')\n async snapshot(signal?: AbortSignal): Promise<PauseSnapshotWire> {\n ownerOnly(this.ctx)\n return await this.api.snapshot(signal)\n }\n\n /**\n * The snapshot for one host version, computed once even when several clients\n * are watching. A new notification discards the cached promise.\n * @param version - the host version this snapshot answers.\n * @param signal - stream cancellation.\n * @returns the shared snapshot promise.\n */\n private snapshotFor(version: number, signal?: AbortSignal): Promise<PauseSnapshotWire> {\n if (this.snapshotCache?.version === version) return this.snapshotCache.value\n const value = this.api.snapshot(signal)\n this.snapshotCache = { version, value }\n return value\n }\n\n /**\n * Live status: the opening snapshot, then one new snapshot whenever the host\n * reports a change.\n * @param signal - stream cancellation.\n * @returns the snapshot stream.\n */\n @Remote({ mode: 'stream' })\n async *observe(signal?: AbortSignal): AsyncIterable<PauseSnapshotWire> {\n ownerOnly(this.ctx)\n let seen = -1\n for (;;) {\n signal?.throwIfAborted()\n if (this.version !== seen) {\n seen = this.version\n yield await this.snapshotFor(seen, signal)\n continue\n }\n await new Promise<void>((resolve, reject) => {\n const finish = (): void => {\n signal?.removeEventListener('abort', onAbort)\n this.waiters.delete(finish)\n resolve()\n }\n const onAbort = (): void => {\n this.waiters.delete(finish)\n signal?.removeEventListener('abort', onAbort)\n reject(signal?.reason)\n }\n this.waiters.add(finish)\n signal?.addEventListener('abort', onAbort, { once: true })\n // A notification may have landed between the version check and the\n // waiter assignment. It still owes this loop one read.\n if (this.version !== seen) finish()\n })\n }\n }\n\n /**\n * Pause, resume, press every tree, resume every clean park, or flip one\n * Session's goal re-arm.\n * @param request - the button action.\n * @param signal - carrier cancellation.\n * @returns the user-facing outcome.\n */\n @Remote('act')\n async act(request: PauseActionRequest, signal?: AbortSignal): Promise<PauseActionResultWire> {\n ownerOnly(this.ctx)\n logAction(this.ctx, request.action, request.sessionId)\n return await this.api.act(request, signal)\n }\n\n /**\n * Read the morning decision list.\n * @param request - the calling Session whose list is read.\n * @param signal - read cancellation.\n * @returns the listed rows.\n */\n @Remote('triage')\n async triage(request: PauseTriageRequest, signal?: AbortSignal): Promise<readonly TriageRowWire[]> {\n ownerOnly(this.ctx)\n return await this.api.triage(request, signal)\n }\n\n /**\n * Take one decision on one listed Session.\n * @param request - the caller, target, and decision.\n * @param signal - load cancellation.\n * @returns the user-facing outcome.\n */\n @Remote('decide')\n async decide(request: PauseDecisionRequest, signal?: AbortSignal): Promise<PauseActionResultWire> {\n ownerOnly(this.ctx)\n logAction(this.ctx, request.decision, request.target)\n return await this.api.decide(request, signal)\n }\n}\n","/**\n * Wire adapter between the pause engine and the generated Remote namespace.\n *\n * The engine speaks in branded Session ids and user-facing answer copy; the Remote\n * contract is plain JSON. Mapping lives here so neither side depends on the\n * other's types.\n * @module dsh-pause-session/remote-adapter\n */\n\nimport { SessionId } from '@deepseek-ai/dsh-session'\nimport type { SessionControl, PressTreeOutcome } from './control.js'\nimport type {\n GlobalStatusWire, PauseActionRequest, PauseActionResultWire, PauseDecisionRequest,\n PauseRemoteApi, PauseSnapshotWire, PauseTriageRequest, SessionStatusWire, TriageRowWire,\n} from './remote.js'\nimport type { GlobalStatus, ParkStatus, TriageAction, TriageRow } from './shared.js'\n\n/** Map the engine's aggregate status to the wire shape. */\nfunction globalOf(status: GlobalStatus): GlobalStatusWire {\n return {\n verdict: status.verdict,\n registered: status.registered,\n safe: status.safe,\n ...status.parkedAt === undefined ? {} : { parkedAt: String(status.parkedAt) },\n draining: status.draining.map(String),\n parking: status.parking,\n stalled: status.stalled.map(String),\n unresumable: status.unresumable.map(String),\n unreadTrees: status.unreadTrees.map(String),\n jobs: status.jobs.map(String),\n blind: [...status.blind],\n }\n}\n\n/** Map one engine status to the wire shape. */\nfunction sessionOf(status: ParkStatus): SessionStatusWire {\n return {\n phase: status.phase,\n runningTools: [...status.runningTools],\n ...status.rearmGoal === undefined ? {} : { rearmGoal: status.rearmGoal },\n }\n}\n\n/** Map one engine triage row to the wire shape. */\nfunction triageRowOf(row: TriageRow): TriageRowWire {\n return {\n sessionId: row.sessionId,\n phase: row.phase,\n updatedAt: row.updatedAt,\n reading: row.reading,\n ...row.lastEvent === undefined ? {} : { lastEvent: row.lastEvent },\n ...row.turn === undefined ? {} : { turn: row.turn },\n ...row.step === undefined ? {} : { step: row.step },\n traces: row.traces.map(trace => ({\n tool: trace.tool,\n callId: trace.callId,\n })),\n owed: row.owed,\n wakeable: row.wakeable,\n rearmGoal: row.rearmGoal,\n }\n}\n\n/** Map the engine's snapshot to the wire shape. */\nexport function snapshotOf(snapshot: { global: GlobalStatus; sessions: Readonly<Record<string, ParkStatus>> }): PauseSnapshotWire {\n return {\n global: globalOf(snapshot.global),\n sessions: Object.fromEntries(Object.entries(snapshot.sessions).map(([id, status]) => [id, sessionOf(status)])),\n }\n}\n\n/** Convert one engine answer to the wire outcome. */\nfunction outcomeOf(answer: { kind: 'success' | 'error'; text?: string }): PauseActionResultWire {\n return { ok: answer.kind === 'success', message: answer.text ?? (answer.kind === 'success' ? 'Done.' : 'Pause action failed.') }\n}\n\n/** Convert a press outcome to the wire outcome. */\nfunction pressOutcomeOf(outcome: PressTreeOutcome): PauseActionResultWire {\n const names = (ids: readonly SessionId[]): string => ids.map(id => `\"${String(id)}\"`).join(', ')\n if (outcome.unrecorded.length > 0) {\n return { ok: false, message: `pause could not record ${names(outcome.unrecorded)}.` }\n }\n if (!outcome.rootRegistered) return { ok: false, message: 'pause did not register this session.' }\n const caveats: string[] = []\n if (outcome.unresumable.length > 0) {\n caveats.push(`these subagents cannot be resumed: ${names(outcome.unresumable)}.`)\n }\n if (outcome.unreadBranches.length > 0) {\n caveats.push(`these subagent branches could not be read: ${names(outcome.unreadBranches)}.`)\n }\n if (outcome.unread && outcome.unreadBranches.length === 0) {\n caveats.push('The subagent tree could not be fully read.')\n }\n return {\n ok: true,\n message: `Paused ${String(outcome.registered)} session${outcome.registered === 1 ? '' : 's'}.`\n + (caveats.length === 0 ? '' : ` ${caveats.join(' ')}`),\n }\n}\n\n/**\n * Build the Remote callbacks over the mounted pause control.\n * @param control - the engine's host control surface.\n * @returns the wire API.\n */\nexport function remoteApiOf(control: SessionControl): PauseRemoteApi {\n return {\n snapshot: async signal => snapshotOf(await control.readSnapshot(signal)),\n subscribe: listener => control.subscribe(listener),\n act: async (request: PauseActionRequest, signal) => {\n const sessionId = SessionId(request.sessionId)\n switch (request.action) {\n case 'pause':\n return pressOutcomeOf(await control.pressTree(sessionId, signal))\n case 'resume':\n return outcomeOf((await control.releaseTree(sessionId, signal)).answer)\n case 'pause-all':\n return outcomeOf(await control.pauseAll(signal))\n case 'resume-all':\n return outcomeOf(await control.resumeAll(signal))\n case 'cancel-all':\n return outcomeOf(await control.cancelAll(signal))\n case 'goal':\n return outcomeOf(await control.toggleGoal(sessionId, signal))\n }\n },\n triage: async (request: PauseTriageRequest, signal) => {\n const list = await control.readTriage(SessionId(request.caller), signal)\n return list.rows.map(triageRowOf)\n },\n decide: async (request: PauseDecisionRequest, signal) => {\n const action = request.decision as TriageAction\n return outcomeOf(await control.decideTriage(\n SessionId(request.caller),\n SessionId(request.target),\n action,\n signal,\n ))\n },\n }\n}\n","/**\n * The durable park registry: which sessions are paused, and how cleanly each\n * one stopped.\n *\n * The registry lives in the profile's storage — `ctx.storageDomain`, the\n * schema-validated domain data form over whichever backend the composition\n * routes it to — and never in the session log: a pause is not part of a\n * session's history, and the list has to be readable by a process that has not\n * opened any session yet. The domain's own backend route is configuration, so\n * this module names no path and performs no IO of its own.\n *\n * The domain keeps the DEFAULT whole-unit layout on purpose. The per-record\n * layout reads a malformed or stale record document as an absent record, which\n * here would silently drop one paused session; a whole-unit file turns any\n * corruption into a failed `open`, and a failed open fails the plugin's mount\n * loudly instead of resuming everything.\n * @module dsh-pause-session/registry\n */\n\nimport { z } from 'zod'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { SessionId } from '@deepseek-ai/dsh-session'\nimport { defineDomain, domainTable, DomainError } from '@deepseek-ai/dsh-storage-domain'\nimport type { Domain } from '@deepseek-ai/dsh-storage-domain'\nimport { PARK_PHASES } from './shared.js'\nimport type { ParkPhase } from './shared.js'\n\n/** Domain and backend-unit name; one document per profile under the storage root. */\nexport const PARK_REGISTRY_DOMAIN = 'pause_registry'\n\n/** One session's stored park outcome. */\nexport const parkRecord = z.object({\n /** How far that session got before its process ended; only `safe` is clean. */\n phase: z.enum(PARK_PHASES),\n /** When this record was last written — a phase change, or a goal opt-out flip. */\n updatedAt: z.number().int().nonnegative(),\n /**\n * Whether resuming this session may re-arm its goal. Re-arming is opt-OUT\n * because a re-armed goal continues on its own and spends the owner's money;\n * a record written before this field existed reads as `true`, which is the\n * product default (a goal session comes back running its rounds).\n *\n * Every phase write of one park episode folds through the stored record, so\n * the opt-out a user sets while the session is still draining survives the\n * `parking` and `safe` writes that follow it.\n */\n rearmGoal: z.boolean().default(true),\n})\n\n/** One session's stored park outcome. */\nexport type ParkRecord = z.infer<typeof parkRecord>\n\n/**\n * The registry declaration. `version: 1` and no `compatibleVersions`: the\n * domain layer rejects a stored unit stamped with any other version rather than\n * migrating it, so an unrecognized registry fails loud at open. Validation is\n * the rejecting default for the same reason — a record this build cannot read\n * must stop the mount, not disappear from the list.\n */\nexport const parkRegistryDomain = defineDomain({\n name: PARK_REGISTRY_DOMAIN,\n version: 1,\n tables: { sessions: domainTable<SessionId, ParkRecord>(parkRecord) },\n})\n\n/** One session the registry remembers. */\nexport interface ParkedSession {\n readonly sessionId: SessionId\n readonly phase: ParkPhase\n /** When the phase was written. */\n readonly updatedAt: number\n /** Whether resuming this session may re-arm its goal; see {@link parkRecord}. */\n readonly rearmGoal: boolean\n}\n\n/** The durable pause list, opened over the profile's storage. */\nexport interface ParkRegistry {\n /**\n * @returns every remembered session, in insertion order.\n */\n list(): readonly ParkedSession[]\n /**\n * The same list as {@link list}, as a lazily kept read-only view.\n *\n * The whole-app aggregate and the decision list read this once per status\n * read, and a status read can happen on every native-stream notification; the\n * view is rebuilt only when the stored entries actually changed, so a read\n * that changes nothing does not build a second copy of the list to look at.\n * A caller must not mutate it.\n */\n readonly parked: ReadonlyMap<SessionId, ParkedSession>\n /**\n * @param sessionId - session to look up.\n * @returns the remembered session, or `undefined` when nothing is parked under that id.\n */\n get(sessionId: SessionId): ParkedSession | undefined\n /**\n * Write one session's outcome; resolves once it is durable. The goal opt-out\n * already recorded for that session survives a phase change — the phases of\n * one park episode all describe the same parked session.\n * @param sessionId - the session being parked.\n * @param phase - how far the park has got.\n */\n record(sessionId: SessionId, phase: ParkPhase): Promise<void>\n /**\n * Set one session's goal opt-out; resolves once it is durable.\n * @param sessionId - the parked session to change.\n * @param rearmGoal - whether the clean resume path may re-arm its goal.\n * @throws when no record exists for that session — the flag describes a\n * parked session, and inventing a record would invent a park.\n */\n setRearmGoal(sessionId: SessionId, rearmGoal: boolean): Promise<void>\n /**\n * Drop one session from the list, so a later process does not re-hold it.\n * @param sessionId - the session being released.\n */\n forget(sessionId: SessionId): Promise<void>\n}\n\n/**\n * Open the registry over the mounted storage. The caller owns the handle's\n * lifetime; this registers the close as an effect on `ctx`, so the unit is\n * released with the plugin.\n * @param ctx - plugin context carrying `storageDomain`.\n * @returns the open registry.\n * @throws whatever `open` rejects with — a `StorageError` for an unreadable\n * unit, a `DomainError('invalid-record')` for a record this build cannot read.\n */\nexport async function openParkRegistry(ctx: Context): Promise<ParkRegistry> {\n const domain: Domain<typeof parkRegistryDomain> = await ctx.storageDomain.open(parkRegistryDomain)\n ctx.effect(() => () => domain.close(), 'pause: registry')\n const sessions = domain.table('sessions')\n /** The entries the cached view was built from; replaced whenever they differ. */\n let cachedFrom: readonly ParkedSession[] = []\n let cached: ReadonlyMap<SessionId, ParkedSession> | undefined\n const entryOf = (sessionId: SessionId): ParkedSession | undefined => {\n const record = sessions.get(sessionId)\n return record === undefined\n ? undefined\n : { sessionId, phase: record.phase, updatedAt: record.updatedAt, rearmGoal: record.rearmGoal }\n }\n const entriesNow = (): readonly ParkedSession[] => [...sessions.entries()].map(([sessionId, record]) => ({\n sessionId,\n phase: record.phase,\n updatedAt: record.updatedAt,\n rearmGoal: record.rearmGoal,\n }))\n return {\n list: entriesNow,\n get parked() {\n const entries = entriesNow()\n // Same length and same records: the view the last read built still\n // describes this list, so hand that one back rather than another copy.\n if (cached !== undefined && entries.length === cachedFrom.length\n && entries.every((entry, at) => {\n const previous = cachedFrom[at]\n return previous !== undefined\n && entry.sessionId === previous.sessionId\n && entry.phase === previous.phase\n && entry.updatedAt === previous.updatedAt\n && entry.rearmGoal === previous.rearmGoal\n })) return cached\n cachedFrom = entries\n cached = new Map(entries.map(entry => [entry.sessionId, entry]))\n return cached\n },\n get: entryOf,\n record: async (sessionId, phase) => {\n const updatedAt = Date.now()\n // A record already there is folded through `update`, so the phase write\n // and the record's own goal opt-out are decided in the backend's job\n // order rather than from a read taken before this write was queued.\n if (sessions.get(sessionId) !== undefined) {\n try {\n await sessions.update(sessionId, current => ({ ...current, phase, updatedAt }))\n return\n } catch (error: unknown) {\n // Released between that read and this job: fall through and start the\n // record again, which is what the park phase is asking for.\n if (!(error instanceof DomainError) || error.code !== 'missing-key') throw error\n }\n }\n // A fresh object per write: domain records are the stored objects and are\n // never mutated in place.\n await sessions.put(sessionId, { phase, updatedAt, rearmGoal: true })\n },\n setRearmGoal: async (sessionId, rearmGoal) => {\n // `update` decides existence and reads the current record inside the\n // backend's own job order, so a phase write queued beside it cannot be\n // clobbered by a stale read.\n await sessions.update(sessionId, current => ({ ...current, rearmGoal, updatedAt: Date.now() }))\n },\n forget: async (sessionId) => {\n await sessions.delete(sessionId)\n },\n }\n}\n","/**\n * Host half of dsh-pause-session.\n *\n * Mounts the pause gate — the per-session hold at the model-request waterfall —\n * the activity fold the park predicate reads, the durable park registry, the\n * session control the browser half drives, and the clean resume path that\n * answers the input a parked session left pending.\n *\n * The registry is read before anything is gated, so a session a previous\n * process left parked is held again by this one without any user action; a\n * registry this build cannot read fails the mount loudly rather than silently\n * resuming every session it named.\n * @module dsh-pause-session\n */\n\nimport { z } from 'zod'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { TRIAGE_LOG_MAX_EVENTS, TRIAGE_WINDOW_EVENTS } from './coldlog.js'\nimport { installSessionControl } from './control.js'\nimport { PauseGate } from './gate.js'\nimport { mountParkWatch } from './park.js'\nimport { PauseRemote } from './remote.js'\nimport { remoteApiOf } from './remote-adapter.js'\nimport { openParkRegistry } from './registry.js'\nexport { PauseRemote } from './remote.js'\n\n/** Plugin name; the Loader row and the bundle patch both use it. */\nexport const name = 'dsh-pause-session'\n\n/**\n * Required host services: the model runtime to gate, the stores the control\n * needs, the projection registry the park predicate reads turn state from, and\n * the profile's storage, which holds the pause registry.\n */\nexport const inject = ['llm', 'agents', 'sessions', 'sessionProjections', 'storageDomain']\n\n/**\n * Provider routes whose request conversion drops an empty user message, so the\n * clean resume path's wake input never reaches the model on them.\n *\n * The list is deployment knowledge, not a constant this plugin may assume:\n * whether an empty user message survives is decided by the adapter (and, for\n * the pi-ai family, by the provider API that adapter is configured for), and a\n * plugin cannot introspect an adapter. The default names the routes the shipped\n * DeepSeek adapter registers; a profile that routes a session elsewhere gets\n * the visible marker instead of a silent empty turn until it declares that\n * route here.\n */\nexport const DEFAULT_SILENT_WAKE_ROUTES = ['deepseek-official', 'deepseek-account'] as const\n\n/** Validated plugin configuration. */\nconst ConfigShape = z.object({\n /** Provider routes known to drop an empty user message; see {@link DEFAULT_SILENT_WAKE_ROUTES}. */\n silentWakeRoutes: z.array(z.string()).default([...DEFAULT_SILENT_WAKE_ROUTES]),\n /**\n * How many events of a parked session's stored log the morning list folds per\n * row, counted back from the end. The list reads a session's stop position\n * and its unknown tool outcomes, both facts about the log's end, so this\n * bounds what a panel left open costs without changing what a row says about\n * a log that fits inside it. A row whose log needs more than this is reported\n * unreadable rather than guessed at; see `./coldlog.ts`.\n */\n maxListedLogEvents: z.number().int().min(1).max(TRIAGE_LOG_MAX_EVENTS).default(TRIAGE_WINDOW_EVENTS),\n})\n\n/** Validated plugin configuration. */\nexport type Config = z.infer<typeof ConfigShape>\n\n/**\n * The Loader hands a row's config through this schema, and an empty row config\n * arrives as `undefined`; folding it to `{}` first is what lets the field\n * defaults above apply instead of failing the mount.\n */\nexport const Config = z.preprocess(value => value ?? {}, ConfigShape)\n\n/**\n * Mount the durable pause registry, the pause gate, the activity fold, their\n * session control, and the clean resume path.\n *\n * The registry opens first on purpose: if it cannot be read, nothing else is\n * registered, so a failed mount leaves no half-installed control behind.\n * @param ctx - the plugin's host context.\n * @param config - validated route knowledge for the resume path's wake content.\n */\nexport async function apply(ctx: Context, config: Config = Config.parse({})): Promise<void> {\n const registry = await openParkRegistry(ctx)\n const lifetime = new AbortController()\n // The gate races this signal, so unloading releases every held request\n // instead of stranding a generator no one can reach again.\n ctx.effect(() => () => { lifetime.abort(new Error('pause: plugin unloaded')) }, 'pause: lifetime')\n const gate = new PauseGate({ lifetime: lifetime.signal })\n ctx.effect(\n () => ctx.on('llm/stream', (request, next) => gate.stream(request, next)),\n 'pause: pause gate',\n )\n const watch = await mountParkWatch(ctx)\n const control = installSessionControl(ctx, gate, watch, registry, {\n silentWakeRoutes: config.silentWakeRoutes,\n maxListedLogEvents: config.maxListedLogEvents,\n })\n new PauseRemote(ctx, remoteApiOf(control))\n await control.adopt()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,UAAU,UAA4B;CACpD,KAAK,IAAI,QAAQ,SAAS,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG;EAC5D,MAAM,UAAU,SAAS;EAEzB,IAAI,YAAY,KAAA,KAAa,QAAQ,SAAS,YAAY,QAAQ,SAAS,aAAa;EACxF,OAAO,QAAQ,SAAS;CAC1B;CACA,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,eACd,QACA,aAAgD;CAEhD,MAAM,SAAS,CAAC,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